repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
loshca/gst-plugins-good | sys/osxaudio/gstosxaudioringbuffer.c | 8 | 10189 | /*
* GStreamer
* Copyright (C) 2006 Zaheer Abbas Merali <zaheerabbas at merali dot org>
* Copyright (C) 2008 Pioneers of the Inevitable <songbird@songbirdnest.com>
* Copyright (C) 2012 Fluendo S.A. <support@fluendo.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include <gst/audio/audio-channels.h>
#include "gstosxaudioringbuffer.h"
#include "gstosxaudiosink.h"
#include "gstosxaudiosrc.h"
#include <unistd.h> /* for getpid() */
GST_DEBUG_CATEGORY_STATIC (osx_audio_debug);
#define GST_CAT_DEFAULT osx_audio_debug
#include "gstosxcoreaudio.h"
static void gst_osx_audio_ring_buffer_dispose (GObject * object);
static gboolean gst_osx_audio_ring_buffer_open_device (GstAudioRingBuffer *
buf);
static gboolean gst_osx_audio_ring_buffer_close_device (GstAudioRingBuffer *
buf);
static gboolean gst_osx_audio_ring_buffer_acquire (GstAudioRingBuffer * buf,
GstAudioRingBufferSpec * spec);
static gboolean gst_osx_audio_ring_buffer_release (GstAudioRingBuffer * buf);
static gboolean gst_osx_audio_ring_buffer_start (GstAudioRingBuffer * buf);
static gboolean gst_osx_audio_ring_buffer_pause (GstAudioRingBuffer * buf);
static gboolean gst_osx_audio_ring_buffer_stop (GstAudioRingBuffer * buf);
static guint gst_osx_audio_ring_buffer_delay (GstAudioRingBuffer * buf);
static GstAudioRingBufferClass *ring_parent_class = NULL;
#define gst_osx_audio_ring_buffer_do_init \
GST_DEBUG_CATEGORY_INIT (osx_audio_debug, "osxaudio", 0, "OSX Audio Elements");
G_DEFINE_TYPE_WITH_CODE (GstOsxAudioRingBuffer, gst_osx_audio_ring_buffer,
GST_TYPE_AUDIO_RING_BUFFER, gst_osx_audio_ring_buffer_do_init);
static void
gst_osx_audio_ring_buffer_class_init (GstOsxAudioRingBufferClass * klass)
{
GObjectClass *gobject_class;
GstAudioRingBufferClass *gstringbuffer_class;
gobject_class = (GObjectClass *) klass;
gstringbuffer_class = (GstAudioRingBufferClass *) klass;
ring_parent_class = g_type_class_peek_parent (klass);
gobject_class->dispose = gst_osx_audio_ring_buffer_dispose;
gstringbuffer_class->open_device =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_open_device);
gstringbuffer_class->close_device =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_close_device);
gstringbuffer_class->acquire =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_acquire);
gstringbuffer_class->release =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_release);
gstringbuffer_class->start =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_start);
gstringbuffer_class->pause =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_pause);
gstringbuffer_class->resume =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_start);
gstringbuffer_class->stop =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_stop);
gstringbuffer_class->delay =
GST_DEBUG_FUNCPTR (gst_osx_audio_ring_buffer_delay);
GST_DEBUG ("osx audio ring buffer class init");
}
static void
gst_osx_audio_ring_buffer_init (GstOsxAudioRingBuffer * ringbuffer)
{
ringbuffer->core_audio = gst_core_audio_new (GST_OBJECT (ringbuffer));
}
static void
gst_osx_audio_ring_buffer_dispose (GObject * object)
{
GstOsxAudioRingBuffer *osxbuf;
osxbuf = GST_OSX_AUDIO_RING_BUFFER (object);
if (osxbuf->core_audio) {
g_object_unref (osxbuf->core_audio);
osxbuf->core_audio = NULL;
}
G_OBJECT_CLASS (ring_parent_class)->dispose (object);
}
static gboolean
gst_osx_audio_ring_buffer_open_device (GstAudioRingBuffer * buf)
{
GstOsxAudioRingBuffer *osxbuf = GST_OSX_AUDIO_RING_BUFFER (buf);
if (!gst_core_audio_select_device (osxbuf->core_audio))
return FALSE;
return gst_core_audio_open (osxbuf->core_audio);
}
static gboolean
gst_osx_audio_ring_buffer_close_device (GstAudioRingBuffer * buf)
{
GstOsxAudioRingBuffer *osxbuf;
osxbuf = GST_OSX_AUDIO_RING_BUFFER (buf);
return gst_core_audio_close (osxbuf->core_audio);
}
static gboolean
gst_osx_audio_ring_buffer_acquire (GstAudioRingBuffer * buf,
GstAudioRingBufferSpec * spec)
{
gboolean ret = FALSE, is_passthrough = FALSE;
GstOsxAudioRingBuffer *osxbuf;
AudioStreamBasicDescription format;
osxbuf = GST_OSX_AUDIO_RING_BUFFER (buf);
if (RINGBUFFER_IS_SPDIF (spec->type)) {
format.mFormatID = kAudioFormat60958AC3;
format.mSampleRate = (double) GST_AUDIO_INFO_RATE (&spec->info);
format.mChannelsPerFrame = 2;
format.mFormatFlags = kAudioFormatFlagIsSignedInteger |
kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonMixable;
format.mBytesPerFrame = 0;
format.mBitsPerChannel = 16;
format.mBytesPerPacket = 6144;
format.mFramesPerPacket = 1536;
format.mReserved = 0;
spec->segsize = 6144;
spec->segtotal = 10;
is_passthrough = TRUE;
} else {
int width, depth;
/* Fill out the audio description we're going to be using */
format.mFormatID = kAudioFormatLinearPCM;
format.mSampleRate = (double) GST_AUDIO_INFO_RATE (&spec->info);
format.mChannelsPerFrame = GST_AUDIO_INFO_CHANNELS (&spec->info);
if (GST_AUDIO_INFO_IS_FLOAT (&spec->info)) {
format.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
width = depth = GST_AUDIO_INFO_WIDTH (&spec->info);
} else {
format.mFormatFlags = kAudioFormatFlagIsSignedInteger;
width = GST_AUDIO_INFO_WIDTH (&spec->info);
depth = GST_AUDIO_INFO_DEPTH (&spec->info);
if (width == depth) {
format.mFormatFlags |= kAudioFormatFlagIsPacked;
} else {
format.mFormatFlags |= kAudioFormatFlagIsAlignedHigh;
}
}
if (GST_AUDIO_INFO_IS_BIG_ENDIAN (&spec->info)) {
format.mFormatFlags |= kAudioFormatFlagIsBigEndian;
}
format.mBytesPerFrame = GST_AUDIO_INFO_BPF (&spec->info);
format.mBitsPerChannel = depth;
format.mBytesPerPacket = GST_AUDIO_INFO_BPF (&spec->info);
format.mFramesPerPacket = 1;
format.mReserved = 0;
spec->segsize =
(spec->latency_time * GST_AUDIO_INFO_RATE (&spec->info) /
G_USEC_PER_SEC) * GST_AUDIO_INFO_BPF (&spec->info);
spec->segtotal = spec->buffer_time / spec->latency_time;
is_passthrough = FALSE;
}
GST_DEBUG_OBJECT (osxbuf, "Format: " CORE_AUDIO_FORMAT,
CORE_AUDIO_FORMAT_ARGS (format));
if (GST_IS_OSX_AUDIO_SINK (GST_OBJECT_PARENT (buf))) {
gst_audio_ring_buffer_set_channel_positions (buf,
GST_OSX_AUDIO_SINK (GST_OBJECT_PARENT (buf))->channel_positions);
}
buf->size = spec->segtotal * spec->segsize;
buf->memory = g_malloc0 (buf->size);
ret = gst_core_audio_initialize (osxbuf->core_audio, format, spec->caps,
is_passthrough);
if (!ret) {
g_free (buf->memory);
buf->memory = NULL;
buf->size = 0;
}
osxbuf->segoffset = 0;
return ret;
}
static gboolean
gst_osx_audio_ring_buffer_release (GstAudioRingBuffer * buf)
{
GstOsxAudioRingBuffer *osxbuf;
osxbuf = GST_OSX_AUDIO_RING_BUFFER (buf);
gst_core_audio_unitialize (osxbuf->core_audio);
g_free (buf->memory);
buf->memory = NULL;
buf->size = 0;
return TRUE;
}
static gboolean
gst_osx_audio_ring_buffer_start (GstAudioRingBuffer * buf)
{
GstOsxAudioRingBuffer *osxbuf;
osxbuf = GST_OSX_AUDIO_RING_BUFFER (buf);
return gst_core_audio_start_processing (osxbuf->core_audio);
}
static gboolean
gst_osx_audio_ring_buffer_pause (GstAudioRingBuffer * buf)
{
GstOsxAudioRingBuffer *osxbuf = GST_OSX_AUDIO_RING_BUFFER (buf);
return gst_core_audio_pause_processing (osxbuf->core_audio);
}
static gboolean
gst_osx_audio_ring_buffer_stop (GstAudioRingBuffer * buf)
{
GstOsxAudioRingBuffer *osxbuf;
osxbuf = GST_OSX_AUDIO_RING_BUFFER (buf);
gst_core_audio_stop_processing (osxbuf->core_audio);
return TRUE;
}
static guint
gst_osx_audio_ring_buffer_delay (GstAudioRingBuffer * buf)
{
GstOsxAudioRingBuffer *osxbuf;
double latency;
guint samples;
osxbuf = GST_OSX_AUDIO_RING_BUFFER (buf);
if (!gst_core_audio_get_samples_and_latency (osxbuf->core_audio,
GST_AUDIO_INFO_RATE (&buf->spec.info), &samples, &latency)) {
return 0;
}
GST_DEBUG_OBJECT (buf, "Got latency: %f seconds -> %d samples",
latency, samples);
return samples;
}
| lgpl-2.1 |
knuesel/gst-plugins-good | gst/rtp/gstasteriskh263.c | 9 | 6661 | /* GStreamer
* Copyright (C) <2005> Wim Taymans <wim.taymans@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <string.h>
#include <gst/rtp/gstrtpbuffer.h>
#include "gstasteriskh263.h"
/* Cygwin has both netinet/in.h and winsock2.h, but
* only one can be included, so prefer the unix one */
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#else
#ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
#endif
#endif
#define GST_ASTERISKH263_HEADER_LEN 6
typedef struct _GstAsteriskH263Header
{
guint32 timestamp; /* Timestamp */
guint16 length; /* Length */
} GstAsteriskH263Header;
#define GST_ASTERISKH263_HEADER_TIMESTAMP(buf) (((GstAsteriskH263Header *)(GST_BUFFER_DATA (buf)))->timestamp)
#define GST_ASTERISKH263_HEADER_LENGTH(buf) (((GstAsteriskH263Header *)(GST_BUFFER_DATA (buf)))->length)
static GstStaticPadTemplate gst_asteriskh263_src_template =
GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("application/x-asteriskh263")
);
static GstStaticPadTemplate gst_asteriskh263_sink_template =
GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("application/x-rtp, "
"media = (string) \"video\", "
"payload = (int) [ 96, 127 ], "
"clock-rate = (int) 90000, " "encoding-name = (string) \"H263-1998\"")
);
static void gst_asteriskh263_finalize (GObject * object);
static GstFlowReturn gst_asteriskh263_chain (GstPad * pad, GstBuffer * buffer);
static GstStateChangeReturn gst_asteriskh263_change_state (GstElement *
element, GstStateChange transition);
GST_BOILERPLATE (GstAsteriskh263, gst_asteriskh263, GstElement,
GST_TYPE_ELEMENT);
static void
gst_asteriskh263_base_init (gpointer klass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
gst_element_class_add_static_pad_template (element_class,
&gst_asteriskh263_src_template);
gst_element_class_add_static_pad_template (element_class,
&gst_asteriskh263_sink_template);
gst_element_class_set_details_simple (element_class,
"RTP Asterisk H263 depayloader", "Codec/Depayloader/Network/RTP",
"Extracts H263 video from RTP and encodes in Asterisk H263 format",
"Neil Stratford <neils@vipadia.com>");
}
static void
gst_asteriskh263_class_init (GstAsteriskh263Class * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
gobject_class->finalize = gst_asteriskh263_finalize;
gstelement_class->change_state = gst_asteriskh263_change_state;
}
static void
gst_asteriskh263_init (GstAsteriskh263 * asteriskh263,
GstAsteriskh263Class * klass)
{
asteriskh263->srcpad =
gst_pad_new_from_static_template (&gst_asteriskh263_src_template, "src");
gst_element_add_pad (GST_ELEMENT (asteriskh263), asteriskh263->srcpad);
asteriskh263->sinkpad =
gst_pad_new_from_static_template (&gst_asteriskh263_sink_template,
"sink");
gst_pad_set_chain_function (asteriskh263->sinkpad, gst_asteriskh263_chain);
gst_element_add_pad (GST_ELEMENT (asteriskh263), asteriskh263->sinkpad);
asteriskh263->adapter = gst_adapter_new ();
}
static void
gst_asteriskh263_finalize (GObject * object)
{
GstAsteriskh263 *asteriskh263;
asteriskh263 = GST_ASTERISK_H263 (object);
g_object_unref (asteriskh263->adapter);
asteriskh263->adapter = NULL;
G_OBJECT_CLASS (parent_class)->finalize (object);
}
static GstFlowReturn
gst_asteriskh263_chain (GstPad * pad, GstBuffer * buf)
{
GstAsteriskh263 *asteriskh263;
GstBuffer *outbuf;
GstFlowReturn ret;
asteriskh263 = GST_ASTERISK_H263 (GST_OBJECT_PARENT (pad));
if (!gst_rtp_buffer_validate (buf))
goto bad_packet;
{
gint payload_len;
guint8 *payload;
gboolean M;
guint32 timestamp;
guint32 samples;
guint16 asterisk_len;
payload_len = gst_rtp_buffer_get_payload_len (buf);
payload = gst_rtp_buffer_get_payload (buf);
M = gst_rtp_buffer_get_marker (buf);
timestamp = gst_rtp_buffer_get_timestamp (buf);
outbuf = gst_buffer_new_and_alloc (payload_len +
GST_ASTERISKH263_HEADER_LEN);
/* build the asterisk header */
asterisk_len = payload_len;
if (M)
asterisk_len |= 0x8000;
if (!asteriskh263->lastts)
asteriskh263->lastts = timestamp;
samples = timestamp - asteriskh263->lastts;
asteriskh263->lastts = timestamp;
GST_ASTERISKH263_HEADER_TIMESTAMP (outbuf) = g_htonl (samples);
GST_ASTERISKH263_HEADER_LENGTH (outbuf) = g_htons (asterisk_len);
/* copy the data into place */
memcpy (GST_BUFFER_DATA (outbuf) + GST_ASTERISKH263_HEADER_LEN, payload,
payload_len);
GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
gst_buffer_set_caps (outbuf,
(GstCaps *) gst_pad_get_pad_template_caps (asteriskh263->srcpad));
ret = gst_pad_push (asteriskh263->srcpad, outbuf);
gst_buffer_unref (buf);
}
return ret;
bad_packet:
{
GST_DEBUG ("Packet does not validate");
gst_buffer_unref (buf);
return GST_FLOW_ERROR;
}
}
static GstStateChangeReturn
gst_asteriskh263_change_state (GstElement * element, GstStateChange transition)
{
GstAsteriskh263 *asteriskh263;
GstStateChangeReturn ret;
asteriskh263 = GST_ASTERISK_H263 (element);
switch (transition) {
case GST_STATE_CHANGE_READY_TO_PAUSED:
gst_adapter_clear (asteriskh263->adapter);
break;
default:
break;
}
ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
/*
switch (transition) {
case GST_STATE_CHANGE_READY_TO_NULL:
break;
default:
break;
}
*/
return ret;
}
gboolean
gst_asteriskh263_plugin_init (GstPlugin * plugin)
{
return gst_element_register (plugin, "asteriskh263",
GST_RANK_SECONDARY, GST_TYPE_ASTERISK_H263);
}
| lgpl-2.1 |
alessandrod/gst-plugins-good | tests/check/elements/cmmlenc.c | 11 | 15640 | /*
* cmmlenc.c - GStreamer CMML decoder test suite
* Copyright (C) 2005 Alessandro Decina
*
* Authors:
* Alessandro Decina <alessandro@nnva.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <gst/check/gstcheck.h>
#include <gst/tag/tag.h>
#define SINK_CAPS "text/x-cmml"
#define SRC_CAPS "text/x-cmml,encoded=(boolean)FALSE"
#define IDENT_HEADER \
"CMML\x00\x00\x00\x00"\
"\x03\x00\x00\x00"\
"\xe8\x03\x00\x00\x00\x00\x00\x00"\
"\x01\x00\x00\x00\x00\x00\x00\x00"\
"\x20"
#define XML_PREAMBLE \
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"\
"<!DOCTYPE cmml SYSTEM \"cmml.dtd\">\n"
#define START_TAG \
"<cmml>"
#define PROCESSING_INSTRUCTION \
"<?cmml ?>"
#define PREAMBLE \
XML_PREAMBLE START_TAG
#define PREAMBLE_ENCODED \
XML_PREAMBLE PROCESSING_INSTRUCTION
#define STREAM_TAG \
"<stream timebase=\"10\">"\
"<import src=\"test.ogg\"/>"\
"<import src=\"test1.ogg\"/>"\
"</stream>"
#define STREAM_TAG_ENCODED STREAM_TAG
#define HEAD_TAG \
"<head>"\
"<title>The Research Hunter</title>"\
"<meta name=\"DC.audience\" content=\"General\"/>"\
"<meta name=\"DC.author\" content=\"CSIRO Publishing\"/>"\
"<meta name=\"DC.format\" content=\"video\"/>"\
"<meta name=\"DC.language\" content=\"English\"/>"\
"<meta name=\"DC.publisher\" content=\"CSIRO Australia\"/>"\
"</head>"
#define HEAD_TAG_ENCODED HEAD_TAG
#define CLIP_TEMPLATE \
"<clip id=\"%s\" track=\"%s\" start=\"%s\">"\
"<a href=\"http://www.annodex.org/\">http://www.annodex.org</a>"\
"<img src=\"images/index.jpg\"/>"\
"<desc>Annodex Foundation</desc>"\
"<meta name=\"test\" content=\"test content\"/>"\
"</clip>"
#define ENDED_CLIP_TEMPLATE \
"<clip id=\"%s\" track=\"%s\" start=\"%s\" end=\"%s\">"\
"<a href=\"http://www.annodex.org/\">http://www.annodex.org</a>"\
"<img src=\"images/index.jpg\"/>"\
"<desc>Annodex Foundation</desc>"\
"<meta name=\"test\" content=\"test content\"/>"\
"</clip>"
#define CLIP_TEMPLATE_ENCODED \
"<clip id=\"%s\" track=\"%s\">"\
"<a href=\"http://www.annodex.org/\">http://www.annodex.org</a>"\
"<img src=\"images/index.jpg\"/>"\
"<desc>Annodex Foundation</desc>"\
"<meta name=\"test\" content=\"test content\"/>"\
"</clip>"
#define EMPTY_CLIP_TEMPLATE_ENCODED \
"<clip track=\"%s\"/>"
#define fail_unless_equals_flow_return(a, b) \
G_STMT_START { \
gchar *a_up = g_ascii_strup (gst_flow_get_name (a), -1); \
gchar *b_up = g_ascii_strup (gst_flow_get_name (b), -1); \
fail_unless (a == b, \
"'" #a "' (GST_FLOW_%s) is not equal to '" #b "' (GST_FLOW_%s)", \
a_up, b_up); \
g_free (a_up); \
g_free (b_up); \
} G_STMT_END;
static GList *current_buf;
static guint64 granulerate;
static guint8 granuleshift;
static GstElement *cmmlenc;
static GstBus *bus;
static GstFlowReturn flow;
static GstPad *srcpad, *sinkpad;
static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (SINK_CAPS)
);
static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (SRC_CAPS)
);
static GstBuffer *
buffer_new (const gchar * buffer_data, guint size)
{
GstBuffer *buffer;
GstCaps *caps;
buffer = gst_buffer_new_and_alloc (size);
memcpy (GST_BUFFER_DATA (buffer), buffer_data, size);
caps = gst_caps_from_string (SRC_CAPS);
gst_buffer_set_caps (buffer, caps);
gst_caps_unref (caps);
return buffer;
}
static void
buffer_unref (void *buffer, void *user_data)
{
gst_buffer_unref (GST_BUFFER (buffer));
}
static void
setup_cmmlenc (void)
{
guint64 granulerate_n, granulerate_d;
GST_DEBUG ("setup_cmmlenc");
cmmlenc = gst_check_setup_element ("cmmlenc");
srcpad = gst_check_setup_src_pad (cmmlenc, &srctemplate, NULL);
sinkpad = gst_check_setup_sink_pad (cmmlenc, &sinktemplate, NULL);
gst_pad_set_active (srcpad, TRUE);
gst_pad_set_active (sinkpad, TRUE);
bus = gst_bus_new ();
gst_element_set_bus (cmmlenc, bus);
fail_unless (gst_element_set_state (cmmlenc,
GST_STATE_PLAYING) != GST_STATE_CHANGE_FAILURE,
"could not set to playing");
g_object_get (cmmlenc, "granule-rate-numerator", &granulerate_n,
"granule-rate-denominator", &granulerate_d,
"granule-shift", &granuleshift, NULL);
granulerate = GST_SECOND * granulerate_d / granulerate_n;
}
static void
teardown_cmmlenc (void)
{
/* free encoded buffers */
g_list_foreach (buffers, buffer_unref, NULL);
g_list_free (buffers);
buffers = NULL;
current_buf = NULL;
gst_bus_set_flushing (bus, TRUE);
gst_object_unref (bus);
GST_DEBUG ("teardown_cmmlenc");
gst_pad_set_active (srcpad, FALSE);
gst_pad_set_active (sinkpad, FALSE);
gst_check_teardown_src_pad (cmmlenc);
gst_check_teardown_sink_pad (cmmlenc);
gst_check_teardown_element (cmmlenc);
}
static void
check_output_buffer_is_equal (const gchar * name,
const gchar * data, gint refcount)
{
GstBuffer *buffer;
if (current_buf == NULL)
current_buf = buffers;
else
current_buf = g_list_next (current_buf);
fail_unless (current_buf != NULL);
buffer = GST_BUFFER (current_buf->data);
ASSERT_OBJECT_REFCOUNT (buffer, name, refcount);
fail_unless (memcmp (GST_BUFFER_DATA (buffer), data,
GST_BUFFER_SIZE (buffer)) == 0,
"'%s' (%s) is not equal to (%s)", name, GST_BUFFER_DATA (buffer), data);
}
static GstFlowReturn
push_data (const gchar * name, const gchar * data, gint size)
{
GstBuffer *buffer;
GstFlowReturn res;
buffer = buffer_new (data, size);
res = gst_pad_push (srcpad, buffer);
return res;
}
static void
check_headers (void)
{
/* push the cmml start tag */
flow = push_data ("preamble", PREAMBLE, strlen (PREAMBLE));
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
/* push the stream tag */
flow = push_data ("stream", STREAM_TAG, strlen (STREAM_TAG));
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
/* push the head tag */
flow = push_data ("head", HEAD_TAG, strlen (HEAD_TAG));
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
/* should output 3 buffers: the ident, preamble and head headers */
fail_unless_equals_int (g_list_length (buffers), 3);
/* check the ident header */
check_output_buffer_is_equal ("cmml-ident-buffer", IDENT_HEADER, 1);
/* check the cmml processing instruction */
check_output_buffer_is_equal ("cmml-preamble-buffer", PREAMBLE_ENCODED, 1);
/* check the encoded head tag */
check_output_buffer_is_equal ("head-tag-buffer", HEAD_TAG_ENCODED, 1);
}
static GstFlowReturn
push_clip (const gchar * name, const gchar * track,
const gchar * start, const gchar * end)
{
gchar *clip;
GstFlowReturn res;
if (end != NULL)
clip = g_strdup_printf (ENDED_CLIP_TEMPLATE, name, track, start, end);
else
clip = g_strdup_printf (CLIP_TEMPLATE, name, track, start);
res = push_data (name, clip, strlen (clip));
g_free (clip);
return res;
}
static void
check_clip_times (GstBuffer * buffer, GstClockTime start, GstClockTime prev)
{
guint64 keyindex, keyoffset, granulepos;
granulepos = GST_BUFFER_OFFSET_END (buffer);
if (granuleshift == 0 || granuleshift == 64)
keyindex = 0;
else
keyindex = granulepos >> granuleshift;
keyoffset = granulepos - (keyindex << granuleshift);
fail_unless_equals_uint64 (keyindex * granulerate, prev);
fail_unless_equals_uint64 ((keyindex + keyoffset) * granulerate, start);
}
static void
check_clip (const gchar * name, const gchar * track,
GstClockTime start, GstClockTime prev)
{
gchar *encoded_clip;
GstBuffer *buffer;
encoded_clip = g_strdup_printf (CLIP_TEMPLATE_ENCODED, name, track);
check_output_buffer_is_equal (name, encoded_clip, 1);
g_free (encoded_clip);
buffer = GST_BUFFER (current_buf->data);
check_clip_times (buffer, start, prev);
}
static void
check_empty_clip (const gchar * name, const gchar * track,
GstClockTime start, GstClockTime prev)
{
gchar *encoded_clip;
GstBuffer *buffer;
encoded_clip = g_strdup_printf (EMPTY_CLIP_TEMPLATE_ENCODED, track);
check_output_buffer_is_equal (name, encoded_clip, 1);
g_free (encoded_clip);
buffer = GST_BUFFER (current_buf->data);
check_clip_times (buffer, start, prev);
}
GST_START_TEST (test_enc)
{
check_headers ();
flow = push_clip ("clip-1", "default", "1.234", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("clip-1", "default", 1 * GST_SECOND + 234 * GST_MSECOND, 0);
flow = push_clip ("clip-2", "default", "5.678", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("clip-2", "default",
5 * GST_SECOND + 678 * GST_MSECOND, 1 * GST_SECOND + 234 * GST_MSECOND);
flow = push_clip ("clip-3", "othertrack", "9.123", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("clip-3", "othertrack", 9 * GST_SECOND + 123 * GST_MSECOND, 0);
flow = push_data ("end-tag", "</cmml>", strlen ("</cmml>"));
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_output_buffer_is_equal ("cmml-eos", NULL, 1);
}
GST_END_TEST;
GST_START_TEST (test_clip_end_time)
{
check_headers ();
/* push a clip that starts at 1.234 an ends at 2.234 */
flow = push_clip ("clip-1", "default", "1.234", "2.234");
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("clip-1", "default", 1 * GST_SECOND + 234 * GST_MSECOND, 0);
/* now check that the encoder created an empty clip starting at 2.234 to mark
* the end of clip-1 */
check_empty_clip ("clip-1-end", "default",
2 * GST_SECOND + 234 * GST_MSECOND, 1 * GST_SECOND + 234 * GST_MSECOND);
/* now push another clip on the same track and check that the keyindex part of
* the granulepos points to clip-1 and not to the empty clip */
flow = push_clip ("clip-2", "default", "5", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("clip-2", "default",
5 * GST_SECOND, 1 * GST_SECOND + 234 * GST_MSECOND);
}
GST_END_TEST;
GST_START_TEST (test_time_order)
{
check_headers ();
/* clips belonging to the same track must have start times in non decreasing
* order */
flow = push_clip ("clip-1", "default", "1000:00:00.000", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("clip-1", "default", 3600 * 1000 * GST_SECOND, 0);
/* this will make the encoder throw an error message */
flow = push_clip ("clip-2", "default", "5.678", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
flow = push_clip ("clip-3", "default", "1000:00:00.001", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("clip-3", "default",
3600 * 1000 * GST_SECOND + 1 * GST_MSECOND, 3600 * 1000 * GST_SECOND);
/* tracks don't interfere with each other */
flow = push_clip ("clip-4", "othertrack", "9.123", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("clip-4", "othertrack", 9 * GST_SECOND + 123 * GST_MSECOND, 0);
}
GST_END_TEST;
GST_START_TEST (test_time_parsing)
{
check_headers ();
flow = push_clip ("bad-msecs", "default", "0.1000", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
flow = push_clip ("bad-secs", "default", "00:00:60.123", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
flow = push_clip ("bad-minutes", "default", "00:60:12.345", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
/* this fails since we can't store 5124096 * 3600 * GST_SECOND in a
* GstClockTime */
flow = push_clip ("bad-hours", "default", "5124096:00:00.000", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
}
GST_END_TEST;
GST_START_TEST (test_time_limits)
{
check_headers ();
/* ugly hack to make sure that the following checks actually overflow parsing
* the times in gst_cmml_clock_time_from_npt rather than converting them to
* granulepos in gst_cmml_clock_time_to_granule */
granuleshift = 64;
g_object_set (cmmlenc, "granule-shift", granuleshift, NULL);
/* 5124095:34:33.709 is the max npt-hhmmss time representable with
* GstClockTime */
flow = push_clip ("max-npt-hhmmss", "foo", "5124095:34:33.709", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("max-npt-hhmmss", "foo",
(GstClockTime) 5124095 * 3600 * GST_SECOND + 34 * 60 * GST_SECOND +
33 * GST_SECOND + 709 * GST_MSECOND, 0);
flow = push_clip ("overflow-max-npt-hhmmss", "overflows",
"5124095:34:33.710", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
/* 18446744073.709 is the max ntp-sec time */
flow = push_clip ("max-npt-secs", "bar", "18446744073.709", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("max-npt-secs", "bar",
(GstClockTime) 5124095 * 3600 * GST_SECOND + 34 * 60 * GST_SECOND +
33 * GST_SECOND + 709 * GST_MSECOND, 0);
/* overflow doing 18446744074 * GST_SECOND */
flow = push_clip ("overflow-max-npt-secs", "overflows",
"18446744074.000", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
/* overflow doing seconds + milliseconds */
flow = push_clip ("overflow-max-npt-secs-msecs", "overflows",
"18446744073.710", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
/* reset granuleshift to 32 to check keyoffset overflows in
* gst_cmml_clock_time_to_granule */
granuleshift = 32;
g_object_set (cmmlenc, "granule-shift", granuleshift, NULL);
/* 1193:02:47.295 is the max time we can encode in the keyoffset part of a
* granulepos given a granuleshift of 32 */
flow = push_clip ("max-granule-keyoffset", "baz", "1193:02:47.295", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_OK);
check_clip ("max-granule-keyoffset", "baz",
1193 * 3600 * GST_SECOND + 2 * 60 * GST_SECOND +
47 * GST_SECOND + 295 * GST_MSECOND, 0);
flow = push_clip ("overflow-max-granule-keyoffset", "overflows",
"1193:02:47.296", NULL);
fail_unless_equals_flow_return (flow, GST_FLOW_ERROR);
}
GST_END_TEST;
static Suite *
cmmlenc_suite (void)
{
Suite *s = suite_create ("cmmlenc");
TCase *tc_general = tcase_create ("general");
suite_add_tcase (s, tc_general);
tcase_add_checked_fixture (tc_general, setup_cmmlenc, teardown_cmmlenc);
tcase_add_test (tc_general, test_enc);
tcase_add_test (tc_general, test_clip_end_time);
tcase_add_test (tc_general, test_time_order);
tcase_add_test (tc_general, test_time_parsing);
tcase_add_test (tc_general, test_time_limits);
return s;
}
GST_CHECK_MAIN (cmmlenc);
| lgpl-2.1 |
kaspar030/RIOT | cpu/stm32/periph/adc_f0_g0.c | 11 | 2659 | /*
* Copyright (C) 2014-2016 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup cpu_stm32
* @ingroup drivers_periph_adc
* @{
*
* @file
* @brief Low-level ADC driver implementation
*
* @author Hauke Petersen <hauke.petersen@fu-berlin.de>
*
* @}
*/
#include "cpu.h"
#include "mutex.h"
#include "periph/adc.h"
#include "periph/vbat.h"
/**
* @brief Default VBAT undefined value
*/
#ifndef VBAT_ADC
#define VBAT_ADC ADC_UNDEF
#endif
/**
* @brief Allocate lock for the ADC device
*
* All STM32F0 & STM32G0 CPUs we support so far only come with a single ADC device.
*/
static mutex_t lock = MUTEX_INIT;
static inline void prep(void)
{
mutex_lock(&lock);
#ifdef RCC_APB2ENR_ADCEN
periph_clk_en(APB2, RCC_APB2ENR_ADCEN);
#endif
#ifdef RCC_APBENR2_ADCEN
periph_clk_en(APB12, RCC_APBENR2_ADCEN);
#endif
}
static inline void done(void)
{
#ifdef RCC_APB2ENR_ADCEN
periph_clk_dis(APB2, RCC_APB2ENR_ADCEN);
#endif
#ifdef RCC_APBENR2_ADCEN
periph_clk_dis(APB12, RCC_APBENR2_ADCEN);
#endif
mutex_unlock(&lock);
}
int adc_init(adc_t line)
{
/* make sure the given line is valid */
if (line >= ADC_NUMOF) {
return -1;
}
/* lock and power on the device */
prep();
/* configure the pin */
if (adc_config[line].pin != GPIO_UNDEF) {
gpio_init_analog(adc_config[line].pin);
}
/* reset configuration */
ADC1->CFGR2 = 0;
/* enable device */
ADC1->CR = ADC_CR_ADEN;
/* configure sampling time to save value */
ADC1->SMPR = 0x3; /* 28.5 ADC clock cycles */
/* power off an release device for now */
done();
return 0;
}
int32_t adc_sample(adc_t line, adc_res_t res)
{
int sample;
/* check if resolution is applicable */
if (res > 0xf0) {
return -1;
}
/* lock and power on the ADC device */
prep();
/* check if this is the VBAT line */
if (IS_USED(MODULE_PERIPH_VBAT) && line == VBAT_ADC) {
vbat_enable();
}
/* set resolution and channel */
ADC1->CFGR1 = res;
ADC1->CHSELR = (1 << adc_config[line].chan);
/* start conversion and wait for results */
ADC1->CR |= ADC_CR_ADSTART;
while (!(ADC1->ISR & ADC_ISR_EOC)) {}
/* read result */
sample = (int)ADC1->DR;
/* check if this is the VBAT line */
if (IS_USED(MODULE_PERIPH_VBAT) && line == VBAT_ADC) {
vbat_disable();
}
/* unlock and power off device again */
done();
return sample;
}
| lgpl-2.1 |
kevleyski/DirectFB-1 | lib/fusiondale/core/dale_core.c | 12 | 15960 | /*
(c) Copyright 2012-2013 DirectFB integrated media GmbH
(c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org)
(c) Copyright 2000-2004 Convergence (integrated media) GmbH
All rights reserved.
Written by Denis Oliver Kropp <dok@directfb.org>,
Andreas Shimokawa <andi@directfb.org>,
Marek Pikarski <mass@directfb.org>,
Sven Neumann <neo@directfb.org>,
Ville Syrjälä <syrjala@sci.fi> and
Claudio Ciccani <klan@users.sf.net>.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <unistd.h>
#include <pthread.h>
#include <direct/debug.h>
#include <direct/mem.h>
#include <direct/messages.h>
#include <direct/signals.h>
#include <direct/util.h>
#include <fusion/arena.h>
#include <fusion/build.h>
#include <fusion/conf.h>
#include <fusion/fusion.h>
#include <fusion/shmalloc.h>
#include <fusion/object.h>
#include <core/dale_core.h>
#include <core/messenger.h>
#include <core/messenger_port.h>
#include <misc/dale_config.h>
#define FUSIONDALE_CORE_ABI 1
D_DEBUG_DOMAIN( Dale_Core, "FusionDale/Core", "FusionDale Core" );
/**********************************************************************************************************************/
static DirectSignalHandlerResult fd_core_signal_handler( int num,
void *addr,
void *ctx );
/**********************************************************************************************************************/
static int fd_core_arena_initialize( FusionArena *arena,
void *ctx );
static int fd_core_arena_join ( FusionArena *arena,
void *ctx );
static int fd_core_arena_leave ( FusionArena *arena,
void *ctx,
bool emergency);
static int fd_core_arena_shutdown ( FusionArena *arena,
void *ctx,
bool emergency);
/**********************************************************************************************************************/
static CoreDale *core_dale = NULL;
static pthread_mutex_t core_dale_lock = PTHREAD_MUTEX_INITIALIZER;
DirectResult
fd_core_create( CoreDale **ret_core )
{
int ret;
CoreDale *core = NULL;
D_ASSERT( ret_core != NULL );
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
/* Lock the core singleton mutex. */
pthread_mutex_lock( &core_dale_lock );
/* Core already created? */
if (core_dale) {
/* Increase its references. */
core_dale->refs++;
/* Return the core. */
*ret_core = core_dale;
/* Unlock the core singleton mutex. */
pthread_mutex_unlock( &core_dale_lock );
return DR_OK;
}
/* Allocate local core structure. */
core = D_CALLOC( 1, sizeof(CoreDale) );
if (!core) {
ret = D_OOM();
goto error;
}
ret = fusion_enter( fusiondale_config->session, FUSIONDALE_CORE_ABI,
fusiondale_config->force_slave ? FER_SLAVE : FER_ANY, &core->world );
if (ret)
goto error;
core->fusion_id = fusion_id( core->world );
fusiondale_config->session = fusion_world_index( core->world );
#if FUSION_BUILD_MULTI
D_DEBUG_AT( Dale_Core, " -> world %d, fusion id %d\n", fusiondale_config->session, core->fusion_id );
#endif
/* Initialize the references. */
core->refs = 1;
direct_signal_handler_add( -1, fd_core_signal_handler, core, &core->signal_handler );
D_MAGIC_SET( core, CoreDale );
/* Enter the FusionDale core arena. */
if (fusion_arena_enter( core->world, "FusionDale/Core",
fd_core_arena_initialize, fd_core_arena_join,
core, &core->arena, &ret ) || ret)
{
D_MAGIC_CLEAR( core );
ret = ret ? : DR_FUSION;
goto error;
}
/* Return the core and store the singleton. */
*ret_core = core_dale = core;
/* Unlock the core singleton mutex. */
pthread_mutex_unlock( &core_dale_lock );
return DR_OK;
error:
if (core) {
if (core->world) {
direct_signal_handler_remove( core->signal_handler );
fusion_exit( core->world, false );
}
D_FREE( core );
}
pthread_mutex_unlock( &core_dale_lock );
return ret;
}
DirectResult
fd_core_destroy( CoreDale *core, bool emergency )
{
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core == core_dale );
D_DEBUG_AT( Dale_Core, "%s( %p, %semergency )\n", __FUNCTION__, core, emergency ? "" : "no " );
/* Lock the core singleton mutex. */
if (!emergency)
pthread_mutex_lock( &core_dale_lock );
/* Decrement and check references. */
if (!emergency && --core->refs) {
/* Unlock the core singleton mutex. */
pthread_mutex_unlock( &core_dale_lock );
return DR_OK;
}
direct_signal_handler_remove( core->signal_handler );
/* Exit the FusionDale core arena. */
if (fusion_arena_exit( core->arena, fd_core_arena_shutdown,
core->master ? NULL : fd_core_arena_leave,
core, emergency, NULL ) == DR_BUSY)
{
if (core->master) {
if (emergency) {
fusion_kill( core->world, 0, SIGKILL, 1000 );
}
else {
fusion_kill( core->world, 0, SIGTERM, 5000 );
fusion_kill( core->world, 0, SIGKILL, 2000 );
}
}
while (fusion_arena_exit( core->arena, fd_core_arena_shutdown,
core->master ? NULL : fd_core_arena_leave,
core, emergency, NULL ) == DR_BUSY)
{
D_ONCE( "waiting for FusionDale slaves to terminate" );
usleep( 100000 );
}
}
fusion_exit( core->world, emergency );
D_MAGIC_CLEAR( core );
/* Deallocate local core structure. */
D_FREE( core );
/* Clear the singleton. */
core_dale = NULL;
/* Unlock the core singleton mutex. */
if (!emergency)
pthread_mutex_unlock( &core_dale_lock );
return DR_OK;
}
/**********************************************************************************************************************/
CoreMessenger *
fd_core_create_messenger( CoreDale *core )
{
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->shared != NULL );
D_ASSERT( core->shared->messenger_pool != NULL );
/* Create a new object in the messenger pool. */
return (CoreMessenger*) fusion_object_create( core->shared->messenger_pool, core->world, 0 );
}
CoreMessengerPort *
fd_core_create_messenger_port( CoreDale *core )
{
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->shared != NULL );
D_ASSERT( core->shared->messenger_port_pool != NULL );
/* Create a new object in the messenger port pool. */
return (CoreMessengerPort*) fusion_object_create( core->shared->messenger_port_pool, core->world, 0 );
}
/**********************************************************************************************************************/
DirectResult
fd_core_enum_messengers( CoreDale *core,
FusionObjectCallback callback,
void *ctx )
{
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->shared != NULL );
D_ASSERT( core->shared->messenger_pool != NULL );
/* Enumerate objects in the messenger pool. */
return fusion_object_pool_enum( core->shared->messenger_pool, callback, ctx );
}
DirectResult
fd_core_enum_messenger_ports( CoreDale *core,
FusionObjectCallback callback,
void *ctx )
{
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->shared != NULL );
D_ASSERT( core->shared->messenger_port_pool != NULL );
/* Enumerate objects in the messenger port pool. */
return fusion_object_pool_enum( core->shared->messenger_port_pool, callback, ctx );
}
DirectResult
fd_core_get_messenger( CoreDale *core,
FusionObjectID object_id,
CoreMessenger **ret_messenger )
{
DirectResult ret;
FusionObject *object;
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->shared != NULL );
D_ASSERT( core->shared->messenger_port_pool != NULL );
D_ASSERT( ret_messenger != NULL );
/* Enumerate objects in the messenger port pool. */
ret = fusion_object_get( core->shared->messenger_pool, object_id, &object );
if (ret)
return ret;
D_MAGIC_ASSERT( (CoreMessenger*) object, CoreMessenger );
*ret_messenger = (CoreMessenger*) object;
return DR_OK;
}
/**********************************************************************************************************************/
FusionWorld *
fd_core_world( CoreDale *core )
{
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->world != NULL );
return core->world;
}
FusionSHMPoolShared *
fd_core_shmpool( CoreDale *core )
{
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->shared != NULL );
D_ASSERT( core->shared->shmpool != NULL );
return core->shared->shmpool;
}
/**********************************************************************************************************************/
static DirectSignalHandlerResult
fd_core_signal_handler( int num, void *addr, void *ctx )
{
CoreDale *core = (CoreDale*) ctx;
D_DEBUG_AT( Dale_Core, "%s( %d, %p, %p )\n", __FUNCTION__, num, addr, ctx );
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->shared != NULL );
D_ASSERT( core == core_dale );
fd_core_destroy( core, true );
return DR_OK;
}
/**********************************************************************************************************************/
static DirectResult
fd_core_initialize( CoreDale *core )
{
CoreDaleShared *shared = core->shared;
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
/* create a pool for messenger (port) objects */
shared->messenger_pool = fd_messenger_pool_create( core->world );
shared->messenger_port_pool = fd_messenger_port_pool_create( core->world );
return DR_OK;
}
static DirectResult
fd_core_join( CoreDale *core )
{
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
/* really nothing to be done here, yet ;) */
return DR_OK;
}
static DirectResult
fd_core_leave( CoreDale *core )
{
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
/* really nothing to be done here, yet ;) */
return DR_OK;
}
static DirectResult
fd_core_shutdown( CoreDale *core )
{
CoreDaleShared *shared;
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
D_ASSERT( core->shared != NULL );
shared = core->shared;
D_ASSERT( shared->messenger_pool != NULL );
/* destroy messenger port object pool */
fusion_object_pool_destroy( shared->messenger_port_pool, core->world );
/* destroy messenger object pool */
fusion_object_pool_destroy( shared->messenger_pool, core->world );
return DR_OK;
}
/**********************************************************************************************************************/
static int
fd_core_arena_initialize( FusionArena *arena,
void *ctx )
{
DirectResult ret;
CoreDale *core = ctx;
CoreDaleShared *shared;
FusionSHMPoolShared *pool;
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
/* Create the shared memory pool first! */
ret = fusion_shm_pool_create( core->world, "FusionDale Main Pool", 0x1000000,
fusion_config->debugshm, &pool );
if (ret)
return ret;
/* Allocate shared structure in the new pool. */
shared = SHCALLOC( pool, 1, sizeof(CoreDaleShared) );
if (!shared) {
fusion_shm_pool_destroy( core->world, pool );
return D_OOSHM();
}
core->shared = shared;
core->master = true;
shared->shmpool = pool;
/* Initialize. */
ret = fd_core_initialize( core );
if (ret) {
SHFREE( pool, shared );
fusion_shm_pool_destroy( core->world, pool );
return ret;
}
/* Register shared data. */
fusion_arena_add_shared_field( arena, "Core/Shared", shared );
/* Let others enter the world. */
fusion_world_activate( core->world );
return DR_OK;
}
static int
fd_core_arena_shutdown( FusionArena *arena,
void *ctx,
bool emergency)
{
DirectResult ret;
CoreDale *core = ctx;
CoreDaleShared *shared;
FusionSHMPoolShared *pool;
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
shared = core->shared;
pool = shared->shmpool;
if (!core->master) {
D_DEBUG( "FusionDale/Core: Refusing shutdown in slave.\n" );
return fd_core_leave( core );
}
/* Shutdown. */
ret = fd_core_shutdown( core );
if (ret)
return ret;
SHFREE( pool, shared );
fusion_dbg_print_memleaks( pool );
fusion_shm_pool_destroy( core->world, pool );
return DR_OK;
}
static int
fd_core_arena_join( FusionArena *arena,
void *ctx )
{
DirectResult ret;
CoreDale *core = ctx;
CoreDaleShared *shared;
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
/* Get shared data. */
if (fusion_arena_get_shared_field( arena, "Core/Shared", (void*)&shared ))
return DR_FUSION;
core->shared = shared;
/* Join. */
ret = fd_core_join( core );
if (ret)
return ret;
return DR_OK;
}
static int
fd_core_arena_leave( FusionArena *arena,
void *ctx,
bool emergency)
{
DirectResult ret;
CoreDale *core = ctx;
D_DEBUG_AT( Dale_Core, "%s()\n", __FUNCTION__ );
D_MAGIC_ASSERT( core, CoreDale );
/* Leave. */
ret = fd_core_leave( core );
if (ret)
return ret;
return DR_OK;
}
| lgpl-2.1 |
buuck/root | interpreter/llvm/src/lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp | 17 | 27814 | //===-- AMDGPUPromoteAlloca.cpp - Promote Allocas -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass eliminates allocas by either converting them into vectors or
// by migrating them to local address space.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "amdgpu-promote-alloca"
using namespace llvm;
namespace {
// FIXME: This can create globals so should be a module pass.
class AMDGPUPromoteAlloca : public FunctionPass {
private:
const TargetMachine *TM;
Module *Mod;
const DataLayout *DL;
MDNode *MaxWorkGroupSizeRange;
// FIXME: This should be per-kernel.
uint32_t LocalMemLimit;
uint32_t CurrentLocalMemUsage;
bool IsAMDGCN;
bool IsAMDHSA;
std::pair<Value *, Value *> getLocalSizeYZ(IRBuilder<> &Builder);
Value *getWorkitemID(IRBuilder<> &Builder, unsigned N);
/// BaseAlloca is the alloca root the search started from.
/// Val may be that alloca or a recursive user of it.
bool collectUsesWithPtrTypes(Value *BaseAlloca,
Value *Val,
std::vector<Value*> &WorkList) const;
/// Val is a derived pointer from Alloca. OpIdx0/OpIdx1 are the operand
/// indices to an instruction with 2 pointer inputs (e.g. select, icmp).
/// Returns true if both operands are derived from the same alloca. Val should
/// be the same value as one of the input operands of UseInst.
bool binaryOpIsDerivedFromSameAlloca(Value *Alloca, Value *Val,
Instruction *UseInst,
int OpIdx0, int OpIdx1) const;
public:
static char ID;
AMDGPUPromoteAlloca(const TargetMachine *TM_ = nullptr) :
FunctionPass(ID),
TM(TM_),
Mod(nullptr),
DL(nullptr),
MaxWorkGroupSizeRange(nullptr),
LocalMemLimit(0),
CurrentLocalMemUsage(0),
IsAMDGCN(false),
IsAMDHSA(false) { }
bool doInitialization(Module &M) override;
bool runOnFunction(Function &F) override;
const char *getPassName() const override {
return "AMDGPU Promote Alloca";
}
void handleAlloca(AllocaInst &I);
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
FunctionPass::getAnalysisUsage(AU);
}
};
} // End anonymous namespace
char AMDGPUPromoteAlloca::ID = 0;
INITIALIZE_TM_PASS(AMDGPUPromoteAlloca, DEBUG_TYPE,
"AMDGPU promote alloca to vector or LDS", false, false)
char &llvm::AMDGPUPromoteAllocaID = AMDGPUPromoteAlloca::ID;
bool AMDGPUPromoteAlloca::doInitialization(Module &M) {
if (!TM)
return false;
Mod = &M;
DL = &Mod->getDataLayout();
// The maximum workitem id.
//
// FIXME: Should get as subtarget property. Usually runtime enforced max is
// 256.
MDBuilder MDB(Mod->getContext());
MaxWorkGroupSizeRange = MDB.createRange(APInt(32, 0), APInt(32, 2048));
const Triple &TT = TM->getTargetTriple();
IsAMDGCN = TT.getArch() == Triple::amdgcn;
IsAMDHSA = TT.getOS() == Triple::AMDHSA;
return false;
}
bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
if (!TM || skipFunction(F))
return false;
const AMDGPUSubtarget &ST = TM->getSubtarget<AMDGPUSubtarget>(F);
if (!ST.isPromoteAllocaEnabled())
return false;
FunctionType *FTy = F.getFunctionType();
// If the function has any arguments in the local address space, then it's
// possible these arguments require the entire local memory space, so
// we cannot use local memory in the pass.
for (Type *ParamTy : FTy->params()) {
PointerType *PtrTy = dyn_cast<PointerType>(ParamTy);
if (PtrTy && PtrTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
LocalMemLimit = 0;
DEBUG(dbgs() << "Function has local memory argument. Promoting to "
"local memory disabled.\n");
return false;
}
}
LocalMemLimit = ST.getLocalMemorySize();
if (LocalMemLimit == 0)
return false;
const DataLayout &DL = Mod->getDataLayout();
// Check how much local memory is being used by global objects
CurrentLocalMemUsage = 0;
for (GlobalVariable &GV : Mod->globals()) {
if (GV.getType()->getAddressSpace() != AMDGPUAS::LOCAL_ADDRESS)
continue;
for (const User *U : GV.users()) {
const Instruction *Use = dyn_cast<Instruction>(U);
if (!Use)
continue;
if (Use->getParent()->getParent() == &F) {
unsigned Align = GV.getAlignment();
if (Align == 0)
Align = DL.getABITypeAlignment(GV.getValueType());
// FIXME: Try to account for padding here. The padding is currently
// determined from the inverse order of uses in the function. I'm not
// sure if the use list order is in any way connected to this, so the
// total reported size is likely incorrect.
uint64_t AllocSize = DL.getTypeAllocSize(GV.getValueType());
CurrentLocalMemUsage = alignTo(CurrentLocalMemUsage, Align);
CurrentLocalMemUsage += AllocSize;
break;
}
}
}
unsigned MaxOccupancy = ST.getOccupancyWithLocalMemSize(CurrentLocalMemUsage);
// Restrict local memory usage so that we don't drastically reduce occupancy,
// unless it is already significantly reduced.
// TODO: Have some sort of hint or other heuristics to guess occupancy based
// on other factors..
unsigned OccupancyHint
= AMDGPU::getIntegerAttribute(F, "amdgpu-max-waves-per-eu", 0);
if (OccupancyHint == 0)
OccupancyHint = 7;
// Clamp to max value.
OccupancyHint = std::min(OccupancyHint, ST.getMaxWavesPerCU());
// Check the hint but ignore it if it's obviously wrong from the existing LDS
// usage.
MaxOccupancy = std::min(OccupancyHint, MaxOccupancy);
// Round up to the next tier of usage.
unsigned MaxSizeWithWaveCount
= ST.getMaxLocalMemSizeWithWaveCount(MaxOccupancy);
// Program is possibly broken by using more local mem than available.
if (CurrentLocalMemUsage > MaxSizeWithWaveCount)
return false;
LocalMemLimit = MaxSizeWithWaveCount;
DEBUG(
dbgs() << F.getName() << " uses " << CurrentLocalMemUsage << " bytes of LDS\n"
<< " Rounding size to " << MaxSizeWithWaveCount
<< " with a maximum occupancy of " << MaxOccupancy << '\n'
<< " and " << (LocalMemLimit - CurrentLocalMemUsage)
<< " available for promotion\n"
);
BasicBlock &EntryBB = *F.begin();
for (auto I = EntryBB.begin(), E = EntryBB.end(); I != E; ) {
AllocaInst *AI = dyn_cast<AllocaInst>(I);
++I;
if (AI)
handleAlloca(*AI);
}
return true;
}
std::pair<Value *, Value *>
AMDGPUPromoteAlloca::getLocalSizeYZ(IRBuilder<> &Builder) {
if (!IsAMDHSA) {
Function *LocalSizeYFn
= Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_y);
Function *LocalSizeZFn
= Intrinsic::getDeclaration(Mod, Intrinsic::r600_read_local_size_z);
CallInst *LocalSizeY = Builder.CreateCall(LocalSizeYFn, {});
CallInst *LocalSizeZ = Builder.CreateCall(LocalSizeZFn, {});
LocalSizeY->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
LocalSizeZ->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
return std::make_pair(LocalSizeY, LocalSizeZ);
}
// We must read the size out of the dispatch pointer.
assert(IsAMDGCN);
// We are indexing into this struct, and want to extract the workgroup_size_*
// fields.
//
// typedef struct hsa_kernel_dispatch_packet_s {
// uint16_t header;
// uint16_t setup;
// uint16_t workgroup_size_x ;
// uint16_t workgroup_size_y;
// uint16_t workgroup_size_z;
// uint16_t reserved0;
// uint32_t grid_size_x ;
// uint32_t grid_size_y ;
// uint32_t grid_size_z;
//
// uint32_t private_segment_size;
// uint32_t group_segment_size;
// uint64_t kernel_object;
//
// #ifdef HSA_LARGE_MODEL
// void *kernarg_address;
// #elif defined HSA_LITTLE_ENDIAN
// void *kernarg_address;
// uint32_t reserved1;
// #else
// uint32_t reserved1;
// void *kernarg_address;
// #endif
// uint64_t reserved2;
// hsa_signal_t completion_signal; // uint64_t wrapper
// } hsa_kernel_dispatch_packet_t
//
Function *DispatchPtrFn
= Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_dispatch_ptr);
CallInst *DispatchPtr = Builder.CreateCall(DispatchPtrFn, {});
DispatchPtr->addAttribute(AttributeSet::ReturnIndex, Attribute::NoAlias);
DispatchPtr->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
// Size of the dispatch packet struct.
DispatchPtr->addDereferenceableAttr(AttributeSet::ReturnIndex, 64);
Type *I32Ty = Type::getInt32Ty(Mod->getContext());
Value *CastDispatchPtr = Builder.CreateBitCast(
DispatchPtr, PointerType::get(I32Ty, AMDGPUAS::CONSTANT_ADDRESS));
// We could do a single 64-bit load here, but it's likely that the basic
// 32-bit and extract sequence is already present, and it is probably easier
// to CSE this. The loads should be mergable later anyway.
Value *GEPXY = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 1);
LoadInst *LoadXY = Builder.CreateAlignedLoad(GEPXY, 4);
Value *GEPZU = Builder.CreateConstInBoundsGEP1_64(CastDispatchPtr, 2);
LoadInst *LoadZU = Builder.CreateAlignedLoad(GEPZU, 4);
MDNode *MD = llvm::MDNode::get(Mod->getContext(), None);
LoadXY->setMetadata(LLVMContext::MD_invariant_load, MD);
LoadZU->setMetadata(LLVMContext::MD_invariant_load, MD);
LoadZU->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
// Extract y component. Upper half of LoadZU should be zero already.
Value *Y = Builder.CreateLShr(LoadXY, 16);
return std::make_pair(Y, LoadZU);
}
Value *AMDGPUPromoteAlloca::getWorkitemID(IRBuilder<> &Builder, unsigned N) {
Intrinsic::ID IntrID = Intrinsic::ID::not_intrinsic;
switch (N) {
case 0:
IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_x
: Intrinsic::r600_read_tidig_x;
break;
case 1:
IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_y
: Intrinsic::r600_read_tidig_y;
break;
case 2:
IntrID = IsAMDGCN ? Intrinsic::amdgcn_workitem_id_z
: Intrinsic::r600_read_tidig_z;
break;
default:
llvm_unreachable("invalid dimension");
}
Function *WorkitemIdFn = Intrinsic::getDeclaration(Mod, IntrID);
CallInst *CI = Builder.CreateCall(WorkitemIdFn);
CI->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
return CI;
}
static VectorType *arrayTypeToVecType(Type *ArrayTy) {
return VectorType::get(ArrayTy->getArrayElementType(),
ArrayTy->getArrayNumElements());
}
static Value *
calculateVectorIndex(Value *Ptr,
const std::map<GetElementPtrInst *, Value *> &GEPIdx) {
if (isa<AllocaInst>(Ptr))
return Constant::getNullValue(Type::getInt32Ty(Ptr->getContext()));
GetElementPtrInst *GEP = cast<GetElementPtrInst>(Ptr);
auto I = GEPIdx.find(GEP);
return I == GEPIdx.end() ? nullptr : I->second;
}
static Value* GEPToVectorIndex(GetElementPtrInst *GEP) {
// FIXME we only support simple cases
if (GEP->getNumOperands() != 3)
return NULL;
ConstantInt *I0 = dyn_cast<ConstantInt>(GEP->getOperand(1));
if (!I0 || !I0->isZero())
return NULL;
return GEP->getOperand(2);
}
// Not an instruction handled below to turn into a vector.
//
// TODO: Check isTriviallyVectorizable for calls and handle other
// instructions.
static bool canVectorizeInst(Instruction *Inst, User *User) {
switch (Inst->getOpcode()) {
case Instruction::Load:
case Instruction::BitCast:
case Instruction::AddrSpaceCast:
return true;
case Instruction::Store: {
// Must be the stored pointer operand, not a stored value.
StoreInst *SI = cast<StoreInst>(Inst);
return SI->getPointerOperand() == User;
}
default:
return false;
}
}
static bool tryPromoteAllocaToVector(AllocaInst *Alloca) {
ArrayType *AllocaTy = dyn_cast<ArrayType>(Alloca->getAllocatedType());
DEBUG(dbgs() << "Alloca candidate for vectorization\n");
// FIXME: There is no reason why we can't support larger arrays, we
// are just being conservative for now.
if (!AllocaTy ||
AllocaTy->getElementType()->isVectorTy() ||
AllocaTy->getNumElements() > 4) {
DEBUG(dbgs() << " Cannot convert type to vector\n");
return false;
}
std::map<GetElementPtrInst*, Value*> GEPVectorIdx;
std::vector<Value*> WorkList;
for (User *AllocaUser : Alloca->users()) {
GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(AllocaUser);
if (!GEP) {
if (!canVectorizeInst(cast<Instruction>(AllocaUser), Alloca))
return false;
WorkList.push_back(AllocaUser);
continue;
}
Value *Index = GEPToVectorIndex(GEP);
// If we can't compute a vector index from this GEP, then we can't
// promote this alloca to vector.
if (!Index) {
DEBUG(dbgs() << " Cannot compute vector index for GEP " << *GEP << '\n');
return false;
}
GEPVectorIdx[GEP] = Index;
for (User *GEPUser : AllocaUser->users()) {
if (!canVectorizeInst(cast<Instruction>(GEPUser), AllocaUser))
return false;
WorkList.push_back(GEPUser);
}
}
VectorType *VectorTy = arrayTypeToVecType(AllocaTy);
DEBUG(dbgs() << " Converting alloca to vector "
<< *AllocaTy << " -> " << *VectorTy << '\n');
for (Value *V : WorkList) {
Instruction *Inst = cast<Instruction>(V);
IRBuilder<> Builder(Inst);
switch (Inst->getOpcode()) {
case Instruction::Load: {
Value *Ptr = Inst->getOperand(0);
Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Value *BitCast = Builder.CreateBitCast(Alloca, VectorTy->getPointerTo(0));
Value *VecValue = Builder.CreateLoad(BitCast);
Value *ExtractElement = Builder.CreateExtractElement(VecValue, Index);
Inst->replaceAllUsesWith(ExtractElement);
Inst->eraseFromParent();
break;
}
case Instruction::Store: {
Value *Ptr = Inst->getOperand(1);
Value *Index = calculateVectorIndex(Ptr, GEPVectorIdx);
Value *BitCast = Builder.CreateBitCast(Alloca, VectorTy->getPointerTo(0));
Value *VecValue = Builder.CreateLoad(BitCast);
Value *NewVecValue = Builder.CreateInsertElement(VecValue,
Inst->getOperand(0),
Index);
Builder.CreateStore(NewVecValue, BitCast);
Inst->eraseFromParent();
break;
}
case Instruction::BitCast:
case Instruction::AddrSpaceCast:
break;
default:
Inst->dump();
llvm_unreachable("Inconsistency in instructions promotable to vector");
}
}
return true;
}
static bool isCallPromotable(CallInst *CI) {
// TODO: We might be able to handle some cases where the callee is a
// constantexpr bitcast of a function.
if (!CI->getCalledFunction())
return false;
IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
if (!II)
return false;
switch (II->getIntrinsicID()) {
case Intrinsic::memcpy:
case Intrinsic::memmove:
case Intrinsic::memset:
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
case Intrinsic::invariant_start:
case Intrinsic::invariant_end:
case Intrinsic::invariant_group_barrier:
case Intrinsic::objectsize:
return true;
default:
return false;
}
}
bool AMDGPUPromoteAlloca::binaryOpIsDerivedFromSameAlloca(Value *BaseAlloca,
Value *Val,
Instruction *Inst,
int OpIdx0,
int OpIdx1) const {
// Figure out which operand is the one we might not be promoting.
Value *OtherOp = Inst->getOperand(OpIdx0);
if (Val == OtherOp)
OtherOp = Inst->getOperand(OpIdx1);
if (isa<ConstantPointerNull>(OtherOp))
return true;
Value *OtherObj = GetUnderlyingObject(OtherOp, *DL);
if (!isa<AllocaInst>(OtherObj))
return false;
// TODO: We should be able to replace undefs with the right pointer type.
// TODO: If we know the other base object is another promotable
// alloca, not necessarily this alloca, we can do this. The
// important part is both must have the same address space at
// the end.
if (OtherObj != BaseAlloca) {
DEBUG(dbgs() << "Found a binary instruction with another alloca object\n");
return false;
}
return true;
}
bool AMDGPUPromoteAlloca::collectUsesWithPtrTypes(
Value *BaseAlloca,
Value *Val,
std::vector<Value*> &WorkList) const {
for (User *User : Val->users()) {
if (std::find(WorkList.begin(), WorkList.end(), User) != WorkList.end())
continue;
if (CallInst *CI = dyn_cast<CallInst>(User)) {
if (!isCallPromotable(CI))
return false;
WorkList.push_back(User);
continue;
}
Instruction *UseInst = cast<Instruction>(User);
if (UseInst->getOpcode() == Instruction::PtrToInt)
return false;
if (LoadInst *LI = dyn_cast_or_null<LoadInst>(UseInst)) {
if (LI->isVolatile())
return false;
continue;
}
if (StoreInst *SI = dyn_cast<StoreInst>(UseInst)) {
if (SI->isVolatile())
return false;
// Reject if the stored value is not the pointer operand.
if (SI->getPointerOperand() != Val)
return false;
} else if (AtomicRMWInst *RMW = dyn_cast_or_null<AtomicRMWInst>(UseInst)) {
if (RMW->isVolatile())
return false;
} else if (AtomicCmpXchgInst *CAS
= dyn_cast_or_null<AtomicCmpXchgInst>(UseInst)) {
if (CAS->isVolatile())
return false;
}
// Only promote a select if we know that the other select operand
// is from another pointer that will also be promoted.
if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, ICmp, 0, 1))
return false;
// May need to rewrite constant operands.
WorkList.push_back(ICmp);
}
if (!User->getType()->isPointerTy())
continue;
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UseInst)) {
// Be conservative if an address could be computed outside the bounds of
// the alloca.
if (!GEP->isInBounds())
return false;
}
// Only promote a select if we know that the other select operand is from
// another pointer that will also be promoted.
if (SelectInst *SI = dyn_cast<SelectInst>(UseInst)) {
if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, SI, 1, 2))
return false;
}
// Repeat for phis.
if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
// TODO: Handle more complex cases. We should be able to replace loops
// over arrays.
switch (Phi->getNumIncomingValues()) {
case 1:
break;
case 2:
if (!binaryOpIsDerivedFromSameAlloca(BaseAlloca, Val, Phi, 0, 1))
return false;
break;
default:
return false;
}
}
WorkList.push_back(User);
if (!collectUsesWithPtrTypes(BaseAlloca, User, WorkList))
return false;
}
return true;
}
// FIXME: Should try to pick the most likely to be profitable allocas first.
void AMDGPUPromoteAlloca::handleAlloca(AllocaInst &I) {
// Array allocations are probably not worth handling, since an allocation of
// the array type is the canonical form.
if (!I.isStaticAlloca() || I.isArrayAllocation())
return;
IRBuilder<> Builder(&I);
// First try to replace the alloca with a vector
Type *AllocaTy = I.getAllocatedType();
DEBUG(dbgs() << "Trying to promote " << I << '\n');
if (tryPromoteAllocaToVector(&I)) {
DEBUG(dbgs() << " alloca is not a candidate for vectorization.\n");
return;
}
const Function &ContainingFunction = *I.getParent()->getParent();
// FIXME: We should also try to get this value from the reqd_work_group_size
// function attribute if it is available.
unsigned WorkGroupSize = AMDGPU::getMaximumWorkGroupSize(ContainingFunction);
const DataLayout &DL = Mod->getDataLayout();
unsigned Align = I.getAlignment();
if (Align == 0)
Align = DL.getABITypeAlignment(I.getAllocatedType());
// FIXME: This computed padding is likely wrong since it depends on inverse
// usage order.
//
// FIXME: It is also possible that if we're allowed to use all of the memory
// could could end up using more than the maximum due to alignment padding.
uint32_t NewSize = alignTo(CurrentLocalMemUsage, Align);
uint32_t AllocSize = WorkGroupSize * DL.getTypeAllocSize(AllocaTy);
NewSize += AllocSize;
if (NewSize > LocalMemLimit) {
DEBUG(dbgs() << " " << AllocSize
<< " bytes of local memory not available to promote\n");
return;
}
CurrentLocalMemUsage = NewSize;
std::vector<Value*> WorkList;
if (!collectUsesWithPtrTypes(&I, &I, WorkList)) {
DEBUG(dbgs() << " Do not know how to convert all uses\n");
return;
}
DEBUG(dbgs() << "Promoting alloca to local memory\n");
Function *F = I.getParent()->getParent();
Type *GVTy = ArrayType::get(I.getAllocatedType(), WorkGroupSize);
GlobalVariable *GV = new GlobalVariable(
*Mod, GVTy, false, GlobalValue::InternalLinkage,
UndefValue::get(GVTy),
Twine(F->getName()) + Twine('.') + I.getName(),
nullptr,
GlobalVariable::NotThreadLocal,
AMDGPUAS::LOCAL_ADDRESS);
GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
GV->setAlignment(I.getAlignment());
Value *TCntY, *TCntZ;
std::tie(TCntY, TCntZ) = getLocalSizeYZ(Builder);
Value *TIdX = getWorkitemID(Builder, 0);
Value *TIdY = getWorkitemID(Builder, 1);
Value *TIdZ = getWorkitemID(Builder, 2);
Value *Tmp0 = Builder.CreateMul(TCntY, TCntZ, "", true, true);
Tmp0 = Builder.CreateMul(Tmp0, TIdX);
Value *Tmp1 = Builder.CreateMul(TIdY, TCntZ, "", true, true);
Value *TID = Builder.CreateAdd(Tmp0, Tmp1);
TID = Builder.CreateAdd(TID, TIdZ);
Value *Indices[] = {
Constant::getNullValue(Type::getInt32Ty(Mod->getContext())),
TID
};
Value *Offset = Builder.CreateInBoundsGEP(GVTy, GV, Indices);
I.mutateType(Offset->getType());
I.replaceAllUsesWith(Offset);
I.eraseFromParent();
for (Value *V : WorkList) {
CallInst *Call = dyn_cast<CallInst>(V);
if (!Call) {
if (ICmpInst *CI = dyn_cast<ICmpInst>(V)) {
Value *Src0 = CI->getOperand(0);
Type *EltTy = Src0->getType()->getPointerElementType();
PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
if (isa<ConstantPointerNull>(CI->getOperand(0)))
CI->setOperand(0, ConstantPointerNull::get(NewTy));
if (isa<ConstantPointerNull>(CI->getOperand(1)))
CI->setOperand(1, ConstantPointerNull::get(NewTy));
continue;
}
// The operand's value should be corrected on its own.
if (isa<AddrSpaceCastInst>(V))
continue;
Type *EltTy = V->getType()->getPointerElementType();
PointerType *NewTy = PointerType::get(EltTy, AMDGPUAS::LOCAL_ADDRESS);
// FIXME: It doesn't really make sense to try to do this for all
// instructions.
V->mutateType(NewTy);
// Adjust the types of any constant operands.
if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
if (isa<ConstantPointerNull>(SI->getOperand(1)))
SI->setOperand(1, ConstantPointerNull::get(NewTy));
if (isa<ConstantPointerNull>(SI->getOperand(2)))
SI->setOperand(2, ConstantPointerNull::get(NewTy));
} else if (PHINode *Phi = dyn_cast<PHINode>(V)) {
for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
if (isa<ConstantPointerNull>(Phi->getIncomingValue(I)))
Phi->setIncomingValue(I, ConstantPointerNull::get(NewTy));
}
}
continue;
}
IntrinsicInst *Intr = dyn_cast<IntrinsicInst>(Call);
if (!Intr) {
// FIXME: What is this for? It doesn't make sense to promote arbitrary
// function calls. If the call is to a defined function that can also be
// promoted, we should be able to do this once that function is also
// rewritten.
std::vector<Type*> ArgTypes;
for (unsigned ArgIdx = 0, ArgEnd = Call->getNumArgOperands();
ArgIdx != ArgEnd; ++ArgIdx) {
ArgTypes.push_back(Call->getArgOperand(ArgIdx)->getType());
}
Function *F = Call->getCalledFunction();
FunctionType *NewType = FunctionType::get(Call->getType(), ArgTypes,
F->isVarArg());
Constant *C = Mod->getOrInsertFunction((F->getName() + ".local").str(),
NewType, F->getAttributes());
Function *NewF = cast<Function>(C);
Call->setCalledFunction(NewF);
continue;
}
Builder.SetInsertPoint(Intr);
switch (Intr->getIntrinsicID()) {
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
// These intrinsics are for address space 0 only
Intr->eraseFromParent();
continue;
case Intrinsic::memcpy: {
MemCpyInst *MemCpy = cast<MemCpyInst>(Intr);
Builder.CreateMemCpy(MemCpy->getRawDest(), MemCpy->getRawSource(),
MemCpy->getLength(), MemCpy->getAlignment(),
MemCpy->isVolatile());
Intr->eraseFromParent();
continue;
}
case Intrinsic::memmove: {
MemMoveInst *MemMove = cast<MemMoveInst>(Intr);
Builder.CreateMemMove(MemMove->getRawDest(), MemMove->getRawSource(),
MemMove->getLength(), MemMove->getAlignment(),
MemMove->isVolatile());
Intr->eraseFromParent();
continue;
}
case Intrinsic::memset: {
MemSetInst *MemSet = cast<MemSetInst>(Intr);
Builder.CreateMemSet(MemSet->getRawDest(), MemSet->getValue(),
MemSet->getLength(), MemSet->getAlignment(),
MemSet->isVolatile());
Intr->eraseFromParent();
continue;
}
case Intrinsic::invariant_start:
case Intrinsic::invariant_end:
case Intrinsic::invariant_group_barrier:
Intr->eraseFromParent();
// FIXME: I think the invariant marker should still theoretically apply,
// but the intrinsics need to be changed to accept pointers with any
// address space.
continue;
case Intrinsic::objectsize: {
Value *Src = Intr->getOperand(0);
Type *SrcTy = Src->getType()->getPointerElementType();
Function *ObjectSize = Intrinsic::getDeclaration(Mod,
Intrinsic::objectsize,
{ Intr->getType(), PointerType::get(SrcTy, AMDGPUAS::LOCAL_ADDRESS) }
);
CallInst *NewCall
= Builder.CreateCall(ObjectSize, { Src, Intr->getOperand(1) });
Intr->replaceAllUsesWith(NewCall);
Intr->eraseFromParent();
continue;
}
default:
Intr->dump();
llvm_unreachable("Don't know how to promote alloca intrinsic use.");
}
}
}
FunctionPass *llvm::createAMDGPUPromoteAlloca(const TargetMachine *TM) {
return new AMDGPUPromoteAlloca(TM);
}
| lgpl-2.1 |
omega-hub/osg | src/osgAnimation/StatsVisitor.cpp | 18 | 2543 | /* -*-c++-*-
* Copyright (C) 2009 Cedric Pinson <cedric.pinson@plopbyte.net>
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osgAnimation/StatsVisitor>
#include <osgAnimation/Timeline>
#include <osgAnimation/ActionBlendIn>
#include <osgAnimation/ActionBlendOut>
#include <osgAnimation/ActionStripAnimation>
#include <osgAnimation/ActionAnimation>
using namespace osgAnimation;
StatsActionVisitor::StatsActionVisitor() {}
void StatsActionVisitor::reset() { _channels.clear(); }
StatsActionVisitor::StatsActionVisitor(osg::Stats* stats,unsigned int frame)
{
_frame = frame;
_stats = stats;
}
void StatsActionVisitor::apply(Timeline& tm)
{
_stats->setAttribute(_frame,"Timeline", tm.getCurrentTime());
tm.traverse(*this);
}
void StatsActionVisitor::apply(Action& action)
{
if (isActive(action))
{
_channels.push_back(action.getName());
_stats->setAttribute(_frame,action.getName(),1);
}
}
void StatsActionVisitor::apply(ActionBlendIn& action)
{
if (isActive(action))
{
_channels.push_back(action.getName());
_stats->setAttribute(_frame,action.getName(), action.getWeight());
}
}
void StatsActionVisitor::apply(ActionBlendOut& action)
{
if (isActive(action))
{
_channels.push_back(action.getName());
_stats->setAttribute(_frame,action.getName(), action.getWeight());
}
}
void StatsActionVisitor::apply(ActionAnimation& action)
{
if (isActive(action))
{
_channels.push_back(action.getName());
_stats->setAttribute(_frame,action.getName(), action.getAnimation()->getWeight());
}
}
void StatsActionVisitor::apply(ActionStripAnimation& action)
{
if (isActive(action))
{
_channels.push_back(action.getName());
double value;
std::string name = action.getName();
if (_stats->getAttribute(_frame, name, value))
name += "+";
_stats->setAttribute(_frame, action.getName(), action.getAnimation()->getAnimation()->getWeight());
}
}
| lgpl-2.1 |
Y--/root | interpreter/llvm/src/tools/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp | 20 | 33163 | //===--- SerializedDiagnosticPrinter.cpp - Serializer for diagnostics -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/SerializedDiagnosticPrinter.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/DiagnosticRenderer.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/SerializedDiagnosticReader.h"
#include "clang/Frontend/SerializedDiagnostics.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
#include <utility>
#include <vector>
using namespace clang;
using namespace clang::serialized_diags;
namespace {
class AbbreviationMap {
llvm::DenseMap<unsigned, unsigned> Abbrevs;
public:
AbbreviationMap() {}
void set(unsigned recordID, unsigned abbrevID) {
assert(Abbrevs.find(recordID) == Abbrevs.end()
&& "Abbreviation already set.");
Abbrevs[recordID] = abbrevID;
}
unsigned get(unsigned recordID) {
assert(Abbrevs.find(recordID) != Abbrevs.end() &&
"Abbreviation not set.");
return Abbrevs[recordID];
}
};
typedef SmallVector<uint64_t, 64> RecordData;
typedef SmallVectorImpl<uint64_t> RecordDataImpl;
typedef ArrayRef<uint64_t> RecordDataRef;
class SDiagsWriter;
class SDiagsRenderer : public DiagnosticNoteRenderer {
SDiagsWriter &Writer;
public:
SDiagsRenderer(SDiagsWriter &Writer, const LangOptions &LangOpts,
DiagnosticOptions *DiagOpts)
: DiagnosticNoteRenderer(LangOpts, DiagOpts), Writer(Writer) {}
~SDiagsRenderer() override {}
protected:
void emitDiagnosticMessage(SourceLocation Loc,
PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
StringRef Message,
ArrayRef<CharSourceRange> Ranges,
const SourceManager *SM,
DiagOrStoredDiag D) override;
void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
ArrayRef<CharSourceRange> Ranges,
const SourceManager &SM) override {}
void emitNote(SourceLocation Loc, StringRef Message,
const SourceManager *SM) override;
void emitCodeContext(SourceLocation Loc,
DiagnosticsEngine::Level Level,
SmallVectorImpl<CharSourceRange>& Ranges,
ArrayRef<FixItHint> Hints,
const SourceManager &SM) override;
void beginDiagnostic(DiagOrStoredDiag D,
DiagnosticsEngine::Level Level) override;
void endDiagnostic(DiagOrStoredDiag D,
DiagnosticsEngine::Level Level) override;
};
typedef llvm::DenseMap<unsigned, unsigned> AbbrevLookup;
class SDiagsMerger : SerializedDiagnosticReader {
SDiagsWriter &Writer;
AbbrevLookup FileLookup;
AbbrevLookup CategoryLookup;
AbbrevLookup DiagFlagLookup;
public:
SDiagsMerger(SDiagsWriter &Writer)
: SerializedDiagnosticReader(), Writer(Writer) {}
std::error_code mergeRecordsFromFile(const char *File) {
return readDiagnostics(File);
}
protected:
std::error_code visitStartOfDiagnostic() override;
std::error_code visitEndOfDiagnostic() override;
std::error_code visitCategoryRecord(unsigned ID, StringRef Name) override;
std::error_code visitDiagFlagRecord(unsigned ID, StringRef Name) override;
std::error_code visitDiagnosticRecord(
unsigned Severity, const serialized_diags::Location &Location,
unsigned Category, unsigned Flag, StringRef Message) override;
std::error_code visitFilenameRecord(unsigned ID, unsigned Size,
unsigned Timestamp,
StringRef Name) override;
std::error_code visitFixitRecord(const serialized_diags::Location &Start,
const serialized_diags::Location &End,
StringRef CodeToInsert) override;
std::error_code
visitSourceRangeRecord(const serialized_diags::Location &Start,
const serialized_diags::Location &End) override;
private:
std::error_code adjustSourceLocFilename(RecordData &Record,
unsigned int offset);
void adjustAbbrevID(RecordData &Record, AbbrevLookup &Lookup,
unsigned NewAbbrev);
void writeRecordWithAbbrev(unsigned ID, RecordData &Record);
void writeRecordWithBlob(unsigned ID, RecordData &Record, StringRef Blob);
};
class SDiagsWriter : public DiagnosticConsumer {
friend class SDiagsRenderer;
friend class SDiagsMerger;
struct SharedState;
explicit SDiagsWriter(IntrusiveRefCntPtr<SharedState> State)
: LangOpts(nullptr), OriginalInstance(false), MergeChildRecords(false),
State(std::move(State)) {}
public:
SDiagsWriter(StringRef File, DiagnosticOptions *Diags, bool MergeChildRecords)
: LangOpts(nullptr), OriginalInstance(true),
MergeChildRecords(MergeChildRecords),
State(new SharedState(File, Diags)) {
if (MergeChildRecords)
RemoveOldDiagnostics();
EmitPreamble();
}
~SDiagsWriter() override {}
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
const Diagnostic &Info) override;
void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
LangOpts = &LO;
}
void finish() override;
private:
/// \brief Build a DiagnosticsEngine to emit diagnostics about the diagnostics
DiagnosticsEngine *getMetaDiags();
/// \brief Remove old copies of the serialized diagnostics. This is necessary
/// so that we can detect when subprocesses write diagnostics that we should
/// merge into our own.
void RemoveOldDiagnostics();
/// \brief Emit the preamble for the serialized diagnostics.
void EmitPreamble();
/// \brief Emit the BLOCKINFO block.
void EmitBlockInfoBlock();
/// \brief Emit the META data block.
void EmitMetaBlock();
/// \brief Start a DIAG block.
void EnterDiagBlock();
/// \brief End a DIAG block.
void ExitDiagBlock();
/// \brief Emit a DIAG record.
void EmitDiagnosticMessage(SourceLocation Loc,
PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
StringRef Message,
const SourceManager *SM,
DiagOrStoredDiag D);
/// \brief Emit FIXIT and SOURCE_RANGE records for a diagnostic.
void EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges,
ArrayRef<FixItHint> Hints,
const SourceManager &SM);
/// \brief Emit a record for a CharSourceRange.
void EmitCharSourceRange(CharSourceRange R, const SourceManager &SM);
/// \brief Emit the string information for the category.
unsigned getEmitCategory(unsigned category = 0);
/// \brief Emit the string information for diagnostic flags.
unsigned getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel,
unsigned DiagID = 0);
unsigned getEmitDiagnosticFlag(StringRef DiagName);
/// \brief Emit (lazily) the file string and retrieved the file identifier.
unsigned getEmitFile(const char *Filename);
/// \brief Add SourceLocation information the specified record.
void AddLocToRecord(SourceLocation Loc, const SourceManager *SM,
PresumedLoc PLoc, RecordDataImpl &Record,
unsigned TokSize = 0);
/// \brief Add SourceLocation information the specified record.
void AddLocToRecord(SourceLocation Loc, RecordDataImpl &Record,
const SourceManager *SM,
unsigned TokSize = 0) {
AddLocToRecord(Loc, SM, SM ? SM->getPresumedLoc(Loc) : PresumedLoc(),
Record, TokSize);
}
/// \brief Add CharSourceRange information the specified record.
void AddCharSourceRangeToRecord(CharSourceRange R, RecordDataImpl &Record,
const SourceManager &SM);
/// \brief Language options, which can differ from one clone of this client
/// to another.
const LangOptions *LangOpts;
/// \brief Whether this is the original instance (rather than one of its
/// clones), responsible for writing the file at the end.
bool OriginalInstance;
/// \brief Whether this instance should aggregate diagnostics that are
/// generated from child processes.
bool MergeChildRecords;
/// \brief State that is shared among the various clones of this diagnostic
/// consumer.
struct SharedState : RefCountedBase<SharedState> {
SharedState(StringRef File, DiagnosticOptions *Diags)
: DiagOpts(Diags), Stream(Buffer), OutputFile(File.str()),
EmittedAnyDiagBlocks(false) {}
/// \brief Diagnostic options.
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
/// \brief The byte buffer for the serialized content.
SmallString<1024> Buffer;
/// \brief The BitStreamWriter for the serialized diagnostics.
llvm::BitstreamWriter Stream;
/// \brief The name of the diagnostics file.
std::string OutputFile;
/// \brief The set of constructed record abbreviations.
AbbreviationMap Abbrevs;
/// \brief A utility buffer for constructing record content.
RecordData Record;
/// \brief A text buffer for rendering diagnostic text.
SmallString<256> diagBuf;
/// \brief The collection of diagnostic categories used.
llvm::DenseSet<unsigned> Categories;
/// \brief The collection of files used.
llvm::DenseMap<const char *, unsigned> Files;
typedef llvm::DenseMap<const void *, std::pair<unsigned, StringRef> >
DiagFlagsTy;
/// \brief Map for uniquing strings.
DiagFlagsTy DiagFlags;
/// \brief Whether we have already started emission of any DIAG blocks. Once
/// this becomes \c true, we never close a DIAG block until we know that we're
/// starting another one or we're done.
bool EmittedAnyDiagBlocks;
/// \brief Engine for emitting diagnostics about the diagnostics.
std::unique_ptr<DiagnosticsEngine> MetaDiagnostics;
};
/// \brief State shared among the various clones of this diagnostic consumer.
IntrusiveRefCntPtr<SharedState> State;
};
} // end anonymous namespace
namespace clang {
namespace serialized_diags {
std::unique_ptr<DiagnosticConsumer>
create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords) {
return llvm::make_unique<SDiagsWriter>(OutputFile, Diags, MergeChildRecords);
}
} // end namespace serialized_diags
} // end namespace clang
//===----------------------------------------------------------------------===//
// Serialization methods.
//===----------------------------------------------------------------------===//
/// \brief Emits a block ID in the BLOCKINFO block.
static void EmitBlockID(unsigned ID, const char *Name,
llvm::BitstreamWriter &Stream,
RecordDataImpl &Record) {
Record.clear();
Record.push_back(ID);
Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
// Emit the block name if present.
if (!Name || Name[0] == 0)
return;
Record.clear();
while (*Name)
Record.push_back(*Name++);
Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
}
/// \brief Emits a record ID in the BLOCKINFO block.
static void EmitRecordID(unsigned ID, const char *Name,
llvm::BitstreamWriter &Stream,
RecordDataImpl &Record){
Record.clear();
Record.push_back(ID);
while (*Name)
Record.push_back(*Name++);
Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
}
void SDiagsWriter::AddLocToRecord(SourceLocation Loc,
const SourceManager *SM,
PresumedLoc PLoc,
RecordDataImpl &Record,
unsigned TokSize) {
if (PLoc.isInvalid()) {
// Emit a "sentinel" location.
Record.push_back((unsigned)0); // File.
Record.push_back((unsigned)0); // Line.
Record.push_back((unsigned)0); // Column.
Record.push_back((unsigned)0); // Offset.
return;
}
Record.push_back(getEmitFile(PLoc.getFilename()));
Record.push_back(PLoc.getLine());
Record.push_back(PLoc.getColumn()+TokSize);
Record.push_back(SM->getFileOffset(Loc));
}
void SDiagsWriter::AddCharSourceRangeToRecord(CharSourceRange Range,
RecordDataImpl &Record,
const SourceManager &SM) {
AddLocToRecord(Range.getBegin(), Record, &SM);
unsigned TokSize = 0;
if (Range.isTokenRange())
TokSize = Lexer::MeasureTokenLength(Range.getEnd(),
SM, *LangOpts);
AddLocToRecord(Range.getEnd(), Record, &SM, TokSize);
}
unsigned SDiagsWriter::getEmitFile(const char *FileName){
if (!FileName)
return 0;
unsigned &entry = State->Files[FileName];
if (entry)
return entry;
// Lazily generate the record for the file.
entry = State->Files.size();
StringRef Name(FileName);
RecordData::value_type Record[] = {RECORD_FILENAME, entry, 0 /* For legacy */,
0 /* For legacy */, Name.size()};
State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_FILENAME), Record,
Name);
return entry;
}
void SDiagsWriter::EmitCharSourceRange(CharSourceRange R,
const SourceManager &SM) {
State->Record.clear();
State->Record.push_back(RECORD_SOURCE_RANGE);
AddCharSourceRangeToRecord(R, State->Record, SM);
State->Stream.EmitRecordWithAbbrev(State->Abbrevs.get(RECORD_SOURCE_RANGE),
State->Record);
}
/// \brief Emits the preamble of the diagnostics file.
void SDiagsWriter::EmitPreamble() {
// Emit the file header.
State->Stream.Emit((unsigned)'D', 8);
State->Stream.Emit((unsigned)'I', 8);
State->Stream.Emit((unsigned)'A', 8);
State->Stream.Emit((unsigned)'G', 8);
EmitBlockInfoBlock();
EmitMetaBlock();
}
static void AddSourceLocationAbbrev(llvm::BitCodeAbbrev *Abbrev) {
using namespace llvm;
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // File ID.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Line.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Column.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Offset;
}
static void AddRangeLocationAbbrev(llvm::BitCodeAbbrev *Abbrev) {
AddSourceLocationAbbrev(Abbrev);
AddSourceLocationAbbrev(Abbrev);
}
void SDiagsWriter::EmitBlockInfoBlock() {
State->Stream.EnterBlockInfoBlock(3);
using namespace llvm;
llvm::BitstreamWriter &Stream = State->Stream;
RecordData &Record = State->Record;
AbbreviationMap &Abbrevs = State->Abbrevs;
// ==---------------------------------------------------------------------==//
// The subsequent records and Abbrevs are for the "Meta" block.
// ==---------------------------------------------------------------------==//
EmitBlockID(BLOCK_META, "Meta", Stream, Record);
EmitRecordID(RECORD_VERSION, "Version", Stream, Record);
BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Abbrev->Add(BitCodeAbbrevOp(RECORD_VERSION));
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Abbrevs.set(RECORD_VERSION, Stream.EmitBlockInfoAbbrev(BLOCK_META, Abbrev));
// ==---------------------------------------------------------------------==//
// The subsequent records and Abbrevs are for the "Diagnostic" block.
// ==---------------------------------------------------------------------==//
EmitBlockID(BLOCK_DIAG, "Diag", Stream, Record);
EmitRecordID(RECORD_DIAG, "DiagInfo", Stream, Record);
EmitRecordID(RECORD_SOURCE_RANGE, "SrcRange", Stream, Record);
EmitRecordID(RECORD_CATEGORY, "CatName", Stream, Record);
EmitRecordID(RECORD_DIAG_FLAG, "DiagFlag", Stream, Record);
EmitRecordID(RECORD_FILENAME, "FileName", Stream, Record);
EmitRecordID(RECORD_FIXIT, "FixIt", Stream, Record);
// Emit abbreviation for RECORD_DIAG.
Abbrev = new BitCodeAbbrev();
Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG));
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Diag level.
AddSourceLocationAbbrev(Abbrev);
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Category.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Text size.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Diagnostc text.
Abbrevs.set(RECORD_DIAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
// Emit abbrevation for RECORD_CATEGORY.
Abbrev = new BitCodeAbbrev();
Abbrev->Add(BitCodeAbbrevOp(RECORD_CATEGORY));
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Category ID.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // Text size.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Category text.
Abbrevs.set(RECORD_CATEGORY, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
// Emit abbrevation for RECORD_SOURCE_RANGE.
Abbrev = new BitCodeAbbrev();
Abbrev->Add(BitCodeAbbrevOp(RECORD_SOURCE_RANGE));
AddRangeLocationAbbrev(Abbrev);
Abbrevs.set(RECORD_SOURCE_RANGE,
Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
// Emit the abbreviation for RECORD_DIAG_FLAG.
Abbrev = new BitCodeAbbrev();
Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG_FLAG));
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Flag name text.
Abbrevs.set(RECORD_DIAG_FLAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
Abbrev));
// Emit the abbreviation for RECORD_FILENAME.
Abbrev = new BitCodeAbbrev();
Abbrev->Add(BitCodeAbbrevOp(RECORD_FILENAME));
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped file ID.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Size.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Modifcation time.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name text.
Abbrevs.set(RECORD_FILENAME, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
Abbrev));
// Emit the abbreviation for RECORD_FIXIT.
Abbrev = new BitCodeAbbrev();
Abbrev->Add(BitCodeAbbrevOp(RECORD_FIXIT));
AddRangeLocationAbbrev(Abbrev);
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // FixIt text.
Abbrevs.set(RECORD_FIXIT, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
Abbrev));
Stream.ExitBlock();
}
void SDiagsWriter::EmitMetaBlock() {
llvm::BitstreamWriter &Stream = State->Stream;
AbbreviationMap &Abbrevs = State->Abbrevs;
Stream.EnterSubblock(BLOCK_META, 3);
RecordData::value_type Record[] = {RECORD_VERSION, VersionNumber};
Stream.EmitRecordWithAbbrev(Abbrevs.get(RECORD_VERSION), Record);
Stream.ExitBlock();
}
unsigned SDiagsWriter::getEmitCategory(unsigned int category) {
if (!State->Categories.insert(category).second)
return category;
// We use a local version of 'Record' so that we can be generating
// another record when we lazily generate one for the category entry.
StringRef catName = DiagnosticIDs::getCategoryNameFromID(category);
RecordData::value_type Record[] = {RECORD_CATEGORY, category, catName.size()};
State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_CATEGORY), Record,
catName);
return category;
}
unsigned SDiagsWriter::getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel,
unsigned DiagID) {
if (DiagLevel == DiagnosticsEngine::Note)
return 0; // No flag for notes.
StringRef FlagName = DiagnosticIDs::getWarningOptionForDiag(DiagID);
return getEmitDiagnosticFlag(FlagName);
}
unsigned SDiagsWriter::getEmitDiagnosticFlag(StringRef FlagName) {
if (FlagName.empty())
return 0;
// Here we assume that FlagName points to static data whose pointer
// value is fixed. This allows us to unique by diagnostic groups.
const void *data = FlagName.data();
std::pair<unsigned, StringRef> &entry = State->DiagFlags[data];
if (entry.first == 0) {
entry.first = State->DiagFlags.size();
entry.second = FlagName;
// Lazily emit the string in a separate record.
RecordData::value_type Record[] = {RECORD_DIAG_FLAG, entry.first,
FlagName.size()};
State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_DIAG_FLAG),
Record, FlagName);
}
return entry.first;
}
void SDiagsWriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
const Diagnostic &Info) {
// Enter the block for a non-note diagnostic immediately, rather than waiting
// for beginDiagnostic, in case associated notes are emitted before we get
// there.
if (DiagLevel != DiagnosticsEngine::Note) {
if (State->EmittedAnyDiagBlocks)
ExitDiagBlock();
EnterDiagBlock();
State->EmittedAnyDiagBlocks = true;
}
// Compute the diagnostic text.
State->diagBuf.clear();
Info.FormatDiagnostic(State->diagBuf);
if (Info.getLocation().isInvalid()) {
// Special-case diagnostics with no location. We may not have entered a
// source file in this case, so we can't use the normal DiagnosticsRenderer
// machinery.
// Make sure we bracket all notes as "sub-diagnostics". This matches
// the behavior in SDiagsRenderer::emitDiagnostic().
if (DiagLevel == DiagnosticsEngine::Note)
EnterDiagBlock();
EmitDiagnosticMessage(SourceLocation(), PresumedLoc(), DiagLevel,
State->diagBuf, nullptr, &Info);
if (DiagLevel == DiagnosticsEngine::Note)
ExitDiagBlock();
return;
}
assert(Info.hasSourceManager() && LangOpts &&
"Unexpected diagnostic with valid location outside of a source file");
SDiagsRenderer Renderer(*this, *LangOpts, &*State->DiagOpts);
Renderer.emitDiagnostic(Info.getLocation(), DiagLevel,
State->diagBuf,
Info.getRanges(),
Info.getFixItHints(),
&Info.getSourceManager(),
&Info);
}
static serialized_diags::Level getStableLevel(DiagnosticsEngine::Level Level) {
switch (Level) {
#define CASE(X) case DiagnosticsEngine::X: return serialized_diags::X;
CASE(Ignored)
CASE(Note)
CASE(Remark)
CASE(Warning)
CASE(Error)
CASE(Fatal)
#undef CASE
}
llvm_unreachable("invalid diagnostic level");
}
void SDiagsWriter::EmitDiagnosticMessage(SourceLocation Loc,
PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
StringRef Message,
const SourceManager *SM,
DiagOrStoredDiag D) {
llvm::BitstreamWriter &Stream = State->Stream;
RecordData &Record = State->Record;
AbbreviationMap &Abbrevs = State->Abbrevs;
// Emit the RECORD_DIAG record.
Record.clear();
Record.push_back(RECORD_DIAG);
Record.push_back(getStableLevel(Level));
AddLocToRecord(Loc, SM, PLoc, Record);
if (const Diagnostic *Info = D.dyn_cast<const Diagnostic*>()) {
// Emit the category string lazily and get the category ID.
unsigned DiagID = DiagnosticIDs::getCategoryNumberForDiag(Info->getID());
Record.push_back(getEmitCategory(DiagID));
// Emit the diagnostic flag string lazily and get the mapped ID.
Record.push_back(getEmitDiagnosticFlag(Level, Info->getID()));
} else {
Record.push_back(getEmitCategory());
Record.push_back(getEmitDiagnosticFlag(Level));
}
Record.push_back(Message.size());
Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_DIAG), Record, Message);
}
void
SDiagsRenderer::emitDiagnosticMessage(SourceLocation Loc,
PresumedLoc PLoc,
DiagnosticsEngine::Level Level,
StringRef Message,
ArrayRef<clang::CharSourceRange> Ranges,
const SourceManager *SM,
DiagOrStoredDiag D) {
Writer.EmitDiagnosticMessage(Loc, PLoc, Level, Message, SM, D);
}
void SDiagsWriter::EnterDiagBlock() {
State->Stream.EnterSubblock(BLOCK_DIAG, 4);
}
void SDiagsWriter::ExitDiagBlock() {
State->Stream.ExitBlock();
}
void SDiagsRenderer::beginDiagnostic(DiagOrStoredDiag D,
DiagnosticsEngine::Level Level) {
if (Level == DiagnosticsEngine::Note)
Writer.EnterDiagBlock();
}
void SDiagsRenderer::endDiagnostic(DiagOrStoredDiag D,
DiagnosticsEngine::Level Level) {
// Only end note diagnostics here, because we can't be sure when we've seen
// the last note associated with a non-note diagnostic.
if (Level == DiagnosticsEngine::Note)
Writer.ExitDiagBlock();
}
void SDiagsWriter::EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges,
ArrayRef<FixItHint> Hints,
const SourceManager &SM) {
llvm::BitstreamWriter &Stream = State->Stream;
RecordData &Record = State->Record;
AbbreviationMap &Abbrevs = State->Abbrevs;
// Emit Source Ranges.
for (ArrayRef<CharSourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
I != E; ++I)
if (I->isValid())
EmitCharSourceRange(*I, SM);
// Emit FixIts.
for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
I != E; ++I) {
const FixItHint &Fix = *I;
if (Fix.isNull())
continue;
Record.clear();
Record.push_back(RECORD_FIXIT);
AddCharSourceRangeToRecord(Fix.RemoveRange, Record, SM);
Record.push_back(Fix.CodeToInsert.size());
Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_FIXIT), Record,
Fix.CodeToInsert);
}
}
void SDiagsRenderer::emitCodeContext(SourceLocation Loc,
DiagnosticsEngine::Level Level,
SmallVectorImpl<CharSourceRange> &Ranges,
ArrayRef<FixItHint> Hints,
const SourceManager &SM) {
Writer.EmitCodeContext(Ranges, Hints, SM);
}
void SDiagsRenderer::emitNote(SourceLocation Loc, StringRef Message,
const SourceManager *SM) {
Writer.EnterDiagBlock();
PresumedLoc PLoc = SM ? SM->getPresumedLoc(Loc) : PresumedLoc();
Writer.EmitDiagnosticMessage(Loc, PLoc, DiagnosticsEngine::Note,
Message, SM, DiagOrStoredDiag());
Writer.ExitDiagBlock();
}
DiagnosticsEngine *SDiagsWriter::getMetaDiags() {
// FIXME: It's slightly absurd to create a new diagnostics engine here, but
// the other options that are available today are worse:
//
// 1. Teach DiagnosticsConsumers to emit diagnostics to the engine they are a
// part of. The DiagnosticsEngine would need to know not to send
// diagnostics back to the consumer that failed. This would require us to
// rework ChainedDiagnosticsConsumer and teach the engine about multiple
// consumers, which is difficult today because most APIs interface with
// consumers rather than the engine itself.
//
// 2. Pass a DiagnosticsEngine to SDiagsWriter on creation - this would need
// to be distinct from the engine the writer was being added to and would
// normally not be used.
if (!State->MetaDiagnostics) {
IntrusiveRefCntPtr<DiagnosticIDs> IDs(new DiagnosticIDs());
auto Client =
new TextDiagnosticPrinter(llvm::errs(), State->DiagOpts.get());
State->MetaDiagnostics = llvm::make_unique<DiagnosticsEngine>(
IDs, State->DiagOpts.get(), Client);
}
return State->MetaDiagnostics.get();
}
void SDiagsWriter::RemoveOldDiagnostics() {
if (!llvm::sys::fs::remove(State->OutputFile))
return;
getMetaDiags()->Report(diag::warn_fe_serialized_diag_merge_failure);
// Disable merging child records, as whatever is in this file may be
// misleading.
MergeChildRecords = false;
}
void SDiagsWriter::finish() {
// The original instance is responsible for writing the file.
if (!OriginalInstance)
return;
// Finish off any diagnostic we were in the process of emitting.
if (State->EmittedAnyDiagBlocks)
ExitDiagBlock();
if (MergeChildRecords) {
if (!State->EmittedAnyDiagBlocks)
// We have no diagnostics of our own, so we can just leave the child
// process' output alone
return;
if (llvm::sys::fs::exists(State->OutputFile))
if (SDiagsMerger(*this).mergeRecordsFromFile(State->OutputFile.c_str()))
getMetaDiags()->Report(diag::warn_fe_serialized_diag_merge_failure);
}
std::error_code EC;
auto OS = llvm::make_unique<llvm::raw_fd_ostream>(State->OutputFile.c_str(),
EC, llvm::sys::fs::F_None);
if (EC) {
getMetaDiags()->Report(diag::warn_fe_serialized_diag_failure)
<< State->OutputFile << EC.message();
return;
}
// Write the generated bitstream to "Out".
OS->write((char *)&State->Buffer.front(), State->Buffer.size());
OS->flush();
}
std::error_code SDiagsMerger::visitStartOfDiagnostic() {
Writer.EnterDiagBlock();
return std::error_code();
}
std::error_code SDiagsMerger::visitEndOfDiagnostic() {
Writer.ExitDiagBlock();
return std::error_code();
}
std::error_code
SDiagsMerger::visitSourceRangeRecord(const serialized_diags::Location &Start,
const serialized_diags::Location &End) {
RecordData::value_type Record[] = {
RECORD_SOURCE_RANGE, FileLookup[Start.FileID], Start.Line, Start.Col,
Start.Offset, FileLookup[End.FileID], End.Line, End.Col, End.Offset};
Writer.State->Stream.EmitRecordWithAbbrev(
Writer.State->Abbrevs.get(RECORD_SOURCE_RANGE), Record);
return std::error_code();
}
std::error_code SDiagsMerger::visitDiagnosticRecord(
unsigned Severity, const serialized_diags::Location &Location,
unsigned Category, unsigned Flag, StringRef Message) {
RecordData::value_type Record[] = {
RECORD_DIAG, Severity, FileLookup[Location.FileID], Location.Line,
Location.Col, Location.Offset, CategoryLookup[Category],
Flag ? DiagFlagLookup[Flag] : 0, Message.size()};
Writer.State->Stream.EmitRecordWithBlob(
Writer.State->Abbrevs.get(RECORD_DIAG), Record, Message);
return std::error_code();
}
std::error_code
SDiagsMerger::visitFixitRecord(const serialized_diags::Location &Start,
const serialized_diags::Location &End,
StringRef Text) {
RecordData::value_type Record[] = {RECORD_FIXIT, FileLookup[Start.FileID],
Start.Line, Start.Col, Start.Offset,
FileLookup[End.FileID], End.Line, End.Col,
End.Offset, Text.size()};
Writer.State->Stream.EmitRecordWithBlob(
Writer.State->Abbrevs.get(RECORD_FIXIT), Record, Text);
return std::error_code();
}
std::error_code SDiagsMerger::visitFilenameRecord(unsigned ID, unsigned Size,
unsigned Timestamp,
StringRef Name) {
FileLookup[ID] = Writer.getEmitFile(Name.str().c_str());
return std::error_code();
}
std::error_code SDiagsMerger::visitCategoryRecord(unsigned ID, StringRef Name) {
CategoryLookup[ID] = Writer.getEmitCategory(ID);
return std::error_code();
}
std::error_code SDiagsMerger::visitDiagFlagRecord(unsigned ID, StringRef Name) {
DiagFlagLookup[ID] = Writer.getEmitDiagnosticFlag(Name);
return std::error_code();
}
| lgpl-2.1 |
satyarth934/root | interpreter/llvm/src/tools/clang/lib/Sema/SemaStmtAsm.cpp | 20 | 29382 | //===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for inline asm statements.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
using namespace clang;
using namespace sema;
/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
/// ignore "noop" casts in places where an lvalue is required by an inline asm.
/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
/// provide a strong guidance to not use it.
///
/// This method checks to see if the argument is an acceptable l-value and
/// returns false if it is a case we can handle.
static bool CheckAsmLValue(const Expr *E, Sema &S) {
// Type dependent expressions will be checked during instantiation.
if (E->isTypeDependent())
return false;
if (E->isLValue())
return false; // Cool, this is an lvalue.
// Okay, this is not an lvalue, but perhaps it is the result of a cast that we
// are supposed to allow.
const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
if (E != E2 && E2->isLValue()) {
if (!S.getLangOpts().HeinousExtensions)
S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
<< E->getSourceRange();
else
S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
<< E->getSourceRange();
// Accept, even if we emitted an error diagnostic.
return false;
}
// None of the above, just randomly invalid non-lvalue.
return true;
}
/// isOperandMentioned - Return true if the specified operand # is mentioned
/// anywhere in the decomposed asm string.
static bool isOperandMentioned(unsigned OpNo,
ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
if (!Piece.isOperand()) continue;
// If this is a reference to the input and if the input was the smaller
// one, then we have to reject this asm.
if (Piece.getOperandNo() == OpNo)
return true;
}
return false;
}
static bool CheckNakedParmReference(Expr *E, Sema &S) {
FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
if (!Func)
return false;
if (!Func->hasAttr<NakedAttr>())
return false;
SmallVector<Expr*, 4> WorkList;
WorkList.push_back(E);
while (WorkList.size()) {
Expr *E = WorkList.pop_back_val();
if (isa<CXXThisExpr>(E)) {
S.Diag(E->getLocStart(), diag::err_asm_naked_this_ref);
S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
return true;
}
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
if (isa<ParmVarDecl>(DRE->getDecl())) {
S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
return true;
}
}
for (Stmt *Child : E->children()) {
if (Expr *E = dyn_cast_or_null<Expr>(Child))
WorkList.push_back(E);
}
}
return false;
}
/// \brief Returns true if given expression is not compatible with inline
/// assembly's memory constraint; false otherwise.
static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
TargetInfo::ConstraintInfo &Info,
bool is_input_expr) {
enum {
ExprBitfield = 0,
ExprVectorElt,
ExprGlobalRegVar,
ExprSafeType
} EType = ExprSafeType;
// Bitfields, vector elements and global register variables are not
// compatible.
if (E->refersToBitField())
EType = ExprBitfield;
else if (E->refersToVectorElement())
EType = ExprVectorElt;
else if (E->refersToGlobalRegisterVar())
EType = ExprGlobalRegVar;
if (EType != ExprSafeType) {
S.Diag(E->getLocStart(), diag::err_asm_non_addr_value_in_memory_constraint)
<< EType << is_input_expr << Info.getConstraintStr()
<< E->getSourceRange();
return true;
}
return false;
}
StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg constraints, MultiExprArg Exprs,
Expr *asmString, MultiExprArg clobbers,
SourceLocation RParenLoc) {
unsigned NumClobbers = clobbers.size();
StringLiteral **Constraints =
reinterpret_cast<StringLiteral**>(constraints.data());
StringLiteral *AsmString = cast<StringLiteral>(asmString);
StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
// The parser verifies that there is a string literal here.
assert(AsmString->isAscii());
// If we're compiling CUDA file and function attributes indicate that it's not
// for this compilation side, skip all the checks.
if (!DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) {
GCCAsmStmt *NS = new (Context) GCCAsmStmt(
Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names,
Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, RParenLoc);
return NS;
}
for (unsigned i = 0; i != NumOutputs; i++) {
StringLiteral *Literal = Constraints[i];
assert(Literal->isAscii());
StringRef OutputName;
if (Names[i])
OutputName = Names[i]->getName();
TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
if (!Context.getTargetInfo().validateOutputConstraint(Info))
return StmtError(Diag(Literal->getLocStart(),
diag::err_asm_invalid_output_constraint)
<< Info.getConstraintStr());
ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
if (ER.isInvalid())
return StmtError();
Exprs[i] = ER.get();
// Check that the output exprs are valid lvalues.
Expr *OutputExpr = Exprs[i];
// Referring to parameters is not allowed in naked functions.
if (CheckNakedParmReference(OutputExpr, *this))
return StmtError();
// Check that the output expression is compatible with memory constraint.
if (Info.allowsMemory() &&
checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
return StmtError();
OutputConstraintInfos.push_back(Info);
// If this is dependent, just continue.
if (OutputExpr->isTypeDependent())
continue;
Expr::isModifiableLvalueResult IsLV =
OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
switch (IsLV) {
case Expr::MLV_Valid:
// Cool, this is an lvalue.
break;
case Expr::MLV_ArrayType:
// This is OK too.
break;
case Expr::MLV_LValueCast: {
const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
if (!getLangOpts().HeinousExtensions) {
Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
<< OutputExpr->getSourceRange();
} else {
Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
<< OutputExpr->getSourceRange();
}
// Accept, even if we emitted an error diagnostic.
break;
}
case Expr::MLV_IncompleteType:
case Expr::MLV_IncompleteVoidType:
if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
diag::err_dereference_incomplete_type))
return StmtError();
default:
return StmtError(Diag(OutputExpr->getLocStart(),
diag::err_asm_invalid_lvalue_in_output)
<< OutputExpr->getSourceRange());
}
unsigned Size = Context.getTypeSize(OutputExpr->getType());
if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
Size))
return StmtError(Diag(OutputExpr->getLocStart(),
diag::err_asm_invalid_output_size)
<< Info.getConstraintStr());
}
SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
StringLiteral *Literal = Constraints[i];
assert(Literal->isAscii());
StringRef InputName;
if (Names[i])
InputName = Names[i]->getName();
TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
Info)) {
return StmtError(Diag(Literal->getLocStart(),
diag::err_asm_invalid_input_constraint)
<< Info.getConstraintStr());
}
ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
if (ER.isInvalid())
return StmtError();
Exprs[i] = ER.get();
Expr *InputExpr = Exprs[i];
// Referring to parameters is not allowed in naked functions.
if (CheckNakedParmReference(InputExpr, *this))
return StmtError();
// Check that the input expression is compatible with memory constraint.
if (Info.allowsMemory() &&
checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
return StmtError();
// Only allow void types for memory constraints.
if (Info.allowsMemory() && !Info.allowsRegister()) {
if (CheckAsmLValue(InputExpr, *this))
return StmtError(Diag(InputExpr->getLocStart(),
diag::err_asm_invalid_lvalue_in_input)
<< Info.getConstraintStr()
<< InputExpr->getSourceRange());
} else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
if (!InputExpr->isValueDependent()) {
llvm::APSInt Result;
if (!InputExpr->EvaluateAsInt(Result, Context))
return StmtError(
Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
<< Info.getConstraintStr() << InputExpr->getSourceRange());
if (!Info.isValidAsmImmediate(Result))
return StmtError(Diag(InputExpr->getLocStart(),
diag::err_invalid_asm_value_for_constraint)
<< Result.toString(10) << Info.getConstraintStr()
<< InputExpr->getSourceRange());
}
} else {
ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
if (Result.isInvalid())
return StmtError();
Exprs[i] = Result.get();
}
if (Info.allowsRegister()) {
if (InputExpr->getType()->isVoidType()) {
return StmtError(Diag(InputExpr->getLocStart(),
diag::err_asm_invalid_type_in_input)
<< InputExpr->getType() << Info.getConstraintStr()
<< InputExpr->getSourceRange());
}
}
InputConstraintInfos.push_back(Info);
const Type *Ty = Exprs[i]->getType().getTypePtr();
if (Ty->isDependentType())
continue;
if (!Ty->isVoidType() || !Info.allowsMemory())
if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
diag::err_dereference_incomplete_type))
return StmtError();
unsigned Size = Context.getTypeSize(Ty);
if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
Size))
return StmtError(Diag(InputExpr->getLocStart(),
diag::err_asm_invalid_input_size)
<< Info.getConstraintStr());
}
// Check that the clobbers are valid.
for (unsigned i = 0; i != NumClobbers; i++) {
StringLiteral *Literal = Clobbers[i];
assert(Literal->isAscii());
StringRef Clobber = Literal->getString();
if (!Context.getTargetInfo().isValidClobber(Clobber))
return StmtError(Diag(Literal->getLocStart(),
diag::err_asm_unknown_register_name) << Clobber);
}
GCCAsmStmt *NS =
new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
NumInputs, Names, Constraints, Exprs.data(),
AsmString, NumClobbers, Clobbers, RParenLoc);
// Validate the asm string, ensuring it makes sense given the operands we
// have.
SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
unsigned DiagOffs;
if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
<< AsmString->getSourceRange();
return StmtError();
}
// Validate constraints and modifiers.
for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
if (!Piece.isOperand()) continue;
// Look for the correct constraint index.
unsigned ConstraintIdx = Piece.getOperandNo();
unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
// Look for the (ConstraintIdx - NumOperands + 1)th constraint with
// modifier '+'.
if (ConstraintIdx >= NumOperands) {
unsigned I = 0, E = NS->getNumOutputs();
for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
ConstraintIdx = I;
break;
}
assert(I != E && "Invalid operand number should have been caught in "
" AnalyzeAsmString");
}
// Now that we have the right indexes go ahead and check.
StringLiteral *Literal = Constraints[ConstraintIdx];
const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
if (Ty->isDependentType() || Ty->isIncompleteType())
continue;
unsigned Size = Context.getTypeSize(Ty);
std::string SuggestedModifier;
if (!Context.getTargetInfo().validateConstraintModifier(
Literal->getString(), Piece.getModifier(), Size,
SuggestedModifier)) {
Diag(Exprs[ConstraintIdx]->getLocStart(),
diag::warn_asm_mismatched_size_modifier);
if (!SuggestedModifier.empty()) {
auto B = Diag(Piece.getRange().getBegin(),
diag::note_asm_missing_constraint_modifier)
<< SuggestedModifier;
SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
SuggestedModifier));
}
}
}
// Validate tied input operands for type mismatches.
unsigned NumAlternatives = ~0U;
for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
StringRef ConstraintStr = Info.getConstraintStr();
unsigned AltCount = ConstraintStr.count(',') + 1;
if (NumAlternatives == ~0U)
NumAlternatives = AltCount;
else if (NumAlternatives != AltCount)
return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
diag::err_asm_unexpected_constraint_alternatives)
<< NumAlternatives << AltCount);
}
SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
~0U);
for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
StringRef ConstraintStr = Info.getConstraintStr();
unsigned AltCount = ConstraintStr.count(',') + 1;
if (NumAlternatives == ~0U)
NumAlternatives = AltCount;
else if (NumAlternatives != AltCount)
return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
diag::err_asm_unexpected_constraint_alternatives)
<< NumAlternatives << AltCount);
// If this is a tied constraint, verify that the output and input have
// either exactly the same type, or that they are int/ptr operands with the
// same size (int/long, int*/long, are ok etc).
if (!Info.hasTiedOperand()) continue;
unsigned TiedTo = Info.getTiedOperand();
unsigned InputOpNo = i+NumOutputs;
Expr *OutputExpr = Exprs[TiedTo];
Expr *InputExpr = Exprs[InputOpNo];
// Make sure no more than one input constraint matches each output.
assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
if (InputMatchedToOutput[TiedTo] != ~0U) {
Diag(NS->getInputExpr(i)->getLocStart(),
diag::err_asm_input_duplicate_match)
<< TiedTo;
Diag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getLocStart(),
diag::note_asm_input_duplicate_first)
<< TiedTo;
return StmtError();
}
InputMatchedToOutput[TiedTo] = i;
if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
continue;
QualType InTy = InputExpr->getType();
QualType OutTy = OutputExpr->getType();
if (Context.hasSameType(InTy, OutTy))
continue; // All types can be tied to themselves.
// Decide if the input and output are in the same domain (integer/ptr or
// floating point.
enum AsmDomain {
AD_Int, AD_FP, AD_Other
} InputDomain, OutputDomain;
if (InTy->isIntegerType() || InTy->isPointerType())
InputDomain = AD_Int;
else if (InTy->isRealFloatingType())
InputDomain = AD_FP;
else
InputDomain = AD_Other;
if (OutTy->isIntegerType() || OutTy->isPointerType())
OutputDomain = AD_Int;
else if (OutTy->isRealFloatingType())
OutputDomain = AD_FP;
else
OutputDomain = AD_Other;
// They are ok if they are the same size and in the same domain. This
// allows tying things like:
// void* to int*
// void* to int if they are the same size.
// double to long double if they are the same size.
//
uint64_t OutSize = Context.getTypeSize(OutTy);
uint64_t InSize = Context.getTypeSize(InTy);
if (OutSize == InSize && InputDomain == OutputDomain &&
InputDomain != AD_Other)
continue;
// If the smaller input/output operand is not mentioned in the asm string,
// then we can promote the smaller one to a larger input and the asm string
// won't notice.
bool SmallerValueMentioned = false;
// If this is a reference to the input and if the input was the smaller
// one, then we have to reject this asm.
if (isOperandMentioned(InputOpNo, Pieces)) {
// This is a use in the asm string of the smaller operand. Since we
// codegen this by promoting to a wider value, the asm will get printed
// "wrong".
SmallerValueMentioned |= InSize < OutSize;
}
if (isOperandMentioned(TiedTo, Pieces)) {
// If this is a reference to the output, and if the output is the larger
// value, then it's ok because we'll promote the input to the larger type.
SmallerValueMentioned |= OutSize < InSize;
}
// If the smaller value wasn't mentioned in the asm string, and if the
// output was a register, just extend the shorter one to the size of the
// larger one.
if (!SmallerValueMentioned && InputDomain != AD_Other &&
OutputConstraintInfos[TiedTo].allowsRegister())
continue;
// Either both of the operands were mentioned or the smaller one was
// mentioned. One more special case that we'll allow: if the tied input is
// integer, unmentioned, and is a constant, then we'll allow truncating it
// down to the size of the destination.
if (InputDomain == AD_Int && OutputDomain == AD_Int &&
!isOperandMentioned(InputOpNo, Pieces) &&
InputExpr->isEvaluatable(Context)) {
CastKind castKind =
(OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Exprs[InputOpNo] = InputExpr;
NS->setInputExpr(i, InputExpr);
continue;
}
Diag(InputExpr->getLocStart(),
diag::err_asm_tying_incompatible_types)
<< InTy << OutTy << OutputExpr->getSourceRange()
<< InputExpr->getSourceRange();
return StmtError();
}
return NS;
}
static void fillInlineAsmTypeInfo(const ASTContext &Context, QualType T,
llvm::InlineAsmIdentifierInfo &Info) {
// Compute the type size (and array length if applicable?).
Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
if (T->isArrayType()) {
const ArrayType *ATy = Context.getAsArrayType(T);
Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
Info.Length = Info.Size / Info.Type;
}
}
ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
llvm::InlineAsmIdentifierInfo &Info,
bool IsUnevaluatedContext) {
Info.clear();
if (IsUnevaluatedContext)
PushExpressionEvaluationContext(UnevaluatedAbstract,
ReuseLambdaContextDecl);
ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
/*trailing lparen*/ false,
/*is & operand*/ false,
/*CorrectionCandidateCallback=*/nullptr,
/*IsInlineAsmIdentifier=*/ true);
if (IsUnevaluatedContext)
PopExpressionEvaluationContext();
if (!Result.isUsable()) return Result;
Result = CheckPlaceholderExpr(Result.get());
if (!Result.isUsable()) return Result;
// Referring to parameters is not allowed in naked functions.
if (CheckNakedParmReference(Result.get(), *this))
return ExprError();
QualType T = Result.get()->getType();
if (T->isDependentType()) {
return Result;
}
// Any sort of function type is fine.
if (T->isFunctionType()) {
return Result;
}
// Otherwise, it needs to be a complete type.
if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
return ExprError();
}
fillInlineAsmTypeInfo(Context, T, Info);
// We can work with the expression as long as it's not an r-value.
if (!Result.get()->isRValue())
Info.IsVarDecl = true;
return Result;
}
bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc) {
Offset = 0;
SmallVector<StringRef, 2> Members;
Member.split(Members, ".");
LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
LookupOrdinaryName);
if (!LookupName(BaseResult, getCurScope()))
return true;
if(!BaseResult.isSingleResult())
return true;
NamedDecl *FoundDecl = BaseResult.getFoundDecl();
for (StringRef NextMember : Members) {
const RecordType *RT = nullptr;
if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
RT = VD->getType()->getAs<RecordType>();
else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
RT = TD->getUnderlyingType()->getAs<RecordType>();
} else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
RT = TD->getTypeForDecl()->getAs<RecordType>();
else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
RT = TD->getType()->getAs<RecordType>();
if (!RT)
return true;
if (RequireCompleteType(AsmLoc, QualType(RT, 0),
diag::err_asm_incomplete_type))
return true;
LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
SourceLocation(), LookupMemberName);
if (!LookupQualifiedName(FieldResult, RT->getDecl()))
return true;
if (!FieldResult.isSingleResult())
return true;
FoundDecl = FieldResult.getFoundDecl();
// FIXME: Handle IndirectFieldDecl?
FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
if (!FD)
return true;
const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
unsigned i = FD->getFieldIndex();
CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
Offset += (unsigned)Result.getQuantity();
}
return false;
}
ExprResult
Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
llvm::InlineAsmIdentifierInfo &Info,
SourceLocation AsmLoc) {
Info.clear();
QualType T = E->getType();
if (T->isDependentType()) {
DeclarationNameInfo NameInfo;
NameInfo.setLoc(AsmLoc);
NameInfo.setName(&Context.Idents.get(Member));
return CXXDependentScopeMemberExpr::Create(
Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
SourceLocation(),
/*FirstQualifierInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
}
const RecordType *RT = T->getAs<RecordType>();
// FIXME: Diagnose this as field access into a scalar type.
if (!RT)
return ExprResult();
LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
LookupMemberName);
if (!LookupQualifiedName(FieldResult, RT->getDecl()))
return ExprResult();
// Only normal and indirect field results will work.
ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
if (!FD)
FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
if (!FD)
return ExprResult();
// Make an Expr to thread through OpDecl.
ExprResult Result = BuildMemberReferenceExpr(
E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
if (Result.isInvalid())
return Result;
Info.OpDecl = Result.get();
fillInlineAsmTypeInfo(Context, Result.get()->getType(), Info);
// Fields are "variables" as far as inline assembly is concerned.
Info.IsVarDecl = true;
return Result;
}
StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc) {
bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
getCurFunction()->setHasBranchProtectedScope();
MSAsmStmt *NS =
new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
/*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
Constraints, Exprs, AsmString,
Clobbers, EndLoc);
return NS;
}
LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate) {
LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
Location);
if (Label->isMSAsmLabel()) {
// If we have previously created this label implicitly, mark it as used.
Label->markUsed(Context);
} else {
// Otherwise, insert it, but only resolve it if we have seen the label itself.
std::string InternalName;
llvm::raw_string_ostream OS(InternalName);
// Create an internal name for the label. The name should not be a valid mangled
// name, and should be unique. We use a dot to make the name an invalid mangled
// name.
OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__";
for (auto it = ExternalLabelName.begin(); it != ExternalLabelName.end();
++it) {
OS << *it;
if (*it == '$') {
// We escape '$' in asm strings by replacing it with "$$"
OS << '$';
}
}
Label->setMSAsmLabel(OS.str());
}
if (AlwaysCreate) {
// The label might have been created implicitly from a previously encountered
// goto statement. So, for both newly created and looked up labels, we mark
// them as resolved.
Label->setMSAsmLabelResolved();
}
// Adjust their location for being able to generate accurate diagnostics.
Label->setLocation(Location);
return Label;
}
| lgpl-2.1 |
hanketgithub/live | liveMedia/MPEGVideoStreamParser.cpp | 23 | 1677 | /**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2015 Live Networks, Inc. All rights reserved.
// An abstract parser for MPEG video streams
// Implementation
#include "MPEGVideoStreamParser.hh"
MPEGVideoStreamParser
::MPEGVideoStreamParser(MPEGVideoStreamFramer* usingSource,
FramedSource* inputSource)
: StreamParser(inputSource, FramedSource::handleClosure, usingSource,
&MPEGVideoStreamFramer::continueReadProcessing, usingSource),
fUsingSource(usingSource) {
}
MPEGVideoStreamParser::~MPEGVideoStreamParser() {
}
void MPEGVideoStreamParser::restoreSavedParserState() {
StreamParser::restoreSavedParserState();
fTo = fSavedTo;
fNumTruncatedBytes = fSavedNumTruncatedBytes;
}
void MPEGVideoStreamParser::registerReadInterest(unsigned char* to,
unsigned maxSize) {
fStartOfFrame = fTo = fSavedTo = to;
fLimit = to + maxSize;
fNumTruncatedBytes = fSavedNumTruncatedBytes = 0;
}
| lgpl-2.1 |
koshman86/osg | src/osgWrappers/deprecated-dotosg/osgParticle/IO_SinkOperator.cpp | 26 | 2711 |
#include <osgParticle/SinkOperator>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include <osg/Vec3>
#include <iostream>
bool SinkOperator_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool SinkOperator_writeLocalData(const osg::Object &obj, osgDB::Output &fw);
REGISTER_DOTOSGWRAPPER(SinkOperator_Proxy)
(
new osgParticle::SinkOperator,
"SinkOperator",
"Object Operator DomainOperator SinkOperator",
SinkOperator_readLocalData,
SinkOperator_writeLocalData
);
bool SinkOperator_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osgParticle::SinkOperator &sp = static_cast<osgParticle::SinkOperator &>(obj);
bool itAdvanced = false;
if (fr[0].matchWord("sinkTarget")) {
const char *ptstr = fr[1].getStr();
if (ptstr) {
std::string str(ptstr);
if (str == "position")
sp.setSinkTarget(osgParticle::SinkOperator::SINK_POSITION);
else if (str == "velocity")
sp.setSinkTarget(osgParticle::SinkOperator::SINK_VELOCITY);
else if (str == "angular_velocity")
sp.setSinkTarget(osgParticle::SinkOperator::SINK_ANGULAR_VELOCITY);
fr += 2;
itAdvanced = true;
}
}
if (fr[0].matchWord("sinkStrategy")) {
const char *ptstr = fr[1].getStr();
if (ptstr) {
std::string str(ptstr);
if (str == "inside")
sp.setSinkStrategy(osgParticle::SinkOperator::SINK_INSIDE);
else if (str == "outside")
sp.setSinkStrategy(osgParticle::SinkOperator::SINK_OUTSIDE);
fr += 2;
itAdvanced = true;
}
}
return itAdvanced;
}
bool SinkOperator_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osgParticle::SinkOperator &sp = static_cast<const osgParticle::SinkOperator &>(obj);
fw.indent() << "sinkTarget ";
switch (sp.getSinkTarget())
{
case osgParticle::SinkOperator::SINK_POSITION:
fw << "position" << std::endl; break;
case osgParticle::SinkOperator::SINK_VELOCITY:
fw << "velocity" << std::endl; break;
case osgParticle::SinkOperator::SINK_ANGULAR_VELOCITY:
fw << "angular_velocity" << std::endl; break;
default:
fw << "undefined" << std::endl; break;
}
fw.indent() << "sinkStrategy ";
switch (sp.getSinkStrategy())
{
case osgParticle::SinkOperator::SINK_INSIDE:
fw << "inside" << std::endl; break;
case osgParticle::SinkOperator::SINK_OUTSIDE:
fw << "outside" << std::endl; break;
default:
fw << "undefined" << std::endl; break;
}
return true;
}
| lgpl-2.1 |
wireload/PythonQt | generator/typeparser.cpp | 27 | 7690 | /****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "typeparser.h"
#include <qdebug.h>
#include <QStack>
class Scanner
{
public:
enum Token {
StarToken,
AmpersandToken,
LessThanToken,
ColonToken,
CommaToken,
OpenParenToken,
CloseParenToken,
SquareBegin,
SquareEnd,
GreaterThanToken,
ConstToken,
Identifier,
NoToken
};
Scanner(const QString &s)
: m_pos(0), m_length(s.length()), m_chars(s.constData())
{
}
Token nextToken();
QString identifier() const;
private:
int m_pos;
int m_length;
int m_token_start;
const QChar *m_chars;
};
QString Scanner::identifier() const
{
return QString(m_chars + m_token_start, m_pos - m_token_start);
}
Scanner::Token Scanner::nextToken()
{
Token tok = NoToken;
// remove whitespace
while (m_pos < m_length && m_chars[m_pos] == ' ') {
++m_pos;
}
m_token_start = m_pos;
while (m_pos < m_length) {
const QChar &c = m_chars[m_pos];
if (tok == NoToken) {
switch (c.toLatin1()) {
case '*': tok = StarToken; break;
case '&': tok = AmpersandToken; break;
case '<': tok = LessThanToken; break;
case '>': tok = GreaterThanToken; break;
case ',': tok = CommaToken; break;
case '(': tok = OpenParenToken; break;
case ')': tok = CloseParenToken; break;
case '[': tok = SquareBegin; break;
case ']' : tok = SquareEnd; break;
case ':':
tok = ColonToken;
Q_ASSERT(m_pos + 1 < m_length);
++m_pos;
break;
default:
if (c.isLetterOrNumber() || c == '_')
tok = Identifier;
else
qFatal("Unrecognized character in lexer: %c", c.toLatin1());
break;
}
}
if (tok <= GreaterThanToken) {
++m_pos;
break;
}
if (tok == Identifier) {
if (c.isLetterOrNumber() || c == '_')
++m_pos;
else
break;
}
}
if (tok == Identifier && m_pos - m_token_start == 5) {
if (m_chars[m_token_start] == 'c'
&& m_chars[m_token_start + 1] == 'o'
&& m_chars[m_token_start + 2] == 'n'
&& m_chars[m_token_start + 3] == 's'
&& m_chars[m_token_start + 4] == 't')
tok = ConstToken;
}
return tok;
}
TypeParser::Info TypeParser::parse(const QString &str)
{
Scanner scanner(str);
Info info;
QStack<Info *> stack;
stack.push(&info);
bool colon_prefix = false;
bool in_array = false;
QString array;
Scanner::Token tok = scanner.nextToken();
while (tok != Scanner::NoToken) {
// switch (tok) {
// case Scanner::StarToken: printf(" - *\n"); break;
// case Scanner::AmpersandToken: printf(" - &\n"); break;
// case Scanner::LessThanToken: printf(" - <\n"); break;
// case Scanner::GreaterThanToken: printf(" - >\n"); break;
// case Scanner::ColonToken: printf(" - ::\n"); break;
// case Scanner::CommaToken: printf(" - ,\n"); break;
// case Scanner::ConstToken: printf(" - const\n"); break;
// case Scanner::SquareBegin: printf(" - [\n"); break;
// case Scanner::SquareEnd: printf(" - ]\n"); break;
// case Scanner::Identifier: printf(" - '%s'\n", qPrintable(scanner.identifier())); break;
// default:
// break;
// }
switch (tok) {
case Scanner::StarToken:
++stack.top()->indirections;
break;
case Scanner::AmpersandToken:
stack.top()->is_reference = true;
break;
case Scanner::LessThanToken:
stack.top()->template_instantiations << Info();
stack.push(&stack.top()->template_instantiations.last());
break;
case Scanner::CommaToken:
stack.pop();
stack.top()->template_instantiations << Info();
stack.push(&stack.top()->template_instantiations.last());
break;
case Scanner::GreaterThanToken:
stack.pop();
break;
case Scanner::ColonToken:
colon_prefix = true;
break;
case Scanner::ConstToken:
stack.top()->is_constant = true;
break;
case Scanner::OpenParenToken: // function pointers not supported
case Scanner::CloseParenToken:
{
Info i;
i.is_busted = true;
return i;
}
case Scanner::Identifier:
if (in_array) {
array = scanner.identifier();
} else if (colon_prefix || stack.top()->qualified_name.isEmpty()) {
stack.top()->qualified_name << scanner.identifier();
colon_prefix = false;
} else {
stack.top()->qualified_name.last().append(" " + scanner.identifier());
}
break;
case Scanner::SquareBegin:
in_array = true;
break;
case Scanner::SquareEnd:
in_array = false;
stack.top()->arrays += array;
break;
default:
break;
}
tok = scanner.nextToken();
}
return info;
}
QString TypeParser::Info::instantiationName() const
{
QString s(qualified_name.join("::"));
if (!template_instantiations.isEmpty()) {
s += '<';
for (int i=0; i<template_instantiations.size(); ++i) {
if (i != 0)
s += ",";
s += template_instantiations.at(i).toString();
}
s += '>';
}
return s;
}
QString TypeParser::Info::toString() const
{
QString s;
if (is_constant) s += "const ";
s += instantiationName();
for (int i=0; i<arrays.size(); ++i)
s += "[" + arrays.at(i) + "]";
s += QString(indirections, '*');
if (is_reference) s += '&';
return s;
}
| lgpl-2.1 |
sgso/RIOT | sys/base64/base64.c | 35 | 5681 | /*
* Copyright (C) 2014 Hochschule für Angewandte Wissenschaften Hamburg (HAW)
* Copyright (C) 2014 Martin Landsmann <Martin.Landsmann@HAW-Hamburg.de>
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup base64
* @{
* @file
* @brief Functions to encode and decode base64
*
* @author Martin Landsmann <Martin.Landsmann@HAW-Hamburg.de>
* @}
*
*/
#include "base64.h"
#define BASE64_CAPITAL_UPPER_BOUND (25) /**< base64 'Z' */
#define BASE64_SMALL_UPPER_BOUND (51) /**< base64 'z' */
#define BASE64_NUMBER_UPPER_BOUND (61) /**< base64 '9' */
#define BASE64_PLUS (62) /**< base64 '+' */
#define BASE64_SLASH (63) /**< base64 '/' */
#define BASE64_EQUALS (0xFE) /**< no base64 symbol '=' */
#define BASE64_NOT_DEFINED (0xFF) /**< no base64 symbol */
/*
* returns the corresponding ascii symbol value for the given base64 code
*/
static char getsymbol(unsigned char code)
{
if (code == BASE64_SLASH) {
return '/';
}
if (code == BASE64_PLUS) {
return '+';
}
if (code <= BASE64_CAPITAL_UPPER_BOUND) {
return (code + 'A');
}
if (code <= BASE64_SMALL_UPPER_BOUND) {
return (code + ('z' - BASE64_SMALL_UPPER_BOUND));
}
if (code <= BASE64_NUMBER_UPPER_BOUND) {
return (code + ('9' - BASE64_NUMBER_UPPER_BOUND));
}
return (char)BASE64_NOT_DEFINED;
}
int base64_encode(unsigned char *data_in, size_t data_in_size, \
unsigned char *base64_out, size_t *base64_out_size)
{
size_t padding_bytes = ((data_in_size % 3) ? (3 - (data_in_size % 3)) : 0);
size_t required_size = (4 * (data_in_size + 2 - ((data_in_size + 2) % 3)) / 3) + padding_bytes;
if (data_in == NULL) {
return BASE64_ERROR_DATA_IN;
}
if (data_in_size < 1) {
return BASE64_ERROR_DATA_IN_SIZE;
}
if (*base64_out_size < required_size) {
*base64_out_size = required_size;
return BASE64_ERROR_BUFFER_OUT_SIZE;
}
if (base64_out == NULL) {
return BASE64_ERROR_BUFFER_OUT;
}
int iterate_base64_buffer = 0;
unsigned char nNum = 0;
int nLst = 0;
int njump = 0;
unsigned char tmpval;
for (int i = 0; i < (int)(data_in_size); ++i) {
njump++;
tmpval = *(data_in + i);
nNum = (tmpval >> (2 * njump));
if (njump == 4) {
nNum = nLst << (8 - 2 * njump);
njump = 0;
nLst = 0;
--i;
}
else {
nNum += nLst << (8 - 2 * njump);
nLst = tmpval & ((1 << njump * 2) - 1);
}
base64_out[iterate_base64_buffer++] = getsymbol(nNum);
}
/* The last character is not finished yet */
njump++;
if (njump == 4) {
nNum = (tmpval >> (2 * njump));
}
nNum = nLst << (8 - 2 * njump);
base64_out[iterate_base64_buffer++] = getsymbol(nNum);
/* if required we append '=' for the required dividability */
while (iterate_base64_buffer % 4) {
base64_out[iterate_base64_buffer++] = '=';
}
*base64_out_size = iterate_base64_buffer;
return BASE64_SUCCESS;
}
/*
* returns the corresponding base64 code for the given ascii symbol
*/
static int getcode(char symbol)
{
if (symbol == '/') {
return BASE64_SLASH;
}
if (symbol == '+') {
return BASE64_PLUS;
}
if (symbol == '=') {
/* indicates a padded base64 end */
return BASE64_EQUALS;
}
if (symbol < '0') {
/* indicates that the given symbol is not base64 and should be ignored */
return BASE64_NOT_DEFINED;
}
if (symbol <= '9' && symbol >= '0') {
return (symbol + (BASE64_NUMBER_UPPER_BOUND - '9'));
}
if (symbol <= 'Z' && symbol >= 'A') {
return (symbol - 'A');
}
if (symbol <= 'z' && symbol >= 'a') {
return (symbol + (BASE64_SMALL_UPPER_BOUND - 'z'));
}
/* indicates that the given symbol is not base64 and should be ignored */
return BASE64_NOT_DEFINED;
}
int base64_decode(unsigned char *base64_in, size_t base64_in_size, \
unsigned char *data_out, size_t *data_out_size)
{
size_t required_size = ((base64_in_size / 4) * 3);
if (base64_in == NULL) {
return BASE64_ERROR_DATA_IN;
}
if (base64_in_size < 4) {
return BASE64_ERROR_DATA_IN_SIZE;
}
if (*data_out_size < required_size) {
*data_out_size = required_size;
return BASE64_ERROR_BUFFER_OUT_SIZE;
}
if (data_out == NULL) {
return BASE64_ERROR_BUFFER_OUT;
}
int iterate_data_buffer = 0;
unsigned char nNum = 0;
int nLst = getcode(base64_in[0]) << 2;
int code = 0;
int mask = 2;
for (int i = 1; i < (int)(base64_in_size); i++) {
code = getcode(base64_in[i]);
if (code == BASE64_NOT_DEFINED || code == BASE64_EQUALS) {
continue;
}
int nm = (0xFF << (2 * mask));
nNum = nLst + ((code & (0xFF & nm)) >> (2 * mask));
nLst = (code & (0xFF & ~nm)) << (8 - (2 * mask));
(mask != 3) ? data_out[iterate_data_buffer++] = nNum : nNum;
(mask == 0) ? mask = 3 : mask--;
}
if (code == BASE64_EQUALS) {
/* add the last character to the data_out buffer */
data_out[iterate_data_buffer] = nNum;
}
*data_out_size = iterate_data_buffer;
return BASE64_SUCCESS;
}
| lgpl-2.1 |
maurerpe/FreeCAD | src/3rdParty/salomesmesh/src/SMDS/duplicate.cpp | 36 | 1759 | // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// SALOME Utils : general SALOME's definitions and tools
// File : duplicate.cxx
// Author : Antoine YESSAYAN, EDF
// Module : SALOME
// $Header$
//
/*!
* This function can be changed by strdup() if strdup() is ANSI.
* It is strongly (and only) used in the Registry environment
* (RegistryService, RegistryConnexion, Identity, ...)
*/
extern "C"
{
#include <stdlib.h>
#include <string.h>
}
#include "utilities.h"
#include "OpUtil.hxx"
const char* duplicate( const char *const str )
{
ASSERT(str!=NULL) ;
const size_t length = strlen( str ) ;
ASSERT(length>0) ;
char *new_str = new char[ 1+length ] ;
ASSERT(new_str) ;
strcpy( new_str , str ) ;
return new_str ;
}
| lgpl-2.1 |
RT-Thread/rtthread_fsl | src/mempool.c | 46 | 12658 | /*
* File : mempool.c
* This file is part of RT-Thread RTOS
* COPYRIGHT (C) 2006 - 2012, RT-Thread Development Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Change Logs:
* Date Author Notes
* 2006-05-27 Bernard implement memory pool
* 2006-06-03 Bernard fix the thread timer init bug
* 2006-06-30 Bernard fix the allocate/free block bug
* 2006-08-04 Bernard add hook support
* 2006-08-10 Bernard fix interrupt bug in rt_mp_alloc
* 2010-07-13 Bernard fix RT_ALIGN issue found by kuronca
* 2010-10-26 yi.qiu add module support in rt_mp_delete
* 2011-01-24 Bernard add object allocation check.
* 2012-03-22 Bernard fix align issue in rt_mp_init and rt_mp_create.
*/
#include <rthw.h>
#include <rtthread.h>
#ifdef RT_USING_MEMPOOL
#ifdef RT_USING_HOOK
static void (*rt_mp_alloc_hook)(struct rt_mempool *mp, void *block);
static void (*rt_mp_free_hook)(struct rt_mempool *mp, void *block);
/**
* @addtogroup Hook
*/
/*@{*/
/**
* This function will set a hook function, which will be invoked when a memory
* block is allocated from memory pool.
*
* @param hook the hook function
*/
void rt_mp_alloc_sethook(void (*hook)(struct rt_mempool *mp, void *block))
{
rt_mp_alloc_hook = hook;
}
/**
* This function will set a hook function, which will be invoked when a memory
* block is released to memory pool.
*
* @param hook the hook function
*/
void rt_mp_free_sethook(void (*hook)(struct rt_mempool *mp, void *block))
{
rt_mp_free_hook = hook;
}
/*@}*/
#endif
/**
* @addtogroup MM
*/
/*@{*/
/**
* This function will initialize a memory pool object, normally which is used
* for static object.
*
* @param mp the memory pool object
* @param name the name of memory pool
* @param start the star address of memory pool
* @param size the total size of memory pool
* @param block_size the size for each block
*
* @return RT_EOK
*/
rt_err_t rt_mp_init(struct rt_mempool *mp,
const char *name,
void *start,
rt_size_t size,
rt_size_t block_size)
{
rt_uint8_t *block_ptr;
register rt_base_t offset;
/* parameter check */
RT_ASSERT(mp != RT_NULL);
/* initialize object */
rt_object_init(&(mp->parent), RT_Object_Class_MemPool, name);
/* initialize memory pool */
mp->start_address = start;
mp->size = RT_ALIGN_DOWN(size, RT_ALIGN_SIZE);
/* align the block size */
block_size = RT_ALIGN(block_size, RT_ALIGN_SIZE);
mp->block_size = block_size;
/* align to align size byte */
mp->block_total_count = mp->size / (mp->block_size + sizeof(rt_uint8_t *));
mp->block_free_count = mp->block_total_count;
/* initialize suspended thread list */
rt_list_init(&(mp->suspend_thread));
mp->suspend_thread_count = 0;
/* initialize free block list */
block_ptr = (rt_uint8_t *)mp->start_address;
for (offset = 0; offset < mp->block_total_count; offset ++)
{
*(rt_uint8_t **)(block_ptr + offset * (block_size + sizeof(rt_uint8_t *))) =
(rt_uint8_t *)(block_ptr + (offset + 1) * (block_size + sizeof(rt_uint8_t *)));
}
*(rt_uint8_t **)(block_ptr + (offset - 1) * (block_size + sizeof(rt_uint8_t *))) =
RT_NULL;
mp->block_list = block_ptr;
return RT_EOK;
}
RTM_EXPORT(rt_mp_init);
/**
* This function will detach a memory pool from system object management.
*
* @param mp the memory pool object
*
* @return RT_EOK
*/
rt_err_t rt_mp_detach(struct rt_mempool *mp)
{
struct rt_thread *thread;
register rt_ubase_t temp;
/* parameter check */
RT_ASSERT(mp != RT_NULL);
/* wake up all suspended threads */
while (!rt_list_isempty(&(mp->suspend_thread)))
{
/* disable interrupt */
temp = rt_hw_interrupt_disable();
/* get next suspend thread */
thread = rt_list_entry(mp->suspend_thread.next, struct rt_thread, tlist);
/* set error code to RT_ERROR */
thread->error = -RT_ERROR;
/*
* resume thread
* In rt_thread_resume function, it will remove current thread from
* suspend list
*/
rt_thread_resume(thread);
/* decrease suspended thread count */
mp->suspend_thread_count --;
/* enable interrupt */
rt_hw_interrupt_enable(temp);
}
/* detach object */
rt_object_detach(&(mp->parent));
return RT_EOK;
}
RTM_EXPORT(rt_mp_detach);
#ifdef RT_USING_HEAP
/**
* This function will create a mempool object and allocate the memory pool from
* heap.
*
* @param name the name of memory pool
* @param block_count the count of blocks in memory pool
* @param block_size the size for each block
*
* @return the created mempool object
*/
rt_mp_t rt_mp_create(const char *name,
rt_size_t block_count,
rt_size_t block_size)
{
rt_uint8_t *block_ptr;
struct rt_mempool *mp;
register rt_base_t offset;
RT_DEBUG_NOT_IN_INTERRUPT;
/* allocate object */
mp = (struct rt_mempool *)rt_object_allocate(RT_Object_Class_MemPool, name);
/* allocate object failed */
if (mp == RT_NULL)
return RT_NULL;
/* initialize memory pool */
block_size = RT_ALIGN(block_size, RT_ALIGN_SIZE);
mp->block_size = block_size;
mp->size = (block_size + sizeof(rt_uint8_t *)) * block_count;
/* allocate memory */
mp->start_address = rt_malloc((block_size + sizeof(rt_uint8_t *)) *
block_count);
if (mp->start_address == RT_NULL)
{
/* no memory, delete memory pool object */
rt_object_delete(&(mp->parent));
return RT_NULL;
}
mp->block_total_count = block_count;
mp->block_free_count = mp->block_total_count;
/* initialize suspended thread list */
rt_list_init(&(mp->suspend_thread));
mp->suspend_thread_count = 0;
/* initialize free block list */
block_ptr = (rt_uint8_t *)mp->start_address;
for (offset = 0; offset < mp->block_total_count; offset ++)
{
*(rt_uint8_t **)(block_ptr + offset * (block_size + sizeof(rt_uint8_t *)))
= block_ptr + (offset + 1) * (block_size + sizeof(rt_uint8_t *));
}
*(rt_uint8_t **)(block_ptr + (offset - 1) * (block_size + sizeof(rt_uint8_t *)))
= RT_NULL;
mp->block_list = block_ptr;
return mp;
}
RTM_EXPORT(rt_mp_create);
/**
* This function will delete a memory pool and release the object memory.
*
* @param mp the memory pool object
*
* @return RT_EOK
*/
rt_err_t rt_mp_delete(rt_mp_t mp)
{
struct rt_thread *thread;
register rt_ubase_t temp;
RT_DEBUG_NOT_IN_INTERRUPT;
/* parameter check */
RT_ASSERT(mp != RT_NULL);
/* wake up all suspended threads */
while (!rt_list_isempty(&(mp->suspend_thread)))
{
/* disable interrupt */
temp = rt_hw_interrupt_disable();
/* get next suspend thread */
thread = rt_list_entry(mp->suspend_thread.next, struct rt_thread, tlist);
/* set error code to RT_ERROR */
thread->error = -RT_ERROR;
/*
* resume thread
* In rt_thread_resume function, it will remove current thread from
* suspend list
*/
rt_thread_resume(thread);
/* decrease suspended thread count */
mp->suspend_thread_count --;
/* enable interrupt */
rt_hw_interrupt_enable(temp);
}
#if defined(RT_USING_MODULE) && defined(RT_USING_SLAB)
/* the mp object belongs to an application module */
if (mp->parent.flag & RT_OBJECT_FLAG_MODULE)
rt_module_free(mp->parent.module_id, mp->start_address);
else
#endif
/* release allocated room */
rt_free(mp->start_address);
/* detach object */
rt_object_delete(&(mp->parent));
return RT_EOK;
}
RTM_EXPORT(rt_mp_delete);
#endif
/**
* This function will allocate a block from memory pool
*
* @param mp the memory pool object
* @param time the waiting time
*
* @return the allocated memory block or RT_NULL on allocated failed
*/
void *rt_mp_alloc(rt_mp_t mp, rt_int32_t time)
{
rt_uint8_t *block_ptr;
register rt_base_t level;
struct rt_thread *thread;
rt_uint32_t before_sleep = 0;
/* get current thread */
thread = rt_thread_self();
/* disable interrupt */
level = rt_hw_interrupt_disable();
while (mp->block_free_count == 0)
{
/* memory block is unavailable. */
if (time == 0)
{
/* enable interrupt */
rt_hw_interrupt_enable(level);
rt_set_errno(-RT_ETIMEOUT);
return RT_NULL;
}
RT_DEBUG_NOT_IN_INTERRUPT;
thread->error = RT_EOK;
/* need suspend thread */
rt_thread_suspend(thread);
rt_list_insert_after(&(mp->suspend_thread), &(thread->tlist));
mp->suspend_thread_count++;
if (time > 0)
{
/* get the start tick of timer */
before_sleep = rt_tick_get();
/* init thread timer and start it */
rt_timer_control(&(thread->thread_timer),
RT_TIMER_CTRL_SET_TIME,
&time);
rt_timer_start(&(thread->thread_timer));
}
/* enable interrupt */
rt_hw_interrupt_enable(level);
/* do a schedule */
rt_schedule();
if (thread->error != RT_EOK)
return RT_NULL;
if (time > 0)
{
time -= rt_tick_get() - before_sleep;
if (time < 0)
time = 0;
}
/* disable interrupt */
level = rt_hw_interrupt_disable();
}
/* memory block is available. decrease the free block counter */
mp->block_free_count--;
/* get block from block list */
block_ptr = mp->block_list;
RT_ASSERT(block_ptr != RT_NULL);
/* Setup the next free node. */
mp->block_list = *(rt_uint8_t **)block_ptr;
/* point to memory pool */
*(rt_uint8_t **)block_ptr = (rt_uint8_t *)mp;
/* enable interrupt */
rt_hw_interrupt_enable(level);
RT_OBJECT_HOOK_CALL(rt_mp_alloc_hook,
(mp, (rt_uint8_t *)(block_ptr + sizeof(rt_uint8_t *))));
return (rt_uint8_t *)(block_ptr + sizeof(rt_uint8_t *));
}
RTM_EXPORT(rt_mp_alloc);
/**
* This function will release a memory block
*
* @param block the address of memory block to be released
*/
void rt_mp_free(void *block)
{
rt_uint8_t **block_ptr;
struct rt_mempool *mp;
struct rt_thread *thread;
register rt_base_t level;
/* get the control block of pool which the block belongs to */
block_ptr = (rt_uint8_t **)((rt_uint8_t *)block - sizeof(rt_uint8_t *));
mp = (struct rt_mempool *)*block_ptr;
RT_OBJECT_HOOK_CALL(rt_mp_free_hook, (mp, block));
/* disable interrupt */
level = rt_hw_interrupt_disable();
/* increase the free block count */
mp->block_free_count ++;
/* link the block into the block list */
*block_ptr = mp->block_list;
mp->block_list = (rt_uint8_t *)block_ptr;
if (mp->suspend_thread_count > 0)
{
/* get the suspended thread */
thread = rt_list_entry(mp->suspend_thread.next,
struct rt_thread,
tlist);
/* set error */
thread->error = RT_EOK;
/* resume thread */
rt_thread_resume(thread);
/* decrease suspended thread count */
mp->suspend_thread_count --;
/* enable interrupt */
rt_hw_interrupt_enable(level);
/* do a schedule */
rt_schedule();
return;
}
/* enable interrupt */
rt_hw_interrupt_enable(level);
}
RTM_EXPORT(rt_mp_free);
/*@}*/
#endif
| lgpl-2.1 |
CyanogenMod/android_external_libsepol | tests/test-expander.c | 59 | 6328 | /*
* Authors: Chad Sellers <csellers@tresys.com>
* Joshua Brindle <jbrindle@tresys.com>
*
* Copyright (C) 2006 Tresys Technology, LLC
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* This is where the expander tests should go, including:
* - check role, type, bool, user mapping
* - add symbols declared in enabled optionals
* - do not add symbols declared in disabled optionals
* - add rules from enabled optionals
* - do not add rules from disabled optionals
* - verify attribute mapping
* - check conditional expressions for correct mapping
*/
#include "test-expander.h"
#include "parse_util.h"
#include "helpers.h"
#include "test-common.h"
#include "test-expander-users.h"
#include "test-expander-roles.h"
#include "test-expander-attr-map.h"
#include <sepol/policydb/policydb.h>
#include <sepol/policydb/expand.h>
#include <sepol/policydb/link.h>
#include <sepol/policydb/conditional.h>
#include <limits.h>
#include <stdlib.h>
policydb_t role_expanded;
policydb_t user_expanded;
policydb_t base_expanded2;
static policydb_t basemod;
static policydb_t basemod2;
static policydb_t mod2;
static policydb_t base_expanded;
static policydb_t base_only_mod;
static policydb_t base_only_expanded;
static policydb_t role_basemod;
static policydb_t role_mod;
static policydb_t user_basemod;
static policydb_t user_mod;
static policydb_t alias_basemod;
static policydb_t alias_mod;
static policydb_t alias_expanded;
static uint32_t *typemap;
extern int mls;
/* Takes base, some number of modules, links them, and expands them
reads source from myfiles array, which has the base string followed by
each module string */
int expander_policy_init(policydb_t * mybase, int num_modules, policydb_t ** mymodules, policydb_t * myexpanded, char **myfiles)
{
char *filename[num_modules + 1];
int i;
for (i = 0; i < num_modules + 1; i++) {
filename[i] = calloc(PATH_MAX, sizeof(char));
if (snprintf(filename[i], PATH_MAX, "policies/test-expander/%s%s", myfiles[i], mls ? ".mls" : ".std") < 0)
return -1;
}
if (policydb_init(mybase)) {
fprintf(stderr, "out of memory!\n");
return -1;
}
for (i = 0; i < num_modules; i++) {
if (policydb_init(mymodules[i])) {
fprintf(stderr, "out of memory!\n");
return -1;
}
}
if (policydb_init(myexpanded)) {
fprintf(stderr, "out of memory!\n");
return -1;
}
mybase->policy_type = POLICY_BASE;
mybase->mls = mls;
if (read_source_policy(mybase, filename[0], myfiles[0])) {
fprintf(stderr, "read source policy failed %s\n", filename[0]);
return -1;
}
for (i = 1; i < num_modules + 1; i++) {
mymodules[i - 1]->policy_type = POLICY_MOD;
mymodules[i - 1]->mls = mls;
if (read_source_policy(mymodules[i - 1], filename[i], myfiles[i])) {
fprintf(stderr, "read source policy failed %s\n", filename[i]);
return -1;
}
}
if (link_modules(NULL, mybase, mymodules, num_modules, 0)) {
fprintf(stderr, "link modules failed\n");
return -1;
}
if (expand_module(NULL, mybase, myexpanded, 0, 0)) {
fprintf(stderr, "expand modules failed\n");
return -1;
}
return 0;
}
int expander_test_init(void)
{
char *small_base_file = "small-base.conf";
char *base_only_file = "base-base-only.conf";
int rc;
policydb_t *mymod2;
char *files2[] = { "small-base.conf", "module.conf" };
char *role_files[] = { "role-base.conf", "role-module.conf" };
char *user_files[] = { "user-base.conf", "user-module.conf" };
char *alias_files[] = { "alias-base.conf", "alias-module.conf" };
rc = expander_policy_init(&basemod, 0, NULL, &base_expanded, &small_base_file);
if (rc != 0)
return rc;
mymod2 = &mod2;
rc = expander_policy_init(&basemod2, 1, &mymod2, &base_expanded2, files2);
if (rc != 0)
return rc;
rc = expander_policy_init(&base_only_mod, 0, NULL, &base_only_expanded, &base_only_file);
if (rc != 0)
return rc;
mymod2 = &role_mod;
rc = expander_policy_init(&role_basemod, 1, &mymod2, &role_expanded, role_files);
if (rc != 0)
return rc;
/* Just init the base for now, until we figure out how to separate out
mls and non-mls tests since users can't be used in mls module */
mymod2 = &user_mod;
rc = expander_policy_init(&user_basemod, 0, NULL, &user_expanded, user_files);
if (rc != 0)
return rc;
mymod2 = &alias_mod;
rc = expander_policy_init(&alias_basemod, 1, &mymod2, &alias_expanded, alias_files);
if (rc != 0)
return rc;
return 0;
}
int expander_test_cleanup(void)
{
policydb_destroy(&basemod);
policydb_destroy(&base_expanded);
free(typemap);
return 0;
}
static void test_expander_indexes(void)
{
test_policydb_indexes(&base_expanded);
}
static void test_expander_alias(void)
{
test_alias_datum(&alias_expanded, "alias_check_1_a", "alias_check_1_t", 1, 0);
test_alias_datum(&alias_expanded, "alias_check_2_a", "alias_check_2_t", 1, 0);
test_alias_datum(&alias_expanded, "alias_check_3_a", "alias_check_3_t", 1, 0);
}
int expander_add_tests(CU_pSuite suite)
{
if (NULL == CU_add_test(suite, "expander_indexes", test_expander_indexes)) {
CU_cleanup_registry();
return CU_get_error();
}
if (NULL == CU_add_test(suite, "expander_attr_mapping", test_expander_attr_mapping)) {
CU_cleanup_registry();
return CU_get_error();
}
if (NULL == CU_add_test(suite, "expander_role_mapping", test_expander_role_mapping)) {
CU_cleanup_registry();
return CU_get_error();
}
if (NULL == CU_add_test(suite, "expander_user_mapping", test_expander_user_mapping)) {
CU_cleanup_registry();
return CU_get_error();
}
if (NULL == CU_add_test(suite, "expander_alias", test_expander_alias)) {
CU_cleanup_registry();
return CU_get_error();
}
return 0;
}
| lgpl-2.1 |
stanxii/wr1004sjl | linux-3.4.6/drivers/staging/vt6655/rc4.c | 8665 | 2364 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* File: rc4.c
*
* Purpose:
*
* Functions:
*
* Revision History:
*
* Author: Kyle Hsu
*
* Date: Sep 4, 2002
*
*/
#include "rc4.h"
void rc4_init(PRC4Ext pRC4, unsigned char *pbyKey, unsigned int cbKey_len)
{
unsigned int ust1, ust2;
unsigned int keyindex;
unsigned int stateindex;
unsigned char *pbyst;
unsigned int idx;
pbyst = pRC4->abystate;
pRC4->ux = 0;
pRC4->uy = 0;
for (idx = 0; idx < 256; idx++)
pbyst[idx] = (unsigned char)idx;
keyindex = 0;
stateindex = 0;
for (idx = 0; idx < 256; idx++) {
ust1 = pbyst[idx];
stateindex = (stateindex + pbyKey[keyindex] + ust1) & 0xff;
ust2 = pbyst[stateindex];
pbyst[stateindex] = (unsigned char)ust1;
pbyst[idx] = (unsigned char)ust2;
if (++keyindex >= cbKey_len)
keyindex = 0;
}
}
unsigned int rc4_byte(PRC4Ext pRC4)
{
unsigned int ux;
unsigned int uy;
unsigned int ustx, usty;
unsigned char *pbyst;
pbyst = pRC4->abystate;
ux = (pRC4->ux + 1) & 0xff;
ustx = pbyst[ux];
uy = (ustx + pRC4->uy) & 0xff;
usty = pbyst[uy];
pRC4->ux = ux;
pRC4->uy = uy;
pbyst[uy] = (unsigned char)ustx;
pbyst[ux] = (unsigned char)usty;
return pbyst[(ustx + usty) & 0xff];
}
void rc4_encrypt(PRC4Ext pRC4, unsigned char *pbyDest,
unsigned char *pbySrc, unsigned int cbData_len)
{
unsigned int ii;
for (ii = 0; ii < cbData_len; ii++)
pbyDest[ii] = (unsigned char)(pbySrc[ii] ^ rc4_byte(pRC4));
}
| lgpl-2.1 |
vrsys/avango | attic/avango-shade/core/src/parser/Element.cpp | 1 | 1729 | // -*- Mode:C++ -*-
/************************************************************************\
* *
* This file is part of AVANGO. *
* *
* Copyright 2007 - 2010 Fraunhofer-Gesellschaft zur Foerderung der *
* angewandten Forschung (FhG), Munich, Germany. *
* *
* AVANGO is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, version 3. *
* *
* AVANGO is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with AVANGO. If not, see <http://www.gnu.org/licenses/>. *
* *
\************************************************************************/
#include "Element.h"
#include "../parser/Value.h"
using namespace shade::parser;
boost::shared_ptr<const Value> Element::evaluate(const Scope&) const { return boost::shared_ptr<const Value>(new Value()); }
| lgpl-3.0 |
marxoft/qdl | qdl-plugins/service-plugins/filestay/filestay.cpp | 1 | 10180 | /*
* Copyright (C) 2014 Stuart Howarth <showarth@marxoft.co.uk>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 3, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "filestay.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QTimer>
#include <QRegExp>
FileStay::FileStay(QObject *parent) :
ServicePlugin(parent),
m_waitTimer(new QTimer(this)),
m_waitTime(0),
m_connections(1)
{
this->connect(m_waitTimer, SIGNAL(timeout()), this, SLOT(updateWaitTime()));
}
QRegExp FileStay::urlPattern() const {
return QRegExp("http(s|)://(www.|)filestay.com/\\w+", Qt::CaseInsensitive);
}
bool FileStay::urlSupported(const QUrl &url) const {
return this->urlPattern().indexIn(url.toString()) == 0;
}
void FileStay::login(const QString &username, const QString &password) {
QString data = QString("op=login&redirect=&login=%1&password=%2&x=0&y=0").arg(username).arg(password);
QUrl url("http://filestay.com/login");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QNetworkReply *reply = this->networkAccessManager()->post(request, data.toUtf8());
this->connect(reply, SIGNAL(finished()), this, SLOT(checkLogin()));
this->connect(this, SIGNAL(currentOperationCancelled()), reply, SLOT(deleteLater()));
}
void FileStay::checkLogin() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());
if (!reply) {
emit error(NetworkError);
return;
}
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
switch (statusCode) {
case 302:
case 200:
case 201:
m_connections = 0;
emit loggedIn(true);
break;
default:
m_connections = 1;
emit loggedIn(false);
break;
}
reply->deleteLater();
}
void FileStay::checkUrl(const QUrl &webUrl) {
QNetworkRequest request(webUrl);
request.setRawHeader("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
QNetworkReply *reply = this->networkAccessManager()->get(request);
this->connect(reply, SIGNAL(finished()), this, SLOT(checkUrlIsValid()));
this->connect(this, SIGNAL(currentOperationCancelled()), reply, SLOT(deleteLater()));
}
void FileStay::checkUrlIsValid() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());
if (!reply) {
emit urlChecked(false);
return;
}
QString redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
QRegExp re("http://\\w+.filestay.com:\\d+/[^'\"]+");
if ((!redirect.isEmpty()) && (re.indexIn(redirect) == -1)) {
this->checkUrl(QUrl(redirect));
}
else {
QString response(reply->readAll());
if (response.contains("File Not Found")) {
emit urlChecked(false);
}
else {
QString fileName = response.section("fname\" value=\"", 1, 1).section('"', 0, 0);
if (fileName.isEmpty()) {
emit urlChecked(false);
}
else {
emit urlChecked(true, reply->request().url(), this->serviceName(), fileName);
}
}
}
reply->deleteLater();
}
void FileStay::getDownloadRequest(const QUrl &webUrl) {
emit statusChanged(Connecting);
m_url = webUrl;
QNetworkRequest request(webUrl);
request.setRawHeader("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
QNetworkReply *reply = this->networkAccessManager()->get(request);
this->connect(reply, SIGNAL(finished()), this, SLOT(onWebPageDownloaded()));
this->connect(this, SIGNAL(currentOperationCancelled()), reply, SLOT(deleteLater()));
}
void FileStay::onWebPageDownloaded() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());
if (!reply) {
emit error(NetworkError);
return;
}
QRegExp re("http://\\w+.filestay.com:\\d+/[^'\"]+");
QString redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
if (re.indexIn(redirect) == 0) {
QNetworkRequest request;
request.setUrl(QUrl(re.cap()));
emit downloadRequestReady(request);
}
else if (!redirect.isEmpty()) {
this->getDownloadRequest(QUrl(redirect));
}
else {
QString response(reply->readAll());
if (re.indexIn(response) >= 0) {
QNetworkRequest request;
request.setUrl(QUrl(re.cap()));
emit downloadRequestReady(request);
}
else if (response.contains("File Not Found")) {
emit error(NotFound);
}
else {
m_fileId = response.section("id\" value=\"", 1, 1).section('"', 0, 0);
m_fileName = response.section("fname\" value=\"", 1, 1).section('"', 0, 0);
if ((m_fileId.isEmpty()) || (m_fileName.isEmpty())) {
emit error(UnknownError);
}
else {
this->getWaitTime();
}
}
}
reply->deleteLater();
}
void FileStay::getWaitTime() {
QString data = QString("op=download1&id=%1&fname=%2&method_free=FREE DOWNLOAD").arg(m_fileId).arg(m_fileName);
QNetworkRequest request(m_url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QNetworkReply *reply = this->networkAccessManager()->post(request, data.toUtf8());
this->connect(reply, SIGNAL(finished()), this, SLOT(checkWaitTime()));
this->connect(this, SIGNAL(currentOperationCancelled()), reply, SLOT(deleteLater()));
}
void FileStay::checkWaitTime() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());
if (!reply) {
emit error(NetworkError);
return;
}
QString response(reply->readAll());
int mins = 0;
int secs = 0;
if (response.contains("You have to wait")) {
mins = response.section("You have to wait ", 1, 1).section(" minutes", 0, 0).toInt();
secs = response.section(" seconds before your next download", 0, 0).section(' ', 1, 1).toInt();
this->startWait((mins * 60000) + (secs + 1000));
this->connect(this, SIGNAL(waitFinished()), this, SLOT(onWaitFinished()));
}
else if (response.contains("You can download files up to ")) {
emit error(TrafficExceeded);
}
else if (response.contains("Only premium users can download this file")) {
this->setErrorString(tr("Premium account required"));
emit error(UnknownError);
}
else {
secs = response.section(QRegExp("countdown_str\">Wait <span id=\"\\w+\">"), 1, 1).section('<', 0, 0).toInt();
m_rand = response.section("rand\" value=\"", 1, 1).section('"', 0, 0);
m_captchaKey = response.section("http://www.google.com/recaptcha/api/challenge?k=", 1, 1).section('"', 0, 0);
if ((secs <= 0) || (m_rand.isEmpty()) || (m_captchaKey.isEmpty())) {
emit error(UnknownError);
}
else {
this->startWait(secs * 1000);
this->connect(this, SIGNAL(waitFinished()), this, SLOT(downloadCaptcha()));
}
}
reply->deleteLater();
}
void FileStay::downloadCaptcha() {
emit statusChanged(CaptchaRequired);
this->disconnect(this, SIGNAL(waitFinished()), this, SLOT(downloadCaptcha()));
}
void FileStay::submitCaptchaResponse(const QString &challenge, const QString &response) {
QString data = QString("op=download2&id=%1&fname=%2&rand=%3&method_free=FREE DOWNLOAD&down_direct=1&recaptcha_challenge_field=%4&recaptcha_response_field=%5").arg(m_fileId).arg(m_fileName).arg(m_rand).arg(challenge).arg(response);
QNetworkRequest request(m_url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QNetworkReply *reply = this->networkAccessManager()->post(request, data.toUtf8());
this->connect(reply, SIGNAL(finished()), this, SLOT(onCaptchaSubmitted()));
this->connect(this, SIGNAL(currentOperationCancelled()), reply, SLOT(deleteLater()));
}
void FileStay::onCaptchaSubmitted() {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(this->sender());
if (!reply) {
emit error(NetworkError);
return;
}
QRegExp re("http://\\w+.filestay.com:\\d+/[^'\"]+");
QString response(reply->readAll());
if (re.indexIn(response) >= 0) {
QNetworkRequest request;
request.setUrl(QUrl(re.cap()));
emit downloadRequestReady(request);
}
else if (response.contains("Wrong captcha")) {
emit error(CaptchaError);
}
else {
emit error(UnknownError);
}
reply->deleteLater();
}
void FileStay::startWait(int msecs) {
if (msecs > 60000) {
emit statusChanged(LongWait);
}
else {
emit statusChanged(ShortWait);
}
emit waiting(msecs);
m_waitTime = msecs;
m_waitTimer->start(1000);
}
void FileStay::updateWaitTime() {
m_waitTime -= m_waitTimer->interval();
emit waiting(m_waitTime);
if (m_waitTime <= 0) {
m_waitTimer->stop();
emit waitFinished();
}
}
void FileStay::onWaitFinished() {
emit statusChanged(Ready);
this->disconnect(this, SIGNAL(waitFinished()), this, SLOT(onWaitFinished()));
}
bool FileStay::cancelCurrentOperation() {
m_waitTimer->stop();
this->disconnect(this, SIGNAL(waitFinished()), this, 0);
emit currentOperationCancelled();
return true;
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(filestay, FileStay)
#endif
| lgpl-3.0 |
Bang3DEngine/Bang | Compile/CompileDependencies/ThirdParty/PhysX/PhysX_3.4/Source/PhysX/src/NpRigidDynamic.cpp | 1 | 19592 | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "NpRigidDynamic.h"
#include "NpRigidActorTemplateInternal.h"
using namespace physx;
NpRigidDynamic::NpRigidDynamic(const PxTransform& bodyPose)
: NpRigidDynamicT(PxConcreteType::eRIGID_DYNAMIC, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, PxActorType::eRIGID_DYNAMIC, bodyPose)
{}
NpRigidDynamic::~NpRigidDynamic()
{
}
// PX_SERIALIZATION
void NpRigidDynamic::requires(PxProcessPxBaseCallback& c)
{
NpRigidDynamicT::requires(c);
}
NpRigidDynamic* NpRigidDynamic::createObject(PxU8*& address, PxDeserializationContext& context)
{
NpRigidDynamic* obj = new (address) NpRigidDynamic(PxBaseFlag::eIS_RELEASABLE);
address += sizeof(NpRigidDynamic);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
//~PX_SERIALIZATION
void NpRigidDynamic::release()
{
releaseActorT(this, mBody);
}
void NpRigidDynamic::setGlobalPose(const PxTransform& pose, bool autowake)
{
NpScene* scene = NpActor::getAPIScene(*this);
#if PX_CHECKED
if(scene)
scene->checkPositionSanity(*this, pose, "PxRigidDynamic::setGlobalPose");
#endif
PX_CHECK_AND_RETURN(pose.isSane(), "PxRigidDynamic::setGlobalPose: pose is not valid.");
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
if(scene)
updateDynamicSceneQueryShapes(mShapeManager, scene->getSceneQueryManagerFast());
const PxTransform newPose = pose.getNormalized(); //AM: added to fix 1461 where users read and write orientations for no reason.
Scb::Body& b = getScbBodyFast();
const PxTransform body2World = newPose * b.getBody2Actor();
b.setBody2World(body2World, false);
// invalidate the pruning structure if the actor bounds changed
if(mShapeManager.getPruningStructure())
{
Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "PxRigidDynamic::setGlobalPose: Actor is part of a pruning structure, pruning structure is now invalid!");
mShapeManager.getPruningStructure()->invalidate(this);
}
if(scene && autowake && !(b.getActorFlags() & PxActorFlag::eDISABLE_SIMULATION))
wakeUpInternal();
}
PX_FORCE_INLINE void NpRigidDynamic::setKinematicTargetInternal(const PxTransform& targetPose)
{
Scb::Body& b = getScbBodyFast();
// The target is actor related. Transform to body related target
const PxTransform bodyTarget = targetPose * b.getBody2Actor();
b.setKinematicTarget(bodyTarget);
NpScene* scene = NpActor::getAPIScene(*this);
if ((b.getFlags() & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES) && scene)
{
updateDynamicSceneQueryShapes(mShapeManager, scene->getSceneQueryManagerFast());
}
}
void NpRigidDynamic::setKinematicTarget(const PxTransform& destination)
{
PX_CHECK_AND_RETURN(destination.isSane(), "PxRigidDynamic::setKinematicTarget: destination is not valid.");
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
#if PX_CHECKED
NpScene* scene = NpActor::getAPIScene(*this);
if(scene)
scene->checkPositionSanity(*this, destination, "PxRigidDynamic::setKinematicTarget");
Scb::Body& b = getScbBodyFast();
PX_CHECK_AND_RETURN((b.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setKinematicTarget: Body must be kinematic!");
PX_CHECK_AND_RETURN(scene, "PxRigidDynamic::setKinematicTarget: Body must be in a scene!");
PX_CHECK_AND_RETURN(!(b.getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::setKinematicTarget: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
#endif
setKinematicTargetInternal(destination.getNormalized());
}
bool NpRigidDynamic::getKinematicTarget(PxTransform& target) const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
const Scb::Body& b = getScbBodyFast();
if(b.getFlags() & PxRigidBodyFlag::eKINEMATIC)
{
PxTransform bodyTarget;
if(b.getKinematicTarget(bodyTarget))
{
// The internal target is body related. Transform to actor related target
target = bodyTarget * b.getBody2Actor().getInverse();
return true;
}
}
return false;
}
void NpRigidDynamic::setCMassLocalPose(const PxTransform& pose)
{
PX_CHECK_AND_RETURN(pose.isSane(), "PxRigidDynamic::setCMassLocalPose pose is not valid.");
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
const PxTransform p = pose.getNormalized();
const PxTransform oldBody2Actor = getScbBodyFast().getBody2Actor();
NpRigidDynamicT::setCMassLocalPoseInternal(p);
Scb::Body& b = getScbBodyFast();
if(b.getFlags() & PxRigidBodyFlag::eKINEMATIC)
{
PxTransform bodyTarget;
if(b.getKinematicTarget(bodyTarget))
{
PxTransform actorTarget = bodyTarget * oldBody2Actor.getInverse(); // get old target pose for the actor from the body target
setKinematicTargetInternal(actorTarget);
}
}
}
void NpRigidDynamic::setLinearDamping(PxReal linearDamping)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(PxIsFinite(linearDamping), "PxRigidDynamic::setLinearDamping: invalid float");
PX_CHECK_AND_RETURN(linearDamping >=0, "PxRigidDynamic::setLinearDamping: The linear damping must be nonnegative!");
getScbBodyFast().setLinearDamping(linearDamping);
}
PxReal NpRigidDynamic::getLinearDamping() const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
return getScbBodyFast().getLinearDamping();
}
void NpRigidDynamic::setAngularDamping(PxReal angularDamping)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(PxIsFinite(angularDamping), "PxRigidDynamic::setAngularDamping: invalid float");
PX_CHECK_AND_RETURN(angularDamping>=0, "PxRigidDynamic::setAngularDamping: The angular damping must be nonnegative!")
getScbBodyFast().setAngularDamping(angularDamping);
}
PxReal NpRigidDynamic::getAngularDamping() const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
return getScbBodyFast().getAngularDamping();
}
void NpRigidDynamic::setLinearVelocity(const PxVec3& velocity, bool autowake)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(velocity.isFinite(), "PxRigidDynamic::setLinearVelocity: velocity is not valid.");
PX_CHECK_AND_RETURN(!(getScbBodyFast().getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setLinearVelocity: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(getScbBodyFast().getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::setLinearVelocity: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
Scb::Body& b = getScbBodyFast();
b.setLinearVelocity(velocity);
NpScene* scene = NpActor::getAPIScene(*this);
if(scene)
wakeUpInternalNoKinematicTest(b, (!velocity.isZero()), autowake);
}
void NpRigidDynamic::setAngularVelocity(const PxVec3& velocity, bool autowake)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(velocity.isFinite(), "PxRigidDynamic::setAngularVelocity: velocity is not valid.");
PX_CHECK_AND_RETURN(!(getScbBodyFast().getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setAngularVelocity: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(getScbBodyFast().getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::setAngularVelocity: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
Scb::Body& b = getScbBodyFast();
b.setAngularVelocity(velocity);
NpScene* scene = NpActor::getAPIScene(*this);
if(scene)
wakeUpInternalNoKinematicTest(b, (!velocity.isZero()), autowake);
}
void NpRigidDynamic::setMaxAngularVelocity(PxReal maxAngularVelocity)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(PxIsFinite(maxAngularVelocity), "PxRigidDynamic::setMaxAngularVelocity: invalid float");
PX_CHECK_AND_RETURN(maxAngularVelocity>=0.0f, "PxRigidDynamic::setMaxAngularVelocity: threshold must be non-negative!");
getScbBodyFast().setMaxAngVelSq(maxAngularVelocity * maxAngularVelocity);
}
PxReal NpRigidDynamic::getMaxAngularVelocity() const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
return PxSqrt(getScbBodyFast().getMaxAngVelSq());
}
void NpRigidDynamic::addForce(const PxVec3& force, PxForceMode::Enum mode, bool autowake)
{
Scb::Body& b = getScbBodyFast();
PX_CHECK_AND_RETURN(force.isFinite(), "PxRigidDynamic::addForce: force is not valid.");
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(NpActor::getAPIScene(*this), "PxRigidDynamic::addForce: Body must be in a scene!");
PX_CHECK_AND_RETURN(!(b.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::addForce: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(b.getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::addForce: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
addSpatialForce(&force, NULL, mode);
wakeUpInternalNoKinematicTest(b, (!force.isZero()), autowake);
}
void NpRigidDynamic::addTorque(const PxVec3& torque, PxForceMode::Enum mode, bool autowake)
{
Scb::Body& b = getScbBodyFast();
PX_CHECK_AND_RETURN(torque.isFinite(), "PxRigidDynamic::addTorque: torque is not valid.");
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(NpActor::getAPIScene(*this), "PxRigidDynamic::addTorque: Body must be in a scene!");
PX_CHECK_AND_RETURN(!(b.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::addTorque: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(b.getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::addTorque: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
addSpatialForce(NULL, &torque, mode);
wakeUpInternalNoKinematicTest(b, (!torque.isZero()), autowake);
}
void NpRigidDynamic::clearForce(PxForceMode::Enum mode)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(NpActor::getAPIScene(*this), "PxRigidDynamic::clearForce: Body must be in a scene!");
PX_CHECK_AND_RETURN(!(getScbBodyFast().getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::clearForce: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(getScbBodyFast().getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::clearForce: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
clearSpatialForce(mode, true, false);
}
void NpRigidDynamic::clearTorque(PxForceMode::Enum mode)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(NpActor::getAPIScene(*this), "PxRigidDynamic::clearTorque: Body must be in a scene!");
PX_CHECK_AND_RETURN(!(getScbBodyFast().getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::clearTorque: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(getScbBodyFast().getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::clearTorque: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
clearSpatialForce(mode, false, true);
}
bool NpRigidDynamic::isSleeping() const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN_VAL(NpActor::getAPIScene(*this), "PxRigidDynamic::isSleeping: Body must be in a scene.", true);
return getScbBodyFast().isSleeping();
}
void NpRigidDynamic::setSleepThreshold(PxReal threshold)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setSleepThreshold: invalid float.");
PX_CHECK_AND_RETURN(threshold>=0.0f, "PxRigidDynamic::setSleepThreshold: threshold must be non-negative!");
getScbBodyFast().setSleepThreshold(threshold);
}
PxReal NpRigidDynamic::getSleepThreshold() const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
return getScbBodyFast().getSleepThreshold();
}
void NpRigidDynamic::setStabilizationThreshold(PxReal threshold)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setSleepThreshold: invalid float.");
PX_CHECK_AND_RETURN(threshold>=0.0f, "PxRigidDynamic::setSleepThreshold: threshold must be non-negative!");
getScbBodyFast().setFreezeThreshold(threshold);
}
PxReal NpRigidDynamic::getStabilizationThreshold() const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
return getScbBodyFast().getFreezeThreshold();
}
void NpRigidDynamic::setWakeCounter(PxReal wakeCounterValue)
{
Scb::Body& b = getScbBodyFast();
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(PxIsFinite(wakeCounterValue), "PxRigidDynamic::setWakeCounter: invalid float.");
PX_CHECK_AND_RETURN(wakeCounterValue>=0.0f, "PxRigidDynamic::setWakeCounter: wakeCounterValue must be non-negative!");
PX_CHECK_AND_RETURN(!(b.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setWakeCounter: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(b.getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::setWakeCounter: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
b.setWakeCounter(wakeCounterValue);
}
PxReal NpRigidDynamic::getWakeCounter() const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
return getScbBodyFast().getWakeCounter();
}
void NpRigidDynamic::wakeUp()
{
Scb::Body& b = getScbBodyFast();
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(NpActor::getAPIScene(*this), "PxRigidDynamic::wakeUp: Body must be in a scene.");
PX_CHECK_AND_RETURN(!(b.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::wakeUp: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(b.getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::wakeUp: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
b.wakeUp();
}
void NpRigidDynamic::putToSleep()
{
Scb::Body& b = getScbBodyFast();
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(NpActor::getAPIScene(*this), "PxRigidDynamic::putToSleep: Body must be in a scene.");
PX_CHECK_AND_RETURN(!(b.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::putToSleep: Body must be non-kinematic!");
PX_CHECK_AND_RETURN(!(b.getActorFlags() & PxActorFlag::eDISABLE_SIMULATION), "PxRigidDynamic::putToSleep: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!");
b.putToSleep();
}
void NpRigidDynamic::setSolverIterationCounts(PxU32 positionIters, PxU32 velocityIters)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(positionIters > 0, "PxRigidDynamic::setSolverIterationCount: positionIters must be more than zero!");
PX_CHECK_AND_RETURN(positionIters <= 255, "PxRigidDynamic::setSolverIterationCount: positionIters must be no greater than 255!");
PX_CHECK_AND_RETURN(velocityIters > 0, "PxRigidDynamic::setSolverIterationCount: velocityIters must be more than zero!");
PX_CHECK_AND_RETURN(velocityIters <= 255, "PxRigidDynamic::setSolverIterationCount: velocityIters must be no greater than 255!");
getScbBodyFast().setSolverIterationCounts((velocityIters & 0xff) << 8 | (positionIters & 0xff));
}
void NpRigidDynamic::getSolverIterationCounts(PxU32 & positionIters, PxU32 & velocityIters) const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
PxU16 x = getScbBodyFast().getSolverIterationCounts();
velocityIters = PxU32(x >> 8);
positionIters = PxU32(x & 0xff);
}
void NpRigidDynamic::setContactReportThreshold(PxReal threshold)
{
NP_WRITE_CHECK(NpActor::getOwnerScene(*this));
PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setContactReportThreshold: invalid float.");
PX_CHECK_AND_RETURN(threshold >= 0.0f, "PxRigidDynamic::setContactReportThreshold: Force threshold must be greater than zero!");
getScbBodyFast().setContactReportThreshold(threshold<0 ? 0 : threshold);
}
PxReal NpRigidDynamic::getContactReportThreshold() const
{
NP_READ_CHECK(NpActor::getOwnerScene(*this));
return getScbBodyFast().getContactReportThreshold();
}
PxU32 physx::NpRigidDynamicGetShapes(Scb::Body& body, void* const*& shapes)
{
NpRigidDynamic* a = static_cast<NpRigidDynamic*>(body.getScBody().getPxActor());
NpShapeManager& sm = a->getShapeManager();
shapes = reinterpret_cast<void *const *>(sm.getShapes());
return sm.getNbShapes();
}
void NpRigidDynamic::switchToNoSim()
{
getScbBodyFast().switchBodyToNoSim();
}
void NpRigidDynamic::switchFromNoSim()
{
getScbBodyFast().switchFromNoSim(true);
}
void NpRigidDynamic::wakeUpInternalNoKinematicTest(Scb::Body& body, bool forceWakeUp, bool autowake)
{
NpScene* scene = NpActor::getOwnerScene(*this);
PX_ASSERT(scene);
PxReal wakeCounterResetValue = scene->getWakeCounterResetValueInteral();
PxReal wakeCounter = body.getWakeCounter();
bool needsWakingUp = body.isSleeping() && (autowake || forceWakeUp);
if (autowake && (wakeCounter < wakeCounterResetValue))
{
wakeCounter = wakeCounterResetValue;
needsWakingUp = true;
}
if (needsWakingUp)
body.wakeUpInternal(wakeCounter);
}
PxRigidDynamicLockFlags NpRigidDynamic::getRigidDynamicLockFlags() const
{
return mBody.getLockFlags();
}
void NpRigidDynamic::setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags)
{
mBody.setLockFlags(flags);
}
void NpRigidDynamic::setRigidDynamicLockFlag(PxRigidDynamicLockFlag::Enum flag, bool value)
{
PxRigidDynamicLockFlags flags = mBody.getLockFlags();
if (value)
flags = flags | flag;
else
flags = flags & (~flag);
mBody.setLockFlags(flags);
}
#if PX_ENABLE_DEBUG_VISUALIZATION
void NpRigidDynamic::visualize(Cm::RenderOutput& out, NpScene* npScene)
{
NpRigidDynamicT::visualize(out, npScene);
if (getScbBodyFast().getActorFlags() & PxActorFlag::eVISUALIZATION)
{
PX_ASSERT(npScene);
const PxReal scale = npScene->getVisualizationParameter(PxVisualizationParameter::eSCALE);
const PxReal massAxes = scale * npScene->getVisualizationParameter(PxVisualizationParameter::eBODY_MASS_AXES);
if (massAxes != 0.0f)
{
PxReal sleepTime = getScbBodyFast().getWakeCounter() / npScene->getWakeCounterResetValueInteral();
PxU32 color = PxU32(0xff * (sleepTime>1.0f ? 1.0f : sleepTime));
color = getScbBodyFast().isSleeping() ? 0xff0000 : (color<<16 | color<<8 | color);
PxVec3 dims = invertDiagInertia(getScbBodyFast().getInverseInertia());
dims = getDimsFromBodyInertia(dims, 1.0f / getScbBodyFast().getInverseMass());
out << color << getScbBodyFast().getBody2World() << Cm::DebugBox(dims * 0.5f);
}
}
}
#endif
| lgpl-3.0 |
bsc-pm/mcxx | tests/07_phases_ompss.dg/cxx/success_static_data_member02.cpp | 1 | 1999 | /*--------------------------------------------------------------------
(C) Copyright 2006-2012 Barcelona Supercomputing Center
Centro Nacional de Supercomputacion
This file is part of Mercurium C/C++ source-to-source compiler.
See AUTHORS file in the top level directory for information
regarding developers and contributors.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
Mercurium C/C++ source-to-source compiler is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public
License along with Mercurium C/C++ source-to-source compiler; if
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA.
--------------------------------------------------------------------*/
/*
<testinfo>
test_generator=(config/mercurium-ompss "config/mercurium-ompss-2 openmp-compatibility")
</testinfo>
*/
#include<assert.h>
struct Test
{
static int n;
static int m;
int x;
#pragma omp task inout(n,m,x,s)
void foo(int & s)
{
n++;
m++;
x++;
s++;
}
};
void inc(int * ptr)
{
(*ptr)++;
}
int Test::n = 1;
int Test::m = 1;
int main()
{
Test a,b;
int * ptr_n = &(Test::n);
assert(Test::n == 1 && Test::m == 1);
a.foo(Test::m);
#pragma omp taskwait
assert(Test::n == 2 && Test::m == 3);
b.foo(Test::m);
#pragma omp taskwait
assert(Test::n == 3 && Test::m == 5);
inc(ptr_n);
assert(Test::n == 4 && Test::m == 5);
}
| lgpl-3.0 |
kilobyte/termrec | tests/vtmir.c | 1 | 1439 | #include "config.h"
#include <tty.h>
#include <stdio.h>
#include "sys/compat.h"
#include "sys/threads.h"
#include "sys/error.h"
#include <stdint.h>
#include <unistd.h>
static tty vt1, vt2;
#define BUFFER_SIZE 128
static void copier(void *args)
{
int fd=(intptr_t)args;
char buf[BUFFER_SIZE];
int len;
while ((len=read(fd, buf, BUFFER_SIZE))>0)
tty_write(vt2, buf, len);
}
static void dump(tty vt)
{
int x,y,c;
for (y=0;y<vt->sy;y++)
{
for (x=0;x<vt->sx;x++)
{
c=vt->scr[y*vt->sx+x].ch;
printf((c>=32 && c<127)?"%lc":"[U+%04X]", c);
}
printf("|\n");
}
printf("===================='\n");
}
#define BUF2 42
int main(void)
{
thread_t cop;
int p[2];
FILE *f;
char buf[BUF2];
int len, i;
vt1=tty_init(20, 5, 0);
vt2=tty_init(20, 5, 0);
if (pipe(p))
die("pipe()");
if (thread_create_joinable(&cop, copier, (void*)(intptr_t)p[0]))
die("thread creation");
f=fdopen(p[1], "w");
vtvt_attach(vt1, f, 0);
while ((len=read(0, buf, BUF2))>0)
tty_write(vt1, buf, len);
fclose(f);
thread_join(cop);
for (i=0; i<vt1->sx*vt1->sy; i++)
if (vt1->scr[i].ch!=vt2->scr[i].ch || vt1->scr[i].attr!=vt2->scr[i].attr)
{
printf("Mismatch! Dumps:\n");
dump(vt1);
dump(vt2);
return 1;
}
return 0;
}
| lgpl-3.0 |
zhuyue1314/Triton | src/ir/builders/ShrIRBuilder.cpp | 1 | 4136 | #include <iostream>
#include <sstream>
#include <stdexcept>
#include <ShrIRBuilder.h>
#include <Registers.h>
#include <SMT2Lib.h>
#include <SymbolicElement.h>
ShrIRBuilder::ShrIRBuilder(uint64_t address, const std::string &disassembly):
BaseIRBuilder(address, disassembly) {
}
void ShrIRBuilder::regImm(AnalysisProcessor &ap, Inst &inst) const {
SymbolicElement *se;
std::stringstream expr, op1, op2;
uint64_t reg = this->operands[0].getValue();
uint64_t imm = this->operands[1].getValue();
uint32_t regSize = this->operands[0].getSize();
/* Create the SMT semantic */
op1 << ap.buildSymbolicRegOperand(reg, regSize);
op2 << smt2lib::bv(imm, regSize * REG_SIZE);
/* Finale expr */
expr << smt2lib::bvlshr(op1.str(), op2.str());
/* Create the symbolic element */
se = ap.createRegSE(inst, expr, reg, regSize);
/* Apply the taint */
ap.aluSpreadTaintRegReg(se, reg, reg);
/* Add the symbolic flags element to the current inst */
EflagsBuilder::cfShr(inst, se, ap, regSize, op1, op2);
EflagsBuilder::ofShr(inst, se, ap, regSize, op1, op2);
EflagsBuilder::pfShl(inst, se, ap, regSize, op2); /* Same that shl */
EflagsBuilder::sfShl(inst, se, ap, regSize, op2); /* Same that shl */
EflagsBuilder::zfShl(inst, se, ap, regSize, op2); /* Same that shl */
}
void ShrIRBuilder::regReg(AnalysisProcessor &ap, Inst &inst) const {
SymbolicElement *se;
std::stringstream expr, op1, op2;
uint64_t reg = this->operands[0].getValue();
uint32_t regSize = this->operands[0].getSize();
/* Create the SMT semantic */
op1 << ap.buildSymbolicRegOperand(reg, regSize);
op2 << smt2lib::zx(ap.buildSymbolicRegOperand(ID_RCX, 1), (regSize - 1) * REG_SIZE);
/* Finale expr */
expr << smt2lib::bvlshr(op1.str(), op2.str());
/* Create the symbolic element */
se = ap.createRegSE(inst, expr, reg, regSize);
/* Apply the taint */
ap.aluSpreadTaintRegReg(se, reg, reg);
/* Add the symbolic flags element to the current inst */
EflagsBuilder::cfShr(inst, se, ap, regSize, op1, op2);
EflagsBuilder::ofShr(inst, se, ap, regSize, op1, op2);
EflagsBuilder::pfShl(inst, se, ap, regSize, op2); /* Same that shl */
EflagsBuilder::sfShl(inst, se, ap, regSize, op2); /* Same that shl */
EflagsBuilder::zfShl(inst, se, ap, regSize, op2); /* Same that shl */
}
void ShrIRBuilder::regMem(AnalysisProcessor &ap, Inst &inst) const {
TwoOperandsTemplate::stop(this->disas);
}
void ShrIRBuilder::memImm(AnalysisProcessor &ap, Inst &inst) const {
SymbolicElement *se;
std::stringstream expr, op1, op2;
uint32_t writeSize = this->operands[0].getSize();
uint64_t mem = this->operands[0].getValue();
uint64_t imm = this->operands[1].getValue();
/* Create the SMT semantic */
op1 << ap.buildSymbolicMemOperand(mem, writeSize);
op2 << smt2lib::bv(imm, writeSize * REG_SIZE);
/* Final expr */
expr << smt2lib::bvlshr(op1.str(), op2.str());
/* Create the symbolic element */
se = ap.createMemSE(inst, expr, mem, writeSize);
/* Apply the taint */
ap.aluSpreadTaintMemMem(se, mem, mem, writeSize);
/* Add the symbolic flags element to the current inst */
EflagsBuilder::cfShr(inst, se, ap, writeSize, op1, op2);
EflagsBuilder::ofShr(inst, se, ap, writeSize, op1, op2);
EflagsBuilder::pfShl(inst, se, ap, writeSize, op2) /* Same that shl */;
EflagsBuilder::sfShl(inst, se, ap, writeSize, op2) /* Same that shl */;
EflagsBuilder::zfShl(inst, se, ap, writeSize, op2) /* Same that shl */;
}
void ShrIRBuilder::memReg(AnalysisProcessor &ap, Inst &inst) const {
TwoOperandsTemplate::stop(this->disas);
}
Inst *ShrIRBuilder::process(AnalysisProcessor &ap) const {
this->checkSetup();
Inst *inst = new Inst(ap.getThreadID(), this->address, this->disas);
try {
this->templateMethod(ap, *inst, this->operands, "SHR");
ap.incNumberOfExpressions(inst->numberOfElements()); /* Used for statistics */
ControlFlow::rip(*inst, ap, this->nextAddress);
}
catch (std::exception &e) {
delete inst;
throw;
}
return inst;
}
| lgpl-3.0 |
boinc-next/boinc-client | client/time_stats.cpp | 2 | 14046 | // This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2008 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC. If not, see <http://www.gnu.org/licenses/>.
#include "config.h"
#include <cstdio>
#include <ctime>
#include <cmath>
#include <cstring>
#include <sys/socket.h>
#include "error_numbers.h"
#include "filesys.h"
#include "parse.h"
#include "util.h"
#include "client_msgs.h"
#include "client_state.h"
#include "file_names.h"
#include "log_flags.h"
#include "network.h"
#include "time_stats.h"
#define CONNECTED_STATE_UNINITIALIZED -1
#define CONNECTED_STATE_NOT_CONNECTED 0
#define CONNECTED_STATE_CONNECTED 1
#define CONNECTED_STATE_UNKNOWN 2
// anyone know how to see if this host has physical network connection?
//
int get_connected_state() {
return CONNECTED_STATE_UNKNOWN;
}
// exponential decay constant.
// The last 10 days have a weight of 1/e;
// everything before that has a weight of (1-1/e)
const float ALPHA = (SECONDS_PER_DAY*10);
//const float ALPHA = 60; // for testing
// called before the client state file is parsed
//
void CLIENT_TIME_STATS::init() {
// members of TIME_STATS
now = 0;
on_frac = 1;
connected_frac = 1;
cpu_and_network_available_frac = 1;
active_frac = 1;
gpu_active_frac = 1;
client_start_time = gstate.now;
previous_uptime = 0;
session_active_duration = 0;
session_gpu_active_duration = 0;
total_start_time = 0;
total_duration = 0;
total_active_duration = 0;
total_gpu_active_duration = 0;
// members of CLIENT_TIME_STATS
first = true;
previous_connected_state = CONNECTED_STATE_UNINITIALIZED;
last_update = 0;
inactive_start = 0;
trim_stats_log();
time_stats_log = NULL;
}
// if log file is over a meg, discard everything older than a year
//
void CLIENT_TIME_STATS::trim_stats_log() {
double size;
char buf[256];
int retval;
double x;
retval = file_size(TIME_STATS_LOG, size);
if (retval) return;
if (size < 1e6) return;
FILE* f = fopen(TIME_STATS_LOG, "r");
if (!f) return;
FILE* f2 = fopen(TEMP_TIME_STATS_FILE_NAME, "w");
if (!f2) {
fclose(f);
return;
}
while (fgets(buf, 256, f)) {
int n = sscanf(buf, "%lf", &x);
if (n != 1) continue;
if (x < gstate.now-86400*365) continue;
fputs(buf, f2);
}
fclose(f);
fclose(f2);
}
void send_log_after(const char* filename, double t, MIOFILE& mf) {
char buf[256];
double x;
FILE* f = fopen(filename, "r");
if (!f) return;
while (fgets(buf, 256, f)) {
int n = sscanf(buf, "%lf", &x);
if (n != 1) continue;
if (x < t) continue;
print(mf, buf);
}
fclose(f);
}
// copy the log file after a given time
//
void CLIENT_TIME_STATS::get_log_after(double t, MIOFILE& mf) {
if (time_stats_log) {
fclose(time_stats_log); // win: can't open twice
}
send_log_after(TIME_STATS_LOG, t, mf);
time_stats_log = fopen(TIME_STATS_LOG, "a");
}
// Update time statistics based on current activities
// NOTE: we don't set the state-file dirty flag here,
// so these get written to disk only when other activities
// cause this to happen. Maybe should change this.
//
void CLIENT_TIME_STATS::update(int suspend_reason, int _gpu_suspend_reason) {
double dt, w1, w2;
bool is_active = (suspend_reason == 0);
bool is_gpu_active = is_active && !_gpu_suspend_reason;
if (total_start_time == 0) {
total_start_time = gstate.now;
}
if (last_update == 0) {
// this is the first time this client has executed.
// Assume that everything is active
on_frac = 1;
connected_frac = 1;
active_frac = 1;
gpu_active_frac = 1;
cpu_and_network_available_frac = 1;
first = false;
last_update = gstate.now;
log_append("power_on", gstate.now);
} else {
dt = gstate.now - last_update;
if (dt <= 10) return;
if (dt > 14*86400) {
// If dt is large it could be because user is upgrading
// from a client version that wasn't updating due to bug.
// Or it could be because user wasn't running for a while
// and is starting up again.
// In either case, don't decay on_frac.
//
dt = 0;
}
w1 = 1 - exp(-dt/ALPHA); // weight for recent period
w2 = 1 - w1; // weight for everything before that
// (close to zero if long gap)
int connected_state;
connected_state = get_connected_state();
if (gstate.network_suspend_reason) {
connected_state = CONNECTED_STATE_NOT_CONNECTED;
}
if (first) {
// the client has just started; this is the first call.
//
on_frac *= w2;
first = false;
log_append("power_off", last_update);
char buf[256];
safe_print(buf,
"platform %s",
gstate.get_platform().data()
);
log_append(buf, gstate.now);
safe_print(buf,
"version %d.%d.%d",
BOINC_MAJOR_VERSION, BOINC_MINOR_VERSION, BOINC_RELEASE
);
log_append(buf, gstate.now);
log_append("power_on", gstate.now);
} else if (dt > 100) {
// large dt - the client or host must have been suspended
on_frac *= w2;
log_append("proc_stop", last_update);
if (is_active) {
log_append("proc_start", gstate.now);
}
} else {
on_frac = w1 + w2*on_frac;
cpu_and_network_available_frac *= w2;
if (connected_frac < 0) connected_frac = 0;
switch (connected_state) {
case CONNECTED_STATE_NOT_CONNECTED:
connected_frac *= w2;
break;
case CONNECTED_STATE_CONNECTED:
connected_frac *= w2;
connected_frac += w1;
if (!gstate.network_suspended && !gstate.tasks_suspended) {
cpu_and_network_available_frac += w1;
}
break;
case CONNECTED_STATE_UNKNOWN:
connected_frac = -1;
if (!gstate.network_suspended && !gstate.tasks_suspended) {
cpu_and_network_available_frac += w1;
}
}
if (connected_state != previous_connected_state) {
log_append_net(connected_state);
previous_connected_state = connected_state;
}
active_frac *= w2;
total_duration += dt;
if (is_active) {
active_frac += w1;
if (inactive_start) {
inactive_start = 0;
log_append("proc_start", gstate.now);
}
session_active_duration += dt;
total_active_duration += dt;
} else if (inactive_start == 0){
inactive_start = gstate.now;
log_append("proc_stop", gstate.now);
}
gpu_active_frac *= w2;
if (is_gpu_active) {
gpu_active_frac += w1;
session_gpu_active_duration += dt;
total_gpu_active_duration += dt;
}
//msg_printf(NULL, MSG_INFO, "is_active %d, active_frac %f", is_active, active_frac);
}
last_update = gstate.now;
if (log_flags.time_debug) {
msg_printf(0, MSG_INFO,
"[time] dt %f susp_reason %d gpu_susp_reason %d",
dt, suspend_reason, _gpu_suspend_reason
);
msg_printf(0, MSG_INFO,
"[time] w2 %f on %f; active %f; gpu_active %f; conn %f, cpu_and_net_avail %f",
w2, on_frac, active_frac, gpu_active_frac, connected_frac,
cpu_and_network_available_frac
);
}
}
}
// Write time statistics
// to_remote means GUI RPC reply; else writing client state file
//
int CLIENT_TIME_STATS::write(MIOFILE& out, bool to_remote) {
print(out,
"<time_stats>\n"
" <on_frac>%f</on_frac>\n"
" <connected_frac>%f</connected_frac>\n"
" <cpu_and_network_available_frac>%f</cpu_and_network_available_frac>\n"
" <active_frac>%f</active_frac>\n"
" <gpu_active_frac>%f</gpu_active_frac>\n"
" <client_start_time>%f</client_start_time>\n"
" <total_start_time>%f</total_start_time>\n"
" <total_duration>%f</total_duration>\n"
" <total_active_duration>%f</total_active_duration>\n"
" <total_gpu_active_duration>%f</total_gpu_active_duration>\n",
on_frac,
connected_frac,
cpu_and_network_available_frac,
active_frac,
gpu_active_frac,
client_start_time,
total_start_time,
total_duration,
total_active_duration,
total_gpu_active_duration
);
if (to_remote) {
print(out,
" <now>%f</now>\n"
" <previous_uptime>%f</previous_uptime>\n"
" <session_active_duration>%f</session_active_duration>\n"
" <session_gpu_active_duration>%f</session_gpu_active_duration>\n",
gstate.now,
previous_uptime,
session_active_duration,
session_gpu_active_duration
);
} else {
print(out,
" <previous_uptime>%f</previous_uptime>\n"
" <last_update>%f</last_update>\n",
gstate.now - client_start_time,
last_update
);
}
print(out, "</time_stats>\n");
return 0;
}
// Parse XML based time statistics from client_state.xml
//
int CLIENT_TIME_STATS::parse(XML_PARSER& xp) {
double x;
while (!xp.get_tag()) {
if (xp.match_tag("/time_stats")) {
return 0;
}
if (xp.parse_double("last_update", x)) {
if (x < 0 || x > gstate.now) {
msg_printf(0, MSG_INTERNAL_ERROR,
"bad value %f of time stats last update; ignoring", x
);
} else {
last_update = x;
}
continue;
}
if (xp.parse_double("on_frac", x)) {
if (x <= 0 || x > 1) {
msg_printf(0, MSG_INTERNAL_ERROR,
"bad value %f of time stats on_frac; ignoring", x
);
} else {
on_frac = x;
}
continue;
}
if (xp.parse_double("connected_frac", x)) {
// -1 means undefined; skip check
connected_frac = x;
continue;
}
if (xp.parse_double("cpu_and_network_available_frac", x)) {
if (x <= 0 || x > 1) {
msg_printf(0, MSG_INTERNAL_ERROR,
"bad value %f of time stats cpu_and_network_available_frac; ignoring", x
);
} else {
cpu_and_network_available_frac = x;
}
continue;
}
if (xp.parse_double("active_frac", x)) {
if (x <= 0 || x > 1) {
msg_printf(0, MSG_INTERNAL_ERROR,
"bad value %f of time stats active_frac; ignoring", x
);
} else {
active_frac = x;
}
continue;
}
if (xp.parse_double("gpu_active_frac", x)) {
if (x <= 0 || x > 1) {
msg_printf(0, MSG_INTERNAL_ERROR,
"bad value %f of time stats gpu_active_frac; ignoring", x
);
} else {
gpu_active_frac = x;
}
continue;
}
if (xp.parse_double("client_start_time", x)) continue;
if (xp.parse_double("previous_uptime", previous_uptime)) continue;
if (xp.parse_double("total_start_time", total_start_time)) continue;
if (xp.parse_double("total_duration", total_duration)) continue;
if (xp.parse_double("total_active_duration", total_active_duration)) continue;
if (xp.parse_double("total_gpu_active_duration", total_gpu_active_duration)) continue;
if (log_flags.unparsed_xml) {
msg_printf(0, MSG_INFO,
"[unparsed_xml] TIME_STATS::parse(): unrecognized: %s\n",
xp.parsed_tag
);
}
}
return ERR_XML_PARSE;
}
void CLIENT_TIME_STATS::start() {
time_stats_log = fopen(TIME_STATS_LOG, "a");
if (time_stats_log) {
setbuf(time_stats_log, 0);
}
}
void CLIENT_TIME_STATS::quit() {
log_append("power_off", gstate.now);
}
void CLIENT_TIME_STATS::log_append(const char* msg, double t) {
if (!time_stats_log) return;
print(time_stats_log, "%f %s\n", t, msg);
}
void CLIENT_TIME_STATS::log_append_net(int new_state) {
switch(new_state) {
case CONNECTED_STATE_NOT_CONNECTED:
log_append("net_not_connected", gstate.now);
break;
case CONNECTED_STATE_CONNECTED:
log_append("net_connected", gstate.now);
break;
case CONNECTED_STATE_UNKNOWN:
log_append("net_unknown", gstate.now);
break;
}
}
| lgpl-3.0 |
AdamYuan/CubeCraft | dep/FastNoiseSIMD/FastNoiseSIMD_avx512.cpp | 2 | 2004 | // FastNoiseSIMD_avx512.cpp
//
// MIT License
//
// Copyright(c) 2017 Jordan Peck
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// The developer's email is jorzixdan.me2@gzixmail.com (for great email, take
// off every 'zix'.)
//
#include "FastNoiseSIMD.h"
// DISABLE WHOLE PROGRAM OPTIMIZATION for this file when using MSVC
// To compile AVX512 support enable AVX(2) code generation compiler flags for this file
#ifdef FN_COMPILE_AVX512
#ifndef __AVX__
#ifdef __GNUC__
#error To compile AVX512 add build command "-march=core-avx2" on FastNoiseSIMD_avx512.cpp, or remove "#define FN_COMPILE_AVX512" from FastNoiseSIMD.h
#else
#error To compile AVX512 set C++ code generation to use /arch:AVX(2) on FastNoiseSIMD_avx512.cpp, or remove "#define FN_COMPILE_AVX512" from FastNoiseSIMD.h
#endif
#endif
#define SIMD_LEVEL_H FN_AVX512
#include "FastNoiseSIMD_internal.h"
#include <intrin.h> //AVX512
#define SIMD_LEVEL FN_AVX512
#include "FastNoiseSIMD_internal.cpp"
#endif | lgpl-3.0 |
eisoku9618/openrtm_aist-release | src/lib/doil/utils/omniidl_be/tests/unitTest/ConfigurationServant/ConfigurationServantTests.cpp | 4 | 13325 | // -*- C++ -*-
/*!
* @file ConfigurationServantTests.cpp
* @brief ConfigurationServant test class
* @date $Date$
* @author Noriaki Ando <n-ando@aist.go.jp>
*
* $Id$
*
*/
/*
* $Log$
*
*/
#ifndef ConfigurationServant_cpp
#define ConfigurationServant_cpp
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestAssert.h>
#include <ConfigurationServant.h>
#include <coil/Properties.h>
#include <doil/ImplBase.h>
#include <doil/ServantFactory.h>
#include <doil/corba/CORBAManager.h>
#include <doil/corba/CORBAServantBase.h>
#include <IConfiguration.h>
#include <stubs/ConfigurationImpl.h>
#include <stubs/Logger.h>
/*!
* @class ConfigurationServantTests class
* @brief ConfigurationServant test
*/
namespace ConfigurationServant
{
class ConfigurationServantTests
: public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(ConfigurationServantTests);
CPPUNIT_TEST(test_call_set_device_profile);
CPPUNIT_TEST(test_call_set_service_profile);
CPPUNIT_TEST(test_call_add_organization);
CPPUNIT_TEST(test_call_remove_service_profile);
CPPUNIT_TEST(test_call_remove_organization);
CPPUNIT_TEST(test_call_get_configuration_parameters);
CPPUNIT_TEST(test_call_get_configuration_parameter_values);
CPPUNIT_TEST(test_call_get_configuration_parameter_value);
CPPUNIT_TEST(test_call_set_configuration_parameter);
CPPUNIT_TEST(test_call_get_configuration_sets);
CPPUNIT_TEST(test_call_get_configuration_set);
CPPUNIT_TEST(test_call_set_configuration_set_values);
CPPUNIT_TEST(test_call_get_active_configuration_set);
CPPUNIT_TEST(test_call_add_configuration_set);
CPPUNIT_TEST(test_call_remove_configuration_set);
CPPUNIT_TEST(test_call_activate_configuration_set);
CPPUNIT_TEST_SUITE_END();
private:
::UnitTest::Servant::ConfigurationImpl* Impl;
::UnitTest::Servant::Logger Log;
::doil::ServantBase* Servant;
::SDOPackage::CORBA::ConfigurationServant * CServant;
public:
/*!
* @brief Constructor
*/
ConfigurationServantTests()
{
// registerFactory
Impl = new UnitTest::Servant::ConfigurationImpl(Log);
doil::CORBA::CORBAManager::instance().registerFactory(Impl->id(),
doil::New<SDOPackage::CORBA::ConfigurationServant>,
doil::Delete<SDOPackage::CORBA::ConfigurationServant>);
doil::ReturnCode_t ret = doil::CORBA::CORBAManager::instance().activateObject(Impl);
Servant = doil::CORBA::CORBAManager::instance().toServant(Impl);
CServant = dynamic_cast<SDOPackage::CORBA::ConfigurationServant*>(Servant);
// std::cout << "ConfigurationServantTests-constractor" << std::endl;
}
/*!
* @brief Destructor
*/
~ConfigurationServantTests()
{
delete Impl;
Impl = 0;
}
/*!
* @brief Test initialization
*/
virtual void setUp()
{
// std::cout << "ConfigurationServantTests-setUp" << std::endl;
}
/*!
* @brief Test finalization
*/
virtual void tearDown()
{
// std::cout << "ConfigurationServantTests-tearDown" << std::endl;
}
/* test case */
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_set_device_profile()
{
CPPUNIT_ASSERT(CServant);
std::string str("set_device_profile");
::SDOPackage::DeviceProfile dp;
::CORBA::Boolean result;
result = CServant->set_device_profile(dp);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_set_service_profile()
{
CPPUNIT_ASSERT(CServant);
std::string str("set_service_profile");
::SDOPackage::ServiceProfile sp;
::CORBA::Boolean result;
result = CServant->set_service_profile(sp);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_add_organization()
{
CPPUNIT_ASSERT(CServant);
std::string str("add_organization");
::SDOPackage::Organization_ptr org;
::CORBA::Boolean result;
result = CServant->add_organization(org);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief øªImplÉn³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_remove_service_profile()
{
CPPUNIT_ASSERT(CServant);
std::string str("remove_service_profile");
std::string id("Hoge");
::CORBA::Boolean result;
result = CServant->remove_service_profile(id.c_str());
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), id);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief øªImplÉn³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_remove_organization()
{
CPPUNIT_ASSERT(CServant);
std::string str("remove_organization");
std::string id("Hoge");
::CORBA::Boolean result;
result = CServant->remove_organization(id.c_str());
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), id);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief ßèlªnullÅÈ¢±Æ
*/
void test_call_get_configuration_parameters()
{
CPPUNIT_ASSERT(CServant);
std::string str("get_configuration_parameters");
::SDOPackage::ParameterList* result;
result = CServant->get_configuration_parameters();
CPPUNIT_ASSERT_MESSAGE("non-exist", result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief ßèlªnullÅÈ¢±Æ
*/
void test_call_get_configuration_parameter_values()
{
CPPUNIT_ASSERT(CServant);
std::string str("get_configuration_parameter_values");
::SDOPackage::NVList* result;
result = CServant->get_configuration_parameter_values();
CPPUNIT_ASSERT_MESSAGE("non-exist", result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief ßèlªnullÅÈ¢±Æ
*/
void test_call_get_configuration_parameter_value()
{
CPPUNIT_ASSERT(CServant);
std::string str("get_configuration_parameter_value");
std::string name("Hoge");
::CORBA::Any* result;
result = CServant->get_configuration_parameter_value(name.c_str());
CPPUNIT_ASSERT_MESSAGE("non-exist", result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), name);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief øªImplÉn³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_set_configuration_parameter()
{
CPPUNIT_ASSERT(CServant);
std::string str("set_configuration_parameter");
std::string name("hoge");
::CORBA::Any value;
::CORBA::Boolean result;
result = CServant->set_configuration_parameter(name.c_str(), value);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), name);
// CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), value);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_get_configuration_sets()
{
CPPUNIT_ASSERT(CServant);
std::string str("get_configuration_sets");
::SDOPackage::ConfigurationSetList* result;
result = CServant->get_configuration_sets();
CPPUNIT_ASSERT_MESSAGE("non-exist", result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief øªImplÉn³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_get_configuration_set()
{
CPPUNIT_ASSERT(CServant);
std::string str("get_configuration_set");
std::string config_id("hoge");
::SDOPackage::ConfigurationSet* result;
result = CServant->get_configuration_set(config_id.c_str());
CPPUNIT_ASSERT_MESSAGE("non-exist", result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), config_id);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief øªImplÉn³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_set_configuration_set_values()
{
CPPUNIT_ASSERT(CServant);
std::string str("set_configuration_set_values");
std::string config_id("hoge");
::SDOPackage::ConfigurationSet set;
::CORBA::Boolean result;
result = CServant->set_configuration_set_values(config_id.c_str(), set);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), config_id);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_get_active_configuration_set()
{
CPPUNIT_ASSERT(CServant);
std::string str("get_active_configuration_set");
::SDOPackage::ConfigurationSet* result;
result = CServant->get_active_configuration_set();
CPPUNIT_ASSERT_MESSAGE("non-exist", result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief øªImplÉn³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_add_configuration_set()
{
CPPUNIT_ASSERT(CServant);
std::string str("add_configuration_set");
::SDOPackage::ConfigurationSet set;
::CORBA::Boolean result;
result = CServant->add_configuration_set(set);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief øªImplÉn³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_remove_configuration_set()
{
CPPUNIT_ASSERT(CServant);
std::string str("remove_configuration_set");
std::string config_id("hoge");
::CORBA::Boolean result;
result = CServant->remove_configuration_set(config_id.c_str());
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), config_id);
}
/*!
* @brief ȺÌvðmF·é
* @brief ImplÌ\hªÄÑo³êĢ鱯
* @brief øªImplÉn³êĢ鱯
* @brief ßèlªÃŠ鱯
*/
void test_call_activate_configuration_set()
{
CPPUNIT_ASSERT(CServant);
std::string str("activate_configuration_set");
std::string str2("hoge");
::CORBA::Boolean result;
result = CServant->activate_configuration_set(str2.c_str());
CPPUNIT_ASSERT_EQUAL_MESSAGE("not true", true, result);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not method name", Log.pop(), str);
CPPUNIT_ASSERT_EQUAL_MESSAGE("not argument", Log.pop(), str2);
}
};
}; // namespace ConfigurationServant
/*
* Register test suite
*/
CPPUNIT_TEST_SUITE_REGISTRATION(ConfigurationServant::ConfigurationServantTests);
#ifdef LOCAL_MAIN
int main(int argc, char* argv[])
{
CppUnit::TextUi::TestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
CppUnit::Outputter* outputter =
new CppUnit::TextOutputter(&runner.result(), std::cout);
runner.setOutputter(outputter);
bool retcode = runner.run();
return !retcode;
}
#endif // MAIN
#endif // ConfigurationServant_cpp
| lgpl-3.0 |
StarLabMakerSpace/Nova4Mixly | nova/hardware/nova/avr/bootloaders/Caterina-ORG/LUFA-111009/Demos/Device/LowLevel/RNDISEthernet/Lib/TCP.c | 11 | 26098 | /*
LUFA Library
Copyright (C) Dean Camera, 2011.
dean [at] fourwalledcubicle [dot] com
www.lufa-lib.org
*/
/*
Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com)
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaim all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
*/
/** \file
*
* Transmission Control Protocol (TCP) packet handling routines. This protocol handles the reliable in-order transmission
* and reception of packets to and from devices on a network, to "ports" on the device. It is used in situations where data
* delivery must be reliable and correct, e.g. HTTP, TELNET and most other non-streaming protocols.
*/
#define INCLUDE_FROM_TCP_C
#include "TCP.h"
/** Port state table array. This contains the current status of TCP ports in the device. To save on space, only open ports are
* stored - closed ports may be overwritten at any time, and the system will assume any ports not present in the array are closed. This
* allows for MAX_OPEN_TCP_PORTS to be less than the number of ports used by the application if desired.
*/
TCP_PortState_t PortStateTable[MAX_OPEN_TCP_PORTS];
/** Connection state table array. This contains the current status of TCP connections in the device. To save on space, only active
* (non-closed) connections are stored - closed connections may be overwritten at any time, and the system will assume any connections
* not present in the array are closed.
*/
TCP_ConnectionState_t ConnectionStateTable[MAX_TCP_CONNECTIONS];
/** Task to handle the calling of each registered application's callback function, to process and generate TCP packets at the application
* level. If an application produces a response, this task constructs the appropriate Ethernet frame and places it into the Ethernet OUT
* buffer for later transmission.
*/
void TCP_Task(void)
{
/* Run each application in sequence, to process incoming and generate outgoing packets */
for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
{
/* Find the corresponding port entry in the port table */
for (uint8_t PTableEntry = 0; PTableEntry < MAX_OPEN_TCP_PORTS; PTableEntry++)
{
/* Run the application handler for the port */
if ((PortStateTable[PTableEntry].Port == ConnectionStateTable[CSTableEntry].Port) &&
(PortStateTable[PTableEntry].State == TCP_Port_Open))
{
PortStateTable[PTableEntry].ApplicationHandler(&ConnectionStateTable[CSTableEntry],
&ConnectionStateTable[CSTableEntry].Info.Buffer);
}
}
}
/* Bail out early if there is already a frame waiting to be sent in the Ethernet OUT buffer */
if (FrameOUT.FrameLength)
return;
/* Send response packets from each application as the TCP packet buffers are filled by the applications */
for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
{
/* For each completely received packet, pass it along to the listening application */
if ((ConnectionStateTable[CSTableEntry].Info.Buffer.Direction == TCP_PACKETDIR_OUT) &&
(ConnectionStateTable[CSTableEntry].Info.Buffer.Ready))
{
Ethernet_Frame_Header_t* FrameOUTHeader = (Ethernet_Frame_Header_t*)&FrameOUT.FrameData;
IP_Header_t* IPHeaderOUT = (IP_Header_t*)&FrameOUT.FrameData[sizeof(Ethernet_Frame_Header_t)];
TCP_Header_t* TCPHeaderOUT = (TCP_Header_t*)&FrameOUT.FrameData[sizeof(Ethernet_Frame_Header_t) +
sizeof(IP_Header_t)];
void* TCPDataOUT = &FrameOUT.FrameData[sizeof(Ethernet_Frame_Header_t) +
sizeof(IP_Header_t) +
sizeof(TCP_Header_t)];
uint16_t PacketSize = ConnectionStateTable[CSTableEntry].Info.Buffer.Length;
/* Fill out the TCP data */
TCPHeaderOUT->SourcePort = ConnectionStateTable[CSTableEntry].Port;
TCPHeaderOUT->DestinationPort = ConnectionStateTable[CSTableEntry].RemotePort;
TCPHeaderOUT->SequenceNumber = SwapEndian_32(ConnectionStateTable[CSTableEntry].Info.SequenceNumberOut);
TCPHeaderOUT->AcknowledgmentNumber = SwapEndian_32(ConnectionStateTable[CSTableEntry].Info.SequenceNumberIn);
TCPHeaderOUT->DataOffset = (sizeof(TCP_Header_t) / sizeof(uint32_t));
TCPHeaderOUT->WindowSize = SwapEndian_16(TCP_WINDOW_SIZE);
TCPHeaderOUT->Flags = TCP_FLAG_ACK;
TCPHeaderOUT->UrgentPointer = 0;
TCPHeaderOUT->Checksum = 0;
TCPHeaderOUT->Reserved = 0;
memcpy(TCPDataOUT, ConnectionStateTable[CSTableEntry].Info.Buffer.Data, PacketSize);
ConnectionStateTable[CSTableEntry].Info.SequenceNumberOut += PacketSize;
TCPHeaderOUT->Checksum = TCP_Checksum16(TCPHeaderOUT, ServerIPAddress,
ConnectionStateTable[CSTableEntry].RemoteAddress,
(sizeof(TCP_Header_t) + PacketSize));
PacketSize += sizeof(TCP_Header_t);
/* Fill out the response IP header */
IPHeaderOUT->TotalLength = SwapEndian_16(sizeof(IP_Header_t) + PacketSize);
IPHeaderOUT->TypeOfService = 0;
IPHeaderOUT->HeaderLength = (sizeof(IP_Header_t) / sizeof(uint32_t));
IPHeaderOUT->Version = 4;
IPHeaderOUT->Flags = 0;
IPHeaderOUT->FragmentOffset = 0;
IPHeaderOUT->Identification = 0;
IPHeaderOUT->HeaderChecksum = 0;
IPHeaderOUT->Protocol = PROTOCOL_TCP;
IPHeaderOUT->TTL = DEFAULT_TTL;
IPHeaderOUT->SourceAddress = ServerIPAddress;
IPHeaderOUT->DestinationAddress = ConnectionStateTable[CSTableEntry].RemoteAddress;
IPHeaderOUT->HeaderChecksum = Ethernet_Checksum16(IPHeaderOUT, sizeof(IP_Header_t));
PacketSize += sizeof(IP_Header_t);
/* Fill out the response Ethernet frame header */
FrameOUTHeader->Source = ServerMACAddress;
FrameOUTHeader->Destination = (MAC_Address_t){{0x02, 0x00, 0x02, 0x00, 0x02, 0x00}};
FrameOUTHeader->EtherType = SwapEndian_16(ETHERTYPE_IPV4);
PacketSize += sizeof(Ethernet_Frame_Header_t);
/* Set the response length in the buffer and indicate that a response is ready to be sent */
FrameOUT.FrameLength = PacketSize;
ConnectionStateTable[CSTableEntry].Info.Buffer.Ready = false;
break;
}
}
}
/** Initializes the TCP protocol handler, clearing the port and connection state tables. This must be called before TCP packets are
* processed.
*/
void TCP_Init(void)
{
/* Initialize the port state table with all CLOSED entries */
for (uint8_t PTableEntry = 0; PTableEntry < MAX_OPEN_TCP_PORTS; PTableEntry++)
PortStateTable[PTableEntry].State = TCP_Port_Closed;
/* Initialize the connection table with all CLOSED entries */
for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
ConnectionStateTable[CSTableEntry].State = TCP_Connection_Closed;
}
/** Sets the state and callback handler of the given port, specified in big endian to the given state.
*
* \param[in] Port Port whose state and callback function to set, specified in big endian
* \param[in] State New state of the port, a value from the \ref TCP_PortStates_t enum
* \param[in] Handler Application callback handler for the port
*
* \return Boolean true if the port state was set, false otherwise (no more space in the port state table)
*/
bool TCP_SetPortState(const uint16_t Port,
const uint8_t State,
void (*Handler)(TCP_ConnectionState_t*, TCP_ConnectionBuffer_t*))
{
/* Note, Port number should be specified in BIG endian to simplify network code */
/* Check to see if the port entry is already in the port state table */
for (uint8_t PTableEntry = 0; PTableEntry < MAX_OPEN_TCP_PORTS; PTableEntry++)
{
/* Find existing entry for the port in the table, update it if found */
if (PortStateTable[PTableEntry].Port == Port)
{
PortStateTable[PTableEntry].State = State;
PortStateTable[PTableEntry].ApplicationHandler = Handler;
return true;
}
}
/* Check if trying to open the port -- if so we need to find an unused (closed) entry and replace it */
if (State == TCP_Port_Open)
{
for (uint8_t PTableEntry = 0; PTableEntry < MAX_OPEN_TCP_PORTS; PTableEntry++)
{
/* Find a closed port entry in the table, change it to the given port and state */
if (PortStateTable[PTableEntry].State == TCP_Port_Closed)
{
PortStateTable[PTableEntry].Port = Port;
PortStateTable[PTableEntry].State = State;
PortStateTable[PTableEntry].ApplicationHandler = Handler;
return true;
}
}
/* Port not in table and no room to add it, return failure */
return false;
}
else
{
/* Port not in table but trying to close it, so operation successful */
return true;
}
}
/** Retrieves the current state of a given TCP port, specified in big endian.
*
* \param[in] Port TCP port whose state is to be retrieved, given in big-endian
*
* \return A value from the \ref TCP_PortStates_t enum
*/
uint8_t TCP_GetPortState(const uint16_t Port)
{
/* Note, Port number should be specified in BIG endian to simplify network code */
for (uint8_t PTableEntry = 0; PTableEntry < MAX_OPEN_TCP_PORTS; PTableEntry++)
{
/* Find existing entry for the port in the table, return the port status if found */
if (PortStateTable[PTableEntry].Port == Port)
return PortStateTable[PTableEntry].State;
}
/* Port not in table, assume closed */
return TCP_Port_Closed;
}
/** Sets the connection state of the given port, remote address and remote port to the given TCP connection state. If the
* connection exists in the connection state table it is updated, otherwise it is created if possible.
*
* \param[in] Port TCP port of the connection on the device, specified in big endian
* \param[in] RemoteAddress Remote protocol IP address of the connected device
* \param[in] RemotePort TCP port of the remote device in the connection, specified in big endian
* \param[in] State TCP connection state, a value from the \ref TCP_ConnectionStates_t enum
*
* \return Boolean true if the connection was updated or created, false otherwise (no more space in the connection state table)
*/
bool TCP_SetConnectionState(const uint16_t Port,
const IP_Address_t RemoteAddress,
const uint16_t RemotePort,
const uint8_t State)
{
/* Note, Port number should be specified in BIG endian to simplify network code */
for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
{
/* Find port entry in the table */
if ((ConnectionStateTable[CSTableEntry].Port == Port) &&
IP_COMPARE(&ConnectionStateTable[CSTableEntry].RemoteAddress, &RemoteAddress) &&
ConnectionStateTable[CSTableEntry].RemotePort == RemotePort)
{
ConnectionStateTable[CSTableEntry].State = State;
return true;
}
}
for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
{
/* Find empty entry in the table */
if (ConnectionStateTable[CSTableEntry].State == TCP_Connection_Closed)
{
ConnectionStateTable[CSTableEntry].Port = Port;
ConnectionStateTable[CSTableEntry].RemoteAddress = RemoteAddress;
ConnectionStateTable[CSTableEntry].RemotePort = RemotePort;
ConnectionStateTable[CSTableEntry].State = State;
return true;
}
}
return false;
}
/** Retrieves the current state of a given TCP connection to a host.
*
* \param[in] Port TCP port on the device in the connection, specified in big endian
* \param[in] RemoteAddress Remote protocol IP address of the connected host
* \param[in] RemotePort Remote TCP port of the connected host, specified in big endian
*
* \return A value from the \ref TCP_ConnectionStates_t enum
*/
uint8_t TCP_GetConnectionState(const uint16_t Port,
const IP_Address_t RemoteAddress,
const uint16_t RemotePort)
{
/* Note, Port number should be specified in BIG endian to simplify network code */
for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
{
/* Find port entry in the table */
if ((ConnectionStateTable[CSTableEntry].Port == Port) &&
IP_COMPARE(&ConnectionStateTable[CSTableEntry].RemoteAddress, &RemoteAddress) &&
ConnectionStateTable[CSTableEntry].RemotePort == RemotePort)
{
return ConnectionStateTable[CSTableEntry].State;
}
}
return TCP_Connection_Closed;
}
/** Retrieves the connection info structure of a given connection to a host.
*
* \param[in] Port TCP port on the device in the connection, specified in big endian
* \param[in] RemoteAddress Remote protocol IP address of the connected host
* \param[in] RemotePort Remote TCP port of the connected host, specified in big endian
*
* \return ConnectionInfo structure of the connection if found, NULL otherwise
*/
TCP_ConnectionInfo_t* TCP_GetConnectionInfo(const uint16_t Port,
const IP_Address_t RemoteAddress,
const uint16_t RemotePort)
{
/* Note, Port number should be specified in BIG endian to simplify network code */
for (uint8_t CSTableEntry = 0; CSTableEntry < MAX_TCP_CONNECTIONS; CSTableEntry++)
{
/* Find port entry in the table */
if ((ConnectionStateTable[CSTableEntry].Port == Port) &&
IP_COMPARE(&ConnectionStateTable[CSTableEntry].RemoteAddress, &RemoteAddress) &&
ConnectionStateTable[CSTableEntry].RemotePort == RemotePort)
{
return &ConnectionStateTable[CSTableEntry].Info;
}
}
return NULL;
}
/** Processes a TCP packet inside an Ethernet frame, and writes the appropriate response
* to the output Ethernet frame if one is created by a application handler.
*
* \param[in] IPHeaderInStart Pointer to the start of the incoming packet's IP header
* \param[in] TCPHeaderInStart Pointer to the start of the incoming packet's TCP header
* \param[out] TCPHeaderOutStart Pointer to the start of the outgoing packet's TCP header
*
* \return The number of bytes written to the out Ethernet frame if any, NO_RESPONSE if no
* response was generated, NO_PROCESS if the packet processing was deferred until the
* next Ethernet packet handler iteration
*/
int16_t TCP_ProcessTCPPacket(void* IPHeaderInStart,
void* TCPHeaderInStart,
void* TCPHeaderOutStart)
{
IP_Header_t* IPHeaderIN = (IP_Header_t*)IPHeaderInStart;
TCP_Header_t* TCPHeaderIN = (TCP_Header_t*)TCPHeaderInStart;
TCP_Header_t* TCPHeaderOUT = (TCP_Header_t*)TCPHeaderOutStart;
TCP_ConnectionInfo_t* ConnectionInfo;
DecodeTCPHeader(TCPHeaderInStart);
bool PacketResponse = false;
/* Check if the destination port is open and allows incoming connections */
if (TCP_GetPortState(TCPHeaderIN->DestinationPort) == TCP_Port_Open)
{
/* Detect SYN from host to start a connection */
if (TCPHeaderIN->Flags & TCP_FLAG_SYN)
TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress, TCPHeaderIN->SourcePort, TCP_Connection_Listen);
/* Detect RST from host to abort existing connection */
if (TCPHeaderIN->Flags & TCP_FLAG_RST)
{
if (TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_Closed))
{
TCPHeaderOUT->Flags = (TCP_FLAG_RST | TCP_FLAG_ACK);
PacketResponse = true;
}
}
else
{
/* Process the incoming TCP packet based on the current connection state for the sender and port */
switch (TCP_GetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress, TCPHeaderIN->SourcePort))
{
case TCP_Connection_Listen:
if (TCPHeaderIN->Flags == TCP_FLAG_SYN)
{
/* SYN connection starts a connection with a peer */
if (TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_SYNReceived))
{
TCPHeaderOUT->Flags = (TCP_FLAG_SYN | TCP_FLAG_ACK);
ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress, TCPHeaderIN->SourcePort);
ConnectionInfo->SequenceNumberIn = (SwapEndian_32(TCPHeaderIN->SequenceNumber) + 1);
ConnectionInfo->SequenceNumberOut = 0;
ConnectionInfo->Buffer.InUse = false;
}
else
{
TCPHeaderOUT->Flags = TCP_FLAG_RST;
}
PacketResponse = true;
}
break;
case TCP_Connection_SYNReceived:
if (TCPHeaderIN->Flags == TCP_FLAG_ACK)
{
/* ACK during the connection process completes the connection to a peer */
TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_Established);
ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort);
ConnectionInfo->SequenceNumberOut++;
}
break;
case TCP_Connection_Established:
if (TCPHeaderIN->Flags == (TCP_FLAG_FIN | TCP_FLAG_ACK))
{
/* FIN ACK when connected to a peer starts the finalization process */
TCPHeaderOUT->Flags = (TCP_FLAG_FIN | TCP_FLAG_ACK);
PacketResponse = true;
TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_CloseWait);
ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort);
ConnectionInfo->SequenceNumberIn++;
ConnectionInfo->SequenceNumberOut++;
}
else if ((TCPHeaderIN->Flags == TCP_FLAG_ACK) || (TCPHeaderIN->Flags == (TCP_FLAG_ACK | TCP_FLAG_PSH)))
{
ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort);
/* Check if the buffer is currently in use either by a buffered data to send, or receive */
if ((ConnectionInfo->Buffer.InUse == false) && (ConnectionInfo->Buffer.Ready == false))
{
ConnectionInfo->Buffer.Direction = TCP_PACKETDIR_IN;
ConnectionInfo->Buffer.InUse = true;
ConnectionInfo->Buffer.Length = 0;
}
/* Check if the buffer has been claimed by us to read in data from the peer */
if ((ConnectionInfo->Buffer.Direction == TCP_PACKETDIR_IN) &&
(ConnectionInfo->Buffer.Length != TCP_WINDOW_SIZE))
{
uint16_t IPOffset = (IPHeaderIN->HeaderLength * sizeof(uint32_t));
uint16_t TCPOffset = (TCPHeaderIN->DataOffset * sizeof(uint32_t));
uint16_t DataLength = (SwapEndian_16(IPHeaderIN->TotalLength) - IPOffset - TCPOffset);
/* Copy the packet data into the buffer */
memcpy(&ConnectionInfo->Buffer.Data[ConnectionInfo->Buffer.Length],
&((uint8_t*)TCPHeaderInStart)[TCPOffset],
DataLength);
ConnectionInfo->SequenceNumberIn += DataLength;
ConnectionInfo->Buffer.Length += DataLength;
/* Check if the buffer is full or if the PSH flag is set, if so indicate buffer ready */
if ((!(TCP_WINDOW_SIZE - ConnectionInfo->Buffer.Length)) || (TCPHeaderIN->Flags & TCP_FLAG_PSH))
{
ConnectionInfo->Buffer.InUse = false;
ConnectionInfo->Buffer.Ready = true;
TCPHeaderOUT->Flags = TCP_FLAG_ACK;
PacketResponse = true;
}
}
else
{
/* Buffer is currently in use by the application, defer processing of the incoming packet */
return NO_PROCESS;
}
}
break;
case TCP_Connection_Closing:
ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort);
TCPHeaderOUT->Flags = (TCP_FLAG_ACK | TCP_FLAG_FIN);
PacketResponse = true;
ConnectionInfo->Buffer.InUse = false;
TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_FINWait1);
break;
case TCP_Connection_FINWait1:
if (TCPHeaderIN->Flags == (TCP_FLAG_FIN | TCP_FLAG_ACK))
{
ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort);
TCPHeaderOUT->Flags = TCP_FLAG_ACK;
PacketResponse = true;
ConnectionInfo->SequenceNumberIn++;
ConnectionInfo->SequenceNumberOut++;
TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_Closed);
}
else if (TCPHeaderIN->Flags == TCP_FLAG_ACK)
{
TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_FINWait2);
}
break;
case TCP_Connection_FINWait2:
if (TCPHeaderIN->Flags == (TCP_FLAG_FIN | TCP_FLAG_ACK))
{
ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort);
TCPHeaderOUT->Flags = TCP_FLAG_ACK;
PacketResponse = true;
ConnectionInfo->SequenceNumberIn++;
ConnectionInfo->SequenceNumberOut++;
TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_Closed);
}
break;
case TCP_Connection_CloseWait:
if (TCPHeaderIN->Flags == TCP_FLAG_ACK)
{
TCP_SetConnectionState(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort, TCP_Connection_Closed);
}
break;
}
}
}
else
{
/* Port is not open, indicate via a RST/ACK response to the sender */
TCPHeaderOUT->Flags = (TCP_FLAG_RST | TCP_FLAG_ACK);
PacketResponse = true;
}
/* Check if we need to respond to the sent packet */
if (PacketResponse)
{
ConnectionInfo = TCP_GetConnectionInfo(TCPHeaderIN->DestinationPort, IPHeaderIN->SourceAddress,
TCPHeaderIN->SourcePort);
TCPHeaderOUT->SourcePort = TCPHeaderIN->DestinationPort;
TCPHeaderOUT->DestinationPort = TCPHeaderIN->SourcePort;
TCPHeaderOUT->SequenceNumber = SwapEndian_32(ConnectionInfo->SequenceNumberOut);
TCPHeaderOUT->AcknowledgmentNumber = SwapEndian_32(ConnectionInfo->SequenceNumberIn);
TCPHeaderOUT->DataOffset = (sizeof(TCP_Header_t) / sizeof(uint32_t));
if (!(ConnectionInfo->Buffer.InUse))
TCPHeaderOUT->WindowSize = SwapEndian_16(TCP_WINDOW_SIZE);
else
TCPHeaderOUT->WindowSize = SwapEndian_16(TCP_WINDOW_SIZE - ConnectionInfo->Buffer.Length);
TCPHeaderOUT->UrgentPointer = 0;
TCPHeaderOUT->Checksum = 0;
TCPHeaderOUT->Reserved = 0;
TCPHeaderOUT->Checksum = TCP_Checksum16(TCPHeaderOUT, IPHeaderIN->DestinationAddress,
IPHeaderIN->SourceAddress, sizeof(TCP_Header_t));
return sizeof(TCP_Header_t);
}
return NO_RESPONSE;
}
/** Calculates the appropriate TCP checksum, consisting of the addition of the one's compliment of each word,
* complimented.
*
* \param[in] TCPHeaderOutStart Pointer to the start of the packet's outgoing TCP header
* \param[in] SourceAddress Source protocol IP address of the outgoing IP header
* \param[in] DestinationAddress Destination protocol IP address of the outgoing IP header
* \param[in] TCPOutSize Size in bytes of the TCP data header and payload
*
* \return A 16-bit TCP checksum value
*/
static uint16_t TCP_Checksum16(void* TCPHeaderOutStart,
const IP_Address_t SourceAddress,
const IP_Address_t DestinationAddress,
uint16_t TCPOutSize)
{
uint32_t Checksum = 0;
/* TCP/IP checksums are the addition of the one's compliment of each word including the IP pseudo-header,
complimented */
Checksum += ((uint16_t*)&SourceAddress)[0];
Checksum += ((uint16_t*)&SourceAddress)[1];
Checksum += ((uint16_t*)&DestinationAddress)[0];
Checksum += ((uint16_t*)&DestinationAddress)[1];
Checksum += SwapEndian_16(PROTOCOL_TCP);
Checksum += SwapEndian_16(TCPOutSize);
for (uint16_t CurrWord = 0; CurrWord < (TCPOutSize >> 1); CurrWord++)
Checksum += ((uint16_t*)TCPHeaderOutStart)[CurrWord];
if (TCPOutSize & 0x01)
Checksum += (((uint16_t*)TCPHeaderOutStart)[TCPOutSize >> 1] & 0x00FF);
while (Checksum & 0xFFFF0000)
Checksum = ((Checksum & 0xFFFF) + (Checksum >> 16));
return ~Checksum;
}
| lgpl-3.0 |
karasuhebi/pcsx2 | 3rdparty/wxwidgets3.0/src/common/translation.cpp | 19 | 58345 | /////////////////////////////////////////////////////////////////////////////
// Name: src/common/translation.cpp
// Purpose: Internationalization and localisation for wxWidgets
// Author: Vadim Zeitlin, Vaclav Slavik,
// Michael N. Filippov <michael@idisys.iae.nsk.su>
// (2003/09/30 - PluralForms support)
// Created: 2010-04-23
// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declaration
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_INTL
#ifndef WX_PRECOMP
#include "wx/dynarray.h"
#include "wx/string.h"
#include "wx/intl.h"
#include "wx/log.h"
#include "wx/utils.h"
#include "wx/hashmap.h"
#include "wx/module.h"
#endif // WX_PRECOMP
// standard headers
#include <ctype.h>
#include <stdlib.h>
#include "wx/arrstr.h"
#include "wx/dir.h"
#include "wx/file.h"
#include "wx/filename.h"
#include "wx/tokenzr.h"
#include "wx/fontmap.h"
#include "wx/stdpaths.h"
#include "wx/private/threadinfo.h"
#ifdef __WINDOWS__
#include "wx/dynlib.h"
#include "wx/scopedarray.h"
#include "wx/msw/wrapwin.h"
#include "wx/msw/missing.h"
#endif
#ifdef __WXOSX__
#include "wx/osx/core/cfstring.h"
#include <CoreFoundation/CFBundle.h>
#include <CoreFoundation/CFLocale.h>
#endif
// ----------------------------------------------------------------------------
// simple types
// ----------------------------------------------------------------------------
typedef wxUint32 size_t32;
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// magic number identifying the .mo format file
const size_t32 MSGCATALOG_MAGIC = 0x950412de;
const size_t32 MSGCATALOG_MAGIC_SW = 0xde120495;
#define TRACE_I18N wxS("i18n")
// ============================================================================
// implementation
// ============================================================================
namespace
{
#if !wxUSE_UNICODE
// We need to keep track of (char*) msgids in non-Unicode legacy builds. Instead
// of making the public wxMsgCatalog and wxTranslationsLoader APIs ugly, we
// store them in this global map.
wxStringToStringHashMap gs_msgIdCharset;
#endif
// ----------------------------------------------------------------------------
// Platform specific helpers
// ----------------------------------------------------------------------------
#if wxUSE_LOG_TRACE
void LogTraceArray(const char *prefix, const wxArrayString& arr)
{
wxLogTrace(TRACE_I18N, "%s: [%s]", prefix, wxJoin(arr, ','));
}
void LogTraceLargeArray(const wxString& prefix, const wxArrayString& arr)
{
wxLogTrace(TRACE_I18N, "%s:", prefix);
for ( wxArrayString::const_iterator i = arr.begin(); i != arr.end(); ++i )
wxLogTrace(TRACE_I18N, " %s", *i);
}
#else // !wxUSE_LOG_TRACE
#define LogTraceArray(prefix, arr)
#define LogTraceLargeArray(prefix, arr)
#endif // wxUSE_LOG_TRACE/!wxUSE_LOG_TRACE
// Use locale-based detection as a fallback
wxString GetPreferredUILanguageFallback(const wxArrayString& WXUNUSED(available))
{
const wxString lang = wxLocale::GetLanguageCanonicalName(wxLocale::GetSystemLanguage());
wxLogTrace(TRACE_I18N, " - obtained best language from locale: %s", lang);
return lang;
}
#ifdef __WINDOWS__
wxString GetPreferredUILanguage(const wxArrayString& available)
{
typedef BOOL (WINAPI *GetUserPreferredUILanguages_t)(DWORD, PULONG, PWSTR, PULONG);
static GetUserPreferredUILanguages_t s_pfnGetUserPreferredUILanguages = NULL;
static bool s_initDone = false;
if ( !s_initDone )
{
wxLoadedDLL dllKernel32("kernel32.dll");
wxDL_INIT_FUNC(s_pfn, GetUserPreferredUILanguages, dllKernel32);
s_initDone = true;
}
if ( s_pfnGetUserPreferredUILanguages )
{
ULONG numLangs;
ULONG bufferSize = 0;
if ( (*s_pfnGetUserPreferredUILanguages)(MUI_LANGUAGE_NAME,
&numLangs,
NULL,
&bufferSize) )
{
wxScopedArray<WCHAR> langs(new WCHAR[bufferSize]);
if ( (*s_pfnGetUserPreferredUILanguages)(MUI_LANGUAGE_NAME,
&numLangs,
langs.get(),
&bufferSize) )
{
wxArrayString preferred;
WCHAR *buf = langs.get();
for ( unsigned i = 0; i < numLangs; i++ )
{
const wxString lang(buf);
preferred.push_back(lang);
buf += lang.length() + 1;
}
LogTraceArray(" - system preferred languages", preferred);
for ( wxArrayString::const_iterator j = preferred.begin();
j != preferred.end();
++j )
{
wxString lang(*j);
lang.Replace("-", "_");
if ( available.Index(lang, /*bCase=*/false) != wxNOT_FOUND )
return lang;
size_t pos = lang.find('_');
if ( pos != wxString::npos )
{
lang = lang.substr(0, pos);
if ( available.Index(lang, /*bCase=*/false) != wxNOT_FOUND )
return lang;
}
}
}
}
}
return GetPreferredUILanguageFallback(available);
}
#elif defined(__WXOSX__)
#if wxUSE_LOG_TRACE
void LogTraceArray(const char *prefix, CFArrayRef arr)
{
wxString s;
const unsigned count = CFArrayGetCount(arr);
if ( count )
{
s += wxCFStringRef::AsString((CFStringRef)CFArrayGetValueAtIndex(arr, 0));
for ( unsigned i = 1 ; i < count; i++ )
s += "," + wxCFStringRef::AsString((CFStringRef)CFArrayGetValueAtIndex(arr, i));
}
wxLogTrace(TRACE_I18N, "%s: [%s]", prefix, s);
}
#endif // wxUSE_LOG_TRACE
wxString GetPreferredUILanguage(const wxArrayString& available)
{
wxStringToStringHashMap availableNormalized;
wxCFRef<CFMutableArrayRef> availableArr(
CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
for ( wxArrayString::const_iterator i = available.begin();
i != available.end();
++i )
{
wxString lang(*i);
wxCFStringRef code_wx(*i);
wxCFStringRef code_norm(
CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorDefault, code_wx));
CFArrayAppendValue(availableArr, code_norm);
availableNormalized[code_norm.AsString()] = *i;
}
LogTraceArray(" - normalized available list", availableArr);
wxCFRef<CFArrayRef> prefArr(
CFBundleCopyLocalizationsForPreferences(availableArr, NULL));
LogTraceArray(" - system preferred languages", prefArr);
unsigned prefArrLength = CFArrayGetCount(prefArr);
if ( prefArrLength > 0 )
{
// Lookup the name in 'available' by index -- we need to get the
// original value corresponding to the normalized one chosen.
wxString lang(wxCFStringRef::AsString((CFStringRef)CFArrayGetValueAtIndex(prefArr, 0)));
wxStringToStringHashMap::const_iterator i = availableNormalized.find(lang);
if ( i == availableNormalized.end() )
return lang;
else
return i->second;
}
return GetPreferredUILanguageFallback(available);
}
#else
// On Unix, there's just one language=locale setting, so we should always
// use that.
#define GetPreferredUILanguage GetPreferredUILanguageFallback
#endif
} // anonymous namespace
// ----------------------------------------------------------------------------
// Plural forms parser
// ----------------------------------------------------------------------------
/*
Simplified Grammar
Expression:
LogicalOrExpression '?' Expression ':' Expression
LogicalOrExpression
LogicalOrExpression:
LogicalAndExpression "||" LogicalOrExpression // to (a || b) || c
LogicalAndExpression
LogicalAndExpression:
EqualityExpression "&&" LogicalAndExpression // to (a && b) && c
EqualityExpression
EqualityExpression:
RelationalExpression "==" RelationalExperession
RelationalExpression "!=" RelationalExperession
RelationalExpression
RelationalExpression:
MultiplicativeExpression '>' MultiplicativeExpression
MultiplicativeExpression '<' MultiplicativeExpression
MultiplicativeExpression ">=" MultiplicativeExpression
MultiplicativeExpression "<=" MultiplicativeExpression
MultiplicativeExpression
MultiplicativeExpression:
PmExpression '%' PmExpression
PmExpression
PmExpression:
N
Number
'(' Expression ')'
*/
class wxPluralFormsToken
{
public:
enum Type
{
T_ERROR, T_EOF, T_NUMBER, T_N, T_PLURAL, T_NPLURALS, T_EQUAL, T_ASSIGN,
T_GREATER, T_GREATER_OR_EQUAL, T_LESS, T_LESS_OR_EQUAL,
T_REMINDER, T_NOT_EQUAL,
T_LOGICAL_AND, T_LOGICAL_OR, T_QUESTION, T_COLON, T_SEMICOLON,
T_LEFT_BRACKET, T_RIGHT_BRACKET
};
Type type() const { return m_type; }
void setType(Type t) { m_type = t; }
// for T_NUMBER only
typedef int Number;
Number number() const { return m_number; }
void setNumber(Number num) { m_number = num; }
private:
Type m_type;
Number m_number;
};
class wxPluralFormsScanner
{
public:
wxPluralFormsScanner(const char* s);
const wxPluralFormsToken& token() const { return m_token; }
bool nextToken(); // returns false if error
private:
const char* m_s;
wxPluralFormsToken m_token;
};
wxPluralFormsScanner::wxPluralFormsScanner(const char* s) : m_s(s)
{
nextToken();
}
bool wxPluralFormsScanner::nextToken()
{
wxPluralFormsToken::Type type = wxPluralFormsToken::T_ERROR;
while (isspace((unsigned char) *m_s))
{
++m_s;
}
if (*m_s == 0)
{
type = wxPluralFormsToken::T_EOF;
}
else if (isdigit((unsigned char) *m_s))
{
wxPluralFormsToken::Number number = *m_s++ - '0';
while (isdigit((unsigned char) *m_s))
{
number = number * 10 + (*m_s++ - '0');
}
m_token.setNumber(number);
type = wxPluralFormsToken::T_NUMBER;
}
else if (isalpha((unsigned char) *m_s))
{
const char* begin = m_s++;
while (isalnum((unsigned char) *m_s))
{
++m_s;
}
size_t size = m_s - begin;
if (size == 1 && memcmp(begin, "n", size) == 0)
{
type = wxPluralFormsToken::T_N;
}
else if (size == 6 && memcmp(begin, "plural", size) == 0)
{
type = wxPluralFormsToken::T_PLURAL;
}
else if (size == 8 && memcmp(begin, "nplurals", size) == 0)
{
type = wxPluralFormsToken::T_NPLURALS;
}
}
else if (*m_s == '=')
{
++m_s;
if (*m_s == '=')
{
++m_s;
type = wxPluralFormsToken::T_EQUAL;
}
else
{
type = wxPluralFormsToken::T_ASSIGN;
}
}
else if (*m_s == '>')
{
++m_s;
if (*m_s == '=')
{
++m_s;
type = wxPluralFormsToken::T_GREATER_OR_EQUAL;
}
else
{
type = wxPluralFormsToken::T_GREATER;
}
}
else if (*m_s == '<')
{
++m_s;
if (*m_s == '=')
{
++m_s;
type = wxPluralFormsToken::T_LESS_OR_EQUAL;
}
else
{
type = wxPluralFormsToken::T_LESS;
}
}
else if (*m_s == '%')
{
++m_s;
type = wxPluralFormsToken::T_REMINDER;
}
else if (*m_s == '!' && m_s[1] == '=')
{
m_s += 2;
type = wxPluralFormsToken::T_NOT_EQUAL;
}
else if (*m_s == '&' && m_s[1] == '&')
{
m_s += 2;
type = wxPluralFormsToken::T_LOGICAL_AND;
}
else if (*m_s == '|' && m_s[1] == '|')
{
m_s += 2;
type = wxPluralFormsToken::T_LOGICAL_OR;
}
else if (*m_s == '?')
{
++m_s;
type = wxPluralFormsToken::T_QUESTION;
}
else if (*m_s == ':')
{
++m_s;
type = wxPluralFormsToken::T_COLON;
} else if (*m_s == ';') {
++m_s;
type = wxPluralFormsToken::T_SEMICOLON;
}
else if (*m_s == '(')
{
++m_s;
type = wxPluralFormsToken::T_LEFT_BRACKET;
}
else if (*m_s == ')')
{
++m_s;
type = wxPluralFormsToken::T_RIGHT_BRACKET;
}
m_token.setType(type);
return type != wxPluralFormsToken::T_ERROR;
}
class wxPluralFormsNode;
// NB: Can't use wxDEFINE_SCOPED_PTR_TYPE because wxPluralFormsNode is not
// fully defined yet:
class wxPluralFormsNodePtr
{
public:
wxPluralFormsNodePtr(wxPluralFormsNode *p = NULL) : m_p(p) {}
~wxPluralFormsNodePtr();
wxPluralFormsNode& operator*() const { return *m_p; }
wxPluralFormsNode* operator->() const { return m_p; }
wxPluralFormsNode* get() const { return m_p; }
wxPluralFormsNode* release();
void reset(wxPluralFormsNode *p);
private:
wxPluralFormsNode *m_p;
};
class wxPluralFormsNode
{
public:
wxPluralFormsNode(const wxPluralFormsToken& t) : m_token(t) {}
const wxPluralFormsToken& token() const { return m_token; }
const wxPluralFormsNode* node(unsigned i) const
{ return m_nodes[i].get(); }
void setNode(unsigned i, wxPluralFormsNode* n);
wxPluralFormsNode* releaseNode(unsigned i);
wxPluralFormsToken::Number evaluate(wxPluralFormsToken::Number n) const;
private:
wxPluralFormsToken m_token;
wxPluralFormsNodePtr m_nodes[3];
};
wxPluralFormsNodePtr::~wxPluralFormsNodePtr()
{
delete m_p;
}
wxPluralFormsNode* wxPluralFormsNodePtr::release()
{
wxPluralFormsNode *p = m_p;
m_p = NULL;
return p;
}
void wxPluralFormsNodePtr::reset(wxPluralFormsNode *p)
{
if (p != m_p)
{
delete m_p;
m_p = p;
}
}
void wxPluralFormsNode::setNode(unsigned i, wxPluralFormsNode* n)
{
m_nodes[i].reset(n);
}
wxPluralFormsNode* wxPluralFormsNode::releaseNode(unsigned i)
{
return m_nodes[i].release();
}
wxPluralFormsToken::Number
wxPluralFormsNode::evaluate(wxPluralFormsToken::Number n) const
{
switch (token().type())
{
// leaf
case wxPluralFormsToken::T_NUMBER:
return token().number();
case wxPluralFormsToken::T_N:
return n;
// 2 args
case wxPluralFormsToken::T_EQUAL:
return node(0)->evaluate(n) == node(1)->evaluate(n);
case wxPluralFormsToken::T_NOT_EQUAL:
return node(0)->evaluate(n) != node(1)->evaluate(n);
case wxPluralFormsToken::T_GREATER:
return node(0)->evaluate(n) > node(1)->evaluate(n);
case wxPluralFormsToken::T_GREATER_OR_EQUAL:
return node(0)->evaluate(n) >= node(1)->evaluate(n);
case wxPluralFormsToken::T_LESS:
return node(0)->evaluate(n) < node(1)->evaluate(n);
case wxPluralFormsToken::T_LESS_OR_EQUAL:
return node(0)->evaluate(n) <= node(1)->evaluate(n);
case wxPluralFormsToken::T_REMINDER:
{
wxPluralFormsToken::Number number = node(1)->evaluate(n);
if (number != 0)
{
return node(0)->evaluate(n) % number;
}
else
{
return 0;
}
}
case wxPluralFormsToken::T_LOGICAL_AND:
return node(0)->evaluate(n) && node(1)->evaluate(n);
case wxPluralFormsToken::T_LOGICAL_OR:
return node(0)->evaluate(n) || node(1)->evaluate(n);
// 3 args
case wxPluralFormsToken::T_QUESTION:
return node(0)->evaluate(n)
? node(1)->evaluate(n)
: node(2)->evaluate(n);
default:
return 0;
}
}
class wxPluralFormsCalculator
{
public:
wxPluralFormsCalculator() : m_nplurals(0), m_plural(0) {}
// input: number, returns msgstr index
int evaluate(int n) const;
// input: text after "Plural-Forms:" (e.g. "nplurals=2; plural=(n != 1);"),
// if s == 0, creates default handler
// returns 0 if error
static wxPluralFormsCalculator* make(const char* s = 0);
~wxPluralFormsCalculator() {}
void init(wxPluralFormsToken::Number nplurals, wxPluralFormsNode* plural);
private:
wxPluralFormsToken::Number m_nplurals;
wxPluralFormsNodePtr m_plural;
};
wxDEFINE_SCOPED_PTR(wxPluralFormsCalculator, wxPluralFormsCalculatorPtr)
void wxPluralFormsCalculator::init(wxPluralFormsToken::Number nplurals,
wxPluralFormsNode* plural)
{
m_nplurals = nplurals;
m_plural.reset(plural);
}
int wxPluralFormsCalculator::evaluate(int n) const
{
if (m_plural.get() == 0)
{
return 0;
}
wxPluralFormsToken::Number number = m_plural->evaluate(n);
if (number < 0 || number > m_nplurals)
{
return 0;
}
return number;
}
class wxPluralFormsParser
{
public:
wxPluralFormsParser(wxPluralFormsScanner& scanner) : m_scanner(scanner) {}
bool parse(wxPluralFormsCalculator& rCalculator);
private:
wxPluralFormsNode* parsePlural();
// stops at T_SEMICOLON, returns 0 if error
wxPluralFormsScanner& m_scanner;
const wxPluralFormsToken& token() const;
bool nextToken();
wxPluralFormsNode* expression();
wxPluralFormsNode* logicalOrExpression();
wxPluralFormsNode* logicalAndExpression();
wxPluralFormsNode* equalityExpression();
wxPluralFormsNode* multiplicativeExpression();
wxPluralFormsNode* relationalExpression();
wxPluralFormsNode* pmExpression();
};
bool wxPluralFormsParser::parse(wxPluralFormsCalculator& rCalculator)
{
if (token().type() != wxPluralFormsToken::T_NPLURALS)
return false;
if (!nextToken())
return false;
if (token().type() != wxPluralFormsToken::T_ASSIGN)
return false;
if (!nextToken())
return false;
if (token().type() != wxPluralFormsToken::T_NUMBER)
return false;
wxPluralFormsToken::Number nplurals = token().number();
if (!nextToken())
return false;
if (token().type() != wxPluralFormsToken::T_SEMICOLON)
return false;
if (!nextToken())
return false;
if (token().type() != wxPluralFormsToken::T_PLURAL)
return false;
if (!nextToken())
return false;
if (token().type() != wxPluralFormsToken::T_ASSIGN)
return false;
if (!nextToken())
return false;
wxPluralFormsNode* plural = parsePlural();
if (plural == 0)
return false;
if (token().type() != wxPluralFormsToken::T_SEMICOLON)
return false;
if (!nextToken())
return false;
if (token().type() != wxPluralFormsToken::T_EOF)
return false;
rCalculator.init(nplurals, plural);
return true;
}
wxPluralFormsNode* wxPluralFormsParser::parsePlural()
{
wxPluralFormsNode* p = expression();
if (p == NULL)
{
return NULL;
}
wxPluralFormsNodePtr n(p);
if (token().type() != wxPluralFormsToken::T_SEMICOLON)
{
return NULL;
}
return n.release();
}
const wxPluralFormsToken& wxPluralFormsParser::token() const
{
return m_scanner.token();
}
bool wxPluralFormsParser::nextToken()
{
if (!m_scanner.nextToken())
return false;
return true;
}
wxPluralFormsNode* wxPluralFormsParser::expression()
{
wxPluralFormsNode* p = logicalOrExpression();
if (p == NULL)
return NULL;
wxPluralFormsNodePtr n(p);
if (token().type() == wxPluralFormsToken::T_QUESTION)
{
wxPluralFormsNodePtr qn(new wxPluralFormsNode(token()));
if (!nextToken())
{
return 0;
}
p = expression();
if (p == 0)
{
return 0;
}
qn->setNode(1, p);
if (token().type() != wxPluralFormsToken::T_COLON)
{
return 0;
}
if (!nextToken())
{
return 0;
}
p = expression();
if (p == 0)
{
return 0;
}
qn->setNode(2, p);
qn->setNode(0, n.release());
return qn.release();
}
return n.release();
}
wxPluralFormsNode*wxPluralFormsParser::logicalOrExpression()
{
wxPluralFormsNode* p = logicalAndExpression();
if (p == NULL)
return NULL;
wxPluralFormsNodePtr ln(p);
if (token().type() == wxPluralFormsToken::T_LOGICAL_OR)
{
wxPluralFormsNodePtr un(new wxPluralFormsNode(token()));
if (!nextToken())
{
return 0;
}
p = logicalOrExpression();
if (p == 0)
{
return 0;
}
wxPluralFormsNodePtr rn(p); // right
if (rn->token().type() == wxPluralFormsToken::T_LOGICAL_OR)
{
// see logicalAndExpression comment
un->setNode(0, ln.release());
un->setNode(1, rn->releaseNode(0));
rn->setNode(0, un.release());
return rn.release();
}
un->setNode(0, ln.release());
un->setNode(1, rn.release());
return un.release();
}
return ln.release();
}
wxPluralFormsNode* wxPluralFormsParser::logicalAndExpression()
{
wxPluralFormsNode* p = equalityExpression();
if (p == NULL)
return NULL;
wxPluralFormsNodePtr ln(p); // left
if (token().type() == wxPluralFormsToken::T_LOGICAL_AND)
{
wxPluralFormsNodePtr un(new wxPluralFormsNode(token())); // up
if (!nextToken())
{
return NULL;
}
p = logicalAndExpression();
if (p == 0)
{
return NULL;
}
wxPluralFormsNodePtr rn(p); // right
if (rn->token().type() == wxPluralFormsToken::T_LOGICAL_AND)
{
// transform 1 && (2 && 3) -> (1 && 2) && 3
// u r
// l r -> u 3
// 2 3 l 2
un->setNode(0, ln.release());
un->setNode(1, rn->releaseNode(0));
rn->setNode(0, un.release());
return rn.release();
}
un->setNode(0, ln.release());
un->setNode(1, rn.release());
return un.release();
}
return ln.release();
}
wxPluralFormsNode* wxPluralFormsParser::equalityExpression()
{
wxPluralFormsNode* p = relationalExpression();
if (p == NULL)
return NULL;
wxPluralFormsNodePtr n(p);
if (token().type() == wxPluralFormsToken::T_EQUAL
|| token().type() == wxPluralFormsToken::T_NOT_EQUAL)
{
wxPluralFormsNodePtr qn(new wxPluralFormsNode(token()));
if (!nextToken())
{
return NULL;
}
p = relationalExpression();
if (p == NULL)
{
return NULL;
}
qn->setNode(1, p);
qn->setNode(0, n.release());
return qn.release();
}
return n.release();
}
wxPluralFormsNode* wxPluralFormsParser::relationalExpression()
{
wxPluralFormsNode* p = multiplicativeExpression();
if (p == NULL)
return NULL;
wxPluralFormsNodePtr n(p);
if (token().type() == wxPluralFormsToken::T_GREATER
|| token().type() == wxPluralFormsToken::T_LESS
|| token().type() == wxPluralFormsToken::T_GREATER_OR_EQUAL
|| token().type() == wxPluralFormsToken::T_LESS_OR_EQUAL)
{
wxPluralFormsNodePtr qn(new wxPluralFormsNode(token()));
if (!nextToken())
{
return NULL;
}
p = multiplicativeExpression();
if (p == NULL)
{
return NULL;
}
qn->setNode(1, p);
qn->setNode(0, n.release());
return qn.release();
}
return n.release();
}
wxPluralFormsNode* wxPluralFormsParser::multiplicativeExpression()
{
wxPluralFormsNode* p = pmExpression();
if (p == NULL)
return NULL;
wxPluralFormsNodePtr n(p);
if (token().type() == wxPluralFormsToken::T_REMINDER)
{
wxPluralFormsNodePtr qn(new wxPluralFormsNode(token()));
if (!nextToken())
{
return NULL;
}
p = pmExpression();
if (p == NULL)
{
return NULL;
}
qn->setNode(1, p);
qn->setNode(0, n.release());
return qn.release();
}
return n.release();
}
wxPluralFormsNode* wxPluralFormsParser::pmExpression()
{
wxPluralFormsNodePtr n;
if (token().type() == wxPluralFormsToken::T_N
|| token().type() == wxPluralFormsToken::T_NUMBER)
{
n.reset(new wxPluralFormsNode(token()));
if (!nextToken())
{
return NULL;
}
}
else if (token().type() == wxPluralFormsToken::T_LEFT_BRACKET) {
if (!nextToken())
{
return NULL;
}
wxPluralFormsNode* p = expression();
if (p == NULL)
{
return NULL;
}
n.reset(p);
if (token().type() != wxPluralFormsToken::T_RIGHT_BRACKET)
{
return NULL;
}
if (!nextToken())
{
return NULL;
}
}
else
{
return NULL;
}
return n.release();
}
wxPluralFormsCalculator* wxPluralFormsCalculator::make(const char* s)
{
wxPluralFormsCalculatorPtr calculator(new wxPluralFormsCalculator);
if (s != NULL)
{
wxPluralFormsScanner scanner(s);
wxPluralFormsParser p(scanner);
if (!p.parse(*calculator))
{
return NULL;
}
}
return calculator.release();
}
// ----------------------------------------------------------------------------
// wxMsgCatalogFile corresponds to one disk-file message catalog.
//
// This is a "low-level" class and is used only by wxMsgCatalog
// NOTE: for the documentation of the binary catalog (.MO) files refer to
// the GNU gettext manual:
// http://www.gnu.org/software/autoconf/manual/gettext/MO-Files.html
// ----------------------------------------------------------------------------
class wxMsgCatalogFile
{
public:
typedef wxScopedCharBuffer DataBuffer;
// ctor & dtor
wxMsgCatalogFile();
~wxMsgCatalogFile();
// load the catalog from disk
bool LoadFile(const wxString& filename,
wxPluralFormsCalculatorPtr& rPluralFormsCalculator);
bool LoadData(const DataBuffer& data,
wxPluralFormsCalculatorPtr& rPluralFormsCalculator);
// fills the hash with string-translation pairs
bool FillHash(wxStringToStringHashMap& hash, const wxString& domain) const;
// return the charset of the strings in this catalog or empty string if
// none/unknown
wxString GetCharset() const { return m_charset; }
private:
// this implementation is binary compatible with GNU gettext() version 0.10
// an entry in the string table
struct wxMsgTableEntry
{
size_t32 nLen; // length of the string
size_t32 ofsString; // pointer to the string
};
// header of a .mo file
struct wxMsgCatalogHeader
{
size_t32 magic, // offset +00: magic id
revision, // +04: revision
numStrings; // +08: number of strings in the file
size_t32 ofsOrigTable, // +0C: start of original string table
ofsTransTable; // +10: start of translated string table
size_t32 nHashSize, // +14: hash table size
ofsHashTable; // +18: offset of hash table start
};
// all data is stored here
DataBuffer m_data;
// data description
size_t32 m_numStrings; // number of strings in this domain
wxMsgTableEntry *m_pOrigTable, // pointer to original strings
*m_pTransTable; // translated
wxString m_charset; // from the message catalog header
// swap the 2 halves of 32 bit integer if needed
size_t32 Swap(size_t32 ui) const
{
return m_bSwapped ? (ui << 24) | ((ui & 0xff00) << 8) |
((ui >> 8) & 0xff00) | (ui >> 24)
: ui;
}
const char *StringAtOfs(wxMsgTableEntry *pTable, size_t32 n) const
{
const wxMsgTableEntry * const ent = pTable + n;
// this check could fail for a corrupt message catalog
size_t32 ofsString = Swap(ent->ofsString);
if ( ofsString + Swap(ent->nLen) > m_data.length())
{
return NULL;
}
return m_data.data() + ofsString;
}
bool m_bSwapped; // wrong endianness?
wxDECLARE_NO_COPY_CLASS(wxMsgCatalogFile);
};
// ----------------------------------------------------------------------------
// wxMsgCatalogFile class
// ----------------------------------------------------------------------------
wxMsgCatalogFile::wxMsgCatalogFile()
{
}
wxMsgCatalogFile::~wxMsgCatalogFile()
{
}
// open disk file and read in it's contents
bool wxMsgCatalogFile::LoadFile(const wxString& filename,
wxPluralFormsCalculatorPtr& rPluralFormsCalculator)
{
wxFile fileMsg(filename);
if ( !fileMsg.IsOpened() )
return false;
// get the file size (assume it is less than 4GB...)
wxFileOffset lenFile = fileMsg.Length();
if ( lenFile == wxInvalidOffset )
return false;
size_t nSize = wx_truncate_cast(size_t, lenFile);
wxASSERT_MSG( nSize == lenFile + size_t(0), wxS("message catalog bigger than 4GB?") );
wxMemoryBuffer filedata;
// read the whole file in memory
if ( fileMsg.Read(filedata.GetWriteBuf(nSize), nSize) != lenFile )
return false;
filedata.UngetWriteBuf(nSize);
bool ok = LoadData
(
DataBuffer::CreateOwned((char*)filedata.release(), nSize),
rPluralFormsCalculator
);
if ( !ok )
{
wxLogWarning(_("'%s' is not a valid message catalog."), filename.c_str());
return false;
}
return true;
}
bool wxMsgCatalogFile::LoadData(const DataBuffer& data,
wxPluralFormsCalculatorPtr& rPluralFormsCalculator)
{
// examine header
bool bValid = data.length() > sizeof(wxMsgCatalogHeader);
const wxMsgCatalogHeader *pHeader = (wxMsgCatalogHeader *)data.data();
if ( bValid ) {
// we'll have to swap all the integers if it's true
m_bSwapped = pHeader->magic == MSGCATALOG_MAGIC_SW;
// check the magic number
bValid = m_bSwapped || pHeader->magic == MSGCATALOG_MAGIC;
}
if ( !bValid ) {
// it's either too short or has incorrect magic number
wxLogWarning(_("Invalid message catalog."));
return false;
}
m_data = data;
// initialize
m_numStrings = Swap(pHeader->numStrings);
m_pOrigTable = (wxMsgTableEntry *)(data.data() +
Swap(pHeader->ofsOrigTable));
m_pTransTable = (wxMsgTableEntry *)(data.data() +
Swap(pHeader->ofsTransTable));
// now parse catalog's header and try to extract catalog charset and
// plural forms formula from it:
const char* headerData = StringAtOfs(m_pOrigTable, 0);
if ( headerData && headerData[0] == '\0' )
{
// Extract the charset:
const char * const header = StringAtOfs(m_pTransTable, 0);
const char *
cset = strstr(header, "Content-Type: text/plain; charset=");
if ( cset )
{
cset += 34; // strlen("Content-Type: text/plain; charset=")
const char * const csetEnd = strchr(cset, '\n');
if ( csetEnd )
{
m_charset = wxString(cset, csetEnd - cset);
if ( m_charset == wxS("CHARSET") )
{
// "CHARSET" is not valid charset, but lazy translator
m_charset.clear();
}
}
}
// else: incorrectly filled Content-Type header
// Extract plural forms:
const char * plurals = strstr(header, "Plural-Forms:");
if ( plurals )
{
plurals += 13; // strlen("Plural-Forms:")
const char * const pluralsEnd = strchr(plurals, '\n');
if ( pluralsEnd )
{
const size_t pluralsLen = pluralsEnd - plurals;
wxCharBuffer buf(pluralsLen);
strncpy(buf.data(), plurals, pluralsLen);
wxPluralFormsCalculator * const
pCalculator = wxPluralFormsCalculator::make(buf);
if ( pCalculator )
{
rPluralFormsCalculator.reset(pCalculator);
}
else
{
wxLogVerbose(_("Failed to parse Plural-Forms: '%s'"),
buf.data());
}
}
}
if ( !rPluralFormsCalculator.get() )
rPluralFormsCalculator.reset(wxPluralFormsCalculator::make());
}
// everything is fine
return true;
}
bool wxMsgCatalogFile::FillHash(wxStringToStringHashMap& hash,
const wxString& domain) const
{
wxUnusedVar(domain); // silence warning in Unicode build
// conversion to use to convert catalog strings to the GUI encoding
wxMBConv *inputConv = NULL;
wxMBConv *inputConvPtr = NULL; // same as inputConv but safely deleteable
if ( !m_charset.empty() )
{
#if !wxUSE_UNICODE && wxUSE_FONTMAP
// determine if we need any conversion at all
wxFontEncoding encCat = wxFontMapperBase::GetEncodingFromName(m_charset);
if ( encCat != wxLocale::GetSystemEncoding() )
#endif
{
inputConvPtr =
inputConv = new wxCSConv(m_charset);
}
}
else // no need or not possible to convert the encoding
{
#if wxUSE_UNICODE
// we must somehow convert the narrow strings in the message catalog to
// wide strings, so use the default conversion if we have no charset
inputConv = wxConvCurrent;
#endif
}
#if !wxUSE_UNICODE
wxString msgIdCharset = gs_msgIdCharset[domain];
// conversion to apply to msgid strings before looking them up: we only
// need it if the msgids are neither in 7 bit ASCII nor in the same
// encoding as the catalog
wxCSConv *sourceConv = msgIdCharset.empty() || (msgIdCharset == m_charset)
? NULL
: new wxCSConv(msgIdCharset);
#endif // !wxUSE_UNICODE
for (size_t32 i = 0; i < m_numStrings; i++)
{
const char *data = StringAtOfs(m_pOrigTable, i);
if (!data)
return false; // may happen for invalid MO files
wxString msgid;
#if wxUSE_UNICODE
msgid = wxString(data, *inputConv);
#else // ASCII
if ( inputConv && sourceConv )
msgid = wxString(inputConv->cMB2WC(data), *sourceConv);
else
msgid = data;
#endif // wxUSE_UNICODE
data = StringAtOfs(m_pTransTable, i);
if (!data)
return false; // may happen for invalid MO files
size_t length = Swap(m_pTransTable[i].nLen);
size_t offset = 0;
size_t index = 0;
while (offset < length)
{
const char * const str = data + offset;
wxString msgstr;
#if wxUSE_UNICODE
msgstr = wxString(str, *inputConv);
#else
if ( inputConv )
msgstr = wxString(inputConv->cMB2WC(str), *wxConvUI);
else
msgstr = str;
#endif // wxUSE_UNICODE/!wxUSE_UNICODE
if ( !msgstr.empty() )
{
hash[index == 0 ? msgid : msgid + wxChar(index)] = msgstr;
}
// skip this string
// IMPORTANT: accesses to the 'data' pointer are valid only for
// the first 'length+1' bytes (GNU specs says that the
// final NUL is not counted in length); using wxStrnlen()
// we make sure we don't access memory beyond the valid range
// (which otherwise may happen for invalid MO files):
offset += wxStrnlen(str, length - offset) + 1;
++index;
}
}
#if !wxUSE_UNICODE
delete sourceConv;
#endif
delete inputConvPtr;
return true;
}
// ----------------------------------------------------------------------------
// wxMsgCatalog class
// ----------------------------------------------------------------------------
#if !wxUSE_UNICODE
wxMsgCatalog::~wxMsgCatalog()
{
if ( m_conv )
{
if ( wxConvUI == m_conv )
{
// we only change wxConvUI if it points to wxConvLocal so we reset
// it back to it too
wxConvUI = &wxConvLocal;
}
delete m_conv;
}
}
#endif // !wxUSE_UNICODE
/* static */
wxMsgCatalog *wxMsgCatalog::CreateFromFile(const wxString& filename,
const wxString& domain)
{
wxScopedPtr<wxMsgCatalog> cat(new wxMsgCatalog(domain));
wxMsgCatalogFile file;
if ( !file.LoadFile(filename, cat->m_pluralFormsCalculator) )
return NULL;
if ( !file.FillHash(cat->m_messages, domain) )
return NULL;
return cat.release();
}
/* static */
wxMsgCatalog *wxMsgCatalog::CreateFromData(const wxScopedCharBuffer& data,
const wxString& domain)
{
wxScopedPtr<wxMsgCatalog> cat(new wxMsgCatalog(domain));
wxMsgCatalogFile file;
if ( !file.LoadData(data, cat->m_pluralFormsCalculator) )
return NULL;
if ( !file.FillHash(cat->m_messages, domain) )
return NULL;
return cat.release();
}
const wxString *wxMsgCatalog::GetString(const wxString& str, unsigned n) const
{
int index = 0;
if (n != UINT_MAX)
{
index = m_pluralFormsCalculator->evaluate(n);
}
wxStringToStringHashMap::const_iterator i;
if (index != 0)
{
i = m_messages.find(wxString(str) + wxChar(index)); // plural
}
else
{
i = m_messages.find(str);
}
if ( i != m_messages.end() )
{
return &i->second;
}
else
return NULL;
}
// ----------------------------------------------------------------------------
// wxTranslations
// ----------------------------------------------------------------------------
namespace
{
wxTranslations *gs_translations = NULL;
bool gs_translationsOwned = false;
} // anonymous namespace
/*static*/
wxTranslations *wxTranslations::Get()
{
return gs_translations;
}
/*static*/
void wxTranslations::Set(wxTranslations *t)
{
if ( gs_translationsOwned )
delete gs_translations;
gs_translations = t;
gs_translationsOwned = true;
}
/*static*/
void wxTranslations::SetNonOwned(wxTranslations *t)
{
if ( gs_translationsOwned )
delete gs_translations;
gs_translations = t;
gs_translationsOwned = false;
}
wxTranslations::wxTranslations()
{
m_pMsgCat = NULL;
m_loader = new wxFileTranslationsLoader;
}
wxTranslations::~wxTranslations()
{
delete m_loader;
// free catalogs memory
wxMsgCatalog *pTmpCat;
while ( m_pMsgCat != NULL )
{
pTmpCat = m_pMsgCat;
m_pMsgCat = m_pMsgCat->m_pNext;
delete pTmpCat;
}
}
void wxTranslations::SetLoader(wxTranslationsLoader *loader)
{
wxCHECK_RET( loader, "loader can't be NULL" );
delete m_loader;
m_loader = loader;
}
void wxTranslations::SetLanguage(wxLanguage lang)
{
if ( lang == wxLANGUAGE_DEFAULT )
SetLanguage("");
else
SetLanguage(wxLocale::GetLanguageCanonicalName(lang));
}
void wxTranslations::SetLanguage(const wxString& lang)
{
m_lang = lang;
}
wxArrayString wxTranslations::GetAvailableTranslations(const wxString& domain) const
{
wxCHECK_MSG( m_loader, wxArrayString(), "loader can't be NULL" );
return m_loader->GetAvailableTranslations(domain);
}
bool wxTranslations::AddStdCatalog()
{
if ( !AddCatalog(wxS("wxstd")) )
return false;
// there may be a catalog with toolkit specific overrides, it is not
// an error if this does not exist
wxString port(wxPlatformInfo::Get().GetPortIdName());
if ( !port.empty() )
{
AddCatalog(port.BeforeFirst(wxS('/')).MakeLower());
}
return true;
}
bool wxTranslations::AddCatalog(const wxString& domain)
{
return AddCatalog(domain, wxLANGUAGE_ENGLISH_US);
}
#if !wxUSE_UNICODE
bool wxTranslations::AddCatalog(const wxString& domain,
wxLanguage msgIdLanguage,
const wxString& msgIdCharset)
{
gs_msgIdCharset[domain] = msgIdCharset;
return AddCatalog(domain, msgIdLanguage);
}
#endif // !wxUSE_UNICODE
bool wxTranslations::AddCatalog(const wxString& domain,
wxLanguage msgIdLanguage)
{
const wxString msgIdLang = wxLocale::GetLanguageCanonicalName(msgIdLanguage);
const wxString domain_lang = GetBestTranslation(domain, msgIdLang);
if ( domain_lang.empty() )
{
wxLogTrace(TRACE_I18N,
wxS("no suitable translation for domain '%s' found"),
domain);
return false;
}
wxLogTrace(TRACE_I18N,
wxS("adding '%s' translation for domain '%s' (msgid language '%s')"),
domain_lang, domain, msgIdLang);
return LoadCatalog(domain, domain_lang, msgIdLang);
}
bool wxTranslations::LoadCatalog(const wxString& domain, const wxString& lang, const wxString& msgIdLang)
{
wxCHECK_MSG( m_loader, false, "loader can't be NULL" );
wxMsgCatalog *cat = NULL;
#if wxUSE_FONTMAP
// first look for the catalog for this language and the current locale:
// notice that we don't use the system name for the locale as this would
// force us to install catalogs in different locations depending on the
// system but always use the canonical name
wxFontEncoding encSys = wxLocale::GetSystemEncoding();
if ( encSys != wxFONTENCODING_SYSTEM )
{
wxString fullname(lang);
fullname << wxS('.') << wxFontMapperBase::GetEncodingName(encSys);
cat = m_loader->LoadCatalog(domain, fullname);
}
#endif // wxUSE_FONTMAP
if ( !cat )
{
// Next try: use the provided name language name:
cat = m_loader->LoadCatalog(domain, lang);
}
if ( !cat )
{
// Also try just base locale name: for things like "fr_BE" (Belgium
// French) we should use fall back on plain "fr" if no Belgium-specific
// message catalogs exist
wxString baselang = lang.BeforeFirst('_');
if ( lang != baselang )
cat = m_loader->LoadCatalog(domain, baselang);
}
if ( !cat )
{
// It is OK to not load catalog if the msgid language and m_language match,
// in which case we can directly display the texts embedded in program's
// source code:
if ( msgIdLang == lang )
return true;
}
if ( cat )
{
// add it to the head of the list so that in GetString it will
// be searched before the catalogs added earlier
cat->m_pNext = m_pMsgCat;
m_pMsgCat = cat;
return true;
}
else
{
// Nothing worked, the catalog just isn't there
wxLogTrace(TRACE_I18N,
"Catalog \"%s.mo\" not found for language \"%s\".",
domain, lang);
return false;
}
}
// check if the given catalog is loaded
bool wxTranslations::IsLoaded(const wxString& domain) const
{
return FindCatalog(domain) != NULL;
}
wxString wxTranslations::GetBestTranslation(const wxString& domain,
wxLanguage msgIdLanguage)
{
const wxString lang = wxLocale::GetLanguageCanonicalName(msgIdLanguage);
return GetBestTranslation(domain, lang);
}
wxString wxTranslations::GetBestTranslation(const wxString& domain,
const wxString& msgIdLanguage)
{
// explicitly set language should always be respected
if ( !m_lang.empty() )
return m_lang;
wxArrayString available(GetAvailableTranslations(domain));
// it's OK to have duplicates, so just add msgid language
available.push_back(msgIdLanguage);
available.push_back(msgIdLanguage.BeforeFirst('_'));
wxLogTrace(TRACE_I18N, "choosing best language for domain '%s'", domain);
LogTraceArray(" - available translations", available);
const wxString lang = GetPreferredUILanguage(available);
wxLogTrace(TRACE_I18N, " => using language '%s'", lang);
return lang;
}
/* static */
const wxString& wxTranslations::GetUntranslatedString(const wxString& str)
{
wxLocaleUntranslatedStrings& strings = wxThreadInfo.untranslatedStrings;
wxLocaleUntranslatedStrings::iterator i = strings.find(str);
if ( i == strings.end() )
return *strings.insert(str).first;
return *i;
}
const wxString *wxTranslations::GetTranslatedString(const wxString& origString,
const wxString& domain) const
{
return GetTranslatedString(origString, UINT_MAX, domain);
}
const wxString *wxTranslations::GetTranslatedString(const wxString& origString,
unsigned n,
const wxString& domain) const
{
if ( origString.empty() )
return NULL;
const wxString *trans = NULL;
wxMsgCatalog *pMsgCat;
if ( !domain.empty() )
{
pMsgCat = FindCatalog(domain);
// does the catalog exist?
if ( pMsgCat != NULL )
trans = pMsgCat->GetString(origString, n);
}
else
{
// search in all domains
for ( pMsgCat = m_pMsgCat; pMsgCat != NULL; pMsgCat = pMsgCat->m_pNext )
{
trans = pMsgCat->GetString(origString, n);
if ( trans != NULL ) // take the first found
break;
}
}
if ( trans == NULL )
{
wxLogTrace
(
TRACE_I18N,
"string \"%s\"%s not found in %slocale '%s'.",
origString,
(n != UINT_MAX ? wxString::Format("[%ld]", (long)n) : wxString()),
(!domain.empty() ? wxString::Format("domain '%s' ", domain) : wxString()),
m_lang
);
}
return trans;
}
wxString wxTranslations::GetHeaderValue(const wxString& header,
const wxString& domain) const
{
if ( header.empty() )
return wxEmptyString;
const wxString *trans = NULL;
wxMsgCatalog *pMsgCat;
if ( !domain.empty() )
{
pMsgCat = FindCatalog(domain);
// does the catalog exist?
if ( pMsgCat == NULL )
return wxEmptyString;
trans = pMsgCat->GetString(wxEmptyString, UINT_MAX);
}
else
{
// search in all domains
for ( pMsgCat = m_pMsgCat; pMsgCat != NULL; pMsgCat = pMsgCat->m_pNext )
{
trans = pMsgCat->GetString(wxEmptyString, UINT_MAX);
if ( trans != NULL ) // take the first found
break;
}
}
if ( !trans || trans->empty() )
return wxEmptyString;
size_t found = trans->find(header);
if ( found == wxString::npos )
return wxEmptyString;
found += header.length() + 2 /* ': ' */;
// Every header is separated by \n
size_t endLine = trans->find(wxS('\n'), found);
size_t len = (endLine == wxString::npos) ?
wxString::npos : (endLine - found);
return trans->substr(found, len);
}
// find catalog by name in a linked list, return NULL if !found
wxMsgCatalog *wxTranslations::FindCatalog(const wxString& domain) const
{
// linear search in the linked list
wxMsgCatalog *pMsgCat;
for ( pMsgCat = m_pMsgCat; pMsgCat != NULL; pMsgCat = pMsgCat->m_pNext )
{
if ( pMsgCat->GetDomain() == domain )
return pMsgCat;
}
return NULL;
}
// ----------------------------------------------------------------------------
// wxFileTranslationsLoader
// ----------------------------------------------------------------------------
namespace
{
// the list of the directories to search for message catalog files
wxArrayString gs_searchPrefixes;
// return the directories to search for message catalogs under the given
// prefix, separated by wxPATH_SEP
wxString GetMsgCatalogSubdirs(const wxString& prefix, const wxString& lang)
{
// Search first in Unix-standard prefix/lang/LC_MESSAGES, then in
// prefix/lang.
//
// Note that we use LC_MESSAGES on all platforms and not just Unix, because
// it doesn't cost much to look into one more directory and doing it this
// way has two important benefits:
// a) we don't break compatibility with wx-2.6 and older by stopping to
// look in a directory where the catalogs used to be and thus silently
// breaking apps after they are recompiled against the latest wx
// b) it makes it possible to package app's support files in the same
// way on all target platforms
const wxString prefixAndLang = wxFileName(prefix, lang).GetFullPath();
wxString searchPath;
searchPath.reserve(4*prefixAndLang.length());
searchPath
#ifdef __WXOSX__
<< prefixAndLang << ".lproj/LC_MESSAGES" << wxPATH_SEP
<< prefixAndLang << ".lproj" << wxPATH_SEP
#endif
<< prefixAndLang << wxFILE_SEP_PATH << "LC_MESSAGES" << wxPATH_SEP
<< prefixAndLang << wxPATH_SEP
;
return searchPath;
}
bool HasMsgCatalogInDir(const wxString& dir, const wxString& domain)
{
return wxFileName(dir, domain, "mo").FileExists() ||
wxFileName(dir + wxFILE_SEP_PATH + "LC_MESSAGES", domain, "mo").FileExists();
}
// get prefixes to locale directories; if lang is empty, don't point to
// OSX's .lproj bundles
wxArrayString GetSearchPrefixes()
{
wxArrayString paths;
// first take the entries explicitly added by the program
paths = gs_searchPrefixes;
#if wxUSE_STDPATHS
// then look in the standard location
wxString stdp;
stdp = wxStandardPaths::Get().GetResourcesDir();
if ( paths.Index(stdp) == wxNOT_FOUND )
paths.Add(stdp);
#endif // wxUSE_STDPATHS
// last look in default locations
#ifdef __UNIX__
// LC_PATH is a standard env var containing the search path for the .mo
// files
const char *pszLcPath = wxGetenv("LC_PATH");
if ( pszLcPath )
{
const wxString lcp = pszLcPath;
if ( paths.Index(lcp) == wxNOT_FOUND )
paths.Add(lcp);
}
// also add the one from where wxWin was installed:
wxString wxp = wxGetInstallPrefix();
if ( !wxp.empty() )
{
wxp += wxS("/share/locale");
if ( paths.Index(wxp) == wxNOT_FOUND )
paths.Add(wxp);
}
#endif // __UNIX__
return paths;
}
// construct the search path for the given language
wxString GetFullSearchPath(const wxString& lang)
{
wxString searchPath;
searchPath.reserve(500);
const wxArrayString prefixes = GetSearchPrefixes();
for ( wxArrayString::const_iterator i = prefixes.begin();
i != prefixes.end();
++i )
{
const wxString p = GetMsgCatalogSubdirs(*i, lang);
if ( !searchPath.empty() )
searchPath += wxPATH_SEP;
searchPath += p;
}
return searchPath;
}
} // anonymous namespace
void wxFileTranslationsLoader::AddCatalogLookupPathPrefix(const wxString& prefix)
{
if ( gs_searchPrefixes.Index(prefix) == wxNOT_FOUND )
{
gs_searchPrefixes.Add(prefix);
}
//else: already have it
}
wxMsgCatalog *wxFileTranslationsLoader::LoadCatalog(const wxString& domain,
const wxString& lang)
{
wxString searchPath = GetFullSearchPath(lang);
LogTraceLargeArray
(
wxString::Format("looking for \"%s.mo\" in search path", domain),
wxSplit(searchPath, wxPATH_SEP[0])
);
wxFileName fn(domain);
fn.SetExt(wxS("mo"));
wxString strFullName;
if ( !wxFindFileInPath(&strFullName, searchPath, fn.GetFullPath()) )
return NULL;
// open file and read its data
wxLogVerbose(_("using catalog '%s' from '%s'."), domain, strFullName.c_str());
wxLogTrace(TRACE_I18N, wxS("Using catalog \"%s\"."), strFullName.c_str());
return wxMsgCatalog::CreateFromFile(strFullName, domain);
}
wxArrayString wxFileTranslationsLoader::GetAvailableTranslations(const wxString& domain) const
{
wxArrayString langs;
const wxArrayString prefixes = GetSearchPrefixes();
LogTraceLargeArray
(
wxString::Format("looking for available translations of \"%s\" in search path", domain),
prefixes
);
for ( wxArrayString::const_iterator i = prefixes.begin();
i != prefixes.end();
++i )
{
if ( i->empty() )
continue;
wxDir dir;
if ( !dir.Open(*i) )
continue;
wxString lang;
for ( bool ok = dir.GetFirst(&lang, "", wxDIR_DIRS);
ok;
ok = dir.GetNext(&lang) )
{
const wxString langdir = *i + wxFILE_SEP_PATH + lang;
if ( HasMsgCatalogInDir(langdir, domain) )
{
#ifdef __WXOSX__
wxString rest;
if ( lang.EndsWith(".lproj", &rest) )
lang = rest;
#endif // __WXOSX__
wxLogTrace(TRACE_I18N,
"found %s translation of \"%s\" in %s",
lang, domain, langdir);
langs.push_back(lang);
}
}
}
return langs;
}
// ----------------------------------------------------------------------------
// wxResourceTranslationsLoader
// ----------------------------------------------------------------------------
#ifdef __WINDOWS__
wxMsgCatalog *wxResourceTranslationsLoader::LoadCatalog(const wxString& domain,
const wxString& lang)
{
const void *mo_data = NULL;
size_t mo_size = 0;
const wxString resname = wxString::Format("%s_%s", domain, lang);
if ( !wxLoadUserResource(&mo_data, &mo_size,
resname,
GetResourceType().t_str(),
GetModule()) )
return NULL;
wxLogTrace(TRACE_I18N,
"Using catalog from Windows resource \"%s\".", resname);
wxMsgCatalog *cat = wxMsgCatalog::CreateFromData(
wxCharBuffer::CreateNonOwned(static_cast<const char*>(mo_data), mo_size),
domain);
if ( !cat )
{
wxLogWarning(_("Resource '%s' is not a valid message catalog."), resname);
}
return cat;
}
namespace
{
struct EnumCallbackData
{
wxString prefix;
wxArrayString langs;
};
BOOL CALLBACK EnumTranslations(HMODULE WXUNUSED(hModule),
LPCTSTR WXUNUSED(lpszType),
LPTSTR lpszName,
LONG_PTR lParam)
{
wxString name(lpszName);
name.MakeLower(); // resource names are case insensitive
EnumCallbackData *data = reinterpret_cast<EnumCallbackData*>(lParam);
wxString lang;
if ( name.StartsWith(data->prefix, &lang) && !lang.empty() )
data->langs.push_back(lang);
return TRUE; // continue enumeration
}
} // anonymous namespace
wxArrayString wxResourceTranslationsLoader::GetAvailableTranslations(const wxString& domain) const
{
EnumCallbackData data;
data.prefix = domain + "_";
data.prefix.MakeLower(); // resource names are case insensitive
if ( !EnumResourceNames(GetModule(),
GetResourceType().t_str(),
EnumTranslations,
reinterpret_cast<LONG_PTR>(&data)) )
{
const DWORD err = GetLastError();
if ( err != NO_ERROR && err != ERROR_RESOURCE_TYPE_NOT_FOUND )
{
wxLogSysError(_("Couldn't enumerate translations"));
}
}
return data.langs;
}
#endif // __WINDOWS__
// ----------------------------------------------------------------------------
// wxTranslationsModule module (for destruction of gs_translations)
// ----------------------------------------------------------------------------
class wxTranslationsModule: public wxModule
{
DECLARE_DYNAMIC_CLASS(wxTranslationsModule)
public:
wxTranslationsModule() {}
bool OnInit()
{
return true;
}
void OnExit()
{
if ( gs_translationsOwned )
delete gs_translations;
gs_translations = NULL;
gs_translationsOwned = true;
}
};
IMPLEMENT_DYNAMIC_CLASS(wxTranslationsModule, wxModule)
#endif // wxUSE_INTL
| lgpl-3.0 |
michaelrhughes/opencore-aacdec | src/long_term_synthesis.c | 21 | 44079 | /* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
* -------------------------------------------------------------------
*/
/*
Filename: long_term_synthesis.cpp
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
Inputs:
win_seq = type of window sequence (WINDOW_SEQUENCE).
sfb_per_win = number of scalefactor bands for each window, 1024 for
long window, 128 for short window, type of Int.
win_sfb_top = buffer (Int16) containing the top coefficient per
scalefactor band for each window.
win_prediction_used = buffer (Int) containing the prediction flag
information for short windows. Each item in the
buffer toggles prediction on(1)/off(0) for each
window separately.
sfb_prediction_used = buffer (Int) containing the prediction flag
information for scalefactor band(sfb). Each item
toggle prediction on(1)/off(0) on each scalefactor
band of every window.
current_frame = channel buffer (Int32) containing the dequantized
spectral coefficients or errors of current frame.
q_format = buffer (Int) containing Q format for each scalefactor band of
input current_frame.
predicted_spectral = buffer (Int32) containing predicted spectral
components of current frame.
pred_q_format = Q format (Int) for predicted spectral components of
current frame.
coef_per_win = number of coefficients per window for short windows.
type of Int.
short_window_num = number of short windows, type of Int.
reconstruct_sfb_num = number of scalefactor bands used for reconstruction
for short windows, type of Int.
Local Stores/Buffers/Pointers Needed:
None
Global Stores/Buffers/Pointers Needed:
None
Outputs:
None
Pointers and Buffers Modified:
current_frame contents are the dequantized spectrum with a prediction
vector added when prediction is turned on.
q_format contents are updated with the new Q format (Int) for each
scalefactor band of output current_frame buffer.
Local Stores Modified:
None
Global Stores Modified:
None
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
This function performs long term synthesis using transmitted spectral
coeffients or errors and predicted spectral components.
Long term synthesis is part of long term prediction (LTP) which is used to
reduce the redundancy of a signal between successive coding frames. The
functionality of long term synthesis is to reconstruct the frequency domain
spectral by adding the predicted spectral components and the transmitted
spectral error when prediction is turned on.
------------------------------------------------------------------------------
REQUIREMENTS
None
------------------------------------------------------------------------------
REFERENCES
(1) ISO/IEC 14496-3:1999(E)
Part 3: Audio
Subpart 4.6.6 Long Term Prediction (LTP)
(2) MPEG-2 NBC Audio Decoder
"This software module was originally developed by Nokia in the course
of development of the MPEG-2 AAC/MPEG-4 Audio standard ISO/IEC13818-7,
14496-1, 2 and 3. This software module is an implementation of a part
of one or more MPEG-2 AAC/MPEG-4 Audio tools as specified by the MPEG-2
aac/MPEG-4 Audio standard. ISO/IEC gives users of the MPEG-2aac/MPEG-4
Audio standards free license to this software module or modifications
thereof for use in hardware or software products claiming conformance
to the MPEG-2 aac/MPEG-4 Audio standards. Those intending to use this
software module in hardware or software products are advised that this
use may infringe existing patents. The original developer of this
software module, the subsequent editors and their companies, and ISO/IEC
have no liability for use of this software module or modifications
thereof in an implementation. Copyright is not released for non MPEG-2
aac/MPEG-4 Audio conforming products. The original developer retains
full right to use the code for the developer's own purpose, assign or
donate the code to a third party and to inhibit third party from using
the code for non MPEG-2 aac/MPEG-4 Audio conforming products. This
copyright notice must be included in all copies or derivative works.
Copyright (c)1997.
------------------------------------------------------------------------------
PSEUDO-CODE
pPredicted_spectral = &predicted_spectral[0];
pPredicted_spectral_start = pPredicted_spectral;
pSfb_prediction_used = &sfb_prediction_used[0];
IF (win_seq != EIGHT_SHORT_SEQUENCE)
THEN
sfb_offset = 0;
pWinSfbTop = &pWin_sfb_top[0];
pQ_format = &q_format[0];
FOR (i = sfb_per_frame; i>0; i--)
IF (*(pSfb_prediction_used++) != FALSE)
THEN
pPredicted_offset = pPredicted_spectral_start +
sfb_offset;
pCurrent_frame = ¤t_frame[sfb_offset];
quarter_sfb_width = (*pWinSfbTop - sfb_offset) >> 2;
max = 0;
pPredicted_spectral = pPredicted_offset;
FOR (j = (*pWinSfbTop - sfb_offset); j>0 ; j--)
tmpInt32 = *(pPredicted_spectral++);
IF (tmpInt32 < 0)
THEN
tmpInt32 = -tmpInt32;
ENDIF
max |= tmpInt32;
ENDFOR
tmpInt = 0;
IF (max != 0)
THEN
WHILE (max < 0x40000000L)
max <<= 1;
tmpInt++;
ENDWHILE
pPredicted_spectral = pPredicted_offset;
FOR (j = quarter_sfb_width; j>0 ; j--)
*(pPredicted_spectral++) <<= tmpInt;
*(pPredicted_spectral++) <<= tmpInt;
*(pPredicted_spectral++) <<= tmpInt;
*(pPredicted_spectral++) <<= tmpInt;
ENDFOR
adjusted_pred_q = pred_q_format + tmpInt;
pPredicted_spectral = pPredicted_offset;
shift_factor = *(pQ_format) - adjusted_pred_q;
IF ((shift_factor >= 0) && (shift_factor < 31))
THEN
shift_factor = shift_factor + 1;
FOR (j = quarter_sfb_width; j>0 ; j--)
*(pCurrent_frame++) =
(*pCurrent_frame>>shift_factor)
+ (*(pPredicted_spectral++)>>1);
*(pCurrent_frame++) =
(*pCurrent_frame>>shift_factor)
+ (*(pPredicted_spectral++)>>1);
*(pCurrent_frame++) =
(*pCurrent_frame>>shift_factor)
+ (*(pPredicted_spectral++)>>1);
*(pCurrent_frame++) =
(*pCurrent_frame>>shift_factor)
+ (*(pPredicted_spectral++)>>1);
ENDFOR
*(pQ_format) = adjusted_pred_q - 1;
ELSEIF (shift_factor >= 31)
THEN
FOR (j = quarter_sfb_width; j>0 ; j--)
*(pCurrent_frame++) = *(pPredicted_spectral++);
*(pCurrent_frame++) = *(pPredicted_spectral++);
*(pCurrent_frame++) = *(pPredicted_spectral++);
*(pCurrent_frame++) = *(pPredicted_spectral++);
ENDFOR
*(pQ_format) = adjusted_pred_q;
ELSEIF ((shift_factor < 0) && (shift_factor > -31))
THEN
shift_factor = 1 - shift_factor;
FOR (j = quarter_sfb_width; j>0 ; j--)
*(pCurrent_frame++) = (*pCurrent_frame>>1) +
(*(pPredicted_spectral++)>>shift_factor);
*(pCurrent_frame++) = (*pCurrent_frame>>1) +
(*(pPredicted_spectral++)>>shift_factor);
*(pCurrent_frame++) = (*pCurrent_frame>>1) +
(*(pPredicted_spectral++)>>shift_factor);
*(pCurrent_frame++) = (*pCurrent_frame>>1) +
(*(pPredicted_spectral++)>>shift_factor);
ENDFOR
*(pQ_format) = *(pQ_format) - 1;
ENDIF
ENDIF
ENDIF [ IF (*(pSfb_prediction_used++) != FALSE) ]
sfb_offset = *pWinSfbTop;
pWinSfbTop = pWinSfbTop + 1;
pQ_format = pQ_format + 1;
ENDFOR [ FOR (i = sfb_per_frame; i>0; i--) ]
ELSE
pCurrent_frame_start = ¤t_frame[0];
pQ_format_start = &q_format[0];
num_sfb = sfb_per_win[0];
FOR (wnd=0; wnd<short_window_num; wnd++)
pWinSfbTop = &pWin_sfb_top[0];
pQ_format = pQ_format_start;
IF (win_prediction_used[wnd] != FALSE)
THEN
sfb_offset = 0;
FOR (i = reconstruct_sfb_num; i > 0; i--)
pPredicted_offset = pPredicted_spectral_start +
sfb_offset;
pCurrent_frame = pCurrent_frame_start + sfb_offset;
quarter_sfb_width = (*pWinSfbTop - sfb_offset) >> 2;
max = 0;
pPredicted_spectral = pPredicted_offset;
FOR (j = (*pWinSfbTop - sfb_offset); j>0 ; j--)
tmpInt32 = *(pPredicted_spectral++);
IF (tmpInt32 < 0)
THEN
tmpInt32 = -tmpInt32;
ENDIF
max |= tmpInt32;
ENDFOR
tmpInt = 0;
IF (max != 0)
THEN
WHILE (max < 0x40000000L)
max <<= 1;
tmpInt++;
ENDWHILE
pPredicted_spectral = pPredicted_offset;
FOR (j = quarter_sfb_width; j>0 ; j--)
*(pPredicted_spectral++) <<= tmpInt;
*(pPredicted_spectral++) <<= tmpInt;
*(pPredicted_spectral++) <<= tmpInt;
*(pPredicted_spectral++) <<= tmpInt;
ENDFOR
adjusted_pred_q = pred_q_format + tmpInt;
pPredicted_spectral = pPredicted_offset;
shift_factor = *(pQ_format) - adjusted_pred_q;
IF ((shift_factor >= 0) && (shift_factor < 31))
THEN
shift_factor = shift_factor + 1;
FOR (j = quarter_sfb_width; j>0 ; j--)
*(pCurrent_frame++) =
(*pCurrent_frame>>shift_factor) +
(*(pPredicted_spectral++)>>1);
*(pCurrent_frame++) =
(*pCurrent_frame>>shift_factor) +
(*(pPredicted_spectral++)>>1);
*(pCurrent_frame++) =
(*pCurrent_frame>>shift_factor) +
(*(pPredicted_spectral++)>>1);
*(pCurrent_frame++) =
(*pCurrent_frame>>shift_factor) +
(*(pPredicted_spectral++)>>1);
ENDFOR
*(pQ_format) = adjusted_pred_q - 1;
ELSEIF (shift_factor >= 31)
THEN
FOR (j = quarter_sfb_width; j>0 ; j--)
*(pCurrent_frame++) = *(pPredicted_spectral++);
*(pCurrent_frame++) = *(pPredicted_spectral++);
*(pCurrent_frame++) = *(pPredicted_spectral++);
*(pCurrent_frame++) = *(pPredicted_spectral++);
ENDFOR
*(pQ_format) = adjusted_pred_q;
ELSEIF ((shift_factor < 0) && (shift_factor > -31))
THEN
shift_factor = 1 - shift_factor;
FOR (j = quarter_sfb_width; j>0 ; j--)
*(pCurrent_frame++) = (*pCurrent_frame>>1) +
(*(pPredicted_spectral++)>>shift_factor);
*(pCurrent_frame++) = (*pCurrent_frame>>1) +
(*(pPredicted_spectral++)>>shift_factor);
*(pCurrent_frame++) = (*pCurrent_frame>>1) +
(*(pPredicted_spectral++)>>shift_factor);
*(pCurrent_frame++) = (*pCurrent_frame>>1) +
(*(pPredicted_spectral++)>>shift_factor);
ENDFOR
*(pQ_format) = *(pQ_format) - 1;
ENDIF
ENDIF
sfb_offset = *pWinSfbTop;
pWinSfbTop = pWinSfbTop + 1;
pQ_format = pQ_format + 1;
ENDFOR [ FOR (i = reconstruct_sfb_num; i > 0; i--) ]
ENDIF [ IF (win_prediction_used[wnd] != FALSE) ]
pPredicted_spectral_start = pPredicted_spectral_start + num_sfb;
pCurrent_frame_start = pCurrent_frame_start + num_sfb;
wnd_offset = wnd_offset + num_sfb;
pQ_format_start = pQ_format_start + num_sfb;
ENDFOR [ FOR (wnd=0; wnd<short_window_num; wnd++) ]
ENDIF [ IF (win_seq != EIGHT_SHORT_SEQUENCE) ]
RETURN
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "pv_audio_type_defs.h"
#include "e_window_sequence.h"
#include "long_term_synthesis.h"
/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here. Include conditional
; compile variables also.
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL STORE/BUFFER/POINTER DEFINITIONS
; Variable declaration - defined here and used outside this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL FUNCTION REFERENCES
; Declare functions defined elsewhere and referenced in this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; FUNCTION CODE
----------------------------------------------------------------------------*/
void long_term_synthesis(
WINDOW_SEQUENCE win_seq,
Int sfb_per_win,
Int16 win_sfb_top[],
Int win_prediction_used[],
Int sfb_prediction_used[],
Int32 current_frame[],
Int q_format[], /* for each sfb */
Int32 predicted_spectral[],
Int pred_q_format, /* for predicted_spectral[] */
Int coef_per_win,
Int short_window_num,
Int reconstruct_sfb_num)
{
/*----------------------------------------------------------------------------
; Define all local variables
----------------------------------------------------------------------------*/
/* Scalefactor band offset */
Int sfb_offset;
/* Window index */
Int wnd;
/* Pointer to array containing predicted samples */
Int32 *pPredicted_spectral;
/* Pointer to the beginning of array containing predicted samples */
Int32 *pPredicted_spectral_start;
Int32 *pPredicted_offset;
/* Pointer to array containing current spectral components for a channel*/
Int32 *pCurrent_frame;
/* Another pointer to array containing current spectral components */
Int32 *pCurrent_frame_start;
/* Pointer to prediction flag for each scalefactor band */
Int *pSfb_prediction_used;
/* Pointer to top coef per scalefactor band */
Int16 *pWinSfbTop;
/* Pointer to q_format array */
Int *pQ_format;
Int *pQ_format_start;
Int32 temp;
Int i;
Int j;
Int quarter_sfb_width;
Int num_sfb;
Int shift_factor;
UInt32 max;
Int32 tmpInt32;
Int tmpInt;
Int adjusted_pred_q;
Int pred_shift;
/*----------------------------------------------------------------------------
; Function body here
----------------------------------------------------------------------------*/
/* Initialize pointers */
pPredicted_spectral = &predicted_spectral[0];
pPredicted_spectral_start = pPredicted_spectral;
/*
* NOTE:
* sfb_prediction_used[] start from 0 or 1 depending on nok_lt_decode.c;
* currently we agree to make it start from 0;
*/
pSfb_prediction_used = &sfb_prediction_used[0];
/*********************************/
/* LTP synthesis for long window */
/*********************************/
if (win_seq != EIGHT_SHORT_SEQUENCE)
{
/*******************************************************/
/* Reconstruction of current frequency domain spectrum */
/*******************************************************/
/* Initialize scalefactor band offset */
sfb_offset = 0;
/*
* Reconstruction is processed on scalefactor band basis.
* 1. When prediction is turned on, all the predicted spectral
* components will be used for reconstruction.
* 2. When prediction is turned off, reconstruction is not
* needed. Spectral components of current frame will directly
* come from the transmitted data.
*/
pWinSfbTop = &win_sfb_top[0];
pQ_format = &q_format[0];
for (i = sfb_per_win; i > 0; i--)
{
/* Check prediction flag for each scalefactor band. */
if (*(pSfb_prediction_used++) != FALSE)
{
/*
* Prediction is on. Do reconstruction routine.
* Reconstruct spectral component of current
* frame by adding the predicted spectral
* components and the quantized prediction
* errors that reconstructed from transmitted
* data when prediction is turned on.
*/
/* Set pointers to the offset of scalefactor bands */
pPredicted_offset = pPredicted_spectral_start +
sfb_offset;
pCurrent_frame = ¤t_frame[sfb_offset];
/*
* (*pWinSfbTop - sfb_offset) is number of coefficients
* of the scalefactor band.
* ">>2" is used to set up for later unrolling the loop.
*/
quarter_sfb_width = (*pWinSfbTop - sfb_offset) >> 2;
/*
* Adjust pred_q_format and predicted_spectral() to
* maximum resolution.
*/
max = 0;
pPredicted_spectral = pPredicted_offset;
/* Find the maximum absolute value */
for (j = (*pWinSfbTop - sfb_offset); j > 0 ; j--)
{
tmpInt32 = *(pPredicted_spectral++);
/*
* Note: overflow is protected here even though
* tmpInt32 = 0x80000000 is very rare case.
*
* if (tmpInt32 == LONG_MIN)
* {
* tmpInt32 = LONG_MAX;
* }
* if (tmpInt32 < 0)
* {
* tmpInt32 = -tmpInt32;
* }
*/
max |= tmpInt32 ^(tmpInt32 >> 31);
}
/*
* IF the LTP data is all zeros
* (max == 0) - do nothing for this sfb.
*/
if (max != 0)
{
/* Find the number of bits to reach the max resolution */
tmpInt = 0;
while (max < 0x40000000L)
{
max <<= 1;
tmpInt++;
}
/*
* The following codes are combinded into shift factor
* adjusting and reconstruction section.
*
* pPredicted_spectral = pPredicted_offset;
* for(j = quarter_sfb_width; j>0 ; j--)
* {
* *(pPredicted_spectral++) <<= tmpInt;
* *(pPredicted_spectral++) <<= tmpInt;
* *(pPredicted_spectral++) <<= tmpInt;
* *(pPredicted_spectral++) <<= tmpInt;
* }
*
*/
/* Adjust Q format for predicted_spectral() */
adjusted_pred_q = pred_q_format + tmpInt;
/*
* Adjust Q format to prevent overflow that may occur during
* frequency domain reconstruction.
*
*/
pPredicted_spectral = pPredicted_offset;
shift_factor = *(pQ_format) - adjusted_pred_q;
if ((shift_factor >= 0) && (shift_factor < 31))
{
shift_factor = shift_factor + 1;
pred_shift = tmpInt - 1;
if (pred_shift >= 0)
{
for (j = quarter_sfb_width; j > 0 ; j--)
{
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) << pred_shift);
}
}
else
{
for (j = quarter_sfb_width; j > 0 ; j--)
{
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) >> 1);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) >> 1);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) >> 1);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) >> 1);
}
}
/* Updated new Q format for current scalefactor band */
*(pQ_format) = adjusted_pred_q - 1;
}
else if (shift_factor >= 31)
{
for (j = quarter_sfb_width; j > 0 ; j--)
{
*(pCurrent_frame++) =
*(pPredicted_spectral++) << tmpInt;
*(pCurrent_frame++) =
*(pPredicted_spectral++) << tmpInt;
*(pCurrent_frame++) =
*(pPredicted_spectral++) << tmpInt;
*(pCurrent_frame++) =
*(pPredicted_spectral++) << tmpInt;
}
/* Updated new Q format for current scalefactor band */
*(pQ_format) = adjusted_pred_q ;
}
else if ((shift_factor < 0) && (shift_factor > -31))
{
shift_factor = 1 - shift_factor;
pred_shift = tmpInt - shift_factor;
if (pred_shift >= 0)
{
for (j = quarter_sfb_width; j > 0 ; j--)
{
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) << pred_shift);
}
}
else
{
pred_shift = -pred_shift;
for (j = quarter_sfb_width; j > 0 ; j--)
{
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) >> pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) >> pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) >> pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) >> pred_shift);
}
}
/*
* Updated new Q format for current scalefactor band
*
* This is NOT a pointer decrement
*/
(*pQ_format)--;
}
} /* if (max != 0) */
/*
* For case (shift_factor <= -31), *pCurrent_frame and
* *pQ_format do not need to be updated.
*/
} /* if (*(pSfb_prediction_used++) != FALSE) */
/* Updated to next scalefactor band. */
sfb_offset = *(pWinSfbTop++);
/* Updated pointer to next scalefactor band's Q-format */
pQ_format++;
} /* for (i = sfb_per_frame; i>0; i--) */
} /* if (win_seq!=EIGHT_SHORT_SEQUENCE) */
/**********************************/
/* LTP synthesis for short window */
/**********************************/
else
{
/******************************************************/
/*Reconstruction of current frequency domain spectrum */
/******************************************************/
pCurrent_frame_start = ¤t_frame[0];
pQ_format_start = &q_format[0];
num_sfb = sfb_per_win;
/* Reconstruction is processed on window basis */
for (wnd = 0; wnd < short_window_num; wnd++)
{
pWinSfbTop = &win_sfb_top[0];
pQ_format = pQ_format_start;
/* Check if prediction flag is on for each window */
if (win_prediction_used[wnd] != FALSE)
{
/* Initialize scalefactor band offset */
sfb_offset = 0;
/*
* Reconstruction is processed on scalefactor band basis.
* 1. When prediction is turned on, all the predicted
* spectral components will be used for reconstruction.
* 2. When prediction is turned off, reconstruction is
* not needed. Spectral components of current frame
* will directly come from the transmitted data.
*/
/*
* According to ISO/IEC 14496-3 pg.91
* Only the spectral components in first eight scalefactor
* bands are added to the quantized prediction error.
*/
for (i = reconstruct_sfb_num; i > 0; i--)
{
/* Set pointer to the offset of scalefactor bands */
pPredicted_offset = pPredicted_spectral_start +
sfb_offset;
pCurrent_frame = pCurrent_frame_start + sfb_offset;
/*
* Prediction is on. Do reconstruction routine.
* Reconstruct spectral component of
* current frame by adding the predicted
* spectral components and the quantized
* prediction errors that reconstructed
* from transmitted data when prediction
* is turned on.
*/
/*
* (*pWinSfbTop - sfb_offset) is number of coefficients
* of the scalefactor band.
* ">>2" is used to set up for later unrolling the loop.
*/
quarter_sfb_width = (*pWinSfbTop - sfb_offset) >> 2;
/*
* Adjust pred_q_format and predicted_spectral() to
* maximum resolution.
*/
max = 0;
pPredicted_spectral = pPredicted_offset;
/* Find the maximum absolute value */
for (j = (*pWinSfbTop - sfb_offset); j > 0 ; j--)
{
tmpInt32 = *(pPredicted_spectral++);
/*
* Note: overflow is protected here even though
* tmpInt32 = 0x80000000 is very rare case.
*
* if (tmpInt32 == LONG_MIN)
* {
* tmpInt32 = LONG_MAX;
* }
* if (tmpInt32 < 0)
* {
* tmpInt32 = -tmpInt32;
* }
*/
max |= tmpInt32 ^(tmpInt32 >> 31);
}
if (max != 0)
{
/* Find the number of bits to reach
* the max resolution
*/
tmpInt = 0;
while (max < 0x40000000L)
{
max <<= 1;
tmpInt++;
}
/*
* The following codes are combined into shift factor
* adjusting and reconstruction section.
*
* pPredicted_spectral = pPredicted_offset;
* for(j = quarter_sfb_width; j>0 ; j--)
* {
* *(pPredicted_spectral++) <<= tmpInt;
* *(pPredicted_spectral++) <<= tmpInt;
* *(pPredicted_spectral++) <<= tmpInt;
* *(pPredicted_spectral++) <<= tmpInt;
* }
*
*/
/* Adjust Q format for predicted_spectral() */
adjusted_pred_q = pred_q_format + tmpInt;
/*
* Adjust Q format to prevent overflow that may occur
* during frequency domain reconstruction.
*/
pPredicted_spectral = pPredicted_offset;
shift_factor = *(pQ_format) - adjusted_pred_q;
if ((shift_factor >= 0) && (shift_factor < 31))
{
shift_factor = shift_factor + 1;
pred_shift = tmpInt - 1;
if (pred_shift >= 0)
{
for (j = quarter_sfb_width; j > 0 ; j--)
{
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) << pred_shift);
}
}
else
{
for (j = quarter_sfb_width; j > 0 ; j--)
{
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) >> 1);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) >> 1);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) >> 1);
temp = *pCurrent_frame >> shift_factor;
*(pCurrent_frame++) = temp
+ (*(pPredicted_spectral++) >> 1);
}
}
/* Updated new Q format for current scalefactor band*/
*(pQ_format) = adjusted_pred_q - 1;
}
else if (shift_factor >= 31)
{
for (j = quarter_sfb_width; j > 0 ; j--)
{
*(pCurrent_frame++) =
*(pPredicted_spectral++) << tmpInt;
*(pCurrent_frame++) =
*(pPredicted_spectral++) << tmpInt;
*(pCurrent_frame++) =
*(pPredicted_spectral++) << tmpInt;
*(pCurrent_frame++) =
*(pPredicted_spectral++) << tmpInt;
}
/* Updated new Q format for current scalefactor band*/
*(pQ_format) = adjusted_pred_q;
}
else if ((shift_factor < 0) && (shift_factor > -31))
{
shift_factor = 1 - shift_factor;
pred_shift = tmpInt - shift_factor;
if (pred_shift >= 0)
{
for (j = quarter_sfb_width; j > 0 ; j--)
{
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) << pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) << pred_shift);
}
}
else
{
pred_shift = -pred_shift;
for (j = quarter_sfb_width; j > 0 ; j--)
{
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) >> pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) >> pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) >> pred_shift);
temp = *pCurrent_frame >> 1;
*(pCurrent_frame++) = temp +
(*(pPredicted_spectral++) >> pred_shift);
}
}
/* Updated new Q format for current scalefactor band*/
*(pQ_format) = *(pQ_format) - 1;
}
/*
* For case (shift_factor <= -31), *pCurrent_frame and
* *pQ_format do not need to be updated.
*/
} /* if (max != 0) */
/* Updated to next scalefactor band. */
sfb_offset = *(pWinSfbTop++);
/* Updated pointer to next scalefactor band's Q-format */
pQ_format++;
} /* for (i = reconstruct_sfb_num; i > 0; i--) */
} /* if (win_prediction_used[wnd] != FALSE) */
/* Updated to next window */
pPredicted_spectral_start += coef_per_win;
pCurrent_frame_start += coef_per_win;
pQ_format_start += num_sfb;
} /* for (wnd=0; wnd<short_window_num; wnd++) */
} /* else */
/*----------------------------------------------------------------------------
; Return nothing or data or data pointer
----------------------------------------------------------------------------*/
return;
} /* long_term_synthesis */
| lgpl-3.0 |
firerszd/kbengine | kbe/src/lib/dependencies/apr-util/dbd/apr_dbd_sqlite2.c | 58 | 14333 | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "apu.h"
#if APU_HAVE_SQLITE2
#include <ctype.h>
#include <stdlib.h>
#include <sqlite.h>
#include "apr_strings.h"
#include "apr_time.h"
#include "apr_buckets.h"
#include "apr_dbd_internal.h"
struct apr_dbd_transaction_t {
int mode;
int errnum;
apr_dbd_t *handle;
};
struct apr_dbd_t {
sqlite *conn;
char *errmsg;
apr_dbd_transaction_t *trans;
};
struct apr_dbd_results_t {
int random;
sqlite *handle;
char **res;
size_t ntuples;
size_t sz;
size_t index;
apr_pool_t *pool;
};
struct apr_dbd_row_t {
int n;
char **data;
apr_dbd_results_t *res;
};
struct apr_dbd_prepared_t {
const char *name;
int prepared;
};
#define FREE_ERROR_MSG(dbd) \
do { \
if(dbd && dbd->errmsg) { \
free(dbd->errmsg); \
dbd->errmsg = NULL; \
} \
} while(0);
static apr_status_t free_table(void *data)
{
sqlite_free_table(data);
return APR_SUCCESS;
}
static int dbd_sqlite_select(apr_pool_t * pool, apr_dbd_t * sql,
apr_dbd_results_t ** results, const char *query,
int seek)
{
char **result;
int ret = 0;
int tuples = 0;
int fields = 0;
if (sql->trans && sql->trans->errnum) {
return sql->trans->errnum;
}
FREE_ERROR_MSG(sql);
ret = sqlite_get_table(sql->conn, query, &result, &tuples, &fields,
&sql->errmsg);
if (ret == SQLITE_OK) {
if (!*results) {
*results = apr_pcalloc(pool, sizeof(apr_dbd_results_t));
}
(*results)->res = result;
(*results)->ntuples = tuples;
(*results)->sz = fields;
(*results)->random = seek;
(*results)->pool = pool;
if (tuples > 0)
apr_pool_cleanup_register(pool, result, free_table,
apr_pool_cleanup_null);
ret = 0;
}
else {
if (TXN_NOTICE_ERRORS(sql->trans)) {
sql->trans->errnum = ret;
}
}
return ret;
}
static const char *dbd_sqlite_get_name(const apr_dbd_results_t *res, int n)
{
if ((n < 0) || (n >= res->sz)) {
return NULL;
}
return res->res[n];
}
static int dbd_sqlite_get_row(apr_pool_t * pool, apr_dbd_results_t * res,
apr_dbd_row_t ** rowp, int rownum)
{
apr_dbd_row_t *row = *rowp;
int sequential = ((rownum >= 0) && res->random) ? 0 : 1;
if (row == NULL) {
row = apr_palloc(pool, sizeof(apr_dbd_row_t));
*rowp = row;
row->res = res;
row->n = sequential ? 0 : rownum - 1;
}
else {
if (sequential) {
++row->n;
}
else {
row->n = rownum - 1;
}
}
if (row->n >= res->ntuples) {
*rowp = NULL;
apr_pool_cleanup_run(res->pool, res->res, free_table);
res->res = NULL;
return -1;
}
/* Pointer magic explanation:
* The sqlite result is an array such that the first res->sz elements are
* the column names and each tuple follows afterwards
* ex: (from the sqlite2 documentation)
SELECT employee_name, login, host FROM users WHERE login LIKE * 'd%';
nrow = 2
ncolumn = 3
result[0] = "employee_name"
result[1] = "login"
result[2] = "host"
result[3] = "dummy"
result[4] = "No such user"
result[5] = 0
result[6] = "D. Richard Hipp"
result[7] = "drh"
result[8] = "zadok"
*/
row->data = res->res + res->sz + (res->sz * row->n);
return 0;
}
static const char *dbd_sqlite_get_entry(const apr_dbd_row_t * row, int n)
{
if ((n < 0) || (n >= row->res->sz)) {
return NULL;
}
return row->data[n];
}
static apr_status_t dbd_sqlite_datum_get(const apr_dbd_row_t *row, int n,
apr_dbd_type_e type, void *data)
{
if ((n < 0) || (n >= row->res->sz)) {
return APR_EGENERAL;
}
if (row->data[n] == NULL) {
return APR_ENOENT;
}
switch (type) {
case APR_DBD_TYPE_TINY:
*(char*)data = atoi(row->data[n]);
break;
case APR_DBD_TYPE_UTINY:
*(unsigned char*)data = atoi(row->data[n]);
break;
case APR_DBD_TYPE_SHORT:
*(short*)data = atoi(row->data[n]);
break;
case APR_DBD_TYPE_USHORT:
*(unsigned short*)data = atoi(row->data[n]);
break;
case APR_DBD_TYPE_INT:
*(int*)data = atoi(row->data[n]);
break;
case APR_DBD_TYPE_UINT:
*(unsigned int*)data = atoi(row->data[n]);
break;
case APR_DBD_TYPE_LONG:
*(long*)data = atol(row->data[n]);
break;
case APR_DBD_TYPE_ULONG:
*(unsigned long*)data = atol(row->data[n]);
break;
case APR_DBD_TYPE_LONGLONG:
*(apr_int64_t*)data = apr_atoi64(row->data[n]);
break;
case APR_DBD_TYPE_ULONGLONG:
*(apr_uint64_t*)data = apr_atoi64(row->data[n]);
break;
case APR_DBD_TYPE_FLOAT:
*(float*)data = atof(row->data[n]);
break;
case APR_DBD_TYPE_DOUBLE:
*(double*)data = atof(row->data[n]);
break;
case APR_DBD_TYPE_STRING:
case APR_DBD_TYPE_TEXT:
case APR_DBD_TYPE_TIME:
case APR_DBD_TYPE_DATE:
case APR_DBD_TYPE_DATETIME:
case APR_DBD_TYPE_TIMESTAMP:
case APR_DBD_TYPE_ZTIMESTAMP:
*(char**)data = row->data[n];
break;
case APR_DBD_TYPE_BLOB:
case APR_DBD_TYPE_CLOB:
{
apr_bucket *e;
apr_bucket_brigade *b = (apr_bucket_brigade*)data;
e = apr_bucket_pool_create(row->data[n],strlen(row->data[n]),
row->res->pool, b->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(b, e);
}
break;
case APR_DBD_TYPE_NULL:
*(void**)data = NULL;
break;
default:
return APR_EGENERAL;
}
return APR_SUCCESS;
}
static const char *dbd_sqlite_error(apr_dbd_t * sql, int n)
{
return sql->errmsg;
}
static int dbd_sqlite_query(apr_dbd_t * sql, int *nrows, const char *query)
{
char **result;
int ret;
int tuples = 0;
int fields = 0;
if (sql->trans && sql->trans->errnum) {
return sql->trans->errnum;
}
FREE_ERROR_MSG(sql);
ret =
sqlite_get_table(sql->conn, query, &result, &tuples, &fields,
&sql->errmsg);
if (ret == SQLITE_OK) {
*nrows = sqlite_changes(sql->conn);
if (tuples > 0)
free(result);
ret = 0;
}
if (TXN_NOTICE_ERRORS(sql->trans)) {
sql->trans->errnum = ret;
}
return ret;
}
static apr_status_t free_mem(void *data)
{
sqlite_freemem(data);
return APR_SUCCESS;
}
static const char *dbd_sqlite_escape(apr_pool_t * pool, const char *arg,
apr_dbd_t * sql)
{
char *ret = sqlite_mprintf("%q", arg);
apr_pool_cleanup_register(pool, ret, free_mem, apr_pool_cleanup_null);
return ret;
}
static int dbd_sqlite_prepare(apr_pool_t * pool, apr_dbd_t * sql,
const char *query, const char *label,
int nargs, int nvals, apr_dbd_type_e *types,
apr_dbd_prepared_t ** statement)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_pquery(apr_pool_t * pool, apr_dbd_t * sql,
int *nrows, apr_dbd_prepared_t * statement,
const char **values)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_pvquery(apr_pool_t * pool, apr_dbd_t * sql,
int *nrows, apr_dbd_prepared_t * statement,
va_list args)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_pselect(apr_pool_t * pool, apr_dbd_t * sql,
apr_dbd_results_t ** results,
apr_dbd_prepared_t * statement,
int seek, const char **values)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_pvselect(apr_pool_t * pool, apr_dbd_t * sql,
apr_dbd_results_t ** results,
apr_dbd_prepared_t * statement, int seek,
va_list args)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_pbquery(apr_pool_t * pool, apr_dbd_t * sql,
int *nrows, apr_dbd_prepared_t * statement,
const void **values)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_pvbquery(apr_pool_t * pool, apr_dbd_t * sql,
int *nrows, apr_dbd_prepared_t * statement,
va_list args)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_pbselect(apr_pool_t * pool, apr_dbd_t * sql,
apr_dbd_results_t ** results,
apr_dbd_prepared_t * statement,
int seek, const void **values)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_pvbselect(apr_pool_t * pool, apr_dbd_t * sql,
apr_dbd_results_t ** results,
apr_dbd_prepared_t * statement, int seek,
va_list args)
{
return APR_ENOTIMPL;
}
static int dbd_sqlite_start_transaction(apr_pool_t * pool, apr_dbd_t * handle,
apr_dbd_transaction_t ** trans)
{
int ret, rows;
ret = dbd_sqlite_query(handle, &rows, "BEGIN TRANSACTION");
if (ret == 0) {
if (!*trans) {
*trans = apr_pcalloc(pool, sizeof(apr_dbd_transaction_t));
}
(*trans)->handle = handle;
handle->trans = *trans;
}
else {
ret = -1;
}
return ret;
}
static int dbd_sqlite_end_transaction(apr_dbd_transaction_t * trans)
{
int rows;
int ret = -1; /* no transaction is an error cond */
if (trans) {
/* rollback on error or explicit rollback request */
if (trans->errnum || TXN_DO_ROLLBACK(trans)) {
trans->errnum = 0;
ret =
dbd_sqlite_query(trans->handle, &rows,
"ROLLBACK TRANSACTION");
}
else {
ret =
dbd_sqlite_query(trans->handle, &rows, "COMMIT TRANSACTION");
}
trans->handle->trans = NULL;
}
return ret;
}
static int dbd_sqlite_transaction_mode_get(apr_dbd_transaction_t *trans)
{
if (!trans)
return APR_DBD_TRANSACTION_COMMIT;
return trans->mode;
}
static int dbd_sqlite_transaction_mode_set(apr_dbd_transaction_t *trans,
int mode)
{
if (!trans)
return APR_DBD_TRANSACTION_COMMIT;
return trans->mode = (mode & TXN_MODE_BITS);
}
static apr_status_t error_free(void *data)
{
free(data);
return APR_SUCCESS;
}
static apr_dbd_t *dbd_sqlite_open(apr_pool_t * pool, const char *params_,
const char **error)
{
apr_dbd_t *sql;
sqlite *conn = NULL;
char *perm;
int iperms = 600;
char* params = apr_pstrdup(pool, params_);
/* params = "[filename]:[permissions]"
* example: "shopping.db:600"
*/
perm = strstr(params, ":");
if (perm) {
*(perm++) = '\x00'; /* split the filename and permissions */
if (strlen(perm) > 0)
iperms = atoi(perm);
}
if (error) {
*error = NULL;
conn = sqlite_open(params, iperms, (char **)error);
if (*error) {
apr_pool_cleanup_register(pool, *error, error_free,
apr_pool_cleanup_null);
}
}
else {
conn = sqlite_open(params, iperms, NULL);
}
sql = apr_pcalloc(pool, sizeof(*sql));
sql->conn = conn;
return sql;
}
static apr_status_t dbd_sqlite_close(apr_dbd_t * handle)
{
if (handle->conn) {
sqlite_close(handle->conn);
handle->conn = NULL;
}
return APR_SUCCESS;
}
static apr_status_t dbd_sqlite_check_conn(apr_pool_t * pool,
apr_dbd_t * handle)
{
if (handle->conn == NULL)
return -1;
return APR_SUCCESS;
}
static int dbd_sqlite_select_db(apr_pool_t * pool, apr_dbd_t * handle,
const char *name)
{
return APR_ENOTIMPL;
}
static void *dbd_sqlite_native(apr_dbd_t * handle)
{
return handle->conn;
}
static int dbd_sqlite_num_cols(apr_dbd_results_t * res)
{
return res->sz;
}
static int dbd_sqlite_num_tuples(apr_dbd_results_t * res)
{
return res->ntuples;
}
APU_MODULE_DECLARE_DATA const apr_dbd_driver_t apr_dbd_sqlite2_driver = {
"sqlite2",
NULL,
dbd_sqlite_native,
dbd_sqlite_open,
dbd_sqlite_check_conn,
dbd_sqlite_close,
dbd_sqlite_select_db,
dbd_sqlite_start_transaction,
dbd_sqlite_end_transaction,
dbd_sqlite_query,
dbd_sqlite_select,
dbd_sqlite_num_cols,
dbd_sqlite_num_tuples,
dbd_sqlite_get_row,
dbd_sqlite_get_entry,
dbd_sqlite_error,
dbd_sqlite_escape,
dbd_sqlite_prepare,
dbd_sqlite_pvquery,
dbd_sqlite_pvselect,
dbd_sqlite_pquery,
dbd_sqlite_pselect,
dbd_sqlite_get_name,
dbd_sqlite_transaction_mode_get,
dbd_sqlite_transaction_mode_set,
NULL,
dbd_sqlite_pvbquery,
dbd_sqlite_pvbselect,
dbd_sqlite_pbquery,
dbd_sqlite_pbselect,
dbd_sqlite_datum_get
};
#endif
| lgpl-3.0 |
sysalexis/kbengine | kbe/src/lib/dependencies/openssl/times/x86/rc4s.cpp | 1379 | 1394 | //
// gettsc.inl
//
// gives access to the Pentium's (secret) cycle counter
//
// This software was written by Leonard Janke (janke@unixg.ubc.ca)
// in 1996-7 and is entered, by him, into the public domain.
#if defined(__WATCOMC__)
void GetTSC(unsigned long&);
#pragma aux GetTSC = 0x0f 0x31 "mov [edi], eax" parm [edi] modify [edx eax];
#elif defined(__GNUC__)
inline
void GetTSC(unsigned long& tsc)
{
asm volatile(".byte 15, 49\n\t"
: "=eax" (tsc)
:
: "%edx", "%eax");
}
#elif defined(_MSC_VER)
inline
void GetTSC(unsigned long& tsc)
{
unsigned long a;
__asm _emit 0fh
__asm _emit 31h
__asm mov a, eax;
tsc=a;
}
#endif
#include <stdio.h>
#include <stdlib.h>
#include <openssl/rc4.h>
void main(int argc,char *argv[])
{
unsigned char buffer[1024];
RC4_KEY ctx;
unsigned long s1,s2,e1,e2;
unsigned char k[16];
unsigned long data[2];
unsigned char iv[8];
int i,num=64,numm;
int j=0;
if (argc >= 2)
num=atoi(argv[1]);
if (num == 0) num=256;
if (num > 1024-16) num=1024-16;
numm=num+8;
for (j=0; j<6; j++)
{
for (i=0; i<10; i++) /**/
{
RC4(&ctx,numm,buffer,buffer);
GetTSC(s1);
RC4(&ctx,numm,buffer,buffer);
GetTSC(e1);
GetTSC(s2);
RC4(&ctx,num,buffer,buffer);
GetTSC(e2);
RC4(&ctx,num,buffer,buffer);
}
printf("RC4 (%d bytes) %d %d (%d) - 8 bytes\n",num,
e1-s1,e2-s2,(e1-s1)-(e2-s2));
}
}
| lgpl-3.0 |
theheros/kbengine | kbe/src/lib/python/Modules/zlib/deflate.c | 918 | 67992 | /* deflate.c -- compress data using the deflation algorithm
* Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/*
* ALGORITHM
*
* The "deflation" process depends on being able to identify portions
* of the input text which are identical to earlier input (within a
* sliding window trailing behind the input currently being processed).
*
* The most straightforward technique turns out to be the fastest for
* most input files: try all possible matches and select the longest.
* The key feature of this algorithm is that insertions into the string
* dictionary are very simple and thus fast, and deletions are avoided
* completely. Insertions are performed at each input character, whereas
* string matches are performed only when the previous match ends. So it
* is preferable to spend more time in matches to allow very fast string
* insertions and avoid deletions. The matching algorithm for small
* strings is inspired from that of Rabin & Karp. A brute force approach
* is used to find longer strings when a small match has been found.
* A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
* (by Leonid Broukhis).
* A previous version of this file used a more sophisticated algorithm
* (by Fiala and Greene) which is guaranteed to run in linear amortized
* time, but has a larger average cost, uses more memory and is patented.
* However the F&G algorithm may be faster for some highly redundant
* files if the parameter max_chain_length (described below) is too large.
*
* ACKNOWLEDGEMENTS
*
* The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
* I found it in 'freeze' written by Leonid Broukhis.
* Thanks to many people for bug reports and testing.
*
* REFERENCES
*
* Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
* Available in http://www.ietf.org/rfc/rfc1951.txt
*
* A description of the Rabin and Karp algorithm is given in the book
* "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
*
* Fiala,E.R., and Greene,D.H.
* Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
*
*/
/* @(#) $Id$ */
#include "deflate.h"
const char deflate_copyright[] =
" deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler ";
/*
If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot
include such an acknowledgment, I would appreciate that you keep this
copyright string in the executable of your product.
*/
/* ===========================================================================
* Function prototypes.
*/
typedef enum {
need_more, /* block not completed, need more input or more output */
block_done, /* block flush performed */
finish_started, /* finish started, need only more output at next deflate */
finish_done /* finish done, accept no more input or output */
} block_state;
typedef block_state (*compress_func) OF((deflate_state *s, int flush));
/* Compression function. Returns the block state after the call. */
local void fill_window OF((deflate_state *s));
local block_state deflate_stored OF((deflate_state *s, int flush));
local block_state deflate_fast OF((deflate_state *s, int flush));
#ifndef FASTEST
local block_state deflate_slow OF((deflate_state *s, int flush));
#endif
local block_state deflate_rle OF((deflate_state *s, int flush));
local block_state deflate_huff OF((deflate_state *s, int flush));
local void lm_init OF((deflate_state *s));
local void putShortMSB OF((deflate_state *s, uInt b));
local void flush_pending OF((z_streamp strm));
local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
#ifdef ASMV
void match_init OF((void)); /* asm code initialization */
uInt longest_match OF((deflate_state *s, IPos cur_match));
#else
local uInt longest_match OF((deflate_state *s, IPos cur_match));
#endif
#ifdef DEBUG
local void check_match OF((deflate_state *s, IPos start, IPos match,
int length));
#endif
/* ===========================================================================
* Local data
*/
#define NIL 0
/* Tail of hash chains */
#ifndef TOO_FAR
# define TOO_FAR 4096
#endif
/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
typedef struct config_s {
ush good_length; /* reduce lazy search above this match length */
ush max_lazy; /* do not perform lazy search above this match length */
ush nice_length; /* quit search above this match length */
ush max_chain;
compress_func func;
} config;
#ifdef FASTEST
local const config configuration_table[2] = {
/* good lazy nice chain */
/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
#else
local const config configuration_table[10] = {
/* good lazy nice chain */
/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
/* 2 */ {4, 5, 16, 8, deflate_fast},
/* 3 */ {4, 6, 32, 32, deflate_fast},
/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
/* 5 */ {8, 16, 32, 32, deflate_slow},
/* 6 */ {8, 16, 128, 128, deflate_slow},
/* 7 */ {8, 32, 128, 256, deflate_slow},
/* 8 */ {32, 128, 258, 1024, deflate_slow},
/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
#endif
/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
* For deflate_fast() (levels <= 3) good is ignored and lazy has a different
* meaning.
*/
#define EQUAL 0
/* result of memcmp for equal strings */
#ifndef NO_DUMMY_DECL
struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
#endif
/* ===========================================================================
* Update a hash value with the given input byte
* IN assertion: all calls to to UPDATE_HASH are made with consecutive
* input characters, so that a running hash key can be computed from the
* previous key instead of complete recalculation each time.
*/
#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
/* ===========================================================================
* Insert string str in the dictionary and set match_head to the previous head
* of the hash chain (the most recent string with same hash key). Return
* the previous length of the hash chain.
* If this file is compiled with -DFASTEST, the compression level is forced
* to 1, and no hash chains are maintained.
* IN assertion: all calls to to INSERT_STRING are made with consecutive
* input characters and the first MIN_MATCH bytes of str are valid
* (except for the last MIN_MATCH-1 bytes of the input file).
*/
#ifdef FASTEST
#define INSERT_STRING(s, str, match_head) \
(UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
match_head = s->head[s->ins_h], \
s->head[s->ins_h] = (Pos)(str))
#else
#define INSERT_STRING(s, str, match_head) \
(UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
s->head[s->ins_h] = (Pos)(str))
#endif
/* ===========================================================================
* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
* prev[] will be initialized on the fly.
*/
#define CLEAR_HASH(s) \
s->head[s->hash_size-1] = NIL; \
zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
/* ========================================================================= */
int ZEXPORT deflateInit_(strm, level, version, stream_size)
z_streamp strm;
int level;
const char *version;
int stream_size;
{
return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY, version, stream_size);
/* To do: ignore strm->next_in if we use it as window */
}
/* ========================================================================= */
int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
version, stream_size)
z_streamp strm;
int level;
int method;
int windowBits;
int memLevel;
int strategy;
const char *version;
int stream_size;
{
deflate_state *s;
int wrap = 1;
static const char my_version[] = ZLIB_VERSION;
ushf *overlay;
/* We overlay pending_buf and d_buf+l_buf. This works since the average
* output size for (length,distance) codes is <= 24 bits.
*/
if (version == Z_NULL || version[0] != my_version[0] ||
stream_size != sizeof(z_stream)) {
return Z_VERSION_ERROR;
}
if (strm == Z_NULL) return Z_STREAM_ERROR;
strm->msg = Z_NULL;
if (strm->zalloc == (alloc_func)0) {
strm->zalloc = zcalloc;
strm->opaque = (voidpf)0;
}
if (strm->zfree == (free_func)0) strm->zfree = zcfree;
#ifdef FASTEST
if (level != 0) level = 1;
#else
if (level == Z_DEFAULT_COMPRESSION) level = 6;
#endif
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
#ifdef GZIP
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
#endif
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return Z_STREAM_ERROR;
}
if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
if (s == Z_NULL) return Z_MEM_ERROR;
strm->state = (struct internal_state FAR *)s;
s->strm = strm;
s->wrap = wrap;
s->gzhead = Z_NULL;
s->w_bits = windowBits;
s->w_size = 1 << s->w_bits;
s->w_mask = s->w_size - 1;
s->hash_bits = memLevel + 7;
s->hash_size = 1 << s->hash_bits;
s->hash_mask = s->hash_size - 1;
s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
s->high_water = 0; /* nothing written to s->window yet */
s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
s->pending_buf = (uchf *) overlay;
s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
s->pending_buf == Z_NULL) {
s->status = FINISH_STATE;
strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
deflateEnd (strm);
return Z_MEM_ERROR;
}
s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
s->level = level;
s->strategy = strategy;
s->method = (Byte)method;
return deflateReset(strm);
}
/* ========================================================================= */
int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
z_streamp strm;
const Bytef *dictionary;
uInt dictLength;
{
deflate_state *s;
uInt length = dictLength;
uInt n;
IPos hash_head = 0;
if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
strm->state->wrap == 2 ||
(strm->state->wrap == 1 && strm->state->status != INIT_STATE))
return Z_STREAM_ERROR;
s = strm->state;
if (s->wrap)
strm->adler = adler32(strm->adler, dictionary, dictLength);
if (length < MIN_MATCH) return Z_OK;
if (length > s->w_size) {
length = s->w_size;
dictionary += dictLength - length; /* use the tail of the dictionary */
}
zmemcpy(s->window, dictionary, length);
s->strstart = length;
s->block_start = (long)length;
/* Insert all strings in the hash table (except for the last two bytes).
* s->lookahead stays null, so s->ins_h will be recomputed at the next
* call of fill_window.
*/
s->ins_h = s->window[0];
UPDATE_HASH(s, s->ins_h, s->window[1]);
for (n = 0; n <= length - MIN_MATCH; n++) {
INSERT_STRING(s, n, hash_head);
}
if (hash_head) hash_head = 0; /* to make compiler happy */
return Z_OK;
}
/* ========================================================================= */
int ZEXPORT deflateReset (strm)
z_streamp strm;
{
deflate_state *s;
if (strm == Z_NULL || strm->state == Z_NULL ||
strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
return Z_STREAM_ERROR;
}
strm->total_in = strm->total_out = 0;
strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
strm->data_type = Z_UNKNOWN;
s = (deflate_state *)strm->state;
s->pending = 0;
s->pending_out = s->pending_buf;
if (s->wrap < 0) {
s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
}
s->status = s->wrap ? INIT_STATE : BUSY_STATE;
strm->adler =
#ifdef GZIP
s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
#endif
adler32(0L, Z_NULL, 0);
s->last_flush = Z_NO_FLUSH;
_tr_init(s);
lm_init(s);
return Z_OK;
}
/* ========================================================================= */
int ZEXPORT deflateSetHeader (strm, head)
z_streamp strm;
gz_headerp head;
{
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
if (strm->state->wrap != 2) return Z_STREAM_ERROR;
strm->state->gzhead = head;
return Z_OK;
}
/* ========================================================================= */
int ZEXPORT deflatePrime (strm, bits, value)
z_streamp strm;
int bits;
int value;
{
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
strm->state->bi_valid = bits;
strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
return Z_OK;
}
/* ========================================================================= */
int ZEXPORT deflateParams(strm, level, strategy)
z_streamp strm;
int level;
int strategy;
{
deflate_state *s;
compress_func func;
int err = Z_OK;
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
s = strm->state;
#ifdef FASTEST
if (level != 0) level = 1;
#else
if (level == Z_DEFAULT_COMPRESSION) level = 6;
#endif
if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
return Z_STREAM_ERROR;
}
func = configuration_table[s->level].func;
if ((strategy != s->strategy || func != configuration_table[level].func) &&
strm->total_in != 0) {
/* Flush the last buffer: */
err = deflate(strm, Z_BLOCK);
}
if (s->level != level) {
s->level = level;
s->max_lazy_match = configuration_table[level].max_lazy;
s->good_match = configuration_table[level].good_length;
s->nice_match = configuration_table[level].nice_length;
s->max_chain_length = configuration_table[level].max_chain;
}
s->strategy = strategy;
return err;
}
/* ========================================================================= */
int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
z_streamp strm;
int good_length;
int max_lazy;
int nice_length;
int max_chain;
{
deflate_state *s;
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
s = strm->state;
s->good_match = good_length;
s->max_lazy_match = max_lazy;
s->nice_match = nice_length;
s->max_chain_length = max_chain;
return Z_OK;
}
/* =========================================================================
* For the default windowBits of 15 and memLevel of 8, this function returns
* a close to exact, as well as small, upper bound on the compressed size.
* They are coded as constants here for a reason--if the #define's are
* changed, then this function needs to be changed as well. The return
* value for 15 and 8 only works for those exact settings.
*
* For any setting other than those defaults for windowBits and memLevel,
* the value returned is a conservative worst case for the maximum expansion
* resulting from using fixed blocks instead of stored blocks, which deflate
* can emit on compressed data for some combinations of the parameters.
*
* This function could be more sophisticated to provide closer upper bounds for
* every combination of windowBits and memLevel. But even the conservative
* upper bound of about 14% expansion does not seem onerous for output buffer
* allocation.
*/
uLong ZEXPORT deflateBound(strm, sourceLen)
z_streamp strm;
uLong sourceLen;
{
deflate_state *s;
uLong complen, wraplen;
Bytef *str;
/* conservative upper bound for compressed data */
complen = sourceLen +
((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
/* if can't get parameters, return conservative bound plus zlib wrapper */
if (strm == Z_NULL || strm->state == Z_NULL)
return complen + 6;
/* compute wrapper length */
s = strm->state;
switch (s->wrap) {
case 0: /* raw deflate */
wraplen = 0;
break;
case 1: /* zlib wrapper */
wraplen = 6 + (s->strstart ? 4 : 0);
break;
case 2: /* gzip wrapper */
wraplen = 18;
if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
if (s->gzhead->extra != Z_NULL)
wraplen += 2 + s->gzhead->extra_len;
str = s->gzhead->name;
if (str != Z_NULL)
do {
wraplen++;
} while (*str++);
str = s->gzhead->comment;
if (str != Z_NULL)
do {
wraplen++;
} while (*str++);
if (s->gzhead->hcrc)
wraplen += 2;
}
break;
default: /* for compiler happiness */
wraplen = 6;
}
/* if not default parameters, return conservative bound */
if (s->w_bits != 15 || s->hash_bits != 8 + 7)
return complen + wraplen;
/* default settings: return tight bound for that case */
return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
(sourceLen >> 25) + 13 - 6 + wraplen;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
local void putShortMSB (s, b)
deflate_state *s;
uInt b;
{
put_byte(s, (Byte)(b >> 8));
put_byte(s, (Byte)(b & 0xff));
}
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->next_out buffer and copying into it.
* (See also read_buf()).
*/
local void flush_pending(strm)
z_streamp strm;
{
unsigned len = strm->state->pending;
if (len > strm->avail_out) len = strm->avail_out;
if (len == 0) return;
zmemcpy(strm->next_out, strm->state->pending_out, len);
strm->next_out += len;
strm->state->pending_out += len;
strm->total_out += len;
strm->avail_out -= len;
strm->state->pending -= len;
if (strm->state->pending == 0) {
strm->state->pending_out = strm->state->pending_buf;
}
}
/* ========================================================================= */
int ZEXPORT deflate (strm, flush)
z_streamp strm;
int flush;
{
int old_flush; /* value of flush param for previous deflate call */
deflate_state *s;
if (strm == Z_NULL || strm->state == Z_NULL ||
flush > Z_BLOCK || flush < 0) {
return Z_STREAM_ERROR;
}
s = strm->state;
if (strm->next_out == Z_NULL ||
(strm->next_in == Z_NULL && strm->avail_in != 0) ||
(s->status == FINISH_STATE && flush != Z_FINISH)) {
ERR_RETURN(strm, Z_STREAM_ERROR);
}
if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
s->strm = strm; /* just in case */
old_flush = s->last_flush;
s->last_flush = flush;
/* Write the header */
if (s->status == INIT_STATE) {
#ifdef GZIP
if (s->wrap == 2) {
strm->adler = crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (s->gzhead == Z_NULL) {
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s->level == 9 ? 2 :
(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s->status = BUSY_STATE;
}
else {
put_byte(s, (s->gzhead->text ? 1 : 0) +
(s->gzhead->hcrc ? 2 : 0) +
(s->gzhead->extra == Z_NULL ? 0 : 4) +
(s->gzhead->name == Z_NULL ? 0 : 8) +
(s->gzhead->comment == Z_NULL ? 0 : 16)
);
put_byte(s, (Byte)(s->gzhead->time & 0xff));
put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
put_byte(s, s->level == 9 ? 2 :
(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
4 : 0));
put_byte(s, s->gzhead->os & 0xff);
if (s->gzhead->extra != Z_NULL) {
put_byte(s, s->gzhead->extra_len & 0xff);
put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
}
if (s->gzhead->hcrc)
strm->adler = crc32(strm->adler, s->pending_buf,
s->pending);
s->gzindex = 0;
s->status = EXTRA_STATE;
}
}
else
#endif
{
uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
uInt level_flags;
if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
level_flags = 0;
else if (s->level < 6)
level_flags = 1;
else if (s->level == 6)
level_flags = 2;
else
level_flags = 3;
header |= (level_flags << 6);
if (s->strstart != 0) header |= PRESET_DICT;
header += 31 - (header % 31);
s->status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s->strstart != 0) {
putShortMSB(s, (uInt)(strm->adler >> 16));
putShortMSB(s, (uInt)(strm->adler & 0xffff));
}
strm->adler = adler32(0L, Z_NULL, 0);
}
}
#ifdef GZIP
if (s->status == EXTRA_STATE) {
if (s->gzhead->extra != Z_NULL) {
uInt beg = s->pending; /* start of bytes to update crc */
while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
if (s->pending == s->pending_buf_size) {
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
flush_pending(strm);
beg = s->pending;
if (s->pending == s->pending_buf_size)
break;
}
put_byte(s, s->gzhead->extra[s->gzindex]);
s->gzindex++;
}
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
if (s->gzindex == s->gzhead->extra_len) {
s->gzindex = 0;
s->status = NAME_STATE;
}
}
else
s->status = NAME_STATE;
}
if (s->status == NAME_STATE) {
if (s->gzhead->name != Z_NULL) {
uInt beg = s->pending; /* start of bytes to update crc */
int val;
do {
if (s->pending == s->pending_buf_size) {
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
flush_pending(strm);
beg = s->pending;
if (s->pending == s->pending_buf_size) {
val = 1;
break;
}
}
val = s->gzhead->name[s->gzindex++];
put_byte(s, val);
} while (val != 0);
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
if (val == 0) {
s->gzindex = 0;
s->status = COMMENT_STATE;
}
}
else
s->status = COMMENT_STATE;
}
if (s->status == COMMENT_STATE) {
if (s->gzhead->comment != Z_NULL) {
uInt beg = s->pending; /* start of bytes to update crc */
int val;
do {
if (s->pending == s->pending_buf_size) {
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
flush_pending(strm);
beg = s->pending;
if (s->pending == s->pending_buf_size) {
val = 1;
break;
}
}
val = s->gzhead->comment[s->gzindex++];
put_byte(s, val);
} while (val != 0);
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
if (val == 0)
s->status = HCRC_STATE;
}
else
s->status = HCRC_STATE;
}
if (s->status == HCRC_STATE) {
if (s->gzhead->hcrc) {
if (s->pending + 2 > s->pending_buf_size)
flush_pending(strm);
if (s->pending + 2 <= s->pending_buf_size) {
put_byte(s, (Byte)(strm->adler & 0xff));
put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
strm->adler = crc32(0L, Z_NULL, 0);
s->status = BUSY_STATE;
}
}
else
s->status = BUSY_STATE;
}
#endif
/* Flush as much pending output as possible */
if (s->pending != 0) {
flush_pending(strm);
if (strm->avail_out == 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s->last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm->avail_in == 0 && flush <= old_flush &&
flush != Z_FINISH) {
ERR_RETURN(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s->status == FINISH_STATE && strm->avail_in != 0) {
ERR_RETURN(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm->avail_in != 0 || s->lookahead != 0 ||
(flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
block_state bstate;
bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
(s->strategy == Z_RLE ? deflate_rle(s, flush) :
(*(configuration_table[s->level].func))(s, flush));
if (bstate == finish_started || bstate == finish_done) {
s->status = FINISH_STATE;
}
if (bstate == need_more || bstate == finish_started) {
if (strm->avail_out == 0) {
s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate == block_done) {
if (flush == Z_PARTIAL_FLUSH) {
_tr_align(s);
} else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
_tr_stored_block(s, (char*)0, 0L, 0);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush == Z_FULL_FLUSH) {
CLEAR_HASH(s); /* forget history */
if (s->lookahead == 0) {
s->strstart = 0;
s->block_start = 0L;
}
}
}
flush_pending(strm);
if (strm->avail_out == 0) {
s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
Assert(strm->avail_out > 0, "bug2");
if (flush != Z_FINISH) return Z_OK;
if (s->wrap <= 0) return Z_STREAM_END;
/* Write the trailer */
#ifdef GZIP
if (s->wrap == 2) {
put_byte(s, (Byte)(strm->adler & 0xff));
put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
put_byte(s, (Byte)(strm->total_in & 0xff));
put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
}
else
#endif
{
putShortMSB(s, (uInt)(strm->adler >> 16));
putShortMSB(s, (uInt)(strm->adler & 0xffff));
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
return s->pending != 0 ? Z_OK : Z_STREAM_END;
}
/* ========================================================================= */
int ZEXPORT deflateEnd (strm)
z_streamp strm;
{
int status;
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
status = strm->state->status;
if (status != INIT_STATE &&
status != EXTRA_STATE &&
status != NAME_STATE &&
status != COMMENT_STATE &&
status != HCRC_STATE &&
status != BUSY_STATE &&
status != FINISH_STATE) {
return Z_STREAM_ERROR;
}
/* Deallocate in reverse order of allocations: */
TRY_FREE(strm, strm->state->pending_buf);
TRY_FREE(strm, strm->state->head);
TRY_FREE(strm, strm->state->prev);
TRY_FREE(strm, strm->state->window);
ZFREE(strm, strm->state);
strm->state = Z_NULL;
return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state.
* To simplify the source, this is not supported for 16-bit MSDOS (which
* doesn't have enough memory anyway to duplicate compression states).
*/
int ZEXPORT deflateCopy (dest, source)
z_streamp dest;
z_streamp source;
{
#ifdef MAXSEG_64K
return Z_STREAM_ERROR;
#else
deflate_state *ds;
deflate_state *ss;
ushf *overlay;
if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
return Z_STREAM_ERROR;
}
ss = source->state;
zmemcpy(dest, source, sizeof(z_stream));
ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
if (ds == Z_NULL) return Z_MEM_ERROR;
dest->state = (struct internal_state FAR *) ds;
zmemcpy(ds, ss, sizeof(deflate_state));
ds->strm = dest;
ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
ds->pending_buf = (uchf *) overlay;
if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
ds->pending_buf == Z_NULL) {
deflateEnd (dest);
return Z_MEM_ERROR;
}
/* following zmemcpy do not work for 16-bit MSDOS */
zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
ds->l_desc.dyn_tree = ds->dyn_ltree;
ds->d_desc.dyn_tree = ds->dyn_dtree;
ds->bl_desc.dyn_tree = ds->bl_tree;
return Z_OK;
#endif /* MAXSEG_64K */
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->next_in buffer and copying from it.
* (See also flush_pending()).
*/
local int read_buf(strm, buf, size)
z_streamp strm;
Bytef *buf;
unsigned size;
{
unsigned len = strm->avail_in;
if (len > size) len = size;
if (len == 0) return 0;
strm->avail_in -= len;
if (strm->state->wrap == 1) {
strm->adler = adler32(strm->adler, strm->next_in, len);
}
#ifdef GZIP
else if (strm->state->wrap == 2) {
strm->adler = crc32(strm->adler, strm->next_in, len);
}
#endif
zmemcpy(buf, strm->next_in, len);
strm->next_in += len;
strm->total_in += len;
return (int)len;
}
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
local void lm_init (s)
deflate_state *s;
{
s->window_size = (ulg)2L*s->w_size;
CLEAR_HASH(s);
/* Set the default configuration parameters:
*/
s->max_lazy_match = configuration_table[s->level].max_lazy;
s->good_match = configuration_table[s->level].good_length;
s->nice_match = configuration_table[s->level].nice_length;
s->max_chain_length = configuration_table[s->level].max_chain;
s->strstart = 0;
s->block_start = 0L;
s->lookahead = 0;
s->match_length = s->prev_length = MIN_MATCH-1;
s->match_available = 0;
s->ins_h = 0;
#ifndef FASTEST
#ifdef ASMV
match_init(); /* initialize the asm code */
#endif
#endif
}
#ifndef FASTEST
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
#ifndef ASMV
/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
* match.S. The code will be functionally equivalent.
*/
local uInt longest_match(s, cur_match)
deflate_state *s;
IPos cur_match; /* current match */
{
unsigned chain_length = s->max_chain_length;/* max hash chain length */
register Bytef *scan = s->window + s->strstart; /* current string */
register Bytef *match; /* matched string */
register int len; /* length of current match */
int best_len = s->prev_length; /* best match length so far */
int nice_match = s->nice_match; /* stop if match long enough */
IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
s->strstart - (IPos)MAX_DIST(s) : NIL;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
Posf *prev = s->prev;
uInt wmask = s->w_mask;
#ifdef UNALIGNED_OK
/* Compare two bytes at a time. Note: this is not always beneficial.
* Try with and without -DUNALIGNED_OK to check.
*/
register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
register ush scan_start = *(ushf*)scan;
register ush scan_end = *(ushf*)(scan+best_len-1);
#else
register Bytef *strend = s->window + s->strstart + MAX_MATCH;
register Byte scan_end1 = scan[best_len-1];
register Byte scan_end = scan[best_len];
#endif
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s->prev_length >= s->good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
Assert(cur_match < s->strstart, "no future");
match = s->window + cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
/* This code assumes sizeof(unsigned short) == 2. Do not use
* UNALIGNED_OK if your compiler uses a different size.
*/
if (*(ushf*)(match+best_len-1) != scan_end ||
*(ushf*)match != scan_start) continue;
/* It is not necessary to compare scan[2] and match[2] since they are
* always equal when the other bytes match, given that the hash keys
* are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
* strstart+3, +5, ... up to strstart+257. We check for insufficient
* lookahead only every 4th comparison; the 128th check will be made
* at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
* necessary to put more guard bytes at the end of the window, or
* to check more often for insufficient lookahead.
*/
Assert(scan[2] == match[2], "scan[2]?");
scan++, match++;
do {
} while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
scan < strend);
/* The funny "do {}" generates better code on most compilers */
/* Here, scan <= window+strstart+257 */
Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
if (*scan == *match) scan++;
len = (MAX_MATCH - 1) - (int)(strend-scan);
scan = strend - (MAX_MATCH-1);
#else /* UNALIGNED_OK */
if (match[best_len] != scan_end ||
match[best_len-1] != scan_end1 ||
*match != *scan ||
*++match != scan[1]) continue;
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2, match++;
Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
} while (*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
scan < strend);
Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (int)(strend - scan);
scan = strend - MAX_MATCH;
#endif /* UNALIGNED_OK */
if (len > best_len) {
s->match_start = cur_match;
best_len = len;
if (len >= nice_match) break;
#ifdef UNALIGNED_OK
scan_end = *(ushf*)(scan+best_len-1);
#else
scan_end1 = scan[best_len-1];
scan_end = scan[best_len];
#endif
}
} while ((cur_match = prev[cur_match & wmask]) > limit
&& --chain_length != 0);
if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
return s->lookahead;
}
#endif /* ASMV */
#else /* FASTEST */
/* ---------------------------------------------------------------------------
* Optimized version for FASTEST only
*/
local uInt longest_match(s, cur_match)
deflate_state *s;
IPos cur_match; /* current match */
{
register Bytef *scan = s->window + s->strstart; /* current string */
register Bytef *match; /* matched string */
register int len; /* length of current match */
register Bytef *strend = s->window + s->strstart + MAX_MATCH;
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
Assert(cur_match < s->strstart, "no future");
match = s->window + cur_match;
/* Return failure if the match length is less than 2:
*/
if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2, match += 2;
Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
} while (*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
scan < strend);
Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (int)(strend - scan);
if (len < MIN_MATCH) return MIN_MATCH - 1;
s->match_start = cur_match;
return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
}
#endif /* FASTEST */
#ifdef DEBUG
/* ===========================================================================
* Check that the match at match_start is indeed a match.
*/
local void check_match(s, start, match, length)
deflate_state *s;
IPos start, match;
int length;
{
/* check that the match is indeed a match */
if (zmemcmp(s->window + match,
s->window + start, length) != EQUAL) {
fprintf(stderr, " start %u, match %u, length %d\n",
start, match, length);
do {
fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
} while (--length != 0);
z_error("invalid match");
}
if (z_verbose > 1) {
fprintf(stderr,"\\[%d,%d]", start-match, length);
do { putc(s->window[start++], stderr); } while (--length != 0);
}
}
#else
# define check_match(s, start, match, length)
#endif /* DEBUG */
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
local void fill_window(s)
deflate_state *s;
{
register unsigned n, m;
register Posf *p;
unsigned more; /* Amount of free space at the end of the window. */
uInt wsize = s->w_size;
do {
more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
/* Deal with !@#$% 64K limit: */
if (sizeof(int) <= 2) {
if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
more = wsize;
} else if (more == (unsigned)(-1)) {
/* Very unlikely, but possible on 16 bit machine if
* strstart == 0 && lookahead == 1 (input done a byte at time)
*/
more--;
}
}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s->strstart >= wsize+MAX_DIST(s)) {
zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
s->match_start -= wsize;
s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
s->block_start -= (long) wsize;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s->hash_size;
p = &s->head[n];
do {
m = *--p;
*p = (Pos)(m >= wsize ? m-wsize : NIL);
} while (--n);
n = wsize;
#ifndef FASTEST
p = &s->prev[n];
do {
m = *--p;
*p = (Pos)(m >= wsize ? m-wsize : NIL);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
#endif
more += wsize;
}
if (s->strm->avail_in == 0) return;
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
Assert(more >= 2, "more < 2");
n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
s->lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s->lookahead >= MIN_MATCH) {
s->ins_h = s->window[s->strstart];
UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
#if MIN_MATCH != 3
Call UPDATE_HASH() MIN_MATCH-3 more times
#endif
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
if (s->high_water < s->window_size) {
ulg curr = s->strstart + (ulg)(s->lookahead);
ulg init;
if (s->high_water < curr) {
/* Previous high water mark below current data -- zero WIN_INIT
* bytes or up to end of window, whichever is less.
*/
init = s->window_size - curr;
if (init > WIN_INIT)
init = WIN_INIT;
zmemzero(s->window + curr, (unsigned)init);
s->high_water = curr + init;
}
else if (s->high_water < (ulg)curr + WIN_INIT) {
/* High water mark at or above current data, but below current data
* plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
* to end of window, whichever is less.
*/
init = (ulg)curr + WIN_INIT - s->high_water;
if (init > s->window_size - s->high_water)
init = s->window_size - s->high_water;
zmemzero(s->window + s->high_water, (unsigned)init);
s->high_water += init;
}
}
}
/* ===========================================================================
* Flush the current block, with given end-of-file flag.
* IN assertion: strstart is set to the end of the current match.
*/
#define FLUSH_BLOCK_ONLY(s, last) { \
_tr_flush_block(s, (s->block_start >= 0L ? \
(charf *)&s->window[(unsigned)s->block_start] : \
(charf *)Z_NULL), \
(ulg)((long)s->strstart - s->block_start), \
(last)); \
s->block_start = s->strstart; \
flush_pending(s->strm); \
Tracev((stderr,"[FLUSH]")); \
}
/* Same but force premature exit if necessary. */
#define FLUSH_BLOCK(s, last) { \
FLUSH_BLOCK_ONLY(s, last); \
if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
local block_state deflate_stored(s, flush)
deflate_state *s;
int flush;
{
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
ulg max_block_size = 0xffff;
ulg max_start;
if (max_block_size > s->pending_buf_size - 5) {
max_block_size = s->pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s->lookahead <= 1) {
Assert(s->strstart < s->w_size+MAX_DIST(s) ||
s->block_start >= (long)s->w_size, "slide too late");
fill_window(s);
if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
if (s->lookahead == 0) break; /* flush the current block */
}
Assert(s->block_start >= 0L, "block gone");
s->strstart += s->lookahead;
s->lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
max_start = s->block_start + max_block_size;
if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s->lookahead = (uInt)(s->strstart - max_start);
s->strstart = (uInt)max_start;
FLUSH_BLOCK(s, 0);
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
FLUSH_BLOCK(s, 0);
}
}
FLUSH_BLOCK(s, flush == Z_FINISH);
return flush == Z_FINISH ? finish_done : block_done;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
local block_state deflate_fast(s, flush)
deflate_state *s;
int flush;
{
IPos hash_head; /* head of the hash chain */
int bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s->lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return need_more;
}
if (s->lookahead == 0) break; /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = NIL;
if (s->lookahead >= MIN_MATCH) {
INSERT_STRING(s, s->strstart, hash_head);
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s->match_length = longest_match (s, hash_head);
/* longest_match() sets match_start */
}
if (s->match_length >= MIN_MATCH) {
check_match(s, s->strstart, s->match_start, s->match_length);
_tr_tally_dist(s, s->strstart - s->match_start,
s->match_length - MIN_MATCH, bflush);
s->lookahead -= s->match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
#ifndef FASTEST
if (s->match_length <= s->max_insert_length &&
s->lookahead >= MIN_MATCH) {
s->match_length--; /* string at strstart already in table */
do {
s->strstart++;
INSERT_STRING(s, s->strstart, hash_head);
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s->match_length != 0);
s->strstart++;
} else
#endif
{
s->strstart += s->match_length;
s->match_length = 0;
s->ins_h = s->window[s->strstart];
UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
#if MIN_MATCH != 3
Call UPDATE_HASH() MIN_MATCH-3 more times
#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
Tracevv((stderr,"%c", s->window[s->strstart]));
_tr_tally_lit (s, s->window[s->strstart], bflush);
s->lookahead--;
s->strstart++;
}
if (bflush) FLUSH_BLOCK(s, 0);
}
FLUSH_BLOCK(s, flush == Z_FINISH);
return flush == Z_FINISH ? finish_done : block_done;
}
#ifndef FASTEST
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
local block_state deflate_slow(s, flush)
deflate_state *s;
int flush;
{
IPos hash_head; /* head of hash chain */
int bflush; /* set if current block must be flushed */
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s->lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return need_more;
}
if (s->lookahead == 0) break; /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = NIL;
if (s->lookahead >= MIN_MATCH) {
INSERT_STRING(s, s->strstart, hash_head);
}
/* Find the longest match, discarding those <= prev_length.
*/
s->prev_length = s->match_length, s->prev_match = s->match_start;
s->match_length = MIN_MATCH-1;
if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
s->strstart - hash_head <= MAX_DIST(s)) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s->match_length = longest_match (s, hash_head);
/* longest_match() sets match_start */
if (s->match_length <= 5 && (s->strategy == Z_FILTERED
#if TOO_FAR <= 32767
|| (s->match_length == MIN_MATCH &&
s->strstart - s->match_start > TOO_FAR)
#endif
)) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s->match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
check_match(s, s->strstart-1, s->prev_match, s->prev_length);
_tr_tally_dist(s, s->strstart -1 - s->prev_match,
s->prev_length - MIN_MATCH, bflush);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s->lookahead -= s->prev_length-1;
s->prev_length -= 2;
do {
if (++s->strstart <= max_insert) {
INSERT_STRING(s, s->strstart, hash_head);
}
} while (--s->prev_length != 0);
s->match_available = 0;
s->match_length = MIN_MATCH-1;
s->strstart++;
if (bflush) FLUSH_BLOCK(s, 0);
} else if (s->match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
Tracevv((stderr,"%c", s->window[s->strstart-1]));
_tr_tally_lit(s, s->window[s->strstart-1], bflush);
if (bflush) {
FLUSH_BLOCK_ONLY(s, 0);
}
s->strstart++;
s->lookahead--;
if (s->strm->avail_out == 0) return need_more;
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s->match_available = 1;
s->strstart++;
s->lookahead--;
}
}
Assert (flush != Z_NO_FLUSH, "no flush?");
if (s->match_available) {
Tracevv((stderr,"%c", s->window[s->strstart-1]));
_tr_tally_lit(s, s->window[s->strstart-1], bflush);
s->match_available = 0;
}
FLUSH_BLOCK(s, flush == Z_FINISH);
return flush == Z_FINISH ? finish_done : block_done;
}
#endif /* FASTEST */
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
local block_state deflate_rle(s, flush)
deflate_state *s;
int flush;
{
int bflush; /* set if current block must be flushed */
uInt prev; /* byte at distance one to match */
Bytef *scan, *strend; /* scan goes up to strend for length of run */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest encodable run.
*/
if (s->lookahead < MAX_MATCH) {
fill_window(s);
if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
return need_more;
}
if (s->lookahead == 0) break; /* flush the current block */
}
/* See how many times the previous byte repeats */
s->match_length = 0;
if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
scan = s->window + s->strstart - 1;
prev = *scan;
if (prev == *++scan && prev == *++scan && prev == *++scan) {
strend = s->window + s->strstart + MAX_MATCH;
do {
} while (prev == *++scan && prev == *++scan &&
prev == *++scan && prev == *++scan &&
prev == *++scan && prev == *++scan &&
prev == *++scan && prev == *++scan &&
scan < strend);
s->match_length = MAX_MATCH - (int)(strend - scan);
if (s->match_length > s->lookahead)
s->match_length = s->lookahead;
}
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s->match_length >= MIN_MATCH) {
check_match(s, s->strstart, s->strstart - 1, s->match_length);
_tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
s->lookahead -= s->match_length;
s->strstart += s->match_length;
s->match_length = 0;
} else {
/* No match, output a literal byte */
Tracevv((stderr,"%c", s->window[s->strstart]));
_tr_tally_lit (s, s->window[s->strstart], bflush);
s->lookahead--;
s->strstart++;
}
if (bflush) FLUSH_BLOCK(s, 0);
}
FLUSH_BLOCK(s, flush == Z_FINISH);
return flush == Z_FINISH ? finish_done : block_done;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
local block_state deflate_huff(s, flush)
deflate_state *s;
int flush;
{
int bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s->lookahead == 0) {
fill_window(s);
if (s->lookahead == 0) {
if (flush == Z_NO_FLUSH)
return need_more;
break; /* flush the current block */
}
}
/* Output a literal byte */
s->match_length = 0;
Tracevv((stderr,"%c", s->window[s->strstart]));
_tr_tally_lit (s, s->window[s->strstart], bflush);
s->lookahead--;
s->strstart++;
if (bflush) FLUSH_BLOCK(s, 0);
}
FLUSH_BLOCK(s, flush == Z_FINISH);
return flush == Z_FINISH ? finish_done : block_done;
}
| lgpl-3.0 |
opentomb/OpenTomb | extern/bullet/BulletDynamics/ConstraintSolver/btGearConstraint.cpp | 422 | 2008 | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2012 Advanced Micro Devices, Inc. http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/// Implemented by Erwin Coumans. The idea for the constraint comes from Dimitris Papavasiliou.
#include "btGearConstraint.h"
btGearConstraint::btGearConstraint(btRigidBody& rbA, btRigidBody& rbB, const btVector3& axisInA,const btVector3& axisInB, btScalar ratio)
:btTypedConstraint(GEAR_CONSTRAINT_TYPE,rbA,rbB),
m_axisInA(axisInA),
m_axisInB(axisInB),
m_ratio(ratio)
{
}
btGearConstraint::~btGearConstraint ()
{
}
void btGearConstraint::getInfo1 (btConstraintInfo1* info)
{
info->m_numConstraintRows = 1;
info->nub = 1;
}
void btGearConstraint::getInfo2 (btConstraintInfo2* info)
{
btVector3 globalAxisA, globalAxisB;
globalAxisA = m_rbA.getWorldTransform().getBasis()*this->m_axisInA;
globalAxisB = m_rbB.getWorldTransform().getBasis()*this->m_axisInB;
info->m_J1angularAxis[0] = globalAxisA[0];
info->m_J1angularAxis[1] = globalAxisA[1];
info->m_J1angularAxis[2] = globalAxisA[2];
info->m_J2angularAxis[0] = m_ratio*globalAxisB[0];
info->m_J2angularAxis[1] = m_ratio*globalAxisB[1];
info->m_J2angularAxis[2] = m_ratio*globalAxisB[2];
}
| lgpl-3.0 |
RobertLeahy/MCPP | src/chat/chat_misc.cpp | 1 | 2462 | #include <chat/chat.hpp>
#include <utility>
#include <new>
namespace MCPP {
//
// CHAT TOKEN
//
ChatToken::ChatToken (String segment) noexcept : Type(ChatFormat::Segment), Segment(std::move(segment)) { }
ChatToken::ChatToken (ChatStyle style) noexcept : Type(ChatFormat::Push), Style(style) { }
ChatToken::ChatToken (ChatFormat type) noexcept : Type(type) {
if (type==ChatFormat::Segment) new (&Segment) String ();
}
inline void ChatToken::destroy () noexcept {
if (Type==ChatFormat::Segment) Segment.~String();
}
inline void ChatToken::copy (const ChatToken & other) {
if (Type==ChatFormat::Segment) {
new (&Segment) String (other.Segment);
} else if (Type==ChatFormat::Push) {
Style=other.Style;
}
}
inline void ChatToken::move (ChatToken && other) noexcept {
if (Type==ChatFormat::Segment) {
new (&Segment) String (std::move(other.Segment));
} else {
copy(other);
}
}
ChatToken::~ChatToken () noexcept {
destroy();
}
ChatToken::ChatToken (const ChatToken & other) : Type(other.Type) {
copy(other);
}
ChatToken::ChatToken (ChatToken && other) noexcept : Type(other.Type) {
move(std::move(other));
}
ChatToken & ChatToken::operator = (const ChatToken & other) {
if (&other!=this) {
Type=other.Type;
destroy();
copy(other);
}
return *this;
}
ChatToken & ChatToken::operator = (ChatToken && other) noexcept {
if (&other!=this) {
Type=other.Type;
destroy();
move(std::move(other));
}
return *this;
}
//
// CHAT MESSAGE
//
ChatMessage::ChatMessage (String message) : Echo(false) {
Message.EmplaceBack(ChatFormat::Label);
Message.EmplaceBack(ChatFormat::LabelSeparator);
Message.EmplaceBack(std::move(message));
}
ChatMessage::ChatMessage (SmartPointer<Client> from, String message) : From(std::move(from)), Echo(false) {
Message.EmplaceBack(ChatFormat::Label);
Message.EmplaceBack(ChatFormat::LabelSeparator);
Message.EmplaceBack(std::move(message));
}
ChatMessage::ChatMessage (SmartPointer<Client> from, String to, String message) : From(std::move(from)), Echo(false) {
To.EmplaceBack(std::move(to));
Message.EmplaceBack(ChatStyle::Pink);
Message.EmplaceBack(ChatFormat::Label);
Message.EmplaceBack(ChatFormat::LabelSeparator);
Message.EmplaceBack(std::move(message));
}
}
| unlicense |
xorware/android_frameworks_base | tools/aapt2/util/Util_test.cpp | 1 | 7298 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "test/Common.h"
#include "util/StringPiece.h"
#include "util/Util.h"
#include <gtest/gtest.h>
#include <string>
namespace aapt {
TEST(UtilTest, TrimOnlyWhitespace) {
const std::u16string full = u"\n ";
StringPiece16 trimmed = util::trimWhitespace(full);
EXPECT_TRUE(trimmed.empty());
EXPECT_EQ(0u, trimmed.size());
}
TEST(UtilTest, StringEndsWith) {
EXPECT_TRUE(util::stringEndsWith<char>("hello.xml", ".xml"));
}
TEST(UtilTest, StringStartsWith) {
EXPECT_TRUE(util::stringStartsWith<char>("hello.xml", "he"));
}
TEST(UtilTest, StringBuilderSplitEscapeSequence) {
EXPECT_EQ(StringPiece16(u"this is a new\nline."),
util::StringBuilder().append(u"this is a new\\")
.append(u"nline.")
.str());
}
TEST(UtilTest, StringBuilderWhitespaceRemoval) {
EXPECT_EQ(StringPiece16(u"hey guys this is so cool"),
util::StringBuilder().append(u" hey guys ")
.append(u" this is so cool ")
.str());
EXPECT_EQ(StringPiece16(u" wow, so many \t spaces. what?"),
util::StringBuilder().append(u" \" wow, so many \t ")
.append(u"spaces. \"what? ")
.str());
EXPECT_EQ(StringPiece16(u"where is the pie?"),
util::StringBuilder().append(u" where \t ")
.append(u" \nis the "" pie?")
.str());
}
TEST(UtilTest, StringBuilderEscaping) {
EXPECT_EQ(StringPiece16(u"hey guys\n this \t is so\\ cool"),
util::StringBuilder().append(u" hey guys\\n ")
.append(u" this \\t is so\\\\ cool ")
.str());
EXPECT_EQ(StringPiece16(u"@?#\\\'"),
util::StringBuilder().append(u"\\@\\?\\#\\\\\\'")
.str());
}
TEST(UtilTest, StringBuilderMisplacedQuote) {
util::StringBuilder builder{};
EXPECT_FALSE(builder.append(u"they're coming!"));
}
TEST(UtilTest, StringBuilderUnicodeCodes) {
EXPECT_EQ(StringPiece16(u"\u00AF\u0AF0 woah"),
util::StringBuilder().append(u"\\u00AF\\u0AF0 woah")
.str());
EXPECT_FALSE(util::StringBuilder().append(u"\\u00 yo"));
}
TEST(UtilTest, TokenizeInput) {
auto tokenizer = util::tokenize(StringPiece16(u"this| is|the|end"), u'|');
auto iter = tokenizer.begin();
ASSERT_EQ(*iter, StringPiece16(u"this"));
++iter;
ASSERT_EQ(*iter, StringPiece16(u" is"));
++iter;
ASSERT_EQ(*iter, StringPiece16(u"the"));
++iter;
ASSERT_EQ(*iter, StringPiece16(u"end"));
++iter;
ASSERT_EQ(tokenizer.end(), iter);
}
TEST(UtilTest, TokenizeEmptyString) {
auto tokenizer = util::tokenize(StringPiece16(u""), u'|');
auto iter = tokenizer.begin();
ASSERT_NE(tokenizer.end(), iter);
ASSERT_EQ(StringPiece16(), *iter);
++iter;
ASSERT_EQ(tokenizer.end(), iter);
}
TEST(UtilTest, TokenizeAtEnd) {
auto tokenizer = util::tokenize(StringPiece16(u"one."), u'.');
auto iter = tokenizer.begin();
ASSERT_EQ(*iter, StringPiece16(u"one"));
++iter;
ASSERT_NE(iter, tokenizer.end());
ASSERT_EQ(*iter, StringPiece16());
}
TEST(UtilTest, IsJavaClassName) {
EXPECT_TRUE(util::isJavaClassName(u"android.test.Class"));
EXPECT_TRUE(util::isJavaClassName(u"android.test.Class$Inner"));
EXPECT_TRUE(util::isJavaClassName(u"android_test.test.Class"));
EXPECT_TRUE(util::isJavaClassName(u"_android_.test._Class_"));
EXPECT_FALSE(util::isJavaClassName(u"android.test.$Inner"));
EXPECT_FALSE(util::isJavaClassName(u"android.test.Inner$"));
EXPECT_FALSE(util::isJavaClassName(u".test.Class"));
EXPECT_FALSE(util::isJavaClassName(u"android"));
}
TEST(UtilTest, IsJavaPackageName) {
EXPECT_TRUE(util::isJavaPackageName(u"android"));
EXPECT_TRUE(util::isJavaPackageName(u"android.test"));
EXPECT_TRUE(util::isJavaPackageName(u"android.test_thing"));
EXPECT_FALSE(util::isJavaPackageName(u"_android"));
EXPECT_FALSE(util::isJavaPackageName(u"android_"));
EXPECT_FALSE(util::isJavaPackageName(u"android."));
EXPECT_FALSE(util::isJavaPackageName(u".android"));
EXPECT_FALSE(util::isJavaPackageName(u"android._test"));
EXPECT_FALSE(util::isJavaPackageName(u".."));
}
TEST(UtilTest, FullyQualifiedClassName) {
Maybe<std::u16string> res = util::getFullyQualifiedClassName(u"android", u"asdf");
AAPT_ASSERT_FALSE(res);
res = util::getFullyQualifiedClassName(u"android", u".asdf");
AAPT_ASSERT_TRUE(res);
EXPECT_EQ(res.value(), u"android.asdf");
res = util::getFullyQualifiedClassName(u"android", u".a.b");
AAPT_ASSERT_TRUE(res);
EXPECT_EQ(res.value(), u"android.a.b");
res = util::getFullyQualifiedClassName(u"android", u"a.b");
AAPT_ASSERT_TRUE(res);
EXPECT_EQ(res.value(), u"a.b");
res = util::getFullyQualifiedClassName(u"", u"a.b");
AAPT_ASSERT_TRUE(res);
EXPECT_EQ(res.value(), u"a.b");
res = util::getFullyQualifiedClassName(u"", u"");
AAPT_ASSERT_FALSE(res);
res = util::getFullyQualifiedClassName(u"android", u"./Apple");
AAPT_ASSERT_FALSE(res);
}
TEST(UtilTest, ExtractResourcePathComponents) {
StringPiece16 prefix, entry, suffix;
ASSERT_TRUE(util::extractResFilePathParts(u"res/xml-sw600dp/entry.xml", &prefix, &entry,
&suffix));
EXPECT_EQ(prefix, u"res/xml-sw600dp/");
EXPECT_EQ(entry, u"entry");
EXPECT_EQ(suffix, u".xml");
ASSERT_TRUE(util::extractResFilePathParts(u"res/xml-sw600dp/entry.9.png", &prefix, &entry,
&suffix));
EXPECT_EQ(prefix, u"res/xml-sw600dp/");
EXPECT_EQ(entry, u"entry");
EXPECT_EQ(suffix, u".9.png");
EXPECT_FALSE(util::extractResFilePathParts(u"AndroidManifest.xml", &prefix, &entry, &suffix));
EXPECT_FALSE(util::extractResFilePathParts(u"res/.xml", &prefix, &entry, &suffix));
ASSERT_TRUE(util::extractResFilePathParts(u"res//.", &prefix, &entry, &suffix));
EXPECT_EQ(prefix, u"res//");
EXPECT_EQ(entry, u"");
EXPECT_EQ(suffix, u".");
}
TEST(UtilTest, VerifyJavaStringFormat) {
ASSERT_TRUE(util::verifyJavaStringFormat(u"%09.34f"));
ASSERT_TRUE(util::verifyJavaStringFormat(u"%9$.34f %8$"));
ASSERT_TRUE(util::verifyJavaStringFormat(u"%% %%"));
ASSERT_FALSE(util::verifyJavaStringFormat(u"%09$f %f"));
ASSERT_FALSE(util::verifyJavaStringFormat(u"%09f %08s"));
}
} // namespace aapt
| apache-2.0 |
OLR-xray/OLR-3.0 | src/xray/editors/LevelEditor/Edit/BuilderOGF.cpp | 1 | 4649 | //----------------------------------------------------
// file: BuilderRModel.cpp
//----------------------------------------------------
#include "stdafx.h"
#pragma hdrstop
#include "Builder.h"
#include "Scene.h"
#include "../ECore/Editor/EditObject.h"
#include "../ECore/Editor/EditMesh.h"
#include "SceneObject.h"
#include "ESceneAIMapTools.h"
//----------------------------------------------------
// some types
bool SceneBuilder::BuildHOMModel()
{
CMemoryWriter F;
F.open_chunk(0);
F.w_u32(0);
F.close_chunk();
F.open_chunk(1);
ObjectList& lst = Scene->ListObj(OBJCLASS_SCENEOBJECT);
for (ObjectIt it=lst.begin(); it!=lst.end(); it++){
CSceneObject* S = (CSceneObject*)(*it);
CEditableObject* E = S->GetReference(); R_ASSERT(E);
if (E->m_Flags.is(CEditableObject::eoHOM)){
Fvector v;
const Fmatrix& parent = S->_Transform();
for (EditMeshIt m_it=E->FirstMesh(); m_it!=E->LastMesh(); m_it++){
for (SurfFacesPairIt sf_it=(*m_it)->m_SurfFaces.begin(); sf_it!=(*m_it)->m_SurfFaces.end(); sf_it++){
BOOL b2Sided = sf_it->first->m_Flags.is(CSurface::sf2Sided);
IntVec& i_lst= sf_it->second;
for (IntIt i_it=i_lst.begin(); i_it!=i_lst.end(); i_it++){
st_Face& face = (*m_it)->m_Faces[*i_it];
for (int k=0; k<3; k++){
parent.transform_tiny(v,(*m_it)->m_Verts[face.pv[k].pindex]);
F.w_fvector3 (v);
}
F.w_u32(b2Sided);
}
}
}
}
}
BOOL bValid = !!F.chunk_size();
F.close_chunk();
if (bValid){
xr_string hom_name = MakeLevelPath("level.hom");
bValid = F.save_to(hom_name.c_str());
}
return bValid;
}
bool SceneBuilder::BuildSOMModel()
{
BOOL bResult = TRUE;
CMemoryWriter F;
F.open_chunk (0);
F.w_u32 (0);
F.close_chunk ();
F.open_chunk (1);
ObjectList& lst = Scene->ListObj(OBJCLASS_SCENEOBJECT);
for (ObjectIt it=lst.begin(); it!=lst.end(); it++){
CSceneObject* S = (CSceneObject*)(*it);
CEditableObject* E = S->GetReference(); R_ASSERT(E);
if (E->m_Flags.is(CEditableObject::eoSoundOccluder)){
Fvector v;
const Fmatrix& parent = S->_Transform();
for (EditMeshIt m_it=E->FirstMesh(); m_it!=E->LastMesh(); m_it++){
for (SurfFacesPairIt sf_it=(*m_it)->m_SurfFaces.begin(); sf_it!=(*m_it)->m_SurfFaces.end(); sf_it++){
CSurface* surf = sf_it->first;
int gm_id = surf->_GameMtl();
if (gm_id==GAMEMTL_NONE_ID){
ELog.DlgMsg (mtError,"Object '%s', surface '%s' contain invalid game material.",(*m_it)->Parent()->m_LibName.c_str(),surf->_Name());
bResult = FALSE;
break;
}
SGameMtl* mtl = GMLib.GetMaterialByID(gm_id);
if (0==mtl){
ELog.DlgMsg (mtError,"Object '%s', surface '%s' contain undefined game material.",(*m_it)->Parent()->m_LibName.c_str(),surf->_Name());
bResult = FALSE;
break;
}
BOOL b2Sided = surf->m_Flags.is(CSurface::sf2Sided);
IntVec& i_lst = sf_it->second;
for (IntIt i_it=i_lst.begin(); i_it!=i_lst.end(); i_it++){
st_Face& face = (*m_it)->m_Faces[*i_it];
for (int k=0; k<3; k++){
parent.transform_tiny(v,(*m_it)->m_Verts[face.pv[k].pindex]);
F.w_fvector3(v);
}
F.w_u32 (b2Sided);
F.w_float (mtl->fSndOcclusionFactor);
}
}
}
}
}
BOOL bValid = !!F.chunk_size()&&bResult;
F.close_chunk();
if (bValid){
xr_string som_name = MakeLevelPath("level.som");
bValid = F.save_to(som_name.c_str());
}
return bValid;
}
bool SceneBuilder::BuildAIMap()
{
// build sky ogf
if (Scene->GetMTools(OBJCLASS_AIMAP)->Valid()){
return Scene->GetMTools(OBJCLASS_AIMAP)->Export(m_LevelPath);
}
return false;
}
bool SceneBuilder::BuildWallmarks()
{
// build sky ogf
if (Scene->GetMTools(OBJCLASS_WM)->Valid()){
return Scene->GetMTools(OBJCLASS_WM)->Export(m_LevelPath);
}
return false;
}
| apache-2.0 |
tavultesoft/keymanweb | windows/src/ext/jedi/jvcl/jvcl/examples/JvTrayIcon/BCB/MainForm.cpp | 1 | 5271 | /******************************************************************
JEDI-VCL Demo
Copyright (C) 2004 Project JEDI
Original author: Olivier Sannier (obones att altern dott org)
You may retrieve the latest version of this file at the JEDI-JVCL
home page, located at http://jvcl.sourceforge.net
The contents of this file are used with permission, subject to
the Mozilla Public License Version 1.1 (the "License"); you may
not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1_1Final.html
Software distributed under the License is distributed on an
"AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
******************************************************************/
// $Id$
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "MainForm.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "JvComponent"
#pragma link "JvTrayIcon"
#pragma resource "*.dfm"
TfrmMain *frmMain;
//---------------------------------------------------------------------------
__fastcall TfrmMain::TfrmMain(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnUpdateClick(TObject *Sender)
{
TTrayVisibilities Options;
// JvTrayIcon1->
JvTrayIcon1->Active = false;
JvTrayIcon1->Animated = chkAnimated->Checked;
JvTrayIcon1->IconIndex = -1;
JvTrayIcon1->Hint = edHint->Text;
JvTrayIcon1->Snap = chkSnap->Checked;
if (chkPopUp->Checked)
JvTrayIcon1->PopupMenu = popTrayIcon;
else
JvTrayIcon1->PopupMenu = NULL;
if (chkDropDown->Checked)
JvTrayIcon1->DropDownMenu = popTrayIcon;
else
JvTrayIcon1->DropDownMenu = NULL;
Options.Clear();
if (chkTaskBar->Checked)
Options << tvVisibleTaskBar;
if (chkTaskList->Checked)
Options << tvVisibleTaskList;
if (chkAutoHide->Checked)
Options << tvAutoHide;
if (chkAutoHideIcon->Checked)
Options << tvAutoHideIcon;
if (chkRestoreClick->Checked && chkRestoreClick->Enabled)
Options << tvRestoreClick;
if (chkRestoreDblClick->Checked && chkRestoreDblClick->Enabled)
Options << tvRestoreDbClick;
// if (chkMinClick->Checked && chkMinClick->Enabled)
// Options << tvMinimizeClick;
// if (chkMinDblClick->Checked && chkMinDblClick->Enabled)
// Options << tvMinimizeDbClick;
JvTrayIcon1->Visibility = Options;
JvTrayIcon1->Active = chkActive->Checked;
btnBalloon->Enabled = JvTrayIcon1->Active;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::mnuShowHideClick(TObject *Sender)
{
if (IsWindowVisible(Handle))
JvTrayIcon1->HideApplication();
else
JvTrayIcon1->ShowApplication();
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::chkRestoreClickClick(TObject *Sender)
{
chkRestoreDblClick->Enabled = !chkRestoreClick->Checked;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::chkRestoreDblClickClick(TObject *Sender)
{
chkRestoreClick->Enabled = !chkRestoreDblClick->Checked;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::chkMinClickClick(TObject *Sender)
{
chkMinDblClick->Enabled = !chkMinClick->Checked;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::chkMinDblClickClick(TObject *Sender)
{
chkMinClick->Enabled = !chkMinDblClick->Checked;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::RestoreTimerTimer(TObject *Sender)
{
if (!IsWindowVisible(Handle))
JvTrayIcon1->ShowApplication();
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::chkAutoRestoreClick(TObject *Sender)
{
RestoreTimer->Enabled = !chkAutoRestore->Checked;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::btnBalloonClick(TObject *Sender)
{
JvTrayIcon1->BalloonHint(edBalloonTitle->Text,
edBalloonText->Text,
static_cast<TBalloonType>(cbBalloonType->ItemIndex),
5000,
true);
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::chkActiveClick(TObject *Sender)
{
JvTrayIcon1->Active = chkActive->Checked;
btnBalloon->Enabled = JvTrayIcon1->Active;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::FormShow(TObject *Sender)
{
cbBalloonType->ItemIndex = 0;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::chkAnimatedClick(TObject *Sender)
{
JvTrayIcon1->Animated = chkAnimated->Checked;
}
//---------------------------------------------------------------------------
| apache-2.0 |
alexge233/relearn | examples/blackjack.cpp | 1 | 4192 | /**
* A Blackjack/21 example showing how non-deterministic (probabilistic)
* Episodic Q-Learning works.
*
* @version 0.1.0
* @author Alex Giokas
* @date 19.11.2016
*
* @see the header (blackjack_header.hpp) for implementation details
*/
#include "blackjack_header.hpp"
#include <boost/predef.h>
// create aliases for state and action:
// - a state is the current hand held by a player
// - an action is draw(true) or stay(false)
//
using state = relearn::state<hand>;
using action = relearn::action<bool>;
// policy memory
relearn::policy<state,action> policies;
// catching CTRL-C works only on Linux for now
#if BOOST_OS_LINUX
#include <signal.h>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/vector.hpp>
volatile sig_atomic_t flag = 0;
void signal_handler(int sig) {
flag = 1;
}
#endif
// TODO: add BOOST_OS_WINDOWS
// and BOOST_OS_MACOS
int main()
{
signal(SIGINT, signal_handler);
// PRNG needed for, magic random voodoo
std::mt19937 gen(static_cast<std::size_t>(std::chrono::high_resolution_clock::now()
.time_since_epoch().count()));
// create the dealer, and two players...
auto dealer = std::make_shared<house>(cards, gen);
auto agent = std::make_shared<client>();
using link = relearn::link<state,action>;
std::deque<std::deque<link>> experience;
float sum = 0;
float wins = 0;
std::cout << "starting! Press CTRL-C to stop at any time!"
<< std::endl;
start:
// play 10 rounds - then stop
for (int i = 0; i < 100; i++) {
sum++;
std::deque<link> episode;
// one card to dealer/house
dealer->reset_deck();
dealer->insert(dealer->deal());
// two cards to player
agent->insert(dealer->deal());
agent->insert(dealer->deal());
// root state is starting hand
auto s_t = agent->state();
play:
// if agent's hand is burnt skip all else
if (agent->min_value() && agent->max_value() > 21) {
goto cmp;
}
// agent decides to draw
if (agent->draw(gen, s_t, policies)) {
episode.push_back(link{s_t, action(true)});
agent->insert(dealer->deal());
s_t = agent->state();
goto play;
}
// agent decides to stay
else {
episode.push_back(link{s_t, action(false)});
}
// dealer's turn
while (dealer->draw()) {
dealer->insert(dealer->deal());
}
cmp:
// compare hands, assign rewards!
if (hand_compare(*agent, *dealer)) {
if (!episode.empty()) {
episode.back().state.set_reward(1);
}
wins++;
}
else {
if (!episode.empty()) {
episode.back().state.set_reward(-1);
}
}
// clear current hand for both players
agent->clear();
dealer->clear();
experience.push_back(episode);
std::cout << "\twin ratio: " << wins / sum << std::endl;
std::cout << "\ton-policy ratio: "
<< agent->policy_actions / (agent->policy_actions + agent->random_actions)
<< std::endl;
}
// CTRL-C/SIGINT => save and exit
if (flag) {
#if USING_BOOST_SERIALIZATION
std::cout << "save & exit\r\n";
std::ofstream ofs("blackjack.policy");
boost::archive::text_oarchive oa(ofs);
oa << policies;
ofs.close();
return 0;
#else
std::cout << "exiting...\r\n";
#endif
}
// at this point, we have some playing experience, which we're going to use
// in order to train the agent.
relearn::q_probabilistic<state,action> learner;
for (auto & episode : experience) {
for (int i = 0; i < 10; i++) {
learner(episode, policies);
}
}
// clear experience - we'll add new ones!
experience.clear();
agent->reset();
// restart - please don't use goto's in modern C++
goto start;
return 0;
}
| apache-2.0 |
oussiden/riffMaker | main.cpp | 1 | 3892 | #include <iostream>
#include <cstring>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
using namespace std;
struct wavHeaderRec {
int bitSize;
int numSeconds;
unsigned char fileType[5]; //1-4
unsigned int fileSize; //5-8
unsigned char fileTypeHeader[5]; //9-12
unsigned char chunkMarker[5]; //13-16
unsigned int formatDataLen; //17-20
unsigned int typeFormat; //21-22
unsigned int numChannels; //23-24
unsigned int sampleRate; //25-28
unsigned int sampleBufSize; //29-32
unsigned int stereo; //33-34
unsigned int bitsPerSample; //35-36
unsigned char dataChunkHeader[5]; //37-40
unsigned int dataSize; //41-44
unsigned char fileName[12];
};
void initWavHeaderRec(wavHeaderRec &header) {
header.bitSize = 16;
header.numSeconds = 1;
header.fileType[0] = 'R';
header.fileType[1] = 'I';
header.fileType[2] = 'F';
header.fileType[3] = 'F';
header.fileType[4] = '\0'; //1-4
header.fileSize = 0; //5-8
header.fileTypeHeader[0] = 'W';
header.fileTypeHeader[1] = 'A';
header.fileTypeHeader[2] = 'V';
header.fileTypeHeader[3] = 'E';
header.fileTypeHeader[4] = '\0'; // 9-12
header.chunkMarker[0] = 'f';
header.chunkMarker[1] = 'm';
header.chunkMarker[2] = 't';
header.chunkMarker[3] = '\0'; //13-16
header.formatDataLen = 16; //17-20
header.typeFormat = 1; //21-22
header.numChannels = 2; //23-24
header.sampleRate = 44100; //25-28
header.sampleBufSize = 176400; //29-32
header.stereo = 4; //33-34
header.bitsPerSample = 16; //35-36
header.dataChunkHeader[0] = 'd';
header.dataChunkHeader[1] = 'a';
header.dataChunkHeader[2] = 't';
header.dataChunkHeader[3] = 'a';
header.dataChunkHeader[4] = '\0'; //37-40
header.dataSize = 0; //41-44
header.fileName[0] = 't';
header.fileName[1] = 'e';
header.fileName[2] = 's';
header.fileName[3] = 't';
header.fileName[4] = 'i';
header.fileName[5] = 'n';
header.fileName[6] = 'g';
header.fileName[7] = '.';
header.fileName[8] = 'w';
header.fileName[9] = 'a';
header.fileName[10] = 'v';
header.fileName[11] = '\0';
}
void printWavHeaderRec(wavHeaderRec &header) {
cout << endl;
cout << "Bit Size: " << header.bitSize << endl;
cout << "numSeconds: " << header.numSeconds << endl;
cout << "fileType: " << header.fileType << endl;
cout << "fileSize: " << header.fileSize << endl;
cout << "fileTypeHeader: " << header.fileTypeHeader << endl;
cout << "chunkMarker: " << header.chunkMarker << endl;
cout << "formatDataLen: " << header.formatDataLen << endl;
cout << "typeFormat: " << header.typeFormat << endl;
cout << "numChannels: " << header.numChannels << endl;
cout << "sampleRate: " << header.sampleRate << endl;
cout << "sampleBufSize: " << header.sampleBufSize << endl;
cout << "stereo: " << header.stereo << endl;
cout << "bitsPerSample: " << header.bitsPerSample << endl;
cout << "dataChunkHeader: "<< header.dataChunkHeader << endl;
cout << "dataSize: " << header.dataSize << endl;
cout << "fileName: " << header.fileName << endl;
cout << "----------" << endl;
}
void buildWavFile(wavHeaderRec &header) {
}
void wavGen() {
struct wavHeaderRec header;
initWavHeaderRec(header);
printWavHeaderRec(header);
}
int main() {
//wavGen();
sf::RenderWindow window(sf::VideoMode(800, 600), "Mi casa es su casa");
sf::CircleShape shape(100.f);
sf::Music music;
if(!music.openFromFile("test.wav")) {
return EXIT_FAILURE;
}
music.setLoop(1);
music.setPosition(-10.0, 10.0, 0.0);
music.play();
shape.setFillColor(sf::Color::Green);
while(window.isOpen()) {
sf::Event event;
while(window.pollEvent(event)) {
if(event.type == sf::Event::Closed) {
window.close();
}
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
| apache-2.0 |
espressif/esp-idf | examples/openthread/ot_rcp/main/esp_ot_rcp.c | 1 | 1764 | /*
* SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: CC0-1.0
*
* OpenThread Radio Co-Processor (RCP) Example
*
* This example code is in the Public Domain (or CC0-1.0 licensed, at your option.)
*
* Unless required by applicable law or agreed to in writing, this
* software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <unistd.h>
#include "esp_event.h"
#include "esp_openthread.h"
#include "esp_ot_config.h"
#include "esp_vfs_eventfd.h"
#include "driver/uart.h"
#if !CONFIG_IDF_TARGET_ESP32H4
#error "RCP is only supported for esp32h4"
#endif
#define TAG "ot_esp_rcp"
extern void otAppNcpInit(otInstance *instance);
static void ot_task_worker(void *aContext)
{
esp_openthread_platform_config_t config = {
.radio_config = ESP_OPENTHREAD_DEFAULT_RADIO_CONFIG(),
.host_config = ESP_OPENTHREAD_DEFAULT_HOST_CONFIG(),
.port_config = ESP_OPENTHREAD_DEFAULT_PORT_CONFIG(),
};
// Initialize the OpenThread stack
ESP_ERROR_CHECK(esp_openthread_init(&config));
// Initialize the OpenThread ncp
otAppNcpInit(esp_openthread_get_instance());
// Run the main loop
esp_openthread_launch_mainloop();
// Clean up
esp_vfs_eventfd_unregister();
vTaskDelete(NULL);
}
void app_main(void)
{
// Used eventfds:
// * ot task queue
// * radio driver
esp_vfs_eventfd_config_t eventfd_config = {
.max_fds = 2,
};
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(esp_vfs_eventfd_register(&eventfd_config));
xTaskCreate(ot_task_worker, "ot_rcp_main", 10240, xTaskGetCurrentTaskHandle(), 5, NULL);
}
| apache-2.0 |
DiligentGraphics/DiligentCore | Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp | 1 | 148929 | /*
* Copyright 2019-2022 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "pch.h"
#include "DeviceContextD3D12Impl.hpp"
#include <sstream>
#include "RenderDeviceD3D12Impl.hpp"
#include "PipelineStateD3D12Impl.hpp"
#include "TextureD3D12Impl.hpp"
#include "BufferD3D12Impl.hpp"
#include "FenceD3D12Impl.hpp"
#include "ShaderBindingTableD3D12Impl.hpp"
#include "ShaderResourceBindingD3D12Impl.hpp"
#include "CommandListD3D12Impl.hpp"
#include "DeviceMemoryD3D12Impl.hpp"
#include "CommandQueueD3D12Impl.hpp"
#include "CommandContext.hpp"
#include "D3D12TypeConversions.hpp"
#include "d3dx12_win.h"
#include "D3D12DynamicHeap.hpp"
#include "QueryManagerD3D12.hpp"
#include "DXGITypeConversions.hpp"
#include "D3D12TileMappingHelper.hpp"
namespace Diligent
{
static std::string GetContextObjectName(const char* Object, bool bIsDeferred, Uint32 ContextId)
{
std::stringstream ss;
ss << Object;
if (bIsDeferred)
ss << " of deferred context #" << ContextId;
else
ss << " of immediate context";
return ss.str();
}
DeviceContextD3D12Impl::DeviceContextD3D12Impl(IReferenceCounters* pRefCounters,
RenderDeviceD3D12Impl* pDeviceD3D12Impl,
const EngineD3D12CreateInfo& EngineCI,
const DeviceContextDesc& Desc) :
// clang-format off
TDeviceContextBase
{
pRefCounters,
pDeviceD3D12Impl,
Desc
},
m_DynamicHeap
{
pDeviceD3D12Impl->GetDynamicMemoryManager(),
GetContextObjectName("Dynamic heap", Desc.IsDeferred, Desc.ContextId),
EngineCI.DynamicHeapPageSize
},
m_DynamicGPUDescriptorAllocator
{
{
GetRawAllocator(),
pDeviceD3D12Impl->GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV),
EngineCI.DynamicDescriptorAllocationChunkSize[D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV],
GetContextObjectName("CBV_SRV_UAV dynamic descriptor allocator", Desc.IsDeferred, Desc.ContextId)
},
{
GetRawAllocator(),
pDeviceD3D12Impl->GetGPUDescriptorHeap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER),
EngineCI.DynamicDescriptorAllocationChunkSize[D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER],
GetContextObjectName("SAMPLER dynamic descriptor allocator", Desc.IsDeferred, Desc.ContextId)
}
},
m_CmdListAllocator{GetRawAllocator(), sizeof(CommandListD3D12Impl), 64},
m_NullRTV{pDeviceD3D12Impl->AllocateDescriptors(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1)}
// clang-format on
{
auto* pd3d12Device = pDeviceD3D12Impl->GetD3D12Device();
if (!IsDeferred())
{
RequestCommandContext();
m_QueryMgr = &pDeviceD3D12Impl->GetQueryMgr(GetCommandQueueId());
}
auto* pDrawIndirectSignature = GetDrawIndirectSignature(sizeof(UINT) * 4);
if (pDrawIndirectSignature == nullptr)
LOG_ERROR_AND_THROW("Failed to create indirect draw command signature");
auto* pDrawIndexedIndirectSignature = GetDrawIndexedIndirectSignature(sizeof(UINT) * 5);
if (pDrawIndexedIndirectSignature == nullptr)
LOG_ERROR_AND_THROW("Failed to create draw indexed indirect command signature");
D3D12_COMMAND_SIGNATURE_DESC CmdSignatureDesc = {};
D3D12_INDIRECT_ARGUMENT_DESC IndirectArg = {};
CmdSignatureDesc.NodeMask = 0;
CmdSignatureDesc.NumArgumentDescs = 1;
CmdSignatureDesc.pArgumentDescs = &IndirectArg;
CmdSignatureDesc.ByteStride = sizeof(UINT) * 3;
IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
auto hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDispatchIndirectSignature), reinterpret_cast<void**>(static_cast<ID3D12CommandSignature**>(&m_pDispatchIndirectSignature)));
CHECK_D3D_RESULT_THROW(hr, "Failed to create dispatch indirect command signature");
#ifdef D3D12_H_HAS_MESH_SHADER
if (pDeviceD3D12Impl->GetFeatures().MeshShaders == DEVICE_FEATURE_STATE_ENABLED)
{
CmdSignatureDesc.ByteStride = sizeof(UINT) * 3;
IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH;
hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDrawMeshIndirectSignature), reinterpret_cast<void**>(static_cast<ID3D12CommandSignature**>(&m_pDrawMeshIndirectSignature)));
CHECK_D3D_RESULT_THROW(hr, "Failed to create draw mesh indirect command signature");
VERIFY_EXPR(CmdSignatureDesc.ByteStride == DrawMeshIndirectCommandStride);
}
#endif
if (pDeviceD3D12Impl->GetFeatures().RayTracing == DEVICE_FEATURE_STATE_ENABLED &&
(pDeviceD3D12Impl->GetAdapterInfo().RayTracing.CapFlags & RAY_TRACING_CAP_FLAG_INDIRECT_RAY_TRACING) != 0)
{
CmdSignatureDesc.ByteStride = sizeof(D3D12_DISPATCH_RAYS_DESC);
IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_RAYS;
hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pTraceRaysIndirectSignature), reinterpret_cast<void**>(static_cast<ID3D12CommandSignature**>(&m_pTraceRaysIndirectSignature)));
CHECK_D3D_RESULT_THROW(hr, "Failed to create trace rays indirect command signature");
static_assert(TraceRaysIndirectCommandSBTSize == offsetof(D3D12_DISPATCH_RAYS_DESC, Width), "Invalid SBT offsets size");
static_assert(TraceRaysIndirectCommandSize == sizeof(D3D12_DISPATCH_RAYS_DESC), "Invalid trace ray indirect command size");
}
{
D3D12_RENDER_TARGET_VIEW_DESC NullRTVDesc{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D};
// A null pResource is used to initialize a null descriptor, which guarantees D3D11-like null binding behavior
// (reading 0s, writes are discarded), but must have a valid pDesc in order to determine the descriptor type.
// https://docs.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createrendertargetview
pd3d12Device->CreateRenderTargetView(nullptr, &NullRTVDesc, m_NullRTV.GetCpuHandle());
VERIFY(!m_NullRTV.IsNull(), "Failed to create null RTV");
}
}
DeviceContextD3D12Impl::~DeviceContextD3D12Impl()
{
if (m_State.NumCommands != 0)
{
if (IsDeferred())
{
LOG_ERROR_MESSAGE("There are outstanding commands in deferred context #", GetContextId(),
" being destroyed, which indicates that FinishCommandList() has not been called."
" This may cause synchronization issues.");
}
else
{
LOG_ERROR_MESSAGE("There are outstanding commands in the immediate context being destroyed, "
"which indicates the context has not been Flush()'ed.",
" This may cause synchronization issues.");
}
}
if (IsDeferred())
{
if (m_CurrCmdCtx)
{
// The command context has never been executed, so it can be disposed without going through release queue
m_pDevice->DisposeCommandContext(std::move(m_CurrCmdCtx));
}
}
else
{
Flush(false);
}
// For deferred contexts, m_SubmittedBuffersCmdQueueMask is reset to 0 after every call to FinishFrame().
// In this case there are no resources to release, so there will be no issues.
FinishFrame();
// Note: as dynamic pages are returned to the global dynamic memory manager hosted by the render device,
// the dynamic heap can be destroyed before all pages are actually returned to the global manager.
DEV_CHECK_ERR(m_DynamicHeap.GetAllocatedPagesCount() == 0, "All dynamic pages must have been released by now.");
for (size_t i = 0; i < _countof(m_DynamicGPUDescriptorAllocator); ++i)
{
// Note: as dynamic descriptor suballocations are returned to the global GPU descriptor heap that
// is hosted by the render device, the descriptor allocator can be destroyed before all suballocations
// are actually returned to the global heap.
DEV_CHECK_ERR(m_DynamicGPUDescriptorAllocator[i].GetSuballocationCount() == 0, "All dynamic suballocations must have been released");
}
}
ID3D12CommandSignature* DeviceContextD3D12Impl::GetDrawIndirectSignature(Uint32 Stride)
{
auto& Sig = m_pDrawIndirectSignatureMap[Stride];
if (Sig == nullptr)
{
VERIFY_EXPR(Stride >= sizeof(UINT) * 4);
D3D12_INDIRECT_ARGUMENT_DESC IndirectArg{};
IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
D3D12_COMMAND_SIGNATURE_DESC CmdSignatureDesc{};
CmdSignatureDesc.NodeMask = 0;
CmdSignatureDesc.NumArgumentDescs = 1;
CmdSignatureDesc.pArgumentDescs = &IndirectArg;
CmdSignatureDesc.ByteStride = Stride;
auto hr = m_pDevice->GetD3D12Device()->CreateCommandSignature(&CmdSignatureDesc, nullptr, IID_PPV_ARGS(&Sig));
CHECK_D3D_RESULT(hr, "Failed to create indirect draw command signature");
}
return Sig;
}
ID3D12CommandSignature* DeviceContextD3D12Impl::GetDrawIndexedIndirectSignature(Uint32 Stride)
{
auto& Sig = m_pDrawIndexedIndirectSignatureMap[Stride];
if (Sig == nullptr)
{
VERIFY_EXPR(Stride >= sizeof(UINT) * 5);
D3D12_INDIRECT_ARGUMENT_DESC IndirectArg{};
IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED;
D3D12_COMMAND_SIGNATURE_DESC CmdSignatureDesc{};
CmdSignatureDesc.NodeMask = 0;
CmdSignatureDesc.NumArgumentDescs = 1;
CmdSignatureDesc.pArgumentDescs = &IndirectArg;
CmdSignatureDesc.ByteStride = Stride;
auto hr = m_pDevice->GetD3D12Device()->CreateCommandSignature(&CmdSignatureDesc, nullptr, IID_PPV_ARGS(&Sig));
CHECK_D3D_RESULT(hr, "Failed to create draw indexed indirect command signature");
}
return Sig;
}
void DeviceContextD3D12Impl::Begin(Uint32 ImmediateContextId)
{
DEV_CHECK_ERR(ImmediateContextId < m_pDevice->GetCommandQueueCount(), "ImmediateContextId is out of range");
SoftwareQueueIndex CommandQueueId{ImmediateContextId};
const auto d3d12CmdListType = m_pDevice->GetCommandQueueType(CommandQueueId);
const auto QueueType = D3D12CommandListTypeToCmdQueueType(d3d12CmdListType);
TDeviceContextBase::Begin(DeviceContextIndex{ImmediateContextId}, QueueType);
RequestCommandContext();
m_QueryMgr = &m_pDevice->GetQueryMgr(CommandQueueId);
}
void DeviceContextD3D12Impl::SetPipelineState(IPipelineState* pPipelineState)
{
RefCntAutoPtr<PipelineStateD3D12Impl> pPipelineStateD3D12{pPipelineState, PipelineStateD3D12Impl::IID_InternalImpl};
VERIFY(pPipelineState == nullptr || pPipelineStateD3D12 != nullptr, "Unknown pipeline state object implementation");
if (PipelineStateD3D12Impl::IsSameObject(m_pPipelineState, pPipelineStateD3D12))
return;
const auto& PSODesc = pPipelineStateD3D12->GetDesc();
bool CommitStates = false;
bool CommitScissor = false;
if (!m_pPipelineState)
{
// If no pipeline state is bound, we are working with the fresh command
// list. We have to commit the states set in the context that are not
// committed by the draw command (render targets, viewports, scissor rects, etc.)
CommitStates = true;
}
else
{
const auto& OldPSODesc = m_pPipelineState->GetDesc();
// Commit all graphics states when switching from compute pipeline
// This is necessary because if the command list had been flushed
// and the first PSO set on the command list was a compute pipeline,
// the states would otherwise never be committed (since m_pPipelineState != nullptr)
CommitStates = !OldPSODesc.IsAnyGraphicsPipeline();
// We also need to update scissor rect if ScissorEnable state has changed
if (OldPSODesc.IsAnyGraphicsPipeline() && PSODesc.IsAnyGraphicsPipeline())
CommitScissor = m_pPipelineState->GetGraphicsPipelineDesc().RasterizerDesc.ScissorEnable != pPipelineStateD3D12->GetGraphicsPipelineDesc().RasterizerDesc.ScissorEnable;
}
TDeviceContextBase::SetPipelineState(std::move(pPipelineStateD3D12), 0 /*Dummy*/);
auto& CmdCtx = GetCmdContext();
auto& RootInfo = GetRootTableInfo(PSODesc.PipelineType);
auto* pd3d12RootSig = m_pPipelineState->GetD3D12RootSignature();
if (RootInfo.pd3d12RootSig != pd3d12RootSig)
{
RootInfo.pd3d12RootSig = pd3d12RootSig;
Uint32 DvpCompatibleSRBCount = 0;
PrepareCommittedResources(RootInfo, DvpCompatibleSRBCount);
// When root signature changes, all resources must be committed anew
RootInfo.MakeAllStale();
}
static_assert(PIPELINE_TYPE_LAST == 4, "Please update the switch below to handle the new pipeline type");
switch (PSODesc.PipelineType)
{
case PIPELINE_TYPE_GRAPHICS:
case PIPELINE_TYPE_MESH:
{
auto& GraphicsPipeline = m_pPipelineState->GetGraphicsPipelineDesc();
auto& GraphicsCtx = CmdCtx.AsGraphicsContext();
auto* pd3d12PSO = m_pPipelineState->GetD3D12PipelineState();
GraphicsCtx.SetPipelineState(pd3d12PSO);
GraphicsCtx.SetGraphicsRootSignature(pd3d12RootSig);
if (PSODesc.PipelineType == PIPELINE_TYPE_GRAPHICS)
{
auto D3D12Topology = TopologyToD3D12Topology(GraphicsPipeline.PrimitiveTopology);
GraphicsCtx.SetPrimitiveTopology(D3D12Topology);
}
if (CommitStates)
{
GraphicsCtx.SetStencilRef(m_StencilRef);
GraphicsCtx.SetBlendFactor(m_BlendFactors);
if (GraphicsPipeline.pRenderPass == nullptr)
{
CommitRenderTargets(RESOURCE_STATE_TRANSITION_MODE_VERIFY);
}
CommitViewports();
}
if (CommitStates || CommitScissor)
{
CommitScissorRects(GraphicsCtx, GraphicsPipeline.RasterizerDesc.ScissorEnable);
}
break;
}
case PIPELINE_TYPE_COMPUTE:
{
auto* pd3d12PSO = m_pPipelineState->GetD3D12PipelineState();
auto& CompCtx = CmdCtx.AsComputeContext();
CompCtx.SetPipelineState(pd3d12PSO);
CompCtx.SetComputeRootSignature(pd3d12RootSig);
break;
}
case PIPELINE_TYPE_RAY_TRACING:
{
auto* pd3d12SO = m_pPipelineState->GetD3D12StateObject();
auto& RTCtx = CmdCtx.AsGraphicsContext4();
RTCtx.SetRayTracingPipelineState(pd3d12SO);
RTCtx.SetComputeRootSignature(pd3d12RootSig);
break;
}
case PIPELINE_TYPE_TILE:
UNEXPECTED("Unsupported pipeline type");
break;
default:
UNEXPECTED("Unknown pipeline type");
}
}
template <bool IsCompute>
void DeviceContextD3D12Impl::CommitRootTablesAndViews(RootTableInfo& RootInfo, Uint32 CommitSRBMask, CommandContext& CmdCtx) const
{
const auto& RootSig = m_pPipelineState->GetRootSignature();
PipelineResourceSignatureD3D12Impl::CommitCacheResourcesAttribs CommitAttribs //
{
m_pDevice->GetD3D12Device(),
CmdCtx,
GetContextId(),
IsCompute //
};
VERIFY(CommitSRBMask != 0, "This method should not be called when there is nothing to commit");
while (CommitSRBMask != 0)
{
const auto SignBit = ExtractLSB(CommitSRBMask);
const auto sign = PlatformMisc::GetLSB(SignBit);
VERIFY_EXPR(sign < m_pPipelineState->GetResourceSignatureCount());
const auto* const pSignature = RootSig.GetResourceSignature(sign);
VERIFY_EXPR(pSignature != nullptr && pSignature->GetTotalResourceCount() > 0);
const auto* pResourceCache = RootInfo.ResourceCaches[sign];
DEV_CHECK_ERR(pResourceCache != nullptr, "Resource cache at index ", sign, " is null.");
CommitAttribs.pResourceCache = pResourceCache;
CommitAttribs.BaseRootIndex = RootSig.GetBaseRootIndex(sign);
if ((RootInfo.StaleSRBMask & SignBit) != 0)
{
// Commit root tables for stale SRBs only
pSignature->CommitRootTables(CommitAttribs);
}
// Always commit root views. If the root view is up-to-date (e.g. it is not stale and is intact),
// the bit should not be set in CommitSRBMask.
if (auto DynamicRootBuffersMask = pResourceCache->GetDynamicRootBuffersMask())
{
DEV_CHECK_ERR((RootInfo.DynamicSRBMask & SignBit) != 0,
"There are dynamic root buffers in the cache, but the bit in DynamicSRBMask is not set. This may indicate that resources "
"in the cache have changed, but the SRB has not been committed before the draw/dispatch command.");
pSignature->CommitRootViews(CommitAttribs, DynamicRootBuffersMask);
}
else
{
DEV_CHECK_ERR((RootInfo.DynamicSRBMask & SignBit) == 0,
"There are no dynamic root buffers in the cache, but the bit in DynamicSRBMask is set. This may indicate that resources "
"in the cache have changed, but the SRB has not been committed before the draw/dispatch command.");
}
}
VERIFY_EXPR((CommitSRBMask & RootInfo.ActiveSRBMask) == 0);
RootInfo.StaleSRBMask &= ~RootInfo.ActiveSRBMask;
}
void DeviceContextD3D12Impl::TransitionShaderResources(IPipelineState* pPipelineState, IShaderResourceBinding* pShaderResourceBinding)
{
DEV_CHECK_ERR(pPipelineState != nullptr, "Pipeline state must not be null");
DEV_CHECK_ERR(!m_pActiveRenderPass, "State transitions are not allowed inside a render pass.");
auto& CmdCtx = GetCmdContext();
auto* pResBindingD3D12Impl = ClassPtrCast<ShaderResourceBindingD3D12Impl>(pShaderResourceBinding);
auto& ResourceCache = pResBindingD3D12Impl->GetResourceCache();
ResourceCache.TransitionResourceStates(CmdCtx, ShaderResourceCacheD3D12::StateTransitionMode::Transition);
}
void DeviceContextD3D12Impl::CommitShaderResources(IShaderResourceBinding* pShaderResourceBinding, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
DeviceContextBase::CommitShaderResources(pShaderResourceBinding, StateTransitionMode, 0 /*Dummy*/);
auto* pResBindingD3D12Impl = ClassPtrCast<ShaderResourceBindingD3D12Impl>(pShaderResourceBinding);
auto& ResourceCache = pResBindingD3D12Impl->GetResourceCache();
auto& CmdCtx = GetCmdContext();
auto* pSignature = pResBindingD3D12Impl->GetSignature();
#ifdef DILIGENT_DEBUG
ResourceCache.DbgValidateDynamicBuffersMask();
#endif
if (StateTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION)
{
ResourceCache.TransitionResourceStates(CmdCtx, ShaderResourceCacheD3D12::StateTransitionMode::Transition);
}
#ifdef DILIGENT_DEVELOPMENT
else if (StateTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY)
{
ResourceCache.TransitionResourceStates(CmdCtx, ShaderResourceCacheD3D12::StateTransitionMode::Verify);
}
#endif
const auto SRBIndex = pResBindingD3D12Impl->GetBindingIndex();
auto& RootInfo = GetRootTableInfo(pSignature->GetPipelineType());
RootInfo.Set(SRBIndex, pResBindingD3D12Impl);
}
DeviceContextD3D12Impl::RootTableInfo& DeviceContextD3D12Impl::GetRootTableInfo(PIPELINE_TYPE PipelineType)
{
return PipelineType == PIPELINE_TYPE_GRAPHICS || PipelineType == PIPELINE_TYPE_MESH ?
m_GraphicsResources :
m_ComputeResources;
}
#ifdef DILIGENT_DEVELOPMENT
void DeviceContextD3D12Impl::DvpValidateCommittedShaderResources(RootTableInfo& RootInfo) const
{
if (RootInfo.ResourcesValidated)
return;
DvpVerifySRBCompatibility(RootInfo,
[this](Uint32 idx) {
// Use signature from the root signature
return m_pPipelineState->GetRootSignature().GetResourceSignature(idx);
});
m_pPipelineState->DvpVerifySRBResources(this, RootInfo.ResourceCaches);
RootInfo.ResourcesValidated = true;
}
#endif
void DeviceContextD3D12Impl::SetStencilRef(Uint32 StencilRef)
{
if (TDeviceContextBase::SetStencilRef(StencilRef, 0))
{
GetCmdContext().AsGraphicsContext().SetStencilRef(m_StencilRef);
}
}
void DeviceContextD3D12Impl::SetBlendFactors(const float* pBlendFactors)
{
if (TDeviceContextBase::SetBlendFactors(pBlendFactors, 0))
{
GetCmdContext().AsGraphicsContext().SetBlendFactor(m_BlendFactors);
}
}
void DeviceContextD3D12Impl::CommitD3D12IndexBuffer(GraphicsContext& GraphCtx, VALUE_TYPE IndexType)
{
DEV_CHECK_ERR(m_pIndexBuffer != nullptr, "Index buffer is not set up for indexed draw command");
D3D12_INDEX_BUFFER_VIEW IBView;
IBView.BufferLocation = m_pIndexBuffer->GetGPUAddress(GetContextId(), this) + m_IndexDataStartOffset;
if (IndexType == VT_UINT32)
IBView.Format = DXGI_FORMAT_R32_UINT;
else
{
DEV_CHECK_ERR(IndexType == VT_UINT16, "Unsupported index format. Only R16_UINT and R32_UINT are allowed.");
IBView.Format = DXGI_FORMAT_R16_UINT;
}
// Note that for a dynamic buffer, what we use here is the size of the buffer itself, not the upload heap buffer!
IBView.SizeInBytes = StaticCast<UINT>(m_pIndexBuffer->GetDesc().Size - m_IndexDataStartOffset);
// Device context keeps strong reference to bound index buffer.
// When the buffer is unbound, the reference to the D3D12 resource
// is added to the context. There is no need to add reference here
//auto &GraphicsCtx = GetCmdContext().AsGraphicsContext();
//auto *pd3d12Resource = pBuffD3D12->GetD3D12Buffer();
//GraphicsCtx.AddReferencedObject(pd3d12Resource);
bool IsDynamic = m_pIndexBuffer->GetDesc().Usage == USAGE_DYNAMIC;
#ifdef DILIGENT_DEVELOPMENT
if (IsDynamic)
m_pIndexBuffer->DvpVerifyDynamicAllocation(this);
#endif
Uint64 BuffDataStartByteOffset;
auto* pd3d12Buff = m_pIndexBuffer->GetD3D12Buffer(BuffDataStartByteOffset, this);
// clang-format off
if (IsDynamic ||
m_State.CommittedD3D12IndexBuffer != pd3d12Buff ||
m_State.CommittedIBFormat != IndexType ||
m_State.CommittedD3D12IndexDataStartOffset != m_IndexDataStartOffset + BuffDataStartByteOffset)
// clang-format on
{
m_State.CommittedD3D12IndexBuffer = pd3d12Buff;
m_State.CommittedIBFormat = IndexType;
m_State.CommittedD3D12IndexDataStartOffset = m_IndexDataStartOffset + BuffDataStartByteOffset;
GraphCtx.SetIndexBuffer(IBView);
}
// GPU virtual address of a dynamic index buffer can change every time
// a draw command is invoked
m_State.bCommittedD3D12IBUpToDate = !IsDynamic;
}
void DeviceContextD3D12Impl::CommitD3D12VertexBuffers(GraphicsContext& GraphCtx)
{
// Do not initialize array with zeroes for performance reasons
D3D12_VERTEX_BUFFER_VIEW VBViews[MAX_BUFFER_SLOTS]; // = {}
VERIFY(m_NumVertexStreams <= MAX_BUFFER_SLOTS, "Too many buffers are being set");
DEV_CHECK_ERR(m_NumVertexStreams >= m_pPipelineState->GetNumBufferSlotsUsed(), "Currently bound pipeline state '", m_pPipelineState->GetDesc().Name, "' expects ", m_pPipelineState->GetNumBufferSlotsUsed(), " input buffer slots, but only ", m_NumVertexStreams, " is bound");
bool DynamicBufferPresent = false;
for (UINT Buff = 0; Buff < m_NumVertexStreams; ++Buff)
{
auto& CurrStream = m_VertexStreams[Buff];
auto& VBView = VBViews[Buff];
if (auto* pBufferD3D12 = CurrStream.pBuffer.RawPtr())
{
if (pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC)
{
DynamicBufferPresent = true;
#ifdef DILIGENT_DEVELOPMENT
pBufferD3D12->DvpVerifyDynamicAllocation(this);
#endif
}
// Device context keeps strong references to all vertex buffers.
// When a buffer is unbound, a reference to D3D12 resource is added to the context,
// so there is no need to reference the resource here
//GraphicsCtx.AddReferencedObject(pd3d12Resource);
VBView.BufferLocation = pBufferD3D12->GetGPUAddress(GetContextId(), this) + CurrStream.Offset;
VBView.StrideInBytes = m_pPipelineState->GetBufferStride(Buff);
// Note that for a dynamic buffer, what we use here is the size of the buffer itself, not the upload heap buffer!
VBView.SizeInBytes = StaticCast<UINT>(pBufferD3D12->GetDesc().Size - CurrStream.Offset);
}
else
{
VBView = D3D12_VERTEX_BUFFER_VIEW{};
}
}
GraphCtx.FlushResourceBarriers();
GraphCtx.SetVertexBuffers(0, m_NumVertexStreams, VBViews);
// GPU virtual address of a dynamic vertex buffer can change every time
// a draw command is invoked
m_State.bCommittedD3D12VBsUpToDate = !DynamicBufferPresent;
}
void DeviceContextD3D12Impl::PrepareForDraw(GraphicsContext& GraphCtx, DRAW_FLAGS Flags)
{
#ifdef DILIGENT_DEVELOPMENT
if ((Flags & DRAW_FLAG_VERIFY_RENDER_TARGETS) != 0)
DvpVerifyRenderTargets();
#endif
if (!m_State.bCommittedD3D12VBsUpToDate && m_pPipelineState->GetNumBufferSlotsUsed() > 0)
{
CommitD3D12VertexBuffers(GraphCtx);
}
#ifdef DILIGENT_DEVELOPMENT
if ((Flags & DRAW_FLAG_VERIFY_STATES) != 0)
{
for (Uint32 Buff = 0; Buff < m_NumVertexStreams; ++Buff)
{
const auto& CurrStream = m_VertexStreams[Buff];
const auto* pBufferD3D12 = CurrStream.pBuffer.RawPtr();
if (pBufferD3D12 != nullptr)
{
DvpVerifyBufferState(*pBufferD3D12, RESOURCE_STATE_VERTEX_BUFFER, "Using vertex buffers (DeviceContextD3D12Impl::Draw())");
}
}
}
#endif
auto& RootInfo = GetRootTableInfo(PIPELINE_TYPE_GRAPHICS);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources(RootInfo);
#endif
if (Uint32 CommitSRBMask = RootInfo.GetCommitMask(Flags & DRAW_FLAG_DYNAMIC_RESOURCE_BUFFERS_INTACT))
{
CommitRootTablesAndViews<false>(RootInfo, CommitSRBMask, GraphCtx);
}
#ifdef NTDDI_WIN10_19H1
// In Vulkan, shading rate is applied to a PSO created with the shading rate dynamic state.
// In D3D12, shading rate is applied to all subsequent draw commands, but for compatibility with Vulkan
// we need to reset shading rate to default state.
if (m_State.bUsingShadingRate && m_pPipelineState->GetGraphicsPipelineDesc().ShadingRateFlags == PIPELINE_SHADING_RATE_FLAG_NONE)
{
m_State.bUsingShadingRate = false;
GraphCtx.AsGraphicsContext5().SetShadingRate(D3D12_SHADING_RATE_1X1, nullptr);
}
#endif
}
void DeviceContextD3D12Impl::PrepareForIndexedDraw(GraphicsContext& GraphCtx, DRAW_FLAGS Flags, VALUE_TYPE IndexType)
{
PrepareForDraw(GraphCtx, Flags);
if (m_State.CommittedIBFormat != IndexType)
m_State.bCommittedD3D12IBUpToDate = false;
if (!m_State.bCommittedD3D12IBUpToDate)
{
CommitD3D12IndexBuffer(GraphCtx, IndexType);
}
#ifdef DILIGENT_DEVELOPMENT
if ((Flags & DRAW_FLAG_VERIFY_STATES) != 0)
{
DvpVerifyBufferState(*m_pIndexBuffer, RESOURCE_STATE_INDEX_BUFFER, "Indexed draw (DeviceContextD3D12Impl::Draw())");
}
#endif
}
void DeviceContextD3D12Impl::Draw(const DrawAttribs& Attribs)
{
DvpVerifyDrawArguments(Attribs);
auto& GraphCtx = GetCmdContext().AsGraphicsContext();
PrepareForDraw(GraphCtx, Attribs.Flags);
if (Attribs.NumVertices > 0 && Attribs.NumInstances > 0)
{
GraphCtx.Draw(Attribs.NumVertices, Attribs.NumInstances, Attribs.StartVertexLocation, Attribs.FirstInstanceLocation);
++m_State.NumCommands;
}
}
void DeviceContextD3D12Impl::DrawIndexed(const DrawIndexedAttribs& Attribs)
{
DvpVerifyDrawIndexedArguments(Attribs);
auto& GraphCtx = GetCmdContext().AsGraphicsContext();
PrepareForIndexedDraw(GraphCtx, Attribs.Flags, Attribs.IndexType);
if (Attribs.NumIndices > 0 && Attribs.NumInstances > 0)
{
GraphCtx.DrawIndexed(Attribs.NumIndices, Attribs.NumInstances, Attribs.FirstIndexLocation, Attribs.BaseVertex, Attribs.FirstInstanceLocation);
++m_State.NumCommands;
}
}
void DeviceContextD3D12Impl::PrepareIndirectAttribsBuffer(CommandContext& CmdCtx,
IBuffer* pAttribsBuffer,
RESOURCE_STATE_TRANSITION_MODE BufferStateTransitionMode,
ID3D12Resource*& pd3d12ArgsBuff,
Uint64& BuffDataStartByteOffset,
const char* OpName)
{
DEV_CHECK_ERR(pAttribsBuffer != nullptr, "Indirect draw attribs buffer must not be null");
auto* pIndirectDrawAttribsD3D12 = ClassPtrCast<BufferD3D12Impl>(pAttribsBuffer);
#ifdef DILIGENT_DEVELOPMENT
if (pIndirectDrawAttribsD3D12->GetDesc().Usage == USAGE_DYNAMIC)
pIndirectDrawAttribsD3D12->DvpVerifyDynamicAllocation(this);
#endif
TransitionOrVerifyBufferState(CmdCtx, *pIndirectDrawAttribsD3D12, BufferStateTransitionMode,
RESOURCE_STATE_INDIRECT_ARGUMENT,
OpName);
pd3d12ArgsBuff = pIndirectDrawAttribsD3D12->GetD3D12Buffer(BuffDataStartByteOffset, this);
}
void DeviceContextD3D12Impl::DrawIndirect(const DrawIndirectAttribs& Attribs)
{
DvpVerifyDrawIndirectArguments(Attribs);
auto& GraphCtx = GetCmdContext().AsGraphicsContext();
PrepareForDraw(GraphCtx, Attribs.Flags);
ID3D12Resource* pd3d12ArgsBuff = nullptr;
Uint64 BuffDataStartByteOffset = 0;
PrepareIndirectAttribsBuffer(GraphCtx, Attribs.pAttribsBuffer, Attribs.AttribsBufferStateTransitionMode, pd3d12ArgsBuff, BuffDataStartByteOffset,
"Indirect draw (DeviceContextD3D12Impl::DrawIndirect)");
auto* pDrawIndirectSignature = GetDrawIndirectSignature(Attribs.DrawCount > 1 ? Attribs.DrawArgsStride : sizeof(UINT) * 4);
VERIFY_EXPR(pDrawIndirectSignature != nullptr);
ID3D12Resource* pd3d12CountBuff = nullptr;
Uint64 CountBuffDataStartByteOffset = 0;
if (Attribs.pCounterBuffer != nullptr)
{
PrepareIndirectAttribsBuffer(GraphCtx, Attribs.pCounterBuffer, Attribs.CounterBufferStateTransitionMode, pd3d12CountBuff, CountBuffDataStartByteOffset,
"Counter buffer (DeviceContextD3D12Impl::DrawIndirect)");
}
if (Attribs.DrawCount > 0)
{
GraphCtx.ExecuteIndirect(pDrawIndirectSignature,
Attribs.DrawCount,
pd3d12ArgsBuff,
Attribs.DrawArgsOffset + BuffDataStartByteOffset,
pd3d12CountBuff,
pd3d12CountBuff != nullptr ? Attribs.CounterOffset + CountBuffDataStartByteOffset : 0);
}
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::DrawIndexedIndirect(const DrawIndexedIndirectAttribs& Attribs)
{
DvpVerifyDrawIndexedIndirectArguments(Attribs);
auto& GraphCtx = GetCmdContext().AsGraphicsContext();
PrepareForIndexedDraw(GraphCtx, Attribs.Flags, Attribs.IndexType);
ID3D12Resource* pd3d12ArgsBuff = nullptr;
Uint64 BuffDataStartByteOffset = 0;
PrepareIndirectAttribsBuffer(GraphCtx, Attribs.pAttribsBuffer, Attribs.AttribsBufferStateTransitionMode, pd3d12ArgsBuff, BuffDataStartByteOffset,
"indexed Indirect draw (DeviceContextD3D12Impl::DrawIndexedIndirect)");
auto* pDrawIndexedIndirectSignature = GetDrawIndexedIndirectSignature(Attribs.DrawCount > 1 ? Attribs.DrawArgsStride : sizeof(UINT) * 5);
VERIFY_EXPR(pDrawIndexedIndirectSignature != nullptr);
ID3D12Resource* pd3d12CountBuff = nullptr;
Uint64 CountBuffDataStartByteOffset = 0;
if (Attribs.pCounterBuffer != nullptr)
{
PrepareIndirectAttribsBuffer(GraphCtx, Attribs.pCounterBuffer, Attribs.CounterBufferStateTransitionMode, pd3d12CountBuff, CountBuffDataStartByteOffset,
"Count buffer (DeviceContextD3D12Impl::DrawIndexedIndirect)");
}
if (Attribs.DrawCount > 0)
{
GraphCtx.ExecuteIndirect(pDrawIndexedIndirectSignature,
Attribs.DrawCount,
pd3d12ArgsBuff,
Attribs.DrawArgsOffset + BuffDataStartByteOffset,
pd3d12CountBuff,
pd3d12CountBuff != nullptr ? Attribs.CounterOffset + CountBuffDataStartByteOffset : 0);
}
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::DrawMesh(const DrawMeshAttribs& Attribs)
{
DvpVerifyDrawMeshArguments(Attribs);
auto& GraphCtx = GetCmdContext().AsGraphicsContext6();
PrepareForDraw(GraphCtx, Attribs.Flags);
if (Attribs.ThreadGroupCount > 0)
{
GraphCtx.DrawMesh(Attribs.ThreadGroupCount, 1, 1);
++m_State.NumCommands;
}
}
void DeviceContextD3D12Impl::DrawMeshIndirect(const DrawMeshIndirectAttribs& Attribs)
{
DvpVerifyDrawMeshIndirectArguments(Attribs);
auto& GraphCtx = GetCmdContext().AsGraphicsContext();
PrepareForDraw(GraphCtx, Attribs.Flags);
ID3D12Resource* pd3d12ArgsBuff = nullptr;
Uint64 BuffDataStartByteOffset = 0;
PrepareIndirectAttribsBuffer(GraphCtx, Attribs.pAttribsBuffer, Attribs.AttribsBufferStateTransitionMode, pd3d12ArgsBuff, BuffDataStartByteOffset,
"Indirect draw mesh (DeviceContextD3D12Impl::DrawMeshIndirect)");
ID3D12Resource* pd3d12CountBuff = nullptr;
Uint64 CountBuffDataStartByteOffset = 0;
if (Attribs.pCounterBuffer != nullptr)
{
PrepareIndirectAttribsBuffer(GraphCtx, Attribs.pCounterBuffer, Attribs.CounterBufferStateTransitionMode, pd3d12CountBuff, CountBuffDataStartByteOffset,
"Counter buffer (DeviceContextD3D12Impl::DrawMeshIndirect)");
}
if (Attribs.CommandCount > 0)
{
GraphCtx.ExecuteIndirect(m_pDrawMeshIndirectSignature,
Attribs.CommandCount,
pd3d12ArgsBuff,
Attribs.DrawArgsOffset + BuffDataStartByteOffset,
pd3d12CountBuff,
Attribs.CounterOffset + CountBuffDataStartByteOffset);
}
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::PrepareForDispatchCompute(ComputeContext& ComputeCtx)
{
auto& RootInfo = GetRootTableInfo(PIPELINE_TYPE_COMPUTE);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources(RootInfo);
#endif
if (Uint32 CommitSRBMask = RootInfo.GetCommitMask())
{
CommitRootTablesAndViews<true>(RootInfo, CommitSRBMask, ComputeCtx);
}
}
void DeviceContextD3D12Impl::PrepareForDispatchRays(GraphicsContext& GraphCtx)
{
auto& RootInfo = GetRootTableInfo(PIPELINE_TYPE_RAY_TRACING);
#ifdef DILIGENT_DEVELOPMENT
DvpValidateCommittedShaderResources(RootInfo);
#endif
if (Uint32 CommitSRBMask = RootInfo.GetCommitMask())
{
CommitRootTablesAndViews<true>(RootInfo, CommitSRBMask, GraphCtx);
}
}
void DeviceContextD3D12Impl::DispatchCompute(const DispatchComputeAttribs& Attribs)
{
DvpVerifyDispatchArguments(Attribs);
auto& ComputeCtx = GetCmdContext().AsComputeContext();
PrepareForDispatchCompute(ComputeCtx);
if (Attribs.ThreadGroupCountX > 0 && Attribs.ThreadGroupCountY > 0 && Attribs.ThreadGroupCountZ > 0)
{
ComputeCtx.Dispatch(Attribs.ThreadGroupCountX, Attribs.ThreadGroupCountY, Attribs.ThreadGroupCountZ);
++m_State.NumCommands;
}
}
void DeviceContextD3D12Impl::DispatchComputeIndirect(const DispatchComputeIndirectAttribs& Attribs)
{
DvpVerifyDispatchIndirectArguments(Attribs);
auto& ComputeCtx = GetCmdContext().AsComputeContext();
PrepareForDispatchCompute(ComputeCtx);
ID3D12Resource* pd3d12ArgsBuff;
Uint64 BuffDataStartByteOffset;
PrepareIndirectAttribsBuffer(ComputeCtx, Attribs.pAttribsBuffer, Attribs.AttribsBufferStateTransitionMode, pd3d12ArgsBuff, BuffDataStartByteOffset,
"Indirect dispatch (DeviceContextD3D12Impl::DispatchComputeIndirect)");
ComputeCtx.ExecuteIndirect(m_pDispatchIndirectSignature, 1, pd3d12ArgsBuff, Attribs.DispatchArgsByteOffset + BuffDataStartByteOffset);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::ClearDepthStencil(ITextureView* pView,
CLEAR_DEPTH_STENCIL_FLAGS ClearFlags,
float fDepth,
Uint8 Stencil,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
DEV_CHECK_ERR(m_pActiveRenderPass == nullptr, "Direct3D12 does not allow depth-stencil clears inside a render pass");
TDeviceContextBase::ClearDepthStencil(pView);
auto* pViewD3D12 = ClassPtrCast<ITextureViewD3D12>(pView);
auto* pTextureD3D12 = ClassPtrCast<TextureD3D12Impl>(pViewD3D12->GetTexture());
auto& CmdCtx = GetCmdContext();
TransitionOrVerifyTextureState(CmdCtx, *pTextureD3D12, StateTransitionMode, RESOURCE_STATE_DEPTH_WRITE, "Clearing depth-stencil buffer (DeviceContextD3D12Impl::ClearDepthStencil)");
D3D12_CLEAR_FLAGS d3d12ClearFlags = (D3D12_CLEAR_FLAGS)0;
if (ClearFlags & CLEAR_DEPTH_FLAG) d3d12ClearFlags |= D3D12_CLEAR_FLAG_DEPTH;
if (ClearFlags & CLEAR_STENCIL_FLAG) d3d12ClearFlags |= D3D12_CLEAR_FLAG_STENCIL;
// The full extent of the resource view is always cleared.
// Viewport and scissor settings are not applied??
GetCmdContext().AsGraphicsContext().ClearDepthStencil(pViewD3D12->GetCPUDescriptorHandle(), d3d12ClearFlags, fDepth, Stencil);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::ClearRenderTarget(ITextureView* pView, const float* RGBA, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
DEV_CHECK_ERR(m_pActiveRenderPass == nullptr, "Direct3D12 does not allow render target clears inside a render pass");
TDeviceContextBase::ClearRenderTarget(pView);
auto* pViewD3D12 = ClassPtrCast<ITextureViewD3D12>(pView);
static constexpr float Zero[4] = {0.f, 0.f, 0.f, 0.f};
if (RGBA == nullptr)
RGBA = Zero;
auto* pTextureD3D12 = ClassPtrCast<TextureD3D12Impl>(pViewD3D12->GetTexture());
auto& CmdCtx = GetCmdContext();
TransitionOrVerifyTextureState(CmdCtx, *pTextureD3D12, StateTransitionMode, RESOURCE_STATE_RENDER_TARGET, "Clearing render target (DeviceContextD3D12Impl::ClearRenderTarget)");
// The full extent of the resource view is always cleared.
// Viewport and scissor settings are not applied??
CmdCtx.AsGraphicsContext().ClearRenderTarget(pViewD3D12->GetCPUDescriptorHandle(), RGBA);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::RequestCommandContext()
{
m_CurrCmdCtx = m_pDevice->AllocateCommandContext(GetCommandQueueId());
m_CurrCmdCtx->SetDynamicGPUDescriptorAllocators(m_DynamicGPUDescriptorAllocator);
}
void DeviceContextD3D12Impl::Flush(bool RequestNewCmdCtx,
Uint32 NumCommandLists,
ICommandList* const* ppCommandLists)
{
VERIFY(!IsDeferred() || NumCommandLists == 0 && ppCommandLists == nullptr, "Only immediate context can execute command lists");
DEV_CHECK_ERR(m_ActiveQueriesCounter == 0,
"Flushing device context that has ", m_ActiveQueriesCounter,
" active queries. Direct3D12 requires that queries are begun and ended in the same command list");
// TODO: use small_vector
std::vector<RenderDeviceD3D12Impl::PooledCommandContext> Contexts;
Contexts.reserve(size_t{NumCommandLists} + 1);
// First, execute current context
if (m_CurrCmdCtx)
{
VERIFY(!IsDeferred(), "Deferred contexts cannot execute command lists directly");
if (m_State.NumCommands != 0)
Contexts.emplace_back(std::move(m_CurrCmdCtx));
else
m_pDevice->DisposeCommandContext(std::move(m_CurrCmdCtx));
}
// Next, add extra command lists from deferred contexts
for (Uint32 i = 0; i < NumCommandLists; ++i)
{
auto* const pCmdListD3D12 = ClassPtrCast<CommandListD3D12Impl>(ppCommandLists[i]);
RefCntAutoPtr<DeviceContextD3D12Impl> pDeferredCtx;
Contexts.emplace_back(pCmdListD3D12->Close(pDeferredCtx));
VERIFY(Contexts.back() && pDeferredCtx, "Trying to execute empty command buffer");
// Set the bit in the deferred context cmd queue mask corresponding to the cmd queue of this context
pDeferredCtx->UpdateSubmittedBuffersCmdQueueMask(GetCommandQueueId());
}
if (!Contexts.empty())
{
m_pDevice->CloseAndExecuteCommandContexts(GetCommandQueueId(), static_cast<Uint32>(Contexts.size()), Contexts.data(), true, &m_SignalFences, &m_WaitFences);
m_SignalFences.clear();
#ifdef DILIGENT_DEBUG
for (Uint32 i = 0; i < NumCommandLists; ++i)
VERIFY(!Contexts[i], "All contexts must be disposed by CloseAndExecuteCommandContexts");
#endif
}
m_WaitFences.clear();
// If there is no command list to submit, but there are pending fences, we need to signal them now
if (!m_SignalFences.empty())
{
m_pDevice->SignalFences(GetCommandQueueId(), m_SignalFences);
m_SignalFences.clear();
}
if (RequestNewCmdCtx)
RequestCommandContext();
m_State = State{};
m_GraphicsResources = RootTableInfo{};
m_ComputeResources = RootTableInfo{};
// Setting pipeline state to null makes sure that render targets and other
// states will be restored in the command list next time a PSO is bound.
m_pPipelineState = nullptr;
}
void DeviceContextD3D12Impl::Flush()
{
DEV_CHECK_ERR(!IsDeferred(), "Flush() should only be called for immediate contexts");
DEV_CHECK_ERR(m_pActiveRenderPass == nullptr, "Flushing device context inside an active render pass.");
Flush(true);
}
void DeviceContextD3D12Impl::FinishFrame()
{
#ifdef DILIGENT_DEBUG
for (const auto& MappedBuffIt : m_DbgMappedBuffers)
{
const auto& BuffDesc = MappedBuffIt.first->GetDesc();
if (BuffDesc.Usage == USAGE_DYNAMIC)
{
LOG_WARNING_MESSAGE("Dynamic buffer '", BuffDesc.Name,
"' is still mapped when finishing the frame. The contents of the buffer and "
"mapped address will become invalid");
}
}
#endif
if (GetNumCommandsInCtx() != 0)
{
if (IsDeferred())
{
LOG_ERROR_MESSAGE("There are outstanding commands in deferred device context #", GetContextId(),
" when finishing the frame. This is an error and may cause unpredicted behaviour. "
"Close all deferred contexts and execute them before finishing the frame");
}
else
{
LOG_ERROR_MESSAGE("There are outstanding commands in the immediate device context when finishing the frame. "
"This is an error and may cause unpredicted behaviour. Call Flush() to submit all commands"
" for execution before finishing the frame");
}
}
if (m_ActiveQueriesCounter > 0)
{
LOG_ERROR_MESSAGE("There are ", m_ActiveQueriesCounter,
" active queries in the device context when finishing the frame. "
"All queries must be ended before the frame is finished.");
}
if (m_pActiveRenderPass != nullptr)
{
LOG_ERROR_MESSAGE("Finishing frame inside an active render pass.");
}
const auto QueueMask = GetSubmittedBuffersCmdQueueMask();
VERIFY_EXPR(IsDeferred() || QueueMask == (Uint64{1} << GetCommandQueueId()));
// Released pages are returned to the global dynamic memory manager hosted by render device.
m_DynamicHeap.ReleaseAllocatedPages(QueueMask);
// Dynamic GPU descriptor allocations are returned to the global GPU descriptor heap
// hosted by the render device.
for (size_t i = 0; i < _countof(m_DynamicGPUDescriptorAllocator); ++i)
m_DynamicGPUDescriptorAllocator[i].ReleaseAllocations(QueueMask);
EndFrame();
}
void DeviceContextD3D12Impl::SetVertexBuffers(Uint32 StartSlot,
Uint32 NumBuffersSet,
IBuffer** ppBuffers,
const Uint64* pOffsets,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode,
SET_VERTEX_BUFFERS_FLAGS Flags)
{
TDeviceContextBase::SetVertexBuffers(StartSlot, NumBuffersSet, ppBuffers, pOffsets, StateTransitionMode, Flags);
auto& CmdCtx = GetCmdContext();
for (Uint32 Buff = 0; Buff < m_NumVertexStreams; ++Buff)
{
auto& CurrStream = m_VertexStreams[Buff];
if (auto* pBufferD3D12 = CurrStream.pBuffer.RawPtr())
TransitionOrVerifyBufferState(CmdCtx, *pBufferD3D12, StateTransitionMode, RESOURCE_STATE_VERTEX_BUFFER, "Setting vertex buffers (DeviceContextD3D12Impl::SetVertexBuffers)");
}
m_State.bCommittedD3D12VBsUpToDate = false;
}
void DeviceContextD3D12Impl::InvalidateState()
{
if (m_State.NumCommands != 0)
LOG_WARNING_MESSAGE("Invalidating context that has outstanding commands in it. Call Flush() to submit commands for execution");
TDeviceContextBase::InvalidateState();
m_State = {};
m_GraphicsResources = {};
m_ComputeResources = {};
}
void DeviceContextD3D12Impl::SetIndexBuffer(IBuffer* pIndexBuffer, Uint64 ByteOffset, RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::SetIndexBuffer(pIndexBuffer, ByteOffset, StateTransitionMode);
if (m_pIndexBuffer)
{
auto& CmdCtx = GetCmdContext();
TransitionOrVerifyBufferState(CmdCtx, *m_pIndexBuffer, StateTransitionMode, RESOURCE_STATE_INDEX_BUFFER, "Setting index buffer (DeviceContextD3D12Impl::SetIndexBuffer)");
}
m_State.bCommittedD3D12IBUpToDate = false;
}
void DeviceContextD3D12Impl::CommitViewports()
{
static_assert(MAX_VIEWPORTS >= D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE, "MaxViewports constant must be greater than D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE");
D3D12_VIEWPORT d3d12Viewports[MAX_VIEWPORTS]; // Do not waste time initializing array to zero
for (Uint32 vp = 0; vp < m_NumViewports; ++vp)
{
d3d12Viewports[vp].TopLeftX = m_Viewports[vp].TopLeftX;
d3d12Viewports[vp].TopLeftY = m_Viewports[vp].TopLeftY;
d3d12Viewports[vp].Width = m_Viewports[vp].Width;
d3d12Viewports[vp].Height = m_Viewports[vp].Height;
d3d12Viewports[vp].MinDepth = m_Viewports[vp].MinDepth;
d3d12Viewports[vp].MaxDepth = m_Viewports[vp].MaxDepth;
}
// All viewports must be set atomically as one operation.
// Any viewports not defined by the call are disabled.
GetCmdContext().AsGraphicsContext().SetViewports(m_NumViewports, d3d12Viewports);
}
void DeviceContextD3D12Impl::SetViewports(Uint32 NumViewports, const Viewport* pViewports, Uint32 RTWidth, Uint32 RTHeight)
{
static_assert(MAX_VIEWPORTS >= D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE, "MaxViewports constant must be greater than D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE");
TDeviceContextBase::SetViewports(NumViewports, pViewports, RTWidth, RTHeight);
VERIFY(NumViewports == m_NumViewports, "Unexpected number of viewports");
CommitViewports();
}
constexpr LONG MaxD3D12TexDim = D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION;
constexpr Uint32 MaxD3D12ScissorRects = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
// clang-format off
static constexpr RECT MaxD3D12TexSizeRects[D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE] =
{
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim},
{0, 0, MaxD3D12TexDim, MaxD3D12TexDim}
};
// clang-format on
void DeviceContextD3D12Impl::CommitScissorRects(GraphicsContext& GraphCtx, bool ScissorEnable)
{
if (ScissorEnable)
{
// Commit currently set scissor rectangles
D3D12_RECT d3d12ScissorRects[MaxD3D12ScissorRects]; // Do not waste time initializing array with zeroes
for (Uint32 sr = 0; sr < m_NumScissorRects; ++sr)
{
d3d12ScissorRects[sr].left = m_ScissorRects[sr].left;
d3d12ScissorRects[sr].top = m_ScissorRects[sr].top;
d3d12ScissorRects[sr].right = m_ScissorRects[sr].right;
d3d12ScissorRects[sr].bottom = m_ScissorRects[sr].bottom;
}
GraphCtx.SetScissorRects(m_NumScissorRects, d3d12ScissorRects);
}
else
{
// Disable scissor rectangles
static_assert(_countof(MaxD3D12TexSizeRects) == MaxD3D12ScissorRects, "Unexpected array size");
GraphCtx.SetScissorRects(MaxD3D12ScissorRects, MaxD3D12TexSizeRects);
}
}
void DeviceContextD3D12Impl::SetScissorRects(Uint32 NumRects, const Rect* pRects, Uint32 RTWidth, Uint32 RTHeight)
{
const Uint32 MaxScissorRects = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
VERIFY(NumRects < MaxScissorRects, "Too many scissor rects are being set");
NumRects = std::min(NumRects, MaxScissorRects);
TDeviceContextBase::SetScissorRects(NumRects, pRects, RTWidth, RTHeight);
// Only commit scissor rects if scissor test is enabled in the rasterizer state.
// If scissor is currently disabled, or no PSO is bound, scissor rects will be committed by
// the SetPipelineState() when a PSO with enabled scissor test is set.
if (m_pPipelineState)
{
const auto& PSODesc = m_pPipelineState->GetDesc();
if (PSODesc.IsAnyGraphicsPipeline() && m_pPipelineState->GetGraphicsPipelineDesc().RasterizerDesc.ScissorEnable)
{
VERIFY(NumRects == m_NumScissorRects, "Unexpected number of scissor rects");
auto& Ctx = GetCmdContext().AsGraphicsContext();
CommitScissorRects(Ctx, true);
}
}
}
void DeviceContextD3D12Impl::CommitRenderTargets(RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
DEV_CHECK_ERR(m_pActiveRenderPass == nullptr, "This method must not be called inside a render pass");
const Uint32 MaxD3D12RTs = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT;
Uint32 NumRenderTargets = m_NumBoundRenderTargets;
VERIFY(NumRenderTargets <= MaxD3D12RTs, "D3D12 only allows 8 simultaneous render targets");
NumRenderTargets = std::min(MaxD3D12RTs, NumRenderTargets);
ITextureViewD3D12* ppRTVs[MaxD3D12RTs]; // Do not initialize with zeroes!
ITextureViewD3D12* pDSV = nullptr;
for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)
ppRTVs[rt] = m_pBoundRenderTargets[rt].RawPtr();
pDSV = m_pBoundDepthStencil.RawPtr();
auto& CmdCtx = GetCmdContext();
D3D12_CPU_DESCRIPTOR_HANDLE RTVHandles[MAX_RENDER_TARGETS]; // Do not waste time initializing array to zero
D3D12_CPU_DESCRIPTOR_HANDLE DSVHandle = {};
for (UINT i = 0; i < NumRenderTargets; ++i)
{
if (auto* pRTV = ppRTVs[i])
{
auto* pTexture = ClassPtrCast<TextureD3D12Impl>(pRTV->GetTexture());
TransitionOrVerifyTextureState(CmdCtx, *pTexture, StateTransitionMode, RESOURCE_STATE_RENDER_TARGET, "Setting render targets (DeviceContextD3D12Impl::CommitRenderTargets)");
RTVHandles[i] = pRTV->GetCPUDescriptorHandle();
VERIFY_EXPR(RTVHandles[i].ptr != 0);
}
else
{
// Binding NULL descriptor handle is invalid. We need to use a non-NULL handle
// that defines null RTV.
RTVHandles[i] = m_NullRTV.GetCpuHandle();
}
}
if (pDSV)
{
auto* pTexture = ClassPtrCast<TextureD3D12Impl>(pDSV->GetTexture());
//if (bReadOnlyDepth)
//{
// TransitionResource(*pTexture, D3D12_RESOURCE_STATE_DEPTH_READ);
// m_pCommandList->OMSetRenderTargets( NumRTVs, RTVHandles, FALSE, &DSV->GetDSV_DepthReadOnly() );
//}
//else
{
TransitionOrVerifyTextureState(CmdCtx, *pTexture, StateTransitionMode, RESOURCE_STATE_DEPTH_WRITE, "Setting depth-stencil buffer (DeviceContextD3D12Impl::CommitRenderTargets)");
DSVHandle = pDSV->GetCPUDescriptorHandle();
VERIFY_EXPR(DSVHandle.ptr != 0);
}
}
if (NumRenderTargets > 0 || DSVHandle.ptr != 0)
{
// No need to flush resource barriers as this is a CPU-side command
CmdCtx.AsGraphicsContext().GetCommandList()->OMSetRenderTargets(NumRenderTargets, RTVHandles, FALSE, DSVHandle.ptr != 0 ? &DSVHandle : nullptr);
}
#ifdef NTDDI_WIN10_19H1
if (m_pBoundShadingRateMap != nullptr)
{
auto* pTexD3D12 = ClassPtrCast<TextureD3D12Impl>(m_pBoundShadingRateMap->GetTexture());
TransitionOrVerifyTextureState(CmdCtx, *pTexD3D12, StateTransitionMode, RESOURCE_STATE_SHADING_RATE, "Shading rate texture (DeviceContextD3D12Impl::CommitRenderTargets)");
m_State.bShadingRateMapBound = true;
CmdCtx.AsGraphicsContext5().SetShadingRateImage(pTexD3D12->GetD3D12Resource());
}
else if (m_State.bShadingRateMapBound)
{
m_State.bShadingRateMapBound = false;
CmdCtx.AsGraphicsContext5().SetShadingRateImage(nullptr);
}
#endif
}
void DeviceContextD3D12Impl::SetRenderTargetsExt(const SetRenderTargetsAttribs& Attribs)
{
DEV_CHECK_ERR(m_pActiveRenderPass == nullptr, "Calling SetRenderTargets inside active render pass is invalid. End the render pass first");
if (TDeviceContextBase::SetRenderTargets(Attribs))
{
CommitRenderTargets(Attribs.StateTransitionMode);
// Set the viewport to match the render target size
SetViewports(1, nullptr, 0, 0);
}
}
void DeviceContextD3D12Impl::TransitionSubpassAttachments(Uint32 NextSubpass)
{
VERIFY_EXPR(m_pActiveRenderPass);
const auto& RPDesc = m_pActiveRenderPass->GetDesc();
VERIFY_EXPR(m_pBoundFramebuffer);
const auto& FBDesc = m_pBoundFramebuffer->GetDesc();
VERIFY_EXPR(RPDesc.AttachmentCount == FBDesc.AttachmentCount);
for (Uint32 att = 0; att < RPDesc.AttachmentCount; ++att)
{
const auto& AttDesc = RPDesc.pAttachments[att];
auto OldState = NextSubpass > 0 ? m_pActiveRenderPass->GetAttachmentState(NextSubpass - 1, att) : AttDesc.InitialState;
auto NewState = NextSubpass < RPDesc.SubpassCount ? m_pActiveRenderPass->GetAttachmentState(NextSubpass, att) : AttDesc.FinalState;
if (OldState != NewState)
{
auto& CmdCtx = GetCmdContext();
const auto ResStateMask = GetSupportedD3D12ResourceStatesForCommandList(CmdCtx.GetCommandListType());
auto* pViewD3D12 = ClassPtrCast<TextureViewD3D12Impl>(FBDesc.ppAttachments[att]);
if (pViewD3D12 == nullptr)
continue;
auto* pTexD3D12 = pViewD3D12->GetTexture<TextureD3D12Impl>();
const auto& ViewDesc = pViewD3D12->GetDesc();
const auto& TexDesc = pTexD3D12->GetDesc();
D3D12_RESOURCE_BARRIER BarrierDesc;
BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
BarrierDesc.Transition.pResource = pTexD3D12->GetD3D12Resource();
BarrierDesc.Transition.StateBefore = ResourceStateFlagsToD3D12ResourceStates(OldState) & ResStateMask;
BarrierDesc.Transition.StateAfter = ResourceStateFlagsToD3D12ResourceStates(NewState) & ResStateMask;
for (Uint32 mip = ViewDesc.MostDetailedMip; mip < ViewDesc.MostDetailedMip + ViewDesc.NumDepthSlices; ++mip)
{
for (Uint32 slice = ViewDesc.FirstArraySlice; slice < ViewDesc.FirstArraySlice + ViewDesc.NumArraySlices; ++slice)
{
BarrierDesc.Transition.Subresource = D3D12CalcSubresource(mip, slice, 0, TexDesc.MipLevels, TexDesc.GetArraySize());
CmdCtx.ResourceBarrier(BarrierDesc);
}
}
}
}
}
void DeviceContextD3D12Impl::CommitSubpassRenderTargets()
{
VERIFY_EXPR(m_pActiveRenderPass);
const auto& RPDesc = m_pActiveRenderPass->GetDesc();
VERIFY_EXPR(m_pBoundFramebuffer);
const auto& FBDesc = m_pBoundFramebuffer->GetDesc();
VERIFY_EXPR(m_SubpassIndex < RPDesc.SubpassCount);
const auto& Subpass = RPDesc.pSubpasses[m_SubpassIndex];
VERIFY(Subpass.RenderTargetAttachmentCount == m_NumBoundRenderTargets,
"The number of currently bound render targets (", m_NumBoundRenderTargets,
") is not consistent with the number of redner target attachments (", Subpass.RenderTargetAttachmentCount,
") in current subpass");
D3D12_RENDER_PASS_RENDER_TARGET_DESC RenderPassRTs[MAX_RENDER_TARGETS];
for (Uint32 rt = 0; rt < m_NumBoundRenderTargets; ++rt)
{
const auto& RTRef = Subpass.pRenderTargetAttachments[rt];
if (RTRef.AttachmentIndex != ATTACHMENT_UNUSED)
{
TextureViewD3D12Impl* pRTV = m_pBoundRenderTargets[rt];
VERIFY(pRTV == FBDesc.ppAttachments[RTRef.AttachmentIndex],
"Render target bound in the device context at slot ", rt, " is not consistent with the corresponding framebuffer attachment");
const auto FirstLastUse = m_pActiveRenderPass->GetAttachmentFirstLastUse(RTRef.AttachmentIndex);
const auto& RTAttachmentDesc = RPDesc.pAttachments[RTRef.AttachmentIndex];
auto& RPRT = RenderPassRTs[rt];
RPRT = D3D12_RENDER_PASS_RENDER_TARGET_DESC{};
RPRT.cpuDescriptor = pRTV->GetCPUDescriptorHandle();
if (FirstLastUse.first == m_SubpassIndex)
{
// This is the first use of this attachment - use LoadOp
RPRT.BeginningAccess.Type = AttachmentLoadOpToD3D12BeginningAccessType(RTAttachmentDesc.LoadOp);
}
else
{
// Preserve the attachment contents
RPRT.BeginningAccess.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE;
}
if (RPRT.BeginningAccess.Type == D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR)
{
RPRT.BeginningAccess.Clear.ClearValue.Format = TexFormatToDXGI_Format(RTAttachmentDesc.Format);
const auto ClearColor = m_AttachmentClearValues[RTRef.AttachmentIndex].Color;
for (Uint32 i = 0; i < 4; ++i)
RPRT.BeginningAccess.Clear.ClearValue.Color[i] = ClearColor[i];
}
if (FirstLastUse.second == m_SubpassIndex)
{
// This is the last use of this attachment - use StoreOp or resolve parameters
if (Subpass.pResolveAttachments != nullptr && Subpass.pResolveAttachments[rt].AttachmentIndex != ATTACHMENT_UNUSED)
{
VERIFY_EXPR(Subpass.pResolveAttachments[rt].AttachmentIndex < RPDesc.AttachmentCount);
auto* pDstView = FBDesc.ppAttachments[Subpass.pResolveAttachments[rt].AttachmentIndex];
auto* pSrcTexD3D12 = pRTV->GetTexture<TextureD3D12Impl>();
auto* pDstTexD3D12 = ClassPtrCast<TextureViewD3D12Impl>(pDstView)->GetTexture<TextureD3D12Impl>();
const auto& SrcRTVDesc = pRTV->GetDesc();
const auto& DstViewDesc = pDstView->GetDesc();
const auto& SrcTexDesc = pSrcTexD3D12->GetDesc();
const auto& DstTexDesc = pDstTexD3D12->GetDesc();
VERIFY_EXPR(SrcRTVDesc.NumArraySlices == 1);
Uint32 SubresourceCount = SrcRTVDesc.NumArraySlices;
m_AttachmentResolveInfo.resize(SubresourceCount);
const auto MipProps = GetMipLevelProperties(SrcTexDesc, SrcRTVDesc.MostDetailedMip);
for (Uint32 slice = 0; slice < SrcRTVDesc.NumArraySlices; ++slice)
{
auto& ARI = m_AttachmentResolveInfo[slice];
ARI.SrcSubresource = D3D12CalcSubresource(SrcRTVDesc.MostDetailedMip, SrcRTVDesc.FirstArraySlice + slice, 0, SrcTexDesc.MipLevels, SrcTexDesc.GetArraySize());
ARI.DstSubresource = D3D12CalcSubresource(DstViewDesc.MostDetailedMip, DstViewDesc.FirstArraySlice + slice, 0, DstTexDesc.MipLevels, DstTexDesc.GetArraySize());
ARI.DstX = 0;
ARI.DstY = 0;
ARI.SrcRect.left = 0;
ARI.SrcRect.top = 0;
ARI.SrcRect.right = MipProps.LogicalWidth;
ARI.SrcRect.bottom = MipProps.LogicalHeight;
}
// The resolve source is left in its initial resource state at the time the render pass ends.
// A resolve operation submitted by a render pass doesn't implicitly change the state of any resource.
// https://docs.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_render_pass_ending_access_type
RPRT.EndingAccess.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE;
auto& ResolveParams = RPRT.EndingAccess.Resolve;
ResolveParams.pSrcResource = pSrcTexD3D12->GetD3D12Resource();
ResolveParams.pDstResource = pDstTexD3D12->GetD3D12Resource();
ResolveParams.SubresourceCount = SubresourceCount;
// This pointer is directly referenced by the command list, and the memory for this array
// must remain alive and intact until EndRenderPass is called.
ResolveParams.pSubresourceParameters = m_AttachmentResolveInfo.data();
ResolveParams.Format = TexFormatToDXGI_Format(RTAttachmentDesc.Format);
ResolveParams.ResolveMode = D3D12_RESOLVE_MODE_AVERAGE;
ResolveParams.PreserveResolveSource = RTAttachmentDesc.StoreOp == ATTACHMENT_STORE_OP_STORE;
}
else
{
RPRT.EndingAccess.Type = AttachmentStoreOpToD3D12EndingAccessType(RTAttachmentDesc.StoreOp);
}
}
else
{
// The attachment will be used in subsequent subpasses - preserve its contents
RPRT.EndingAccess.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE;
}
}
else
{
// Attachment is not used
RenderPassRTs[rt].BeginningAccess.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_NO_ACCESS;
RenderPassRTs[rt].EndingAccess.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_NO_ACCESS;
continue;
}
}
D3D12_RENDER_PASS_DEPTH_STENCIL_DESC RenderPassDS;
if (m_pBoundDepthStencil)
{
RenderPassDS = D3D12_RENDER_PASS_DEPTH_STENCIL_DESC{};
const auto& DSAttachmentRef = *Subpass.pDepthStencilAttachment;
VERIFY_EXPR(Subpass.pDepthStencilAttachment != nullptr && DSAttachmentRef.AttachmentIndex != ATTACHMENT_UNUSED);
VERIFY(m_pBoundDepthStencil == FBDesc.ppAttachments[DSAttachmentRef.AttachmentIndex],
"Depth-stencil buffer in the device context is inconsistent with the framebuffer");
const auto FirstLastUse = m_pActiveRenderPass->GetAttachmentFirstLastUse(DSAttachmentRef.AttachmentIndex);
const auto& DSAttachmentDesc = RPDesc.pAttachments[DSAttachmentRef.AttachmentIndex];
RenderPassDS.cpuDescriptor = m_pBoundDepthStencil->GetCPUDescriptorHandle();
if (FirstLastUse.first == m_SubpassIndex)
{
RenderPassDS.DepthBeginningAccess.Type = AttachmentLoadOpToD3D12BeginningAccessType(DSAttachmentDesc.LoadOp);
RenderPassDS.StencilBeginningAccess.Type = AttachmentLoadOpToD3D12BeginningAccessType(DSAttachmentDesc.StencilLoadOp);
}
else
{
RenderPassDS.DepthBeginningAccess.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE;
RenderPassDS.StencilBeginningAccess.Type = D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_PRESERVE;
}
if (RenderPassDS.DepthBeginningAccess.Type == D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR)
{
RenderPassDS.DepthBeginningAccess.Clear.ClearValue.Format = TexFormatToDXGI_Format(DSAttachmentDesc.Format);
RenderPassDS.DepthBeginningAccess.Clear.ClearValue.DepthStencil.Depth =
m_AttachmentClearValues[DSAttachmentRef.AttachmentIndex].DepthStencil.Depth;
}
if (RenderPassDS.StencilBeginningAccess.Type == D3D12_RENDER_PASS_BEGINNING_ACCESS_TYPE_CLEAR)
{
RenderPassDS.StencilBeginningAccess.Clear.ClearValue.Format = TexFormatToDXGI_Format(DSAttachmentDesc.Format);
RenderPassDS.StencilBeginningAccess.Clear.ClearValue.DepthStencil.Stencil =
m_AttachmentClearValues[DSAttachmentRef.AttachmentIndex].DepthStencil.Stencil;
}
if (FirstLastUse.second == m_SubpassIndex)
{
RenderPassDS.DepthEndingAccess.Type = AttachmentStoreOpToD3D12EndingAccessType(DSAttachmentDesc.StoreOp);
RenderPassDS.StencilEndingAccess.Type = AttachmentStoreOpToD3D12EndingAccessType(DSAttachmentDesc.StencilStoreOp);
}
else
{
RenderPassDS.DepthEndingAccess.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE;
RenderPassDS.StencilEndingAccess.Type = D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_PRESERVE;
}
}
auto& CmdCtx = GetCmdContext();
CmdCtx.AsGraphicsContext4().BeginRenderPass(
Subpass.RenderTargetAttachmentCount,
RenderPassRTs,
m_pBoundDepthStencil ? &RenderPassDS : nullptr,
D3D12_RENDER_PASS_FLAG_NONE);
// Set the viewport to match the framebuffer size
SetViewports(1, nullptr, 0, 0);
if (m_pBoundShadingRateMap != nullptr)
{
auto* pTexD3D12 = ClassPtrCast<TextureD3D12Impl>(m_pBoundShadingRateMap->GetTexture());
CmdCtx.AsGraphicsContext5().SetShadingRateImage(pTexD3D12->GetD3D12Resource());
}
}
void DeviceContextD3D12Impl::BeginRenderPass(const BeginRenderPassAttribs& Attribs)
{
TDeviceContextBase::BeginRenderPass(Attribs);
m_AttachmentClearValues.resize(Attribs.ClearValueCount);
for (Uint32 i = 0; i < Attribs.ClearValueCount; ++i)
m_AttachmentClearValues[i] = Attribs.pClearValues[i];
TransitionSubpassAttachments(m_SubpassIndex);
CommitSubpassRenderTargets();
}
void DeviceContextD3D12Impl::NextSubpass()
{
auto& CmdCtx = GetCmdContext();
CmdCtx.AsGraphicsContext4().EndRenderPass();
TDeviceContextBase::NextSubpass();
TransitionSubpassAttachments(m_SubpassIndex);
CommitSubpassRenderTargets();
}
void DeviceContextD3D12Impl::EndRenderPass()
{
auto& CmdCtx = GetCmdContext();
CmdCtx.AsGraphicsContext4().EndRenderPass();
TransitionSubpassAttachments(m_SubpassIndex + 1);
if (m_pBoundShadingRateMap)
CmdCtx.AsGraphicsContext5().SetShadingRateImage(nullptr);
TDeviceContextBase::EndRenderPass();
}
D3D12DynamicAllocation DeviceContextD3D12Impl::AllocateDynamicSpace(Uint64 NumBytes, Uint32 Alignment)
{
return m_DynamicHeap.Allocate(NumBytes, Alignment, GetFrameNumber());
}
void DeviceContextD3D12Impl::UpdateBufferRegion(BufferD3D12Impl* pBuffD3D12,
D3D12DynamicAllocation& Allocation,
Uint64 DstOffset,
Uint64 NumBytes,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
auto& CmdCtx = GetCmdContext();
TransitionOrVerifyBufferState(CmdCtx, *pBuffD3D12, StateTransitionMode, RESOURCE_STATE_COPY_DEST, "Updating buffer (DeviceContextD3D12Impl::UpdateBufferRegion)");
Uint64 DstBuffDataStartByteOffset;
auto* pd3d12Buff = pBuffD3D12->GetD3D12Buffer(DstBuffDataStartByteOffset, this);
VERIFY(DstBuffDataStartByteOffset == 0, "Dst buffer must not be suballocated");
CmdCtx.FlushResourceBarriers();
CmdCtx.GetCommandList()->CopyBufferRegion(pd3d12Buff, DstOffset + DstBuffDataStartByteOffset, Allocation.pBuffer, Allocation.Offset, NumBytes);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::UpdateBuffer(IBuffer* pBuffer,
Uint64 Offset,
Uint64 Size,
const void* pData,
RESOURCE_STATE_TRANSITION_MODE StateTransitionMode)
{
TDeviceContextBase::UpdateBuffer(pBuffer, Offset, Size, pData, StateTransitionMode);
// We must use cmd context from the device context provided, otherwise there will
// be resource barrier issues in the cmd list in the device context
auto* pBuffD3D12 = ClassPtrCast<BufferD3D12Impl>(pBuffer);
VERIFY(pBuffD3D12->GetDesc().Usage != USAGE_DYNAMIC, "Dynamic buffers must be updated via Map()");
constexpr size_t DefaultAlignment = 16;
auto TmpSpace = m_DynamicHeap.Allocate(Size, DefaultAlignment, GetFrameNumber());
memcpy(TmpSpace.CPUAddress, pData, StaticCast<size_t>(Size));
UpdateBufferRegion(pBuffD3D12, TmpSpace, Offset, Size, StateTransitionMode);
}
void DeviceContextD3D12Impl::CopyBuffer(IBuffer* pSrcBuffer,
Uint64 SrcOffset,
RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode,
IBuffer* pDstBuffer,
Uint64 DstOffset,
Uint64 Size,
RESOURCE_STATE_TRANSITION_MODE DstBufferTransitionMode)
{
TDeviceContextBase::CopyBuffer(pSrcBuffer, SrcOffset, SrcBufferTransitionMode, pDstBuffer, DstOffset, Size, DstBufferTransitionMode);
auto* pSrcBuffD3D12 = ClassPtrCast<BufferD3D12Impl>(pSrcBuffer);
auto* pDstBuffD3D12 = ClassPtrCast<BufferD3D12Impl>(pDstBuffer);
VERIFY(pDstBuffD3D12->GetDesc().Usage != USAGE_DYNAMIC, "Dynamic buffers cannot be copy destinations");
auto& CmdCtx = GetCmdContext();
TransitionOrVerifyBufferState(CmdCtx, *pSrcBuffD3D12, SrcBufferTransitionMode, RESOURCE_STATE_COPY_SOURCE, "Using resource as copy source (DeviceContextD3D12Impl::CopyBuffer)");
TransitionOrVerifyBufferState(CmdCtx, *pDstBuffD3D12, DstBufferTransitionMode, RESOURCE_STATE_COPY_DEST, "Using resource as copy destination (DeviceContextD3D12Impl::CopyBuffer)");
Uint64 DstDataStartByteOffset;
auto* pd3d12DstBuff = pDstBuffD3D12->GetD3D12Buffer(DstDataStartByteOffset, this);
VERIFY(DstDataStartByteOffset == 0, "Dst buffer must not be suballocated");
Uint64 SrcDataStartByteOffset;
auto* pd3d12SrcBuff = pSrcBuffD3D12->GetD3D12Buffer(SrcDataStartByteOffset, this);
CmdCtx.FlushResourceBarriers();
CmdCtx.GetCommandList()->CopyBufferRegion(pd3d12DstBuff, DstOffset + DstDataStartByteOffset, pd3d12SrcBuff, SrcOffset + SrcDataStartByteOffset, Size);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::MapBuffer(IBuffer* pBuffer, MAP_TYPE MapType, MAP_FLAGS MapFlags, PVoid& pMappedData)
{
TDeviceContextBase::MapBuffer(pBuffer, MapType, MapFlags, pMappedData);
auto* pBufferD3D12 = ClassPtrCast<BufferD3D12Impl>(pBuffer);
const auto& BuffDesc = pBufferD3D12->GetDesc();
auto* pd3d12Resource = pBufferD3D12->m_pd3d12Resource.p;
if (MapType == MAP_READ)
{
DEV_CHECK_ERR(BuffDesc.Usage == USAGE_STAGING, "Buffer must be created as USAGE_STAGING to be mapped for reading");
DEV_CHECK_ERR(pd3d12Resource != nullptr, "USAGE_STAGING buffer must initialize D3D12 resource");
if ((MapFlags & MAP_FLAG_DO_NOT_WAIT) == 0)
{
LOG_WARNING_MESSAGE("D3D12 backend never waits for GPU when mapping staging buffers for reading. "
"Applications must use fences or other synchronization methods to explicitly synchronize "
"access and use MAP_FLAG_DO_NOT_WAIT flag.");
}
D3D12_RANGE MapRange;
MapRange.Begin = 0;
MapRange.End = StaticCast<SIZE_T>(BuffDesc.Size);
pd3d12Resource->Map(0, &MapRange, &pMappedData);
}
else if (MapType == MAP_WRITE)
{
if (BuffDesc.Usage == USAGE_STAGING)
{
DEV_CHECK_ERR(pd3d12Resource != nullptr, "USAGE_STAGING buffer mapped for writing must initialize D3D12 resource");
if (MapFlags & MAP_FLAG_DISCARD)
{
// Nothing to do
}
pd3d12Resource->Map(0, nullptr, &pMappedData);
}
else if (BuffDesc.Usage == USAGE_DYNAMIC)
{
DEV_CHECK_ERR((MapFlags & (MAP_FLAG_DISCARD | MAP_FLAG_NO_OVERWRITE)) != 0, "D3D12 buffer must be mapped for writing with MAP_FLAG_DISCARD or MAP_FLAG_NO_OVERWRITE flag");
auto& DynamicData = pBufferD3D12->m_DynamicData[GetContextId()];
if ((MapFlags & MAP_FLAG_DISCARD) != 0 || DynamicData.CPUAddress == nullptr)
{
Uint32 Alignment = (BuffDesc.BindFlags & BIND_UNIFORM_BUFFER) ? D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT : 16;
DynamicData = AllocateDynamicSpace(BuffDesc.Size, Alignment);
}
else
{
VERIFY_EXPR(MapFlags & MAP_FLAG_NO_OVERWRITE);
if (pd3d12Resource != nullptr)
{
LOG_ERROR("Formatted buffers require actual Direct3D12 backing resource and cannot be suballocated "
"from dynamic heap. In current implementation, the entire contents of the backing buffer is updated when the buffer is unmapped. "
"As a consequence, the buffer cannot be mapped with MAP_FLAG_NO_OVERWRITE flag because updating the whole "
"buffer will overwrite regions that may still be in use by the GPU.");
return;
}
// Reuse previously mapped region
}
pMappedData = DynamicData.CPUAddress;
}
else
{
LOG_ERROR("Only USAGE_DYNAMIC and USAGE_STAGING D3D12 buffers can be mapped for writing");
}
}
else if (MapType == MAP_READ_WRITE)
{
LOG_ERROR("MAP_READ_WRITE is not supported in D3D12");
}
else
{
LOG_ERROR("Only MAP_WRITE_DISCARD and MAP_READ are currently implemented in D3D12");
}
}
void DeviceContextD3D12Impl::UnmapBuffer(IBuffer* pBuffer, MAP_TYPE MapType)
{
TDeviceContextBase::UnmapBuffer(pBuffer, MapType);
auto* pBufferD3D12 = ClassPtrCast<BufferD3D12Impl>(pBuffer);
const auto& BuffDesc = pBufferD3D12->GetDesc();
auto* pd3d12Resource = pBufferD3D12->m_pd3d12Resource.p;
if (MapType == MAP_READ)
{
D3D12_RANGE MapRange;
// It is valid to specify the CPU didn't write any data by passing a range where End is less than or equal to Begin.
MapRange.Begin = 1;
MapRange.End = 0;
pd3d12Resource->Unmap(0, &MapRange);
}
else if (MapType == MAP_WRITE)
{
if (BuffDesc.Usage == USAGE_STAGING)
{
VERIFY(pd3d12Resource != nullptr, "USAGE_STAGING buffer mapped for writing must initialize D3D12 resource");
pd3d12Resource->Unmap(0, nullptr);
}
else if (BuffDesc.Usage == USAGE_DYNAMIC)
{
// Copy data into the resource
if (pd3d12Resource)
{
UpdateBufferRegion(pBufferD3D12, pBufferD3D12->m_DynamicData[GetContextId()], 0, BuffDesc.Size, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
}
}
}
}
void DeviceContextD3D12Impl::UpdateTexture(ITexture* pTexture,
Uint32 MipLevel,
Uint32 Slice,
const Box& DstBox,
const TextureSubResData& SubresData,
RESOURCE_STATE_TRANSITION_MODE SrcBufferTransitionMode,
RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode)
{
TDeviceContextBase::UpdateTexture(pTexture, MipLevel, Slice, DstBox, SubresData, SrcBufferTransitionMode, TextureTransitionMode);
auto* pTexD3D12 = ClassPtrCast<TextureD3D12Impl>(pTexture);
const auto& Desc = pTexD3D12->GetDesc();
// OpenGL backend uses UpdateData() to initialize textures, so we can't check the usage in ValidateUpdateTextureParams()
DEV_CHECK_ERR(Desc.Usage == USAGE_DEFAULT || Desc.Usage == USAGE_SPARSE,
"Only USAGE_DEFAULT or USAGE_SPARSE textures should be updated with UpdateData()");
Box BlockAlignedBox;
const auto& FmtAttribs = GetTextureFormatAttribs(Desc.Format);
const Box* pBox = nullptr;
if (FmtAttribs.ComponentType == COMPONENT_TYPE_COMPRESSED)
{
// Align update region by the compressed block size
VERIFY((DstBox.MinX % FmtAttribs.BlockWidth) == 0, "Update region min X coordinate (", DstBox.MinX, ") must be multiple of a compressed block width (", Uint32{FmtAttribs.BlockWidth}, ")");
BlockAlignedBox.MinX = DstBox.MinX;
VERIFY((FmtAttribs.BlockWidth & (FmtAttribs.BlockWidth - 1)) == 0, "Compressed block width (", Uint32{FmtAttribs.BlockWidth}, ") is expected to be power of 2");
BlockAlignedBox.MaxX = (DstBox.MaxX + FmtAttribs.BlockWidth - 1) & ~(FmtAttribs.BlockWidth - 1);
VERIFY((DstBox.MinY % FmtAttribs.BlockHeight) == 0, "Update region min Y coordinate (", DstBox.MinY, ") must be multiple of a compressed block height (", Uint32{FmtAttribs.BlockHeight}, ")");
BlockAlignedBox.MinY = DstBox.MinY;
VERIFY((FmtAttribs.BlockHeight & (FmtAttribs.BlockHeight - 1)) == 0, "Compressed block height (", Uint32{FmtAttribs.BlockHeight}, ") is expected to be power of 2");
BlockAlignedBox.MaxY = (DstBox.MaxY + FmtAttribs.BlockHeight - 1) & ~(FmtAttribs.BlockHeight - 1);
BlockAlignedBox.MinZ = DstBox.MinZ;
BlockAlignedBox.MaxZ = DstBox.MaxZ;
pBox = &BlockAlignedBox;
}
else
{
pBox = &DstBox;
}
auto DstSubResIndex = D3D12CalcSubresource(MipLevel, Slice, 0, Desc.MipLevels, Desc.GetArraySize());
if (SubresData.pSrcBuffer == nullptr)
{
UpdateTextureRegion(SubresData.pData, SubresData.Stride, SubresData.DepthStride,
*pTexD3D12, DstSubResIndex, *pBox, TextureTransitionMode);
}
else
{
CopyTextureRegion(SubresData.pSrcBuffer, 0, SubresData.Stride, SubresData.DepthStride,
*pTexD3D12, DstSubResIndex, *pBox,
SrcBufferTransitionMode, TextureTransitionMode);
}
}
void DeviceContextD3D12Impl::CopyTexture(const CopyTextureAttribs& CopyAttribs)
{
TDeviceContextBase::CopyTexture(CopyAttribs);
auto* pSrcTexD3D12 = ClassPtrCast<TextureD3D12Impl>(CopyAttribs.pSrcTexture);
auto* pDstTexD3D12 = ClassPtrCast<TextureD3D12Impl>(CopyAttribs.pDstTexture);
const auto& SrcTexDesc = pSrcTexD3D12->GetDesc();
const auto& DstTexDesc = pDstTexD3D12->GetDesc();
D3D12_BOX D3D12SrcBox, *pD3D12SrcBox = nullptr;
if (const auto* pSrcBox = CopyAttribs.pSrcBox)
{
D3D12SrcBox.left = pSrcBox->MinX;
D3D12SrcBox.right = pSrcBox->MaxX;
D3D12SrcBox.top = pSrcBox->MinY;
D3D12SrcBox.bottom = pSrcBox->MaxY;
D3D12SrcBox.front = pSrcBox->MinZ;
D3D12SrcBox.back = pSrcBox->MaxZ;
pD3D12SrcBox = &D3D12SrcBox;
}
auto DstSubResIndex = D3D12CalcSubresource(CopyAttribs.DstMipLevel, CopyAttribs.DstSlice, 0, DstTexDesc.MipLevels, DstTexDesc.GetArraySize());
auto SrcSubResIndex = D3D12CalcSubresource(CopyAttribs.SrcMipLevel, CopyAttribs.SrcSlice, 0, SrcTexDesc.MipLevels, SrcTexDesc.GetArraySize());
CopyTextureRegion(pSrcTexD3D12, SrcSubResIndex, pD3D12SrcBox, CopyAttribs.SrcTextureTransitionMode,
pDstTexD3D12, DstSubResIndex, CopyAttribs.DstX, CopyAttribs.DstY, CopyAttribs.DstZ,
CopyAttribs.DstTextureTransitionMode);
}
void DeviceContextD3D12Impl::CopyTextureRegion(TextureD3D12Impl* pSrcTexture,
Uint32 SrcSubResIndex,
const D3D12_BOX* pD3D12SrcBox,
RESOURCE_STATE_TRANSITION_MODE SrcTextureTransitionMode,
TextureD3D12Impl* pDstTexture,
Uint32 DstSubResIndex,
Uint32 DstX,
Uint32 DstY,
Uint32 DstZ,
RESOURCE_STATE_TRANSITION_MODE DstTextureTransitionMode)
{
// We must unbind the textures from framebuffer because
// we will transition their states. If we later try to commit
// them as render targets (e.g. from SetPipelineState()), a
// state mismatch error will occur.
UnbindTextureFromFramebuffer(pSrcTexture, true);
UnbindTextureFromFramebuffer(pDstTexture, true);
auto& CmdCtx = GetCmdContext();
if (pSrcTexture->GetDesc().Usage == USAGE_STAGING)
{
DEV_CHECK_ERR((pSrcTexture->GetDesc().CPUAccessFlags & CPU_ACCESS_WRITE) != 0, "Source staging texture must be created with CPU_ACCESS_WRITE flag");
DEV_CHECK_ERR(pSrcTexture->GetState() == RESOURCE_STATE_GENERIC_READ || !pSrcTexture->IsInKnownState(), "Staging texture must always be in RESOURCE_STATE_GENERIC_READ state");
}
TransitionOrVerifyTextureState(CmdCtx, *pSrcTexture, SrcTextureTransitionMode, RESOURCE_STATE_COPY_SOURCE, "Using resource as copy source (DeviceContextD3D12Impl::CopyTextureRegion)");
if (pDstTexture->GetDesc().Usage == USAGE_STAGING)
{
DEV_CHECK_ERR((pDstTexture->GetDesc().CPUAccessFlags & CPU_ACCESS_READ) != 0, "Destination staging texture must be created with CPU_ACCESS_READ flag");
DEV_CHECK_ERR(pDstTexture->GetState() == RESOURCE_STATE_COPY_DEST || !pDstTexture->IsInKnownState(), "Staging texture must always be in RESOURCE_STATE_COPY_DEST state");
}
TransitionOrVerifyTextureState(CmdCtx, *pDstTexture, DstTextureTransitionMode, RESOURCE_STATE_COPY_DEST, "Using resource as copy destination (DeviceContextD3D12Impl::CopyTextureRegion)");
D3D12_TEXTURE_COPY_LOCATION DstLocation = {}, SrcLocation = {};
SrcLocation.pResource = pSrcTexture->GetD3D12Resource();
if (pSrcTexture->GetDesc().Usage == USAGE_STAGING)
{
SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
SrcLocation.PlacedFootprint = pSrcTexture->GetStagingFootprint(SrcSubResIndex);
}
else
{
SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
SrcLocation.SubresourceIndex = SrcSubResIndex;
}
DstLocation.pResource = pDstTexture->GetD3D12Resource();
if (pDstTexture->GetDesc().Usage == USAGE_STAGING)
{
DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
DstLocation.PlacedFootprint = pDstTexture->GetStagingFootprint(DstSubResIndex);
}
else
{
DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
DstLocation.SubresourceIndex = DstSubResIndex;
}
CmdCtx.FlushResourceBarriers();
CmdCtx.GetCommandList()->CopyTextureRegion(&DstLocation, DstX, DstY, DstZ, &SrcLocation, pD3D12SrcBox);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::CopyTextureRegion(ID3D12Resource* pd3d12Buffer,
Uint64 SrcOffset,
Uint64 SrcStride,
Uint64 SrcDepthStride,
Uint64 BufferSize,
TextureD3D12Impl& TextureD3D12,
Uint32 DstSubResIndex,
const Box& DstBox,
RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode)
{
const auto& TexDesc = TextureD3D12.GetDesc();
auto& CmdCtx = GetCmdContext();
bool StateTransitionRequired = false;
if (TextureTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION)
{
StateTransitionRequired = TextureD3D12.IsInKnownState() && !TextureD3D12.CheckState(RESOURCE_STATE_COPY_DEST);
}
#ifdef DILIGENT_DEVELOPMENT
else if (TextureTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY)
{
DvpVerifyTextureState(TextureD3D12, RESOURCE_STATE_COPY_DEST, "Using texture as copy destination (DeviceContextD3D12Impl::CopyTextureRegion)");
}
#endif
D3D12_RESOURCE_BARRIER BarrierDesc;
if (StateTransitionRequired)
{
const auto ResStateMask = GetSupportedD3D12ResourceStatesForCommandList(CmdCtx.GetCommandListType());
BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
BarrierDesc.Transition.pResource = TextureD3D12.GetD3D12Resource();
BarrierDesc.Transition.Subresource = DstSubResIndex;
BarrierDesc.Transition.StateBefore = ResourceStateFlagsToD3D12ResourceStates(TextureD3D12.GetState()) & ResStateMask;
BarrierDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
CmdCtx.ResourceBarrier(BarrierDesc);
}
D3D12_TEXTURE_COPY_LOCATION DstLocation;
DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
DstLocation.pResource = TextureD3D12.GetD3D12Resource();
DstLocation.SubresourceIndex = StaticCast<UINT>(DstSubResIndex);
D3D12_TEXTURE_COPY_LOCATION SrcLocation;
SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
SrcLocation.pResource = pd3d12Buffer;
D3D12_PLACED_SUBRESOURCE_FOOTPRINT& Footprint = SrcLocation.PlacedFootprint;
Footprint.Offset = SrcOffset;
Footprint.Footprint.Width = StaticCast<UINT>(DstBox.Width());
Footprint.Footprint.Height = StaticCast<UINT>(DstBox.Height());
Footprint.Footprint.Depth = StaticCast<UINT>(DstBox.Depth()); // Depth cannot be 0
Footprint.Footprint.Format = TexFormatToDXGI_Format(TexDesc.Format);
Footprint.Footprint.RowPitch = StaticCast<UINT>(SrcStride);
#ifdef DILIGENT_DEBUG
{
const auto& FmtAttribs = GetTextureFormatAttribs(TexDesc.Format);
const Uint32 RowCount = std::max((Footprint.Footprint.Height / FmtAttribs.BlockHeight), 1u);
VERIFY(BufferSize >= Uint64{Footprint.Footprint.RowPitch} * RowCount * Footprint.Footprint.Depth, "Buffer is not large enough");
VERIFY(Footprint.Footprint.Depth == 1 || StaticCast<UINT>(SrcDepthStride) == Footprint.Footprint.RowPitch * RowCount, "Depth stride must be equal to the size of 2D plane");
}
#endif
D3D12_BOX D3D12SrcBox;
D3D12SrcBox.left = 0;
D3D12SrcBox.right = Footprint.Footprint.Width;
D3D12SrcBox.top = 0;
D3D12SrcBox.bottom = Footprint.Footprint.Height;
D3D12SrcBox.front = 0;
D3D12SrcBox.back = Footprint.Footprint.Depth;
CmdCtx.FlushResourceBarriers();
CmdCtx.GetCommandList()->CopyTextureRegion(&DstLocation,
StaticCast<UINT>(DstBox.MinX),
StaticCast<UINT>(DstBox.MinY),
StaticCast<UINT>(DstBox.MinZ),
&SrcLocation, &D3D12SrcBox);
++m_State.NumCommands;
if (StateTransitionRequired)
{
std::swap(BarrierDesc.Transition.StateBefore, BarrierDesc.Transition.StateAfter);
CmdCtx.ResourceBarrier(BarrierDesc);
}
}
void DeviceContextD3D12Impl::CopyTextureRegion(IBuffer* pSrcBuffer,
Uint64 SrcOffset,
Uint64 SrcStride,
Uint64 SrcDepthStride,
class TextureD3D12Impl& TextureD3D12,
Uint32 DstSubResIndex,
const Box& DstBox,
RESOURCE_STATE_TRANSITION_MODE BufferTransitionMode,
RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode)
{
auto* pBufferD3D12 = ClassPtrCast<BufferD3D12Impl>(pSrcBuffer);
if (pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC)
DEV_CHECK_ERR(pBufferD3D12->GetState() == RESOURCE_STATE_GENERIC_READ, "Dynamic buffer is expected to always be in RESOURCE_STATE_GENERIC_READ state");
else
{
if (BufferTransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION)
{
if (pBufferD3D12->IsInKnownState() && pBufferD3D12->GetState() != RESOURCE_STATE_GENERIC_READ)
GetCmdContext().TransitionResource(*pBufferD3D12, RESOURCE_STATE_GENERIC_READ);
}
#ifdef DILIGENT_DEVELOPMENT
else if (BufferTransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY)
{
DvpVerifyBufferState(*pBufferD3D12, RESOURCE_STATE_COPY_SOURCE, "Using buffer as copy source (DeviceContextD3D12Impl::CopyTextureRegion)");
}
#endif
}
GetCmdContext().FlushResourceBarriers();
Uint64 DataStartByteOffset = 0;
auto* pd3d12Buffer = pBufferD3D12->GetD3D12Buffer(DataStartByteOffset, this);
CopyTextureRegion(pd3d12Buffer, StaticCast<Uint32>(DataStartByteOffset) + SrcOffset, SrcStride, SrcDepthStride,
pBufferD3D12->GetDesc().Size, TextureD3D12, DstSubResIndex, DstBox, TextureTransitionMode);
}
DeviceContextD3D12Impl::TextureUploadSpace DeviceContextD3D12Impl::AllocateTextureUploadSpace(TEXTURE_FORMAT TexFmt,
const Box& Region)
{
TextureUploadSpace UploadSpace;
VERIFY_EXPR(Region.IsValid());
auto UpdateRegionWidth = Region.Width();
auto UpdateRegionHeight = Region.Height();
auto UpdateRegionDepth = Region.Depth();
const auto& FmtAttribs = GetTextureFormatAttribs(TexFmt);
if (FmtAttribs.ComponentType == COMPONENT_TYPE_COMPRESSED)
{
// Box must be aligned by the calling function
VERIFY_EXPR((UpdateRegionWidth % FmtAttribs.BlockWidth) == 0);
VERIFY_EXPR((UpdateRegionHeight % FmtAttribs.BlockHeight) == 0);
UploadSpace.RowSize = Uint64{UpdateRegionWidth} / Uint64{FmtAttribs.BlockWidth} * Uint64{FmtAttribs.ComponentSize};
UploadSpace.RowCount = UpdateRegionHeight / FmtAttribs.BlockHeight;
}
else
{
UploadSpace.RowSize = Uint64{UpdateRegionWidth} * Uint32{FmtAttribs.ComponentSize} * Uint32{FmtAttribs.NumComponents};
UploadSpace.RowCount = UpdateRegionHeight;
}
// RowPitch must be a multiple of 256 (aka. D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)
UploadSpace.Stride = (UploadSpace.RowSize + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1);
UploadSpace.DepthStride = UploadSpace.RowCount * UploadSpace.Stride;
const auto MemorySize = UpdateRegionDepth * UploadSpace.DepthStride;
UploadSpace.Allocation = AllocateDynamicSpace(MemorySize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
UploadSpace.AlignedOffset = (UploadSpace.Allocation.Offset + (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT - 1)) & ~(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT - 1);
UploadSpace.Region = Region;
return UploadSpace;
}
void DeviceContextD3D12Impl::UpdateTextureRegion(const void* pSrcData,
Uint64 SrcStride,
Uint64 SrcDepthStride,
TextureD3D12Impl& TextureD3D12,
Uint32 DstSubResIndex,
const Box& DstBox,
RESOURCE_STATE_TRANSITION_MODE TextureTransitionMode)
{
const auto& TexDesc = TextureD3D12.GetDesc();
auto UploadSpace = AllocateTextureUploadSpace(TexDesc.Format, DstBox);
auto UpdateRegionDepth = DstBox.Depth();
#ifdef DILIGENT_DEBUG
{
VERIFY(SrcStride >= UploadSpace.RowSize, "Source data stride (", SrcStride, ") is below the image row size (", UploadSpace.RowSize, ")");
const auto PlaneSize = SrcStride * UploadSpace.RowCount;
VERIFY(UpdateRegionDepth == 1 || SrcDepthStride >= PlaneSize, "Source data depth stride (", SrcDepthStride, ") is below the image plane size (", PlaneSize, ")");
}
#endif
const auto AlignedOffset = UploadSpace.AlignedOffset;
for (Uint32 DepthSlice = 0; DepthSlice < UpdateRegionDepth; ++DepthSlice)
{
for (Uint32 row = 0; row < UploadSpace.RowCount; ++row)
{
const auto* pSrcPtr =
reinterpret_cast<const Uint8*>(pSrcData) + row * SrcStride + DepthSlice * SrcDepthStride;
auto* pDstPtr =
reinterpret_cast<Uint8*>(UploadSpace.Allocation.CPUAddress) + (AlignedOffset - UploadSpace.Allocation.Offset) + row * UploadSpace.Stride + DepthSlice * UploadSpace.DepthStride;
memcpy(pDstPtr, pSrcPtr, StaticCast<size_t>(UploadSpace.RowSize));
}
}
CopyTextureRegion(UploadSpace.Allocation.pBuffer,
StaticCast<Uint32>(AlignedOffset),
UploadSpace.Stride,
UploadSpace.DepthStride,
StaticCast<Uint32>(UploadSpace.Allocation.Size - (AlignedOffset - UploadSpace.Allocation.Offset)),
TextureD3D12,
DstSubResIndex,
DstBox,
TextureTransitionMode);
}
void DeviceContextD3D12Impl::MapTextureSubresource(ITexture* pTexture,
Uint32 MipLevel,
Uint32 ArraySlice,
MAP_TYPE MapType,
MAP_FLAGS MapFlags,
const Box* pMapRegion,
MappedTextureSubresource& MappedData)
{
TDeviceContextBase::MapTextureSubresource(pTexture, MipLevel, ArraySlice, MapType, MapFlags, pMapRegion, MappedData);
auto& TextureD3D12 = *ClassPtrCast<TextureD3D12Impl>(pTexture);
const auto& TexDesc = TextureD3D12.GetDesc();
auto Subres = D3D12CalcSubresource(MipLevel, ArraySlice, 0, TexDesc.MipLevels, TexDesc.GetArraySize());
if (TexDesc.Usage == USAGE_DYNAMIC)
{
if (MapType != MAP_WRITE)
{
LOG_ERROR("USAGE_DYNAMIC textures can only be mapped for writing");
MappedData = MappedTextureSubresource{};
return;
}
if ((MapFlags & (MAP_FLAG_DISCARD | MAP_FLAG_NO_OVERWRITE)) != 0)
LOG_INFO_MESSAGE_ONCE("Mapping textures with flags MAP_FLAG_DISCARD or MAP_FLAG_NO_OVERWRITE has no effect in D3D12 backend");
Box FullExtentBox;
if (pMapRegion == nullptr)
{
FullExtentBox.MaxX = std::max(TexDesc.Width >> MipLevel, 1u);
FullExtentBox.MaxY = std::max(TexDesc.Height >> MipLevel, 1u);
FullExtentBox.MaxZ = std::max(TexDesc.GetDepth() >> MipLevel, 1u);
pMapRegion = &FullExtentBox;
}
auto UploadSpace = AllocateTextureUploadSpace(TexDesc.Format, *pMapRegion);
MappedData.pData = reinterpret_cast<Uint8*>(UploadSpace.Allocation.CPUAddress) + (UploadSpace.AlignedOffset - UploadSpace.Allocation.Offset);
MappedData.Stride = UploadSpace.Stride;
MappedData.DepthStride = UploadSpace.DepthStride;
auto it = m_MappedTextures.emplace(MappedTextureKey{&TextureD3D12, Subres}, std::move(UploadSpace));
if (!it.second)
LOG_ERROR_MESSAGE("Mip level ", MipLevel, ", slice ", ArraySlice, " of texture '", TexDesc.Name, "' has already been mapped");
}
else if (TexDesc.Usage == USAGE_STAGING)
{
const auto& Footprint = TextureD3D12.GetStagingFootprint(Subres);
// It is valid to specify the CPU won't read any data by passing a range where
// End is less than or equal to Begin.
// https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12resource-map
D3D12_RANGE InvalidateRange = {1, 0};
if (MapType == MAP_READ)
{
if ((MapFlags & MAP_FLAG_DO_NOT_WAIT) == 0)
{
LOG_WARNING_MESSAGE("D3D12 backend never waits for GPU when mapping staging textures for reading. "
"Applications must use fences or other synchronization methods to explicitly synchronize "
"access and use MAP_FLAG_DO_NOT_WAIT flag.");
}
DEV_CHECK_ERR((TexDesc.CPUAccessFlags & CPU_ACCESS_READ), "Texture '", TexDesc.Name, "' was not created with CPU_ACCESS_READ flag and can't be mapped for reading");
// Resources on D3D12_HEAP_TYPE_READBACK heaps do not support persistent map.
InvalidateRange.Begin = StaticCast<SIZE_T>(Footprint.Offset);
const auto& NextFootprint = TextureD3D12.GetStagingFootprint(Subres + 1);
InvalidateRange.End = StaticCast<SIZE_T>(NextFootprint.Offset);
}
else if (MapType == MAP_WRITE)
{
DEV_CHECK_ERR((TexDesc.CPUAccessFlags & CPU_ACCESS_WRITE), "Texture '", TexDesc.Name, "' was not created with CPU_ACCESS_WRITE flag and can't be mapped for writing");
}
// Nested Map() calls are supported and are ref-counted. The first call to Map() allocates
// a CPU virtual address range for the resource. The last call to Unmap deallocates the CPU
// virtual address range.
// Map() invalidates the CPU cache, when necessary, so that CPU reads to this address
// reflect any modifications made by the GPU.
void* pMappedDataPtr = nullptr;
TextureD3D12.GetD3D12Resource()->Map(0, &InvalidateRange, &pMappedDataPtr);
MappedData.pData = reinterpret_cast<Uint8*>(pMappedDataPtr) + Footprint.Offset;
MappedData.Stride = StaticCast<Uint32>(Footprint.Footprint.RowPitch);
const auto& FmtAttribs = GetTextureFormatAttribs(TexDesc.Format);
MappedData.DepthStride = StaticCast<Uint32>(Footprint.Footprint.Height / FmtAttribs.BlockHeight * Footprint.Footprint.RowPitch);
}
else
{
UNSUPPORTED(GetUsageString(TexDesc.Usage), " textures cannot currently be mapped in D3D12 back-end");
}
}
void DeviceContextD3D12Impl::UnmapTextureSubresource(ITexture* pTexture, Uint32 MipLevel, Uint32 ArraySlice)
{
TDeviceContextBase::UnmapTextureSubresource(pTexture, MipLevel, ArraySlice);
TextureD3D12Impl& TextureD3D12 = *ClassPtrCast<TextureD3D12Impl>(pTexture);
const auto& TexDesc = TextureD3D12.GetDesc();
auto Subres = D3D12CalcSubresource(MipLevel, ArraySlice, 0, TexDesc.MipLevels, TexDesc.GetArraySize());
if (TexDesc.Usage == USAGE_DYNAMIC)
{
auto UploadSpaceIt = m_MappedTextures.find(MappedTextureKey{&TextureD3D12, Subres});
if (UploadSpaceIt != m_MappedTextures.end())
{
auto& UploadSpace = UploadSpaceIt->second;
CopyTextureRegion(UploadSpace.Allocation.pBuffer,
UploadSpace.AlignedOffset,
UploadSpace.Stride,
UploadSpace.DepthStride,
StaticCast<Uint32>(UploadSpace.Allocation.Size - (UploadSpace.AlignedOffset - UploadSpace.Allocation.Offset)),
TextureD3D12,
Subres,
UploadSpace.Region,
RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
m_MappedTextures.erase(UploadSpaceIt);
}
else
{
LOG_ERROR_MESSAGE("Failed to unmap mip level ", MipLevel, ", slice ", ArraySlice, " of texture '", TexDesc.Name, "'. The texture has either been unmapped already or has not been mapped");
}
}
else if (TexDesc.Usage == USAGE_STAGING)
{
// It is valid to specify the CPU didn't write any data by passing a range where
// End is less than or equal to Begin.
// https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/nf-d3d12-id3d12resource-unmap
D3D12_RANGE FlushRange = {1, 0};
if (TexDesc.CPUAccessFlags == CPU_ACCESS_WRITE)
{
const auto& Footprint = TextureD3D12.GetStagingFootprint(Subres);
const auto& NextFootprint = TextureD3D12.GetStagingFootprint(Subres + 1);
FlushRange.Begin = StaticCast<SIZE_T>(Footprint.Offset);
FlushRange.End = StaticCast<SIZE_T>(NextFootprint.Offset);
}
// Map and Unmap can be called by multiple threads safely. Nested Map calls are supported
// and are ref-counted. The first call to Map allocates a CPU virtual address range for the
// resource. The last call to Unmap deallocates the CPU virtual address range.
// Unmap() flushes the CPU cache, when necessary, so that GPU reads to this address reflect
// any modifications made by the CPU.
TextureD3D12.GetD3D12Resource()->Unmap(0, &FlushRange);
}
else
{
UNSUPPORTED(GetUsageString(TexDesc.Usage), " textures cannot currently be mapped in D3D12 back-end");
}
}
void DeviceContextD3D12Impl::GenerateMips(ITextureView* pTexView)
{
TDeviceContextBase::GenerateMips(pTexView);
PipelineStateD3D12Impl* pCurrPSO = nullptr;
if (m_pPipelineState)
{
const auto& PSODesc = m_pPipelineState->GetDesc();
if (PSODesc.IsComputePipeline() || PSODesc.IsRayTracingPipeline())
{
// Mips generator will set its own compute pipeline, root signature and root resources.
// We need to invalidate current PSO and reset it afterwards.
pCurrPSO = m_pPipelineState;
m_pPipelineState.Release();
m_ComputeResources.pd3d12RootSig = nullptr;
}
}
auto& Ctx = GetCmdContext();
const auto& MipsGenerator = m_pDevice->GetMipsGenerator();
MipsGenerator.GenerateMips(m_pDevice->GetD3D12Device(), ClassPtrCast<TextureViewD3D12Impl>(pTexView), Ctx);
++m_State.NumCommands;
if (pCurrPSO != nullptr)
{
SetPipelineState(pCurrPSO);
}
}
void DeviceContextD3D12Impl::FinishCommandList(ICommandList** ppCommandList)
{
DEV_CHECK_ERR(IsDeferred(), "Only deferred context can record command list");
DEV_CHECK_ERR(m_pActiveRenderPass == nullptr, "Finishing command list inside an active render pass.");
CommandListD3D12Impl* pCmdListD3D12(NEW_RC_OBJ(m_CmdListAllocator, "CommandListD3D12Impl instance", CommandListD3D12Impl)(m_pDevice, this, std::move(m_CurrCmdCtx)));
pCmdListD3D12->QueryInterface(IID_CommandList, reinterpret_cast<IObject**>(ppCommandList));
// We can't request new cmd context because we don't know the command queue type
constexpr auto RequestNewCmdCtx = false;
Flush(RequestNewCmdCtx);
m_QueryMgr = nullptr;
InvalidateState();
TDeviceContextBase::FinishCommandList();
}
void DeviceContextD3D12Impl::ExecuteCommandLists(Uint32 NumCommandLists,
ICommandList* const* ppCommandLists)
{
DEV_CHECK_ERR(!IsDeferred(), "Only immediate context can execute command list");
if (NumCommandLists == 0)
return;
DEV_CHECK_ERR(ppCommandLists != nullptr, "ppCommandLists must not be null when NumCommandLists is not zero");
Flush(true, NumCommandLists, ppCommandLists);
InvalidateState();
}
void DeviceContextD3D12Impl::EnqueueSignal(IFence* pFence, Uint64 Value)
{
TDeviceContextBase::EnqueueSignal(pFence, Value, 0);
m_SignalFences.emplace_back(Value, pFence);
}
void DeviceContextD3D12Impl::DeviceWaitForFence(IFence* pFence, Uint64 Value)
{
TDeviceContextBase::DeviceWaitForFence(pFence, Value, 0);
m_WaitFences.emplace_back(Value, pFence);
}
void DeviceContextD3D12Impl::WaitForIdle()
{
DEV_CHECK_ERR(!IsDeferred(), "Only immediate contexts can be idled");
Flush();
m_pDevice->IdleCommandQueue(GetCommandQueueId(), true);
}
void DeviceContextD3D12Impl::BeginQuery(IQuery* pQuery)
{
TDeviceContextBase::BeginQuery(pQuery, 0);
auto* pQueryD3D12Impl = ClassPtrCast<QueryD3D12Impl>(pQuery);
const auto QueryType = pQueryD3D12Impl->GetDesc().Type;
if (QueryType != QUERY_TYPE_TIMESTAMP)
++m_ActiveQueriesCounter;
auto& QueryMgr = GetQueryManager();
auto& Ctx = GetCmdContext();
auto Idx = pQueryD3D12Impl->GetQueryHeapIndex(0);
if (QueryType != QUERY_TYPE_DURATION)
QueryMgr.BeginQuery(Ctx, QueryType, Idx);
else
QueryMgr.EndQuery(Ctx, QueryType, Idx);
}
void DeviceContextD3D12Impl::EndQuery(IQuery* pQuery)
{
TDeviceContextBase::EndQuery(pQuery, 0);
auto* pQueryD3D12Impl = ClassPtrCast<QueryD3D12Impl>(pQuery);
const auto QueryType = pQueryD3D12Impl->GetDesc().Type;
if (QueryType != QUERY_TYPE_TIMESTAMP)
{
VERIFY(m_ActiveQueriesCounter > 0, "Active query counter is 0 which means there was a mismatch between BeginQuery() / EndQuery() calls");
--m_ActiveQueriesCounter;
}
auto& QueryMgr = GetQueryManager();
auto& Ctx = GetCmdContext();
auto Idx = pQueryD3D12Impl->GetQueryHeapIndex(QueryType == QUERY_TYPE_DURATION ? 1 : 0);
QueryMgr.EndQuery(Ctx, QueryType, Idx);
}
static void AliasingBarrier(CommandContext& CmdCtx, IDeviceObject* pResourceBefore, IDeviceObject* pResourceAfter)
{
bool UseNVApi = false;
auto GetD3D12Resource = [&UseNVApi](IDeviceObject* pResource) -> ID3D12Resource* //
{
if (RefCntAutoPtr<ITextureD3D12> pTexture{pResource, IID_TextureD3D12})
{
const auto* pTexD3D12 = pTexture.RawPtr<const TextureD3D12Impl>();
if (pTexD3D12->IsUsingNVApi())
UseNVApi = true;
return pTexD3D12->GetD3D12Texture();
}
else if (RefCntAutoPtr<IBufferD3D12> pBuffer{pResource, IID_BufferD3D12})
{
return pBuffer.RawPtr<BufferD3D12Impl>()->GetD3D12Resource();
}
else
{
return nullptr;
}
};
D3D12_RESOURCE_BARRIER Barrier{};
Barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING;
Barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
Barrier.Aliasing.pResourceBefore = GetD3D12Resource(pResourceBefore);
Barrier.Aliasing.pResourceAfter = GetD3D12Resource(pResourceAfter);
#ifdef DILIGENT_ENABLE_D3D_NVAPI
if (UseNVApi)
{
NvAPI_D3D12_ResourceAliasingBarrier(CmdCtx.GetCommandList(), 1, &Barrier);
}
else
#endif
{
VERIFY_EXPR(!UseNVApi);
CmdCtx.ResourceBarrier(Barrier);
}
}
void DeviceContextD3D12Impl::TransitionResourceStates(Uint32 BarrierCount, const StateTransitionDesc* pResourceBarriers)
{
DEV_CHECK_ERR(m_pActiveRenderPass == nullptr, "State transitions are not allowed inside a render pass");
auto& CmdCtx = GetCmdContext();
for (Uint32 i = 0; i < BarrierCount; ++i)
{
#ifdef DILIGENT_DEVELOPMENT
DvpVerifyStateTransitionDesc(pResourceBarriers[i]);
#endif
const auto& Barrier = pResourceBarriers[i];
if (Barrier.Flags & STATE_TRANSITION_FLAG_ALIASING)
{
AliasingBarrier(CmdCtx, Barrier.pResourceBefore, Barrier.pResource);
}
else
{
if (RefCntAutoPtr<TextureD3D12Impl> pTextureD3D12Impl{Barrier.pResource, IID_TextureD3D12})
CmdCtx.TransitionResource(*pTextureD3D12Impl, Barrier);
else if (RefCntAutoPtr<BufferD3D12Impl> pBufferD3D12Impl{Barrier.pResource, IID_BufferD3D12})
CmdCtx.TransitionResource(*pBufferD3D12Impl, Barrier);
else if (RefCntAutoPtr<BottomLevelASD3D12Impl> pBLASD3D12Impl{Barrier.pResource, IID_BottomLevelASD3D12})
CmdCtx.TransitionResource(*pBLASD3D12Impl, Barrier);
else if (RefCntAutoPtr<TopLevelASD3D12Impl> pTLASD3D12Impl{Barrier.pResource, IID_TopLevelASD3D12})
CmdCtx.TransitionResource(*pTLASD3D12Impl, Barrier);
else
UNEXPECTED("Unknown resource type");
}
}
}
void DeviceContextD3D12Impl::TransitionOrVerifyBufferState(CommandContext& CmdCtx,
BufferD3D12Impl& Buffer,
RESOURCE_STATE_TRANSITION_MODE TransitionMode,
RESOURCE_STATE RequiredState,
const char* OperationName)
{
if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION)
{
if (Buffer.IsInKnownState())
CmdCtx.TransitionResource(Buffer, RequiredState);
}
#ifdef DILIGENT_DEVELOPMENT
else if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY)
{
DvpVerifyBufferState(Buffer, RequiredState, OperationName);
}
#endif
}
void DeviceContextD3D12Impl::TransitionOrVerifyTextureState(CommandContext& CmdCtx,
TextureD3D12Impl& Texture,
RESOURCE_STATE_TRANSITION_MODE TransitionMode,
RESOURCE_STATE RequiredState,
const char* OperationName)
{
if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION)
{
if (Texture.IsInKnownState())
CmdCtx.TransitionResource(Texture, RequiredState);
}
#ifdef DILIGENT_DEVELOPMENT
else if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY)
{
DvpVerifyTextureState(Texture, RequiredState, OperationName);
}
#endif
}
void DeviceContextD3D12Impl::TransitionOrVerifyBLASState(CommandContext& CmdCtx,
BottomLevelASD3D12Impl& BLAS,
RESOURCE_STATE_TRANSITION_MODE TransitionMode,
RESOURCE_STATE RequiredState,
const char* OperationName)
{
if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION)
{
if (BLAS.IsInKnownState())
CmdCtx.TransitionResource(BLAS, RequiredState);
}
#ifdef DILIGENT_DEVELOPMENT
else if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY)
{
DvpVerifyBLASState(BLAS, RequiredState, OperationName);
}
#endif
}
void DeviceContextD3D12Impl::TransitionOrVerifyTLASState(CommandContext& CmdCtx,
TopLevelASD3D12Impl& TLAS,
RESOURCE_STATE_TRANSITION_MODE TransitionMode,
RESOURCE_STATE RequiredState,
const char* OperationName)
{
if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_TRANSITION)
{
if (TLAS.IsInKnownState())
CmdCtx.TransitionResource(TLAS, RequiredState);
}
#ifdef DILIGENT_DEVELOPMENT
else if (TransitionMode == RESOURCE_STATE_TRANSITION_MODE_VERIFY)
{
DvpVerifyTLASState(TLAS, RequiredState, OperationName);
}
#endif
}
void DeviceContextD3D12Impl::TransitionTextureState(ITexture* pTexture, D3D12_RESOURCE_STATES State)
{
DEV_CHECK_ERR(pTexture != nullptr, "pTexture must not be null");
DEV_CHECK_ERR(pTexture->GetState() != RESOURCE_STATE_UNKNOWN, "Texture state is unknown");
auto& CmdCtx = GetCmdContext();
CmdCtx.TransitionResource(*ClassPtrCast<TextureD3D12Impl>(pTexture), D3D12ResourceStatesToResourceStateFlags(State));
}
void DeviceContextD3D12Impl::TransitionBufferState(IBuffer* pBuffer, D3D12_RESOURCE_STATES State)
{
DEV_CHECK_ERR(pBuffer != nullptr, "pBuffer must not be null");
DEV_CHECK_ERR(pBuffer->GetState() != RESOURCE_STATE_UNKNOWN, "Buffer state is unknown");
auto& CmdCtx = GetCmdContext();
CmdCtx.TransitionResource(*ClassPtrCast<BufferD3D12Impl>(pBuffer), D3D12ResourceStatesToResourceStateFlags(State));
}
ID3D12GraphicsCommandList* DeviceContextD3D12Impl::GetD3D12CommandList()
{
auto& CmdCtx = GetCmdContext();
CmdCtx.FlushResourceBarriers();
return CmdCtx.GetCommandList();
}
void DeviceContextD3D12Impl::ResolveTextureSubresource(ITexture* pSrcTexture,
ITexture* pDstTexture,
const ResolveTextureSubresourceAttribs& ResolveAttribs)
{
TDeviceContextBase::ResolveTextureSubresource(pSrcTexture, pDstTexture, ResolveAttribs);
auto* pSrcTexD3D12 = ClassPtrCast<TextureD3D12Impl>(pSrcTexture);
auto* pDstTexD3D12 = ClassPtrCast<TextureD3D12Impl>(pDstTexture);
const auto& SrcTexDesc = pSrcTexD3D12->GetDesc();
const auto& DstTexDesc = pDstTexD3D12->GetDesc();
auto& CmdCtx = GetCmdContext();
TransitionOrVerifyTextureState(CmdCtx, *pSrcTexD3D12, ResolveAttribs.SrcTextureTransitionMode, RESOURCE_STATE_RESOLVE_SOURCE, "Resolving multi-sampled texture (DeviceContextD3D12Impl::ResolveTextureSubresource)");
TransitionOrVerifyTextureState(CmdCtx, *pDstTexD3D12, ResolveAttribs.DstTextureTransitionMode, RESOURCE_STATE_RESOLVE_DEST, "Resolving multi-sampled texture (DeviceContextD3D12Impl::ResolveTextureSubresource)");
auto Format = ResolveAttribs.Format;
if (Format == TEX_FORMAT_UNKNOWN)
{
const auto& SrcFmtAttribs = GetTextureFormatAttribs(SrcTexDesc.Format);
if (!SrcFmtAttribs.IsTypeless)
{
Format = SrcTexDesc.Format;
}
else
{
const auto& DstFmtAttribs = GetTextureFormatAttribs(DstTexDesc.Format);
DEV_CHECK_ERR(!DstFmtAttribs.IsTypeless, "Resolve operation format can't be typeless when both source and destination textures are typeless");
Format = DstFmtAttribs.Format;
}
}
auto DXGIFmt = TexFormatToDXGI_Format(Format);
auto SrcSubresIndex = D3D12CalcSubresource(ResolveAttribs.SrcMipLevel, ResolveAttribs.SrcSlice, 0, SrcTexDesc.MipLevels, SrcTexDesc.GetArraySize());
auto DstSubresIndex = D3D12CalcSubresource(ResolveAttribs.DstMipLevel, ResolveAttribs.DstSlice, 0, DstTexDesc.MipLevels, DstTexDesc.GetArraySize());
CmdCtx.ResolveSubresource(pDstTexD3D12->GetD3D12Resource(), DstSubresIndex, pSrcTexD3D12->GetD3D12Resource(), SrcSubresIndex, DXGIFmt);
}
void DeviceContextD3D12Impl::BuildBLAS(const BuildBLASAttribs& Attribs)
{
TDeviceContextBase::BuildBLAS(Attribs, 0);
auto* const pBLASD3D12 = ClassPtrCast<BottomLevelASD3D12Impl>(Attribs.pBLAS);
auto* const pScratchD3D12 = ClassPtrCast<BufferD3D12Impl>(Attribs.pScratchBuffer);
const auto& BLASDesc = pBLASD3D12->GetDesc();
auto& CmdCtx = GetCmdContext();
const char* OpName = "Build BottomLevelAS (DeviceContextD3D12Impl::BuildBLAS)";
TransitionOrVerifyBLASState(CmdCtx, *pBLASD3D12, Attribs.BLASTransitionMode, RESOURCE_STATE_BUILD_AS_WRITE, OpName);
TransitionOrVerifyBufferState(CmdCtx, *pScratchD3D12, Attribs.ScratchBufferTransitionMode, RESOURCE_STATE_BUILD_AS_WRITE, OpName);
D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC d3d12BuildASDesc = {};
D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS& d3d12BuildASInputs = d3d12BuildASDesc.Inputs;
std::vector<D3D12_RAYTRACING_GEOMETRY_DESC> Geometries;
if (Attribs.pTriangleData != nullptr)
{
Geometries.resize(Attribs.TriangleDataCount);
pBLASD3D12->SetActualGeometryCount(Attribs.TriangleDataCount);
for (Uint32 i = 0; i < Attribs.TriangleDataCount; ++i)
{
const auto& SrcTris = Attribs.pTriangleData[i];
Uint32 Idx = i;
Uint32 GeoIdx = pBLASD3D12->UpdateGeometryIndex(SrcTris.GeometryName, Idx, Attribs.Update);
if (GeoIdx == INVALID_INDEX || Idx == INVALID_INDEX)
{
UNEXPECTED("Failed to find geometry '", SrcTris.GeometryName, '\'');
continue;
}
auto& d3d12Geo = Geometries[Idx];
auto& d3d12Tris = d3d12Geo.Triangles;
const auto& TriDesc = BLASDesc.pTriangles[GeoIdx];
d3d12Geo.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES;
d3d12Geo.Flags = GeometryFlagsToD3D12RTGeometryFlags(SrcTris.Flags);
auto* const pVB = ClassPtrCast<BufferD3D12Impl>(SrcTris.pVertexBuffer);
// vertex format in SrcTris may be undefined, so use vertex format from description
d3d12Tris.VertexBuffer.StartAddress = pVB->GetGPUAddress() + SrcTris.VertexOffset;
d3d12Tris.VertexBuffer.StrideInBytes = SrcTris.VertexStride;
d3d12Tris.VertexCount = SrcTris.VertexCount;
d3d12Tris.VertexFormat = TypeToRayTracingVertexFormat(TriDesc.VertexValueType, TriDesc.VertexComponentCount);
VERIFY(d3d12Tris.VertexFormat != DXGI_FORMAT_UNKNOWN, "Unsupported combination of vertex value type and component count");
VERIFY(d3d12Tris.VertexBuffer.StartAddress % GetValueSize(TriDesc.VertexValueType) == 0, "Vertex start address is not properly aligned");
VERIFY(d3d12Tris.VertexBuffer.StrideInBytes % GetValueSize(TriDesc.VertexValueType) == 0, "Vertex stride is not properly aligned");
TransitionOrVerifyBufferState(CmdCtx, *pVB, Attribs.GeometryTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
if (SrcTris.pIndexBuffer)
{
auto* const pIB = ClassPtrCast<BufferD3D12Impl>(SrcTris.pIndexBuffer);
// index type in SrcTris may be undefined, so use index type from description
d3d12Tris.IndexFormat = ValueTypeToIndexType(TriDesc.IndexType);
d3d12Tris.IndexBuffer = pIB->GetGPUAddress() + SrcTris.IndexOffset;
d3d12Tris.IndexCount = SrcTris.PrimitiveCount * 3;
VERIFY(d3d12Tris.IndexBuffer % GetValueSize(TriDesc.IndexType) == 0, "Index start address is not properly aligned");
TransitionOrVerifyBufferState(CmdCtx, *pIB, Attribs.GeometryTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
}
else
{
d3d12Tris.IndexFormat = DXGI_FORMAT_UNKNOWN;
d3d12Tris.IndexBuffer = 0;
}
if (SrcTris.pTransformBuffer)
{
auto* const pTB = ClassPtrCast<BufferD3D12Impl>(SrcTris.pTransformBuffer);
d3d12Tris.Transform3x4 = pTB->GetGPUAddress() + SrcTris.TransformBufferOffset;
VERIFY(d3d12Tris.Transform3x4 % D3D12_RAYTRACING_TRANSFORM3X4_BYTE_ALIGNMENT == 0, "Transform start address is not properly aligned");
TransitionOrVerifyBufferState(CmdCtx, *pTB, Attribs.GeometryTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
}
else
{
d3d12Tris.Transform3x4 = 0;
}
}
}
else if (Attribs.pBoxData != nullptr)
{
Geometries.resize(Attribs.BoxDataCount);
pBLASD3D12->SetActualGeometryCount(Attribs.BoxDataCount);
for (Uint32 i = 0; i < Attribs.BoxDataCount; ++i)
{
const auto& SrcBoxes = Attribs.pBoxData[i];
Uint32 Idx = i;
Uint32 GeoIdx = pBLASD3D12->UpdateGeometryIndex(SrcBoxes.GeometryName, Idx, Attribs.Update);
if (GeoIdx == INVALID_INDEX || Idx == INVALID_INDEX)
{
UNEXPECTED("Failed to find geometry '", SrcBoxes.GeometryName, '\'');
continue;
}
auto& d3d12Geo = Geometries[Idx];
auto& d3d12AABs = d3d12Geo.AABBs;
d3d12Geo.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_PROCEDURAL_PRIMITIVE_AABBS;
d3d12Geo.Flags = GeometryFlagsToD3D12RTGeometryFlags(SrcBoxes.Flags);
auto* pBB = ClassPtrCast<BufferD3D12Impl>(SrcBoxes.pBoxBuffer);
d3d12AABs.AABBCount = SrcBoxes.BoxCount;
d3d12AABs.AABBs.StartAddress = pBB->GetGPUAddress() + SrcBoxes.BoxOffset;
d3d12AABs.AABBs.StrideInBytes = SrcBoxes.BoxStride;
DEV_CHECK_ERR(d3d12AABs.AABBs.StartAddress % D3D12_RAYTRACING_AABB_BYTE_ALIGNMENT == 0, "AABB start address is not properly aligned");
DEV_CHECK_ERR(d3d12AABs.AABBs.StrideInBytes % D3D12_RAYTRACING_AABB_BYTE_ALIGNMENT == 0, "AABB stride is not properly aligned");
TransitionOrVerifyBufferState(CmdCtx, *pBB, Attribs.GeometryTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
}
}
d3d12BuildASInputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
d3d12BuildASInputs.Flags = BuildASFlagsToD3D12ASBuildFlags(BLASDesc.Flags);
d3d12BuildASInputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
d3d12BuildASInputs.NumDescs = static_cast<UINT>(Geometries.size());
d3d12BuildASInputs.pGeometryDescs = Geometries.data();
d3d12BuildASDesc.DestAccelerationStructureData = pBLASD3D12->GetGPUAddress();
d3d12BuildASDesc.ScratchAccelerationStructureData = pScratchD3D12->GetGPUAddress() + Attribs.ScratchBufferOffset;
d3d12BuildASDesc.SourceAccelerationStructureData = 0;
if (Attribs.Update)
{
d3d12BuildASInputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;
d3d12BuildASDesc.SourceAccelerationStructureData = d3d12BuildASDesc.DestAccelerationStructureData;
}
DEV_CHECK_ERR(d3d12BuildASDesc.ScratchAccelerationStructureData % D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT == 0,
"Scratch data address is not properly aligned");
CmdCtx.AsGraphicsContext4().BuildRaytracingAccelerationStructure(d3d12BuildASDesc, 0, nullptr);
++m_State.NumCommands;
#ifdef DILIGENT_DEVELOPMENT
pBLASD3D12->DvpUpdateVersion();
#endif
}
void DeviceContextD3D12Impl::BuildTLAS(const BuildTLASAttribs& Attribs)
{
TDeviceContextBase::BuildTLAS(Attribs, 0);
static_assert(TLAS_INSTANCE_DATA_SIZE == sizeof(D3D12_RAYTRACING_INSTANCE_DESC), "Value in TLAS_INSTANCE_DATA_SIZE doesn't match the actual instance description size");
auto* pTLASD3D12 = ClassPtrCast<TopLevelASD3D12Impl>(Attribs.pTLAS);
auto* pScratchD3D12 = ClassPtrCast<BufferD3D12Impl>(Attribs.pScratchBuffer);
auto* pInstancesD3D12 = ClassPtrCast<BufferD3D12Impl>(Attribs.pInstanceBuffer);
auto& CmdCtx = GetCmdContext();
const char* OpName = "Build TopLevelAS (DeviceContextD3D12Impl::BuildTLAS)";
TransitionOrVerifyTLASState(CmdCtx, *pTLASD3D12, Attribs.TLASTransitionMode, RESOURCE_STATE_BUILD_AS_WRITE, OpName);
TransitionOrVerifyBufferState(CmdCtx, *pScratchD3D12, Attribs.ScratchBufferTransitionMode, RESOURCE_STATE_BUILD_AS_WRITE, OpName);
if (Attribs.Update)
{
if (!pTLASD3D12->UpdateInstances(Attribs.pInstances, Attribs.InstanceCount, Attribs.BaseContributionToHitGroupIndex, Attribs.HitGroupStride, Attribs.BindingMode))
return;
}
else
{
if (!pTLASD3D12->SetInstanceData(Attribs.pInstances, Attribs.InstanceCount, Attribs.BaseContributionToHitGroupIndex, Attribs.HitGroupStride, Attribs.BindingMode))
return;
}
// copy instance data into instance buffer
{
size_t Size = Attribs.InstanceCount * sizeof(D3D12_RAYTRACING_INSTANCE_DESC);
auto TmpSpace = m_DynamicHeap.Allocate(Size, 16, m_FrameNumber);
for (Uint32 i = 0; i < Attribs.InstanceCount; ++i)
{
const auto& Inst = Attribs.pInstances[i];
const auto InstDesc = pTLASD3D12->GetInstanceDesc(Inst.InstanceName);
if (InstDesc.InstanceIndex >= Attribs.InstanceCount)
{
UNEXPECTED("Failed to find instance by name");
return;
}
auto& d3d12Inst = static_cast<D3D12_RAYTRACING_INSTANCE_DESC*>(TmpSpace.CPUAddress)[InstDesc.InstanceIndex];
auto* pBLASD3D12 = ClassPtrCast<BottomLevelASD3D12Impl>(Inst.pBLAS);
static_assert(sizeof(d3d12Inst.Transform) == sizeof(Inst.Transform), "size mismatch");
std::memcpy(&d3d12Inst.Transform, Inst.Transform.data, sizeof(d3d12Inst.Transform));
d3d12Inst.InstanceID = Inst.CustomId;
d3d12Inst.InstanceContributionToHitGroupIndex = InstDesc.ContributionToHitGroupIndex;
d3d12Inst.InstanceMask = Inst.Mask;
d3d12Inst.Flags = InstanceFlagsToD3D12RTInstanceFlags(Inst.Flags);
d3d12Inst.AccelerationStructure = pBLASD3D12->GetGPUAddress();
TransitionOrVerifyBLASState(CmdCtx, *pBLASD3D12, Attribs.BLASTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
}
UpdateBufferRegion(pInstancesD3D12, TmpSpace, Attribs.InstanceBufferOffset, Size, Attribs.InstanceBufferTransitionMode);
}
TransitionOrVerifyBufferState(CmdCtx, *pInstancesD3D12, Attribs.InstanceBufferTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC d3d12BuildASDesc = {};
D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS& d3d12BuildASInputs = d3d12BuildASDesc.Inputs;
d3d12BuildASInputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL;
d3d12BuildASInputs.Flags = BuildASFlagsToD3D12ASBuildFlags(pTLASD3D12->GetDesc().Flags);
d3d12BuildASInputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY;
d3d12BuildASInputs.NumDescs = Attribs.InstanceCount;
d3d12BuildASInputs.InstanceDescs = pInstancesD3D12->GetGPUAddress() + Attribs.InstanceBufferOffset;
d3d12BuildASDesc.DestAccelerationStructureData = pTLASD3D12->GetGPUAddress();
d3d12BuildASDesc.ScratchAccelerationStructureData = pScratchD3D12->GetGPUAddress() + Attribs.ScratchBufferOffset;
d3d12BuildASDesc.SourceAccelerationStructureData = 0;
if (Attribs.Update)
{
d3d12BuildASInputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;
d3d12BuildASDesc.SourceAccelerationStructureData = d3d12BuildASDesc.DestAccelerationStructureData;
}
DEV_CHECK_ERR(d3d12BuildASInputs.InstanceDescs % D3D12_RAYTRACING_INSTANCE_DESCS_BYTE_ALIGNMENT == 0,
"Instance data address is not properly aligned");
DEV_CHECK_ERR(d3d12BuildASDesc.ScratchAccelerationStructureData % D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT == 0,
"Scratch data address is not properly aligned");
CmdCtx.AsGraphicsContext4().BuildRaytracingAccelerationStructure(d3d12BuildASDesc, 0, nullptr);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::CopyBLAS(const CopyBLASAttribs& Attribs)
{
TDeviceContextBase::CopyBLAS(Attribs, 0);
auto* pSrcD3D12 = ClassPtrCast<BottomLevelASD3D12Impl>(Attribs.pSrc);
auto* pDstD3D12 = ClassPtrCast<BottomLevelASD3D12Impl>(Attribs.pDst);
auto& CmdCtx = GetCmdContext();
auto Mode = CopyASModeToD3D12ASCopyMode(Attribs.Mode);
// Dst BLAS description has specified CompactedSize, but doesn't have specified pTriangles and pBoxes.
// We should copy geometries because it required for SBT to map geometry name to hit group.
pDstD3D12->CopyGeometryDescription(*pSrcD3D12);
pDstD3D12->SetActualGeometryCount(pSrcD3D12->GetActualGeometryCount());
const char* OpName = "Copy BottomLevelAS (DeviceContextD3D12Impl::CopyBLAS)";
TransitionOrVerifyBLASState(CmdCtx, *pSrcD3D12, Attribs.SrcTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
TransitionOrVerifyBLASState(CmdCtx, *pDstD3D12, Attribs.DstTransitionMode, RESOURCE_STATE_BUILD_AS_WRITE, OpName);
CmdCtx.AsGraphicsContext4().CopyRaytracingAccelerationStructure(pDstD3D12->GetGPUAddress(), pSrcD3D12->GetGPUAddress(), Mode);
++m_State.NumCommands;
#ifdef DILIGENT_DEVELOPMENT
pDstD3D12->DvpUpdateVersion();
#endif
}
void DeviceContextD3D12Impl::CopyTLAS(const CopyTLASAttribs& Attribs)
{
TDeviceContextBase::CopyTLAS(Attribs, 0);
auto* pSrcD3D12 = ClassPtrCast<TopLevelASD3D12Impl>(Attribs.pSrc);
auto* pDstD3D12 = ClassPtrCast<TopLevelASD3D12Impl>(Attribs.pDst);
auto& CmdCtx = GetCmdContext();
auto Mode = CopyASModeToD3D12ASCopyMode(Attribs.Mode);
// Instances specified in BuildTLAS command.
// We should copy instances because it required for SBT to map instance name to hit group.
pDstD3D12->CopyInstanceData(*pSrcD3D12);
const char* OpName = "Copy BottomLevelAS (DeviceContextD3D12Impl::CopyTLAS)";
TransitionOrVerifyTLASState(CmdCtx, *pSrcD3D12, Attribs.SrcTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
TransitionOrVerifyTLASState(CmdCtx, *pDstD3D12, Attribs.DstTransitionMode, RESOURCE_STATE_BUILD_AS_WRITE, OpName);
CmdCtx.AsGraphicsContext4().CopyRaytracingAccelerationStructure(pDstD3D12->GetGPUAddress(), pSrcD3D12->GetGPUAddress(), Mode);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::WriteBLASCompactedSize(const WriteBLASCompactedSizeAttribs& Attribs)
{
TDeviceContextBase::WriteBLASCompactedSize(Attribs, 0);
static_assert(sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC) == sizeof(Uint64),
"Engine api specifies that compacted size is 64 bits");
auto* pBLASD3D12 = ClassPtrCast<BottomLevelASD3D12Impl>(Attribs.pBLAS);
auto* pDestBuffD3D12 = ClassPtrCast<BufferD3D12Impl>(Attribs.pDestBuffer);
auto& CmdCtx = GetCmdContext();
const char* OpName = "Write AS compacted size (DeviceContextD3D12Impl::WriteBLASCompactedSize)";
TransitionOrVerifyBLASState(CmdCtx, *pBLASD3D12, Attribs.BLASTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
TransitionOrVerifyBufferState(CmdCtx, *pDestBuffD3D12, Attribs.BufferTransitionMode, RESOURCE_STATE_UNORDERED_ACCESS, OpName);
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC d3d12Desc = {};
d3d12Desc.DestBuffer = pDestBuffD3D12->GetGPUAddress() + Attribs.DestBufferOffset;
d3d12Desc.InfoType = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE;
CmdCtx.AsGraphicsContext4().EmitRaytracingAccelerationStructurePostbuildInfo(d3d12Desc, pBLASD3D12->GetGPUAddress());
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::WriteTLASCompactedSize(const WriteTLASCompactedSizeAttribs& Attribs)
{
TDeviceContextBase::WriteTLASCompactedSize(Attribs, 0);
static_assert(sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC) == sizeof(Uint64),
"Engine api specifies that compacted size is 64 bits");
auto* pTLASD3D12 = ClassPtrCast<TopLevelASD3D12Impl>(Attribs.pTLAS);
auto* pDestBuffD3D12 = ClassPtrCast<BufferD3D12Impl>(Attribs.pDestBuffer);
auto& CmdCtx = GetCmdContext();
const char* OpName = "Write AS compacted size (DeviceContextD3D12Impl::WriteTLASCompactedSize)";
TransitionOrVerifyTLASState(CmdCtx, *pTLASD3D12, Attribs.TLASTransitionMode, RESOURCE_STATE_BUILD_AS_READ, OpName);
TransitionOrVerifyBufferState(CmdCtx, *pDestBuffD3D12, Attribs.BufferTransitionMode, RESOURCE_STATE_UNORDERED_ACCESS, OpName);
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC d3d12Desc = {};
d3d12Desc.DestBuffer = pDestBuffD3D12->GetGPUAddress() + Attribs.DestBufferOffset;
d3d12Desc.InfoType = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE;
CmdCtx.AsGraphicsContext4().EmitRaytracingAccelerationStructurePostbuildInfo(d3d12Desc, pTLASD3D12->GetGPUAddress());
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::TraceRays(const TraceRaysAttribs& Attribs)
{
TDeviceContextBase::TraceRays(Attribs, 0);
auto& CmdCtx = GetCmdContext().AsGraphicsContext4();
const auto* pSBTD3D12 = ClassPtrCast<const ShaderBindingTableD3D12Impl>(Attribs.pSBT);
D3D12_DISPATCH_RAYS_DESC d3d12DispatchDesc = pSBTD3D12->GetD3D12BindingTable();
d3d12DispatchDesc.Width = Attribs.DimensionX;
d3d12DispatchDesc.Height = Attribs.DimensionY;
d3d12DispatchDesc.Depth = Attribs.DimensionZ;
PrepareForDispatchRays(CmdCtx);
CmdCtx.DispatchRays(d3d12DispatchDesc);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::TraceRaysIndirect(const TraceRaysIndirectAttribs& Attribs)
{
TDeviceContextBase::TraceRaysIndirect(Attribs, 0);
auto& CmdCtx = GetCmdContext().AsGraphicsContext4();
auto* pAttribsBufferD3D12 = ClassPtrCast<BufferD3D12Impl>(Attribs.pAttribsBuffer);
const char* OpName = "Trace rays indirect (DeviceContextD3D12Impl::TraceRaysIndirect)";
TransitionOrVerifyBufferState(CmdCtx, *pAttribsBufferD3D12, Attribs.AttribsBufferStateTransitionMode, RESOURCE_STATE_INDIRECT_ARGUMENT, OpName);
PrepareForDispatchRays(CmdCtx);
CmdCtx.ExecuteIndirect(m_pTraceRaysIndirectSignature, 1, pAttribsBufferD3D12->GetD3D12Resource(), Attribs.ArgsByteOffset);
++m_State.NumCommands;
}
void DeviceContextD3D12Impl::UpdateSBT(IShaderBindingTable* pSBT, const UpdateIndirectRTBufferAttribs* pUpdateIndirectBufferAttribs)
{
TDeviceContextBase::UpdateSBT(pSBT, pUpdateIndirectBufferAttribs, 0);
auto& CmdCtx = GetCmdContext().AsGraphicsContext();
const char* OpName = "Update shader binding table (DeviceContextD3D12Impl::UpdateSBT)";
auto* pSBTD3D12 = ClassPtrCast<ShaderBindingTableD3D12Impl>(pSBT);
BufferD3D12Impl* pSBTBufferD3D12 = nullptr;
ShaderBindingTableD3D12Impl::BindingTable RayGenShaderRecord = {};
ShaderBindingTableD3D12Impl::BindingTable MissShaderTable = {};
ShaderBindingTableD3D12Impl::BindingTable HitGroupTable = {};
ShaderBindingTableD3D12Impl::BindingTable CallableShaderTable = {};
pSBTD3D12->GetData(pSBTBufferD3D12, RayGenShaderRecord, MissShaderTable, HitGroupTable, CallableShaderTable);
if (RayGenShaderRecord.pData || MissShaderTable.pData || HitGroupTable.pData || CallableShaderTable.pData)
{
TransitionOrVerifyBufferState(CmdCtx, *pSBTBufferD3D12, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, RESOURCE_STATE_COPY_DEST, OpName);
// Buffer ranges do not intersect, so we don't need to add barriers between them
if (RayGenShaderRecord.pData)
UpdateBuffer(pSBTBufferD3D12, RayGenShaderRecord.Offset, RayGenShaderRecord.Size, RayGenShaderRecord.pData, RESOURCE_STATE_TRANSITION_MODE_VERIFY);
if (MissShaderTable.pData)
UpdateBuffer(pSBTBufferD3D12, MissShaderTable.Offset, MissShaderTable.Size, MissShaderTable.pData, RESOURCE_STATE_TRANSITION_MODE_VERIFY);
if (HitGroupTable.pData)
UpdateBuffer(pSBTBufferD3D12, HitGroupTable.Offset, HitGroupTable.Size, HitGroupTable.pData, RESOURCE_STATE_TRANSITION_MODE_VERIFY);
if (CallableShaderTable.pData)
UpdateBuffer(pSBTBufferD3D12, CallableShaderTable.Offset, CallableShaderTable.Size, CallableShaderTable.pData, RESOURCE_STATE_TRANSITION_MODE_VERIFY);
TransitionOrVerifyBufferState(CmdCtx, *pSBTBufferD3D12, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, RESOURCE_STATE_RAY_TRACING, OpName);
}
else
{
// Ray tracing command can be used in parallel with the same SBT, so internal buffer state must be RESOURCE_STATE_RAY_TRACING to allow it.
VERIFY(pSBTBufferD3D12->CheckState(RESOURCE_STATE_RAY_TRACING), "SBT buffer must always be in RESOURCE_STATE_RAY_TRACING state");
}
if (pUpdateIndirectBufferAttribs != nullptr)
{
const auto& d3d12DispatchDesc = pSBTD3D12->GetD3D12BindingTable();
UpdateBuffer(pUpdateIndirectBufferAttribs->pAttribsBuffer,
pUpdateIndirectBufferAttribs->AttribsBufferOffset,
TraceRaysIndirectCommandSBTSize,
&d3d12DispatchDesc,
pUpdateIndirectBufferAttribs->TransitionMode);
}
}
void DeviceContextD3D12Impl::BeginDebugGroup(const Char* Name, const float* pColor)
{
TDeviceContextBase::BeginDebugGroup(Name, pColor, 0);
GetCmdContext().PixBeginEvent(Name, pColor);
}
void DeviceContextD3D12Impl::EndDebugGroup()
{
TDeviceContextBase::EndDebugGroup(0);
GetCmdContext().PixEndEvent();
}
void DeviceContextD3D12Impl::InsertDebugLabel(const Char* Label, const float* pColor)
{
TDeviceContextBase::InsertDebugLabel(Label, pColor, 0);
GetCmdContext().PixSetMarker(Label, pColor);
}
void DeviceContextD3D12Impl::SetShadingRate(SHADING_RATE BaseRate, SHADING_RATE_COMBINER PrimitiveCombiner, SHADING_RATE_COMBINER TextureCombiner)
{
TDeviceContextBase::SetShadingRate(BaseRate, PrimitiveCombiner, TextureCombiner, 0);
const D3D12_SHADING_RATE_COMBINER Combiners[] =
{
ShadingRateCombinerToD3D12ShadingRateCombiner(PrimitiveCombiner),
ShadingRateCombinerToD3D12ShadingRateCombiner(TextureCombiner) //
};
GetCmdContext().AsGraphicsContext5().SetShadingRate(ShadingRateToD3D12ShadingRate(BaseRate), Combiners);
m_State.bUsingShadingRate = !(BaseRate == SHADING_RATE_1X1 && PrimitiveCombiner == SHADING_RATE_COMBINER_PASSTHROUGH && TextureCombiner == SHADING_RATE_COMBINER_PASSTHROUGH);
}
namespace
{
struct TileMappingKey
{
ID3D12Resource* const pResource;
ID3D12Heap* const pHeap;
bool operator==(const TileMappingKey& Rhs) const noexcept
{
return pResource == Rhs.pResource && pHeap == Rhs.pHeap;
}
struct Hasher
{
size_t operator()(const TileMappingKey& Key) const noexcept
{
return ComputeHash(Key.pResource, Key.pHeap);
}
};
};
} // namespace
void DeviceContextD3D12Impl::BindSparseResourceMemory(const BindSparseResourceMemoryAttribs& Attribs)
{
TDeviceContextBase::BindSparseResourceMemory(Attribs, 0);
VERIFY_EXPR(Attribs.NumBufferBinds != 0 || Attribs.NumTextureBinds != 0);
Flush();
std::unordered_map<TileMappingKey, D3D12TileMappingHelper, TileMappingKey::Hasher> TileMappingMap;
for (Uint32 i = 0; i < Attribs.NumBufferBinds; ++i)
{
const auto& BuffBind = Attribs.pBufferBinds[i];
auto* pd3d12Buff = ClassPtrCast<const BufferD3D12Impl>(BuffBind.pBuffer)->GetD3D12Resource();
for (Uint32 r = 0; r < BuffBind.NumRanges; ++r)
{
const auto& BindRange = BuffBind.pRanges[r];
const auto pMemD3D12 = RefCntAutoPtr<IDeviceMemoryD3D12>{BindRange.pMemory, IID_DeviceMemoryD3D12};
DEV_CHECK_ERR((BindRange.pMemory != nullptr) == (pMemD3D12 != nullptr),
"Failed to query IDeviceMemoryD3D12 interface from non-null memory object");
const auto MemRange = pMemD3D12 ? pMemD3D12->GetRange(BindRange.MemoryOffset, BindRange.MemorySize) : DeviceMemoryRangeD3D12{};
DEV_CHECK_ERR((MemRange.Offset % D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES) == 0,
"MemoryOffset must be a multiple of sparse block size");
auto& DstMapping = TileMappingMap[TileMappingKey{pd3d12Buff, MemRange.pHandle}];
DstMapping.AddBufferBindRange(BindRange, MemRange.Offset);
}
}
for (Uint32 i = 0; i < Attribs.NumTextureBinds; ++i)
{
const auto& TexBind = Attribs.pTextureBinds[i];
const auto* pTexD3D12 = ClassPtrCast<const TextureD3D12Impl>(TexBind.pTexture);
const auto& TexSparseProps = pTexD3D12->GetSparseProperties();
const auto& TexDesc = pTexD3D12->GetDesc();
const auto UseNVApi = pTexD3D12->IsUsingNVApi();
for (Uint32 r = 0; r < TexBind.NumRanges; ++r)
{
const auto& BindRange = TexBind.pRanges[r];
const auto pMemD3D12 = RefCntAutoPtr<IDeviceMemoryD3D12>{BindRange.pMemory, IID_DeviceMemoryD3D12};
DEV_CHECK_ERR((BindRange.pMemory != nullptr) == (pMemD3D12 != nullptr),
"Failed to query IDeviceMemoryD3D12 interface from non-null memory object");
const auto MemRange = pMemD3D12 ? pMemD3D12->GetRange(BindRange.MemoryOffset, BindRange.MemorySize) : DeviceMemoryRangeD3D12{};
DEV_CHECK_ERR((MemRange.Offset % D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES) == 0,
"MemoryOffset must be a multiple of sparse block size");
VERIFY_EXPR(pMemD3D12 == nullptr || pMemD3D12->IsUsingNVApi() == UseNVApi);
auto& DstMapping = TileMappingMap[TileMappingKey{pTexD3D12->GetD3D12Resource(), MemRange.pHandle}];
DstMapping.AddTextureBindRange(BindRange, TexSparseProps, TexDesc, UseNVApi, MemRange.Offset);
}
}
auto* pQueueD3D12 = LockCommandQueue();
for (Uint32 i = 0; i < Attribs.NumWaitFences; ++i)
{
auto* pFenceD3D12 = ClassPtrCast<FenceD3D12Impl>(Attribs.ppWaitFences[i]);
DEV_CHECK_ERR(pFenceD3D12 != nullptr, "Wait fence must not be null");
auto Value = Attribs.pWaitFenceValues[i];
pQueueD3D12->WaitFence(pFenceD3D12->GetD3D12Fence(), Value);
pFenceD3D12->DvpDeviceWait(Value);
}
std::vector<ResourceTileMappingsD3D12> TileMappings;
TileMappings.reserve(TileMappingMap.size());
for (const auto& it : TileMappingMap)
{
TileMappings.emplace_back(it.second.GetMappings(it.first.pResource, it.first.pHeap));
}
pQueueD3D12->UpdateTileMappings(TileMappings.data(), static_cast<Uint32>(TileMappings.size()));
for (Uint32 i = 0; i < Attribs.NumSignalFences; ++i)
{
auto* pFenceD3D12 = ClassPtrCast<FenceD3D12Impl>(Attribs.ppSignalFences[i]);
DEV_CHECK_ERR(pFenceD3D12 != nullptr, "Signal fence must not be null");
auto Value = Attribs.pSignalFenceValues[i];
pQueueD3D12->EnqueueSignal(pFenceD3D12->GetD3D12Fence(), Value);
pFenceD3D12->DvpSignal(Value);
}
UnlockCommandQueue();
}
} // namespace Diligent
| apache-2.0 |
apple/swift-lldb | source/Host/common/Editline.cpp | 1 | 51492 | //===-- Editline.cpp --------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <iomanip>
#include <iostream>
#include <limits.h>
#include "lldb/Host/ConnectionFileDescriptor.h"
#include "lldb/Host/Editline.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/Host.h"
#include "lldb/Utility/CompletionRequest.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/SelectHelper.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/StringList.h"
#include "lldb/Utility/Timeout.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Threading.h"
using namespace lldb_private;
using namespace lldb_private::line_editor;
// Workaround for what looks like an OS X-specific issue, but other platforms
// may benefit from something similar if issues arise. The libedit library
// doesn't explicitly initialize the curses termcap library, which it gets away
// with until TERM is set to VT100 where it stumbles over an implementation
// assumption that may not exist on other platforms. The setupterm() function
// would normally require headers that don't work gracefully in this context,
// so the function declaraction has been hoisted here.
#if defined(__APPLE__)
extern "C" {
int setupterm(char *term, int fildes, int *errret);
}
#define USE_SETUPTERM_WORKAROUND
#endif
// Editline uses careful cursor management to achieve the illusion of editing a
// multi-line block of text with a single line editor. Preserving this
// illusion requires fairly careful management of cursor state. Read and
// understand the relationship between DisplayInput(), MoveCursor(),
// SetCurrentLine(), and SaveEditedLine() before making changes.
#define ESCAPE "\x1b"
#define ANSI_FAINT ESCAPE "[2m"
#define ANSI_UNFAINT ESCAPE "[22m"
#define ANSI_CLEAR_BELOW ESCAPE "[J"
#define ANSI_CLEAR_RIGHT ESCAPE "[K"
#define ANSI_SET_COLUMN_N ESCAPE "[%dG"
#define ANSI_UP_N_ROWS ESCAPE "[%dA"
#define ANSI_DOWN_N_ROWS ESCAPE "[%dB"
#if LLDB_EDITLINE_USE_WCHAR
#define EditLineConstString(str) L##str
#define EditLineStringFormatSpec "%ls"
#else
#define EditLineConstString(str) str
#define EditLineStringFormatSpec "%s"
// use #defines so wide version functions and structs will resolve to old
// versions for case of libedit not built with wide char support
#define history_w history
#define history_winit history_init
#define history_wend history_end
#define HistoryW History
#define HistEventW HistEvent
#define LineInfoW LineInfo
#define el_wgets el_gets
#define el_wgetc el_getc
#define el_wpush el_push
#define el_wparse el_parse
#define el_wset el_set
#define el_wget el_get
#define el_wline el_line
#define el_winsertstr el_insertstr
#define el_wdeletestr el_deletestr
#endif // #if LLDB_EDITLINE_USE_WCHAR
bool IsOnlySpaces(const EditLineStringType &content) {
for (wchar_t ch : content) {
if (ch != EditLineCharType(' '))
return false;
}
return true;
}
EditLineStringType CombineLines(const std::vector<EditLineStringType> &lines) {
EditLineStringStreamType combined_stream;
for (EditLineStringType line : lines) {
combined_stream << line.c_str() << "\n";
}
return combined_stream.str();
}
std::vector<EditLineStringType> SplitLines(const EditLineStringType &input) {
std::vector<EditLineStringType> result;
size_t start = 0;
while (start < input.length()) {
size_t end = input.find('\n', start);
if (end == std::string::npos) {
result.insert(result.end(), input.substr(start));
break;
}
result.insert(result.end(), input.substr(start, end - start));
start = end + 1;
}
return result;
}
EditLineStringType FixIndentation(const EditLineStringType &line,
int indent_correction) {
if (indent_correction == 0)
return line;
if (indent_correction < 0)
return line.substr(-indent_correction);
return EditLineStringType(indent_correction, EditLineCharType(' ')) + line;
}
int GetIndentation(const EditLineStringType &line) {
int space_count = 0;
for (EditLineCharType ch : line) {
if (ch != EditLineCharType(' '))
break;
++space_count;
}
return space_count;
}
bool IsInputPending(FILE *file) {
// FIXME: This will be broken on Windows if we ever re-enable Editline. You
// can't use select
// on something that isn't a socket. This will have to be re-written to not
// use a FILE*, but instead use some kind of yet-to-be-created abstraction
// that select-like functionality on non-socket objects.
const int fd = fileno(file);
SelectHelper select_helper;
select_helper.SetTimeout(std::chrono::microseconds(0));
select_helper.FDSetRead(fd);
return select_helper.Select().Success();
}
namespace lldb_private {
namespace line_editor {
typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
// EditlineHistory objects are sometimes shared between multiple Editline
// instances with the same program name.
class EditlineHistory {
private:
// Use static GetHistory() function to get a EditlineHistorySP to one of
// these objects
EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
: m_history(nullptr), m_event(), m_prefix(prefix), m_path() {
m_history = history_winit();
history_w(m_history, &m_event, H_SETSIZE, size);
if (unique_entries)
history_w(m_history, &m_event, H_SETUNIQUE, 1);
}
const char *GetHistoryFilePath() {
// Compute the history path lazily.
if (m_path.empty() && m_history && !m_prefix.empty()) {
llvm::SmallString<128> lldb_history_file;
llvm::sys::path::home_directory(lldb_history_file);
llvm::sys::path::append(lldb_history_file, ".lldb");
// LLDB stores its history in ~/.lldb/. If for some reason this directory
// isn't writable or cannot be created, history won't be available.
if (!llvm::sys::fs::create_directory(lldb_history_file)) {
#if LLDB_EDITLINE_USE_WCHAR
std::string filename = m_prefix + "-widehistory";
#else
std::string filename = m_prefix + "-history";
#endif
llvm::sys::path::append(lldb_history_file, filename);
m_path = lldb_history_file.str();
}
}
if (m_path.empty())
return nullptr;
return m_path.c_str();
}
public:
~EditlineHistory() {
Save();
if (m_history) {
history_wend(m_history);
m_history = nullptr;
}
}
static EditlineHistorySP GetHistory(const std::string &prefix) {
typedef std::map<std::string, EditlineHistoryWP> WeakHistoryMap;
static std::recursive_mutex g_mutex;
static WeakHistoryMap g_weak_map;
std::lock_guard<std::recursive_mutex> guard(g_mutex);
WeakHistoryMap::const_iterator pos = g_weak_map.find(prefix);
EditlineHistorySP history_sp;
if (pos != g_weak_map.end()) {
history_sp = pos->second.lock();
if (history_sp)
return history_sp;
g_weak_map.erase(pos);
}
history_sp.reset(new EditlineHistory(prefix, 800, true));
g_weak_map[prefix] = history_sp;
return history_sp;
}
bool IsValid() const { return m_history != nullptr; }
HistoryW *GetHistoryPtr() { return m_history; }
void Enter(const EditLineCharType *line_cstr) {
if (m_history)
history_w(m_history, &m_event, H_ENTER, line_cstr);
}
bool Load() {
if (m_history) {
const char *path = GetHistoryFilePath();
if (path) {
history_w(m_history, &m_event, H_LOAD, path);
return true;
}
}
return false;
}
bool Save() {
if (m_history) {
const char *path = GetHistoryFilePath();
if (path) {
history_w(m_history, &m_event, H_SAVE, path);
return true;
}
}
return false;
}
protected:
HistoryW *m_history; // The history object
HistEventW m_event; // The history event needed to contain all history events
std::string m_prefix; // The prefix name (usually the editline program name)
// to use when loading/saving history
std::string m_path; // Path to the history file
};
}
}
// Editline private methods
void Editline::SetBaseLineNumber(int line_number) {
std::stringstream line_number_stream;
line_number_stream << line_number;
m_base_line_number = line_number;
m_line_number_digits =
std::max(3, (int)line_number_stream.str().length() + 1);
}
std::string Editline::PromptForIndex(int line_index) {
bool use_line_numbers = m_multiline_enabled && m_base_line_number > 0;
std::string prompt = m_set_prompt;
if (use_line_numbers && prompt.length() == 0) {
prompt = ": ";
}
std::string continuation_prompt = prompt;
if (m_set_continuation_prompt.length() > 0) {
continuation_prompt = m_set_continuation_prompt;
// Ensure that both prompts are the same length through space padding
while (continuation_prompt.length() < prompt.length()) {
continuation_prompt += ' ';
}
while (prompt.length() < continuation_prompt.length()) {
prompt += ' ';
}
}
if (use_line_numbers) {
StreamString prompt_stream;
prompt_stream.Printf(
"%*d%s", m_line_number_digits, m_base_line_number + line_index,
(line_index == 0) ? prompt.c_str() : continuation_prompt.c_str());
return std::move(prompt_stream.GetString());
}
return (line_index == 0) ? prompt : continuation_prompt;
}
void Editline::SetCurrentLine(int line_index) {
m_current_line_index = line_index;
m_current_prompt = PromptForIndex(line_index);
}
int Editline::GetPromptWidth() { return (int)PromptForIndex(0).length(); }
bool Editline::IsEmacs() {
const char *editor;
el_get(m_editline, EL_EDITOR, &editor);
return editor[0] == 'e';
}
bool Editline::IsOnlySpaces() {
const LineInfoW *info = el_wline(m_editline);
for (const EditLineCharType *character = info->buffer;
character < info->lastchar; character++) {
if (*character != ' ')
return false;
}
return true;
}
int Editline::GetLineIndexForLocation(CursorLocation location, int cursor_row) {
int line = 0;
if (location == CursorLocation::EditingPrompt ||
location == CursorLocation::BlockEnd ||
location == CursorLocation::EditingCursor) {
for (unsigned index = 0; index < m_current_line_index; index++) {
line += CountRowsForLine(m_input_lines[index]);
}
if (location == CursorLocation::EditingCursor) {
line += cursor_row;
} else if (location == CursorLocation::BlockEnd) {
for (unsigned index = m_current_line_index; index < m_input_lines.size();
index++) {
line += CountRowsForLine(m_input_lines[index]);
}
--line;
}
}
return line;
}
void Editline::MoveCursor(CursorLocation from, CursorLocation to) {
const LineInfoW *info = el_wline(m_editline);
int editline_cursor_position =
(int)((info->cursor - info->buffer) + GetPromptWidth());
int editline_cursor_row = editline_cursor_position / m_terminal_width;
// Determine relative starting and ending lines
int fromLine = GetLineIndexForLocation(from, editline_cursor_row);
int toLine = GetLineIndexForLocation(to, editline_cursor_row);
if (toLine != fromLine) {
fprintf(m_output_file,
(toLine > fromLine) ? ANSI_DOWN_N_ROWS : ANSI_UP_N_ROWS,
std::abs(toLine - fromLine));
}
// Determine target column
int toColumn = 1;
if (to == CursorLocation::EditingCursor) {
toColumn =
editline_cursor_position - (editline_cursor_row * m_terminal_width) + 1;
} else if (to == CursorLocation::BlockEnd && !m_input_lines.empty()) {
toColumn =
((m_input_lines[m_input_lines.size() - 1].length() + GetPromptWidth()) %
80) +
1;
}
fprintf(m_output_file, ANSI_SET_COLUMN_N, toColumn);
}
void Editline::DisplayInput(int firstIndex) {
fprintf(m_output_file, ANSI_SET_COLUMN_N ANSI_CLEAR_BELOW, 1);
int line_count = (int)m_input_lines.size();
const char *faint = m_color_prompts ? ANSI_FAINT : "";
const char *unfaint = m_color_prompts ? ANSI_UNFAINT : "";
for (int index = firstIndex; index < line_count; index++) {
fprintf(m_output_file, "%s"
"%s"
"%s" EditLineStringFormatSpec " ",
faint, PromptForIndex(index).c_str(), unfaint,
m_input_lines[index].c_str());
if (index < line_count - 1)
fprintf(m_output_file, "\n");
}
}
int Editline::CountRowsForLine(const EditLineStringType &content) {
auto prompt =
PromptForIndex(0); // Prompt width is constant during an edit session
int line_length = (int)(content.length() + prompt.length());
return (line_length / m_terminal_width) + 1;
}
void Editline::SaveEditedLine() {
const LineInfoW *info = el_wline(m_editline);
m_input_lines[m_current_line_index] =
EditLineStringType(info->buffer, info->lastchar - info->buffer);
}
StringList Editline::GetInputAsStringList(int line_count) {
StringList lines;
for (EditLineStringType line : m_input_lines) {
if (line_count == 0)
break;
#if LLDB_EDITLINE_USE_WCHAR
lines.AppendString(m_utf8conv.to_bytes(line));
#else
lines.AppendString(line);
#endif
--line_count;
}
return lines;
}
unsigned char Editline::RecallHistory(bool earlier) {
if (!m_history_sp || !m_history_sp->IsValid())
return CC_ERROR;
HistoryW *pHistory = m_history_sp->GetHistoryPtr();
HistEventW history_event;
std::vector<EditLineStringType> new_input_lines;
// Treat moving from the "live" entry differently
if (!m_in_history) {
if (!earlier)
return CC_ERROR; // Can't go newer than the "live" entry
if (history_w(pHistory, &history_event, H_FIRST) == -1)
return CC_ERROR;
// Save any edits to the "live" entry in case we return by moving forward
// in history (it would be more bash-like to save over any current entry,
// but libedit doesn't offer the ability to add entries anywhere except the
// end.)
SaveEditedLine();
m_live_history_lines = m_input_lines;
m_in_history = true;
} else {
if (history_w(pHistory, &history_event, earlier ? H_PREV : H_NEXT) == -1) {
// Can't move earlier than the earliest entry
if (earlier)
return CC_ERROR;
// ... but moving to newer than the newest yields the "live" entry
new_input_lines = m_live_history_lines;
m_in_history = false;
}
}
// If we're pulling the lines from history, split them apart
if (m_in_history)
new_input_lines = SplitLines(history_event.str);
// Erase the current edit session and replace it with a new one
MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
m_input_lines = new_input_lines;
DisplayInput();
// Prepare to edit the last line when moving to previous entry, or the first
// line when moving to next entry
SetCurrentLine(m_current_line_index =
earlier ? (int)m_input_lines.size() - 1 : 0);
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
return CC_NEWLINE;
}
int Editline::GetCharacter(EditLineGetCharType *c) {
const LineInfoW *info = el_wline(m_editline);
// Paint a faint version of the desired prompt over the version libedit draws
// (will only be requested if colors are supported)
if (m_needs_prompt_repaint) {
MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
fprintf(m_output_file, "%s"
"%s"
"%s",
ANSI_FAINT, Prompt(), ANSI_UNFAINT);
MoveCursor(CursorLocation::EditingPrompt, CursorLocation::EditingCursor);
m_needs_prompt_repaint = false;
}
if (m_multiline_enabled) {
// Detect when the number of rows used for this input line changes due to
// an edit
int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
int new_line_rows = (lineLength / m_terminal_width) + 1;
if (m_current_line_rows != -1 && new_line_rows != m_current_line_rows) {
// Respond by repainting the current state from this line on
MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
SaveEditedLine();
DisplayInput(m_current_line_index);
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
}
m_current_line_rows = new_line_rows;
}
// Read an actual character
while (true) {
lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
char ch = 0;
// This mutex is locked by our caller (GetLine). Unlock it while we read a
// character (blocking operation), so we do not hold the mutex
// indefinitely. This gives a chance for someone to interrupt us. After
// Read returns, immediately lock the mutex again and check if we were
// interrupted.
m_output_mutex.unlock();
int read_count =
m_input_connection.Read(&ch, 1, llvm::None, status, nullptr);
m_output_mutex.lock();
if (m_editor_status == EditorStatus::Interrupted) {
while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
read_count =
m_input_connection.Read(&ch, 1, llvm::None, status, nullptr);
lldbassert(status == lldb::eConnectionStatusInterrupted);
return 0;
}
if (read_count) {
if (CompleteCharacter(ch, *c))
return 1;
} else {
switch (status) {
case lldb::eConnectionStatusSuccess: // Success
break;
case lldb::eConnectionStatusInterrupted:
llvm_unreachable("Interrupts should have been handled above.");
case lldb::eConnectionStatusError: // Check GetError() for details
case lldb::eConnectionStatusTimedOut: // Request timed out
case lldb::eConnectionStatusEndOfFile: // End-of-file encountered
case lldb::eConnectionStatusNoConnection: // No connection
case lldb::eConnectionStatusLostConnection: // Lost connection while
// connected to a valid
// connection
m_editor_status = EditorStatus::EndOfInput;
return 0;
}
}
}
}
const char *Editline::Prompt() {
if (m_color_prompts)
m_needs_prompt_repaint = true;
return m_current_prompt.c_str();
}
unsigned char Editline::BreakLineCommand(int ch) {
// Preserve any content beyond the cursor, truncate and save the current line
const LineInfoW *info = el_wline(m_editline);
auto current_line =
EditLineStringType(info->buffer, info->cursor - info->buffer);
auto new_line_fragment =
EditLineStringType(info->cursor, info->lastchar - info->cursor);
m_input_lines[m_current_line_index] = current_line;
// Ignore whitespace-only extra fragments when breaking a line
if (::IsOnlySpaces(new_line_fragment))
new_line_fragment = EditLineConstString("");
// Establish the new cursor position at the start of a line when inserting a
// line break
m_revert_cursor_index = 0;
// Don't perform automatic formatting when pasting
if (!IsInputPending(m_input_file)) {
// Apply smart indentation
if (m_fix_indentation_callback) {
StringList lines = GetInputAsStringList(m_current_line_index + 1);
#if LLDB_EDITLINE_USE_WCHAR
lines.AppendString(m_utf8conv.to_bytes(new_line_fragment));
#else
lines.AppendString(new_line_fragment);
#endif
int indent_correction = m_fix_indentation_callback(
this, lines, 0, m_fix_indentation_callback_baton);
new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
m_revert_cursor_index = GetIndentation(new_line_fragment);
}
}
// Insert the new line and repaint everything from the split line on down
m_input_lines.insert(m_input_lines.begin() + m_current_line_index + 1,
new_line_fragment);
MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
DisplayInput(m_current_line_index);
// Reposition the cursor to the right line and prepare to edit the new line
SetCurrentLine(m_current_line_index + 1);
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
return CC_NEWLINE;
}
unsigned char Editline::EndOrAddLineCommand(int ch) {
// Don't perform end of input detection when pasting, always treat this as a
// line break
if (IsInputPending(m_input_file)) {
return BreakLineCommand(ch);
}
// Save any edits to this line
SaveEditedLine();
// If this is the end of the last line, consider whether to add a line
// instead
const LineInfoW *info = el_wline(m_editline);
if (m_current_line_index == m_input_lines.size() - 1 &&
info->cursor == info->lastchar) {
if (m_is_input_complete_callback) {
auto lines = GetInputAsStringList();
if (!m_is_input_complete_callback(this, lines,
m_is_input_complete_callback_baton)) {
return BreakLineCommand(ch);
}
// The completion test is allowed to change the input lines when complete
m_input_lines.clear();
for (unsigned index = 0; index < lines.GetSize(); index++) {
#if LLDB_EDITLINE_USE_WCHAR
m_input_lines.insert(m_input_lines.end(),
m_utf8conv.from_bytes(lines[index]));
#else
m_input_lines.insert(m_input_lines.end(), lines[index]);
#endif
}
}
}
MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
fprintf(m_output_file, "\n");
m_editor_status = EditorStatus::Complete;
return CC_NEWLINE;
}
unsigned char Editline::DeleteNextCharCommand(int ch) {
LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
// Just delete the next character normally if possible
if (info->cursor < info->lastchar) {
info->cursor++;
el_deletestr(m_editline, 1);
return CC_REFRESH;
}
// Fail when at the end of the last line, except when ^D is pressed on the
// line is empty, in which case it is treated as EOF
if (m_current_line_index == m_input_lines.size() - 1) {
if (ch == 4 && info->buffer == info->lastchar) {
fprintf(m_output_file, "^D\n");
m_editor_status = EditorStatus::EndOfInput;
return CC_EOF;
}
return CC_ERROR;
}
// Prepare to combine this line with the one below
MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
// Insert the next line of text at the cursor and restore the cursor position
const EditLineCharType *cursor = info->cursor;
el_winsertstr(m_editline, m_input_lines[m_current_line_index + 1].c_str());
info->cursor = cursor;
SaveEditedLine();
// Delete the extra line
m_input_lines.erase(m_input_lines.begin() + m_current_line_index + 1);
// Clear and repaint from this line on down
DisplayInput(m_current_line_index);
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
return CC_REFRESH;
}
unsigned char Editline::DeletePreviousCharCommand(int ch) {
LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
// Just delete the previous character normally when not at the start of a
// line
if (info->cursor > info->buffer) {
el_deletestr(m_editline, 1);
return CC_REFRESH;
}
// No prior line and no prior character? Let the user know
if (m_current_line_index == 0)
return CC_ERROR;
// No prior character, but prior line? Combine with the line above
SaveEditedLine();
SetCurrentLine(m_current_line_index - 1);
auto priorLine = m_input_lines[m_current_line_index];
m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
m_input_lines[m_current_line_index] =
priorLine + m_input_lines[m_current_line_index];
// Repaint from the new line down
fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
CountRowsForLine(priorLine), 1);
DisplayInput(m_current_line_index);
// Put the cursor back where libedit expects it to be before returning to
// editing by telling libedit about the newly inserted text
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
el_winsertstr(m_editline, priorLine.c_str());
return CC_REDISPLAY;
}
unsigned char Editline::PreviousLineCommand(int ch) {
SaveEditedLine();
if (m_current_line_index == 0) {
return RecallHistory(true);
}
// Start from a known location
MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
// Treat moving up from a blank last line as a deletion of that line
if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
fprintf(m_output_file, ANSI_CLEAR_BELOW);
}
SetCurrentLine(m_current_line_index - 1);
fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
CountRowsForLine(m_input_lines[m_current_line_index]), 1);
return CC_NEWLINE;
}
unsigned char Editline::NextLineCommand(int ch) {
SaveEditedLine();
// Handle attempts to move down from the last line
if (m_current_line_index == m_input_lines.size() - 1) {
// Don't add an extra line if the existing last line is blank, move through
// history instead
if (IsOnlySpaces()) {
return RecallHistory(false);
}
// Determine indentation for the new line
int indentation = 0;
if (m_fix_indentation_callback) {
StringList lines = GetInputAsStringList();
lines.AppendString("");
indentation = m_fix_indentation_callback(
this, lines, 0, m_fix_indentation_callback_baton);
}
m_input_lines.insert(
m_input_lines.end(),
EditLineStringType(indentation, EditLineCharType(' ')));
}
// Move down past the current line using newlines to force scrolling if
// needed
SetCurrentLine(m_current_line_index + 1);
const LineInfoW *info = el_wline(m_editline);
int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
int cursor_row = cursor_position / m_terminal_width;
for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
line_count++) {
fprintf(m_output_file, "\n");
}
return CC_NEWLINE;
}
unsigned char Editline::PreviousHistoryCommand(int ch) {
SaveEditedLine();
return RecallHistory(true);
}
unsigned char Editline::NextHistoryCommand(int ch) {
SaveEditedLine();
return RecallHistory(false);
}
unsigned char Editline::FixIndentationCommand(int ch) {
if (!m_fix_indentation_callback)
return CC_NORM;
// Insert the character typed before proceeding
EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
el_winsertstr(m_editline, inserted);
LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
int cursor_position = info->cursor - info->buffer;
// Save the edits and determine the correct indentation level
SaveEditedLine();
StringList lines = GetInputAsStringList(m_current_line_index + 1);
int indent_correction = m_fix_indentation_callback(
this, lines, cursor_position, m_fix_indentation_callback_baton);
// If it is already correct no special work is needed
if (indent_correction == 0)
return CC_REFRESH;
// Change the indentation level of the line
std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
if (indent_correction > 0) {
currentLine = currentLine.insert(0, indent_correction, ' ');
} else {
currentLine = currentLine.erase(0, -indent_correction);
}
#if LLDB_EDITLINE_USE_WCHAR
m_input_lines[m_current_line_index] = m_utf8conv.from_bytes(currentLine);
#else
m_input_lines[m_current_line_index] = currentLine;
#endif
// Update the display to reflect the change
MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
DisplayInput(m_current_line_index);
// Reposition the cursor back on the original line and prepare to restart
// editing with a new cursor position
SetCurrentLine(m_current_line_index);
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
m_revert_cursor_index = cursor_position + indent_correction;
return CC_NEWLINE;
}
unsigned char Editline::RevertLineCommand(int ch) {
el_winsertstr(m_editline, m_input_lines[m_current_line_index].c_str());
if (m_revert_cursor_index >= 0) {
LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
info->cursor = info->buffer + m_revert_cursor_index;
if (info->cursor > info->lastchar) {
info->cursor = info->lastchar;
}
m_revert_cursor_index = -1;
}
return CC_REFRESH;
}
unsigned char Editline::BufferStartCommand(int ch) {
SaveEditedLine();
MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
SetCurrentLine(0);
m_revert_cursor_index = 0;
return CC_NEWLINE;
}
unsigned char Editline::BufferEndCommand(int ch) {
SaveEditedLine();
MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
SetCurrentLine((int)m_input_lines.size() - 1);
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
return CC_NEWLINE;
}
/// Prints completions and their descriptions to the given file. Only the
/// completions in the interval [start, end) are printed.
static void
PrintCompletion(FILE *output_file,
llvm::ArrayRef<CompletionResult::Completion> results,
size_t max_len) {
for (const CompletionResult::Completion &c : results) {
fprintf(output_file, "\t%-*s", (int)max_len, c.GetCompletion().c_str());
if (!c.GetDescription().empty())
fprintf(output_file, " -- %s", c.GetDescription().c_str());
fprintf(output_file, "\n");
}
}
static void
DisplayCompletions(::EditLine *editline, FILE *output_file,
llvm::ArrayRef<CompletionResult::Completion> results) {
assert(!results.empty());
fprintf(output_file, "\n" ANSI_CLEAR_BELOW "Available completions:\n");
const size_t page_size = 40;
bool all = false;
auto longest =
std::max_element(results.begin(), results.end(), [](auto &c1, auto &c2) {
return c1.GetCompletion().size() < c2.GetCompletion().size();
});
const size_t max_len = longest->GetCompletion().size();
if (results.size() < page_size) {
PrintCompletion(output_file, results, max_len);
return;
}
size_t cur_pos = 0;
while (cur_pos < results.size()) {
size_t remaining = results.size() - cur_pos;
size_t next_size = all ? remaining : std::min(page_size, remaining);
PrintCompletion(output_file, results.slice(cur_pos, next_size), max_len);
cur_pos += next_size;
if (cur_pos >= results.size())
break;
fprintf(output_file, "More (Y/n/a): ");
char reply = 'n';
int got_char = el_getc(editline, &reply);
fprintf(output_file, "\n");
if (got_char == -1 || reply == 'n')
break;
if (reply == 'a')
all = true;
}
}
unsigned char Editline::TabCommand(int ch) {
if (m_completion_callback == nullptr)
return CC_ERROR;
const LineInfo *line_info = el_line(m_editline);
llvm::StringRef line(line_info->buffer,
line_info->lastchar - line_info->buffer);
unsigned cursor_index = line_info->cursor - line_info->buffer;
CompletionResult result;
CompletionRequest request(line, cursor_index, result);
m_completion_callback(request, m_completion_callback_baton);
llvm::ArrayRef<CompletionResult::Completion> results = result.GetResults();
StringList completions;
result.GetMatches(completions);
if (results.size() == 0)
return CC_ERROR;
if (results.size() == 1) {
CompletionResult::Completion completion = results.front();
switch (completion.GetMode()) {
case CompletionMode::Normal: {
std::string to_add = completion.GetCompletion();
to_add = to_add.substr(request.GetCursorArgumentPrefix().size());
if (request.GetParsedArg().IsQuoted())
to_add.push_back(request.GetParsedArg().quote);
to_add.push_back(' ');
el_insertstr(m_editline, to_add.c_str());
break;
}
case CompletionMode::Partial: {
std::string to_add = completion.GetCompletion();
to_add = to_add.substr(request.GetCursorArgumentPrefix().size());
el_insertstr(m_editline, to_add.c_str());
break;
}
case CompletionMode::RewriteLine: {
el_deletestr(m_editline, line_info->cursor - line_info->buffer);
el_insertstr(m_editline, completion.GetCompletion().c_str());
break;
}
}
return CC_REDISPLAY;
}
// If we get a longer match display that first.
std::string longest_prefix = completions.LongestCommonPrefix();
if (!longest_prefix.empty())
longest_prefix =
longest_prefix.substr(request.GetCursorArgumentPrefix().size());
if (!longest_prefix.empty()) {
el_insertstr(m_editline, longest_prefix.c_str());
return CC_REDISPLAY;
}
DisplayCompletions(m_editline, m_output_file, results);
DisplayInput();
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
return CC_REDISPLAY;
}
void Editline::ConfigureEditor(bool multiline) {
if (m_editline && m_multiline_enabled == multiline)
return;
m_multiline_enabled = multiline;
if (m_editline) {
// Disable edit mode to stop the terminal from flushing all input during
// the call to el_end() since we expect to have multiple editline instances
// in this program.
el_set(m_editline, EL_EDITMODE, 0);
el_end(m_editline);
}
m_editline =
el_init(m_editor_name.c_str(), m_input_file, m_output_file, m_error_file);
TerminalSizeChanged();
if (m_history_sp && m_history_sp->IsValid()) {
if (!m_history_sp->Load()) {
fputs("Could not load history file\n.", m_output_file);
}
el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
}
el_set(m_editline, EL_CLIENTDATA, this);
el_set(m_editline, EL_SIGNAL, 0);
el_set(m_editline, EL_EDITOR, "emacs");
el_set(m_editline, EL_PROMPT,
(EditlinePromptCallbackType)([](EditLine *editline) {
return Editline::InstanceFor(editline)->Prompt();
}));
el_wset(m_editline, EL_GETCFN, (EditlineGetCharCallbackType)([](
EditLine *editline, EditLineGetCharType *c) {
return Editline::InstanceFor(editline)->GetCharacter(c);
}));
// Commands used for multiline support, registered whether or not they're
// used
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-break-line"),
EditLineConstString("Insert a line break"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->BreakLineCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-end-or-add-line"),
EditLineConstString("End editing or continue when incomplete"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-next-char"),
EditLineConstString("Delete next character"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
}));
el_wset(
m_editline, EL_ADDFN, EditLineConstString("lldb-delete-previous-char"),
EditLineConstString("Delete previous character"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-line"),
EditLineConstString("Move to previous line"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-line"),
EditLineConstString("Move to next line"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->NextLineCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-history"),
EditLineConstString("Move to previous history"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-history"),
EditLineConstString("Move to next history"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-start"),
EditLineConstString("Move to start of buffer"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->BufferStartCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-end"),
EditLineConstString("Move to end of buffer"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->BufferEndCommand(ch);
}));
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-fix-indentation"),
EditLineConstString("Fix line indentation"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
}));
// Register the complete callback under two names for compatibility with
// older clients using custom .editrc files (largely because libedit has a
// bad bug where if you have a bind command that tries to bind to a function
// name that doesn't exist, it can corrupt the heap and crash your process
// later.)
EditlineCommandCallbackType complete_callback = [](EditLine *editline,
int ch) {
return Editline::InstanceFor(editline)->TabCommand(ch);
};
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-complete"),
EditLineConstString("Invoke completion"), complete_callback);
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb_complete"),
EditLineConstString("Invoke completion"), complete_callback);
// General bindings we don't mind being overridden
if (!multiline) {
el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
NULL); // Cycle through backwards search, entering string
}
el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
NULL); // Delete previous word, behave like bash in emacs mode
el_set(m_editline, EL_BIND, "\t", "lldb-complete",
NULL); // Bind TAB to auto complete
// Allow user-specific customization prior to registering bindings we
// absolutely require
el_source(m_editline, nullptr);
// Register an internal binding that external developers shouldn't use
el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-revert-line"),
EditLineConstString("Revert line to saved state"),
(EditlineCommandCallbackType)([](EditLine *editline, int ch) {
return Editline::InstanceFor(editline)->RevertLineCommand(ch);
}));
// Register keys that perform auto-indent correction
if (m_fix_indentation_callback && m_fix_indentation_callback_chars) {
char bind_key[2] = {0, 0};
const char *indent_chars = m_fix_indentation_callback_chars;
while (*indent_chars) {
bind_key[0] = *indent_chars;
el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
++indent_chars;
}
}
// Multi-line editor bindings
if (multiline) {
el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
// Editor-specific bindings
if (IsEmacs()) {
el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
NULL);
el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
NULL);
el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
NULL);
el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
} else {
el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
NULL);
el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
NULL);
el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
NULL);
// Escape is absorbed exiting edit mode, so re-register important
// sequences without the prefix
el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
}
}
}
// Editline public methods
Editline *Editline::InstanceFor(EditLine *editline) {
Editline *editor;
el_get(editline, EL_CLIENTDATA, &editor);
return editor;
}
Editline::Editline(const char *editline_name, FILE *input_file,
FILE *output_file, FILE *error_file, bool color_prompts)
: m_editor_status(EditorStatus::Complete), m_color_prompts(color_prompts),
m_input_file(input_file), m_output_file(output_file),
m_error_file(error_file), m_input_connection(fileno(input_file), false) {
// Get a shared history instance
m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name;
m_history_sp = EditlineHistory::GetHistory(m_editor_name);
#ifdef USE_SETUPTERM_WORKAROUND
if (m_output_file) {
const int term_fd = fileno(m_output_file);
if (term_fd != -1) {
static std::mutex *g_init_terminal_fds_mutex_ptr = nullptr;
static std::set<int> *g_init_terminal_fds_ptr = nullptr;
static std::once_flag g_once_flag;
llvm::call_once(g_once_flag, [&]() {
g_init_terminal_fds_mutex_ptr =
new std::mutex(); // NOTE: Leak to avoid C++ destructor chain issues
g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid
// C++ destructor chain
// issues
});
// We must make sure to initialize the terminal a given file descriptor
// only once. If we do this multiple times, we start leaking memory.
std::lock_guard<std::mutex> guard(*g_init_terminal_fds_mutex_ptr);
if (g_init_terminal_fds_ptr->find(term_fd) ==
g_init_terminal_fds_ptr->end()) {
g_init_terminal_fds_ptr->insert(term_fd);
setupterm((char *)0, term_fd, (int *)0);
}
}
}
#endif
}
Editline::~Editline() {
if (m_editline) {
// Disable edit mode to stop the terminal from flushing all input during
// the call to el_end() since we expect to have multiple editline instances
// in this program.
el_set(m_editline, EL_EDITMODE, 0);
el_end(m_editline);
m_editline = nullptr;
}
// EditlineHistory objects are sometimes shared between multiple Editline
// instances with the same program name. So just release our shared pointer
// and if we are the last owner, it will save the history to the history save
// file automatically.
m_history_sp.reset();
}
void Editline::SetPrompt(const char *prompt) {
m_set_prompt = prompt == nullptr ? "" : prompt;
}
void Editline::SetContinuationPrompt(const char *continuation_prompt) {
m_set_continuation_prompt =
continuation_prompt == nullptr ? "" : continuation_prompt;
}
void Editline::TerminalSizeChanged() {
if (m_editline != nullptr) {
el_resize(m_editline);
int columns;
// This function is documenting as taking (const char *, void *) for the
// vararg part, but in reality in was consuming arguments until the first
// null pointer. This was fixed in libedit in April 2019
// <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>,
// but we're keeping the workaround until a version with that fix is more
// widely available.
if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) {
m_terminal_width = columns;
if (m_current_line_rows != -1) {
const LineInfoW *info = el_wline(m_editline);
int lineLength =
(int)((info->lastchar - info->buffer) + GetPromptWidth());
m_current_line_rows = (lineLength / columns) + 1;
}
} else {
m_terminal_width = INT_MAX;
m_current_line_rows = 1;
}
}
}
const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
uint32_t Editline::GetCurrentLine() { return m_current_line_index; }
bool Editline::Interrupt() {
bool result = true;
std::lock_guard<std::mutex> guard(m_output_mutex);
if (m_editor_status == EditorStatus::Editing) {
fprintf(m_output_file, "^C\n");
result = m_input_connection.InterruptRead();
}
m_editor_status = EditorStatus::Interrupted;
return result;
}
bool Editline::Cancel() {
bool result = true;
std::lock_guard<std::mutex> guard(m_output_mutex);
if (m_editor_status == EditorStatus::Editing) {
MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
fprintf(m_output_file, ANSI_CLEAR_BELOW);
result = m_input_connection.InterruptRead();
}
m_editor_status = EditorStatus::Interrupted;
return result;
}
void Editline::SetAutoCompleteCallback(CompleteCallbackType callback,
void *baton) {
m_completion_callback = callback;
m_completion_callback_baton = baton;
}
void Editline::SetIsInputCompleteCallback(IsInputCompleteCallbackType callback,
void *baton) {
m_is_input_complete_callback = callback;
m_is_input_complete_callback_baton = baton;
}
bool Editline::SetFixIndentationCallback(FixIndentationCallbackType callback,
void *baton,
const char *indent_chars) {
m_fix_indentation_callback = callback;
m_fix_indentation_callback_baton = baton;
m_fix_indentation_callback_chars = indent_chars;
return false;
}
bool Editline::GetLine(std::string &line, bool &interrupted) {
ConfigureEditor(false);
m_input_lines = std::vector<EditLineStringType>();
m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
std::lock_guard<std::mutex> guard(m_output_mutex);
lldbassert(m_editor_status != EditorStatus::Editing);
if (m_editor_status == EditorStatus::Interrupted) {
m_editor_status = EditorStatus::Complete;
interrupted = true;
return true;
}
SetCurrentLine(0);
m_in_history = false;
m_editor_status = EditorStatus::Editing;
m_revert_cursor_index = -1;
int count;
auto input = el_wgets(m_editline, &count);
interrupted = m_editor_status == EditorStatus::Interrupted;
if (!interrupted) {
if (input == nullptr) {
fprintf(m_output_file, "\n");
m_editor_status = EditorStatus::EndOfInput;
} else {
m_history_sp->Enter(input);
#if LLDB_EDITLINE_USE_WCHAR
line = m_utf8conv.to_bytes(SplitLines(input)[0]);
#else
line = SplitLines(input)[0];
#endif
m_editor_status = EditorStatus::Complete;
}
}
return m_editor_status != EditorStatus::EndOfInput;
}
bool Editline::GetLines(int first_line_number, StringList &lines,
bool &interrupted) {
ConfigureEditor(true);
// Print the initial input lines, then move the cursor back up to the start
// of input
SetBaseLineNumber(first_line_number);
m_input_lines = std::vector<EditLineStringType>();
m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
std::lock_guard<std::mutex> guard(m_output_mutex);
// Begin the line editing loop
DisplayInput();
SetCurrentLine(0);
MoveCursor(CursorLocation::BlockEnd, CursorLocation::BlockStart);
m_editor_status = EditorStatus::Editing;
m_in_history = false;
m_revert_cursor_index = -1;
while (m_editor_status == EditorStatus::Editing) {
int count;
m_current_line_rows = -1;
el_wpush(m_editline, EditLineConstString(
"\x1b[^")); // Revert to the existing line content
el_wgets(m_editline, &count);
}
interrupted = m_editor_status == EditorStatus::Interrupted;
if (!interrupted) {
// Save the completed entry in history before returning
if (m_input_lines.size() > 1 || !m_input_lines[0].empty())
m_history_sp->Enter(CombineLines(m_input_lines).c_str());
lines = GetInputAsStringList();
}
return m_editor_status != EditorStatus::EndOfInput;
}
void Editline::PrintAsync(Stream *stream, const char *s, size_t len) {
std::lock_guard<std::mutex> guard(m_output_mutex);
if (m_editor_status == EditorStatus::Editing) {
MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
fprintf(m_output_file, ANSI_CLEAR_BELOW);
}
stream->Write(s, len);
stream->Flush();
if (m_editor_status == EditorStatus::Editing) {
DisplayInput();
MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
}
}
bool Editline::CompleteCharacter(char ch, EditLineGetCharType &out) {
#if !LLDB_EDITLINE_USE_WCHAR
if (ch == (char)EOF)
return false;
out = (unsigned char)ch;
return true;
#else
std::codecvt_utf8<wchar_t> cvt;
llvm::SmallString<4> input;
for (;;) {
const char *from_next;
wchar_t *to_next;
std::mbstate_t state = std::mbstate_t();
input.push_back(ch);
switch (cvt.in(state, input.begin(), input.end(), from_next, &out, &out + 1,
to_next)) {
case std::codecvt_base::ok:
return out != WEOF;
case std::codecvt_base::error:
case std::codecvt_base::noconv:
return false;
case std::codecvt_base::partial:
lldb::ConnectionStatus status;
size_t read_count = m_input_connection.Read(
&ch, 1, std::chrono::seconds(0), status, nullptr);
if (read_count == 0)
return false;
break;
}
}
#endif
}
| apache-2.0 |
ningfei/u3d | RTL/Component/Exporting/IFXExporting.cpp | 1 | 10713 | //***************************************************************************
//
// Copyright (c) 1999 - 2006 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//***************************************************************************
/**
@file IFXExporting.cpp
This module contains the plug-in specific functions required to
be exported from the DL by the IFXCOM component system. In
addition, it also provides common cross-platform startup and
shutdown functionality for the DL.
*/
//***************************************************************************
// Includes
//***************************************************************************
#include "IFXExportingCIDs.h"
#include "IFXMemory.h"
#include "IFXOSUtilities.h"
#include "IFXPlugin.h"
extern IFXRESULT IFXAPI_CALLTYPE CIFXAuthorGeomCompiler_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXAuthorCLODEncoderX_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXMaterialResourceEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXMotionResourceEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXGlyphGeneratorEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXShaderLitTextureEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXSubdivisionModifierEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXShadingModifierEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXAnimationModifierEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXGroupNodeEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXLightNodeEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXLightResourceEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXModelNodeEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXViewNodeEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXViewResourceEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXFileReferenceEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXBlockPriorityQueueX_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXBlockWriterX_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXWriteManager_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXStdioWriteBufferX_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXPointSetEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXLineSetEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXBoneWeightsModifierEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXCLODModifierEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
extern IFXRESULT IFXAPI_CALLTYPE CIFXDummyModifierEncoder_Factory( IFXREFIID interfaceId, void** ppInterface );
//***************************************************************************
// Defines
//***************************************************************************
//***************************************************************************
// Constants
//***************************************************************************
//***************************************************************************
// Enumerations
//***************************************************************************
//***************************************************************************
// Classes, structures and types
//***************************************************************************
//***************************************************************************
// Global data
//***************************************************************************
/**
Count of active objects.
This counter is used by IFXPluginCanUnloadNow and defined in the
IFXCorePluginStatic.cpp.
If this counter equals 0 it means there is no active plug-in objects
and plug-in can be successfully unloaded.
*/
extern U32 g_countActiveObjects;
// extern U32 g_countActiveExportingObjects;
//***************************************************************************
// Local data
//***************************************************************************
/**
gs_componentDescriptorList
List of ComponentDescriptor structures for each IFXCOM component
exposed by the plug-in module.
Look at the IFXPlugin.h for IFXComponentDescriptor declaration.
*/
static IFXComponentDescriptor gs_componentDescriptorList[] =
{
{
&CID_IFXAuthorCLODEncoderX,
{CIFXAuthorCLODEncoderX_Factory},
1
},
{
&CID_IFXAnimationModifierEncoder,
{CIFXAnimationModifierEncoder_Factory},
1
},
{
&CID_IFXMaterialResourceEncoder,
{CIFXMaterialResourceEncoder_Factory},
1
},
{
&CID_IFXMotionResourceEncoder,
{CIFXMotionResourceEncoder_Factory},
1
},
{
&CID_IFXGlyphGeneratorEncoder,
{CIFXGlyphGeneratorEncoder_Factory},
1
},
{
&CID_IFXShaderLitTextureEncoder,
{CIFXShaderLitTextureEncoder_Factory},
1
},
{
&CID_IFXSubdivisionModifierEncoder,
{CIFXSubdivisionModifierEncoder_Factory},
1
},
{
&CID_IFXShadingModifierEncoder,
{CIFXShadingModifierEncoder_Factory},
1
},
{
&CID_IFXGroupNodeEncoder,
{CIFXGroupNodeEncoder_Factory},
1
},
{
&CID_IFXLightNodeEncoder,
{CIFXLightNodeEncoder_Factory},
1
},
{
&CID_IFXLightResourceEncoder,
{CIFXLightResourceEncoder_Factory},
1
},
{
&CID_IFXViewResourceEncoder,
{CIFXViewResourceEncoder_Factory},
1
},
{
&CID_IFXModelNodeEncoder,
{CIFXModelNodeEncoder_Factory},
1
},
{
&CID_IFXViewNodeEncoder,
{CIFXViewNodeEncoder_Factory},
1
},
{
&CID_IFXFileReferenceEncoder,
{CIFXFileReferenceEncoder_Factory},
1
},
{
&CID_IFXBlockPriorityQueueX,
{CIFXBlockPriorityQueueX_Factory},
1
},
{
&CID_IFXBlockWriterX,
{CIFXBlockWriterX_Factory},
1
},
{
&CID_IFXWriteManager,
{CIFXWriteManager_Factory},
1
},
{
&CID_IFXAuthorGeomCompiler,
{CIFXAuthorGeomCompiler_Factory},
1
},
{
&CID_IFXStdioWriteBuffer,
{CIFXStdioWriteBufferX_Factory},
1
},
{
&CID_IFXStdioWriteBufferX,
{CIFXStdioWriteBufferX_Factory},
1
},
{
&CID_IFXPointSetEncoder,
{CIFXPointSetEncoder_Factory},
1
},
{
&CID_IFXLineSetEncoderX,
{CIFXLineSetEncoder_Factory},
1
},
{
&CID_IFXBoneWeightsModifierEncoder,
{CIFXBoneWeightsModifierEncoder_Factory},
1
},
{
&CID_IFXCLODModifierEncoder,
{CIFXCLODModifierEncoder_Factory},
1
},
{
&CID_IFXDummyModifierEncoder,
{CIFXDummyModifierEncoder_Factory},
1
}
};
//***************************************************************************
// Global functions
//***************************************************************************
//---------------------------------------------------------------------------
/**
This function should be invoked by dynamic library initialization
function.
@note For Windows this is the DLL_PROCESS_ATTACH section of DllMain.
*/
IFXRESULT IFXAPI_CALLTYPE IFXExportingStartup()
{
IFXRESULT result = IFX_OK;
// Initialize persistent global data.
// TODO: put your code for initialization here
IFXOSInitialize();
IFXDEBUG_STARTUP();
return result;
}
//---------------------------------------------------------------------------
/**
This function should be invoked by dynamic library uninitialization
function.
@note For Windows this is the DLL_PROCESS_DETACH section of DllMain.
*/
IFXRESULT IFXAPI_CALLTYPE IFXExportingShutdown()
{
IFXRESULT result = IFX_OK;
// Dispose of persistent global data
// TODO: put your code for uninitialization here
IFXDEBUG_SHUTDOWN();
IFXOSUninitialize();
return result;
}
//***************************************************************************
// Exported functions
//***************************************************************************
//---------------------------------------------------------------------------
/**
This function provides registration information about plug-in components
to the IFXCOM.
Input parameters for this functions should be defined in the caller
function.
@param pComponentNumber Pointer to the number of components in
component descriptor list.
@param ppComponentDescriptorList
Pointer to the component descriptor list
array (or pointer to the first element pointer
of component descriptor list).
@return Upon success, it returns the valuse IFX_OK. If input pointers
were not defined, it will return the value IFX_E_PARAMETER_NOT_INITIALIZED.
*/
extern "C"
IFXRESULT IFXAPI IFXPluginRegister(
U32* pComponentNumber,
IFXComponentDescriptor** ppComponentDescriptorList )
{
IFXRESULT result = IFX_OK;
if( 0 != pComponentNumber && 0 != ppComponentDescriptorList )
{
*pComponentNumber =
sizeof(gs_componentDescriptorList)/sizeof(IFXComponentDescriptor);
*ppComponentDescriptorList = gs_componentDescriptorList;
}
else
result = IFX_E_PARAMETER_NOT_INITIALIZED;
return result;
}
//---------------------------------------------------------------------------
/**
This function is used to let component system know if plug-in can be
unloaded now or not.
@return If plug-in can be unloaded, it will return the value IFX_OK.
Otherwise, it will return the value IFX_E_NOT_DONE.
*/
extern "C"
IFXRESULT IFXAPI IFXPluginCanUnloadNow()
{
IFXRESULT result = IFX_OK;
if( 0 != g_countActiveObjects )
// if( 0 != g_countActiveExportingObjects )
result = IFX_E_NOT_DONE;
return result;
}
| apache-2.0 |
wilebeast/FireFox-OS | B2G/gecko/toolkit/mozapps/update/test/TestAUSReadStrings.cpp | 2 | 5956 | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* This binary tests the updater's ReadStrings ini parser and should run in a
* directory with a Unicode character to test bug 473417.
*/
#ifdef XP_WIN
#include <windows.h>
#define NS_main wmain
#define NS_tstrrchr wcsrchr
#define NS_tsnprintf _snwprintf
#define NS_T(str) L ## str
#define PATH_SEPARATOR_CHAR L'\\'
// On Windows, argv[0] can also have forward slashes instead
#define ALT_PATH_SEPARATOR_CHAR L'/'
#else
#include <unistd.h>
#define NS_main main
#define NS_tstrrchr strrchr
#define NS_tsnprintf snprintf
#define NS_T(str) str
#ifdef XP_OS2
#define PATH_SEPARATOR_CHAR '\\'
#else
#define PATH_SEPARATOR_CHAR '/'
#endif
#endif
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "updater/resource.h"
#include "updater/progressui.h"
#include "common/readstrings.h"
#include "common/errors.h"
#include "mozilla/Util.h"
#ifndef MAXPATHLEN
# ifdef PATH_MAX
# define MAXPATHLEN PATH_MAX
# elif defined(MAX_PATH)
# define MAXPATHLEN MAX_PATH
# elif defined(_MAX_PATH)
# define MAXPATHLEN _MAX_PATH
# elif defined(CCHMAXPATH)
# define MAXPATHLEN CCHMAXPATH
# else
# define MAXPATHLEN 1024
# endif
#endif
#define TEST_NAME "Updater ReadStrings"
using namespace mozilla;
static int gFailCount = 0;
/**
* Prints the given failure message and arguments using printf, prepending
* "TEST-UNEXPECTED-FAIL " for the benefit of the test harness and
* appending "\n" to eliminate having to type it at each call site.
*/
void fail(const char* msg, ...)
{
va_list ap;
printf("TEST-UNEXPECTED-FAIL | ");
va_start(ap, msg);
vprintf(msg, ap);
va_end(ap);
putchar('\n');
++gFailCount;
}
/**
* Prints the given string prepending "TEST-PASS | " for the benefit of
* the test harness and with "\n" at the end, to be used at the end of a
* successful test function.
*/
void passed(const char* test)
{
printf("TEST-PASS | %s\n", test);
}
int NS_main(int argc, NS_tchar **argv)
{
printf("Running TestAUSReadStrings tests\n");
int rv = 0;
int retval;
NS_tchar inifile[MAXPATHLEN];
StringTable testStrings;
NS_tchar *slash = NS_tstrrchr(argv[0], PATH_SEPARATOR_CHAR);
#ifdef ALT_PATH_SEPARATOR_CHAR
NS_tchar *altslash = NS_tstrrchr(argv[0], ALT_PATH_SEPARATOR_CHAR);
slash = (slash > altslash) ? slash : altslash;
#endif // ALT_PATH_SEPARATOR_CHAR
if (!slash) {
fail("%s | unable to find platform specific path separator (check 1)", TEST_NAME);
return 20;
}
*(++slash) = '\0';
// Test success when the ini file exists with both Title and Info in the
// Strings section and the values for Title and Info.
NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings1.ini"), argv[0]);
retval = ReadStrings(inifile, &testStrings);
if (retval == OK) {
if (strcmp(testStrings.title, "Title Test - \xD0\x98\xD1\x81\xD0\xBF\xD1\x8B" \
"\xD1\x82\xD0\xB0\xD0\xBD\xD0\xB8\xD0\xB5 " \
"\xCE\x94\xCE\xBF\xCE\xBA\xCE\xB9\xCE\xBC\xCE\xAE " \
"\xE3\x83\x86\xE3\x82\xB9\xE3\x83\x88 " \
"\xE6\xB8\xAC\xE8\xA9\xA6 " \
"\xE6\xB5\x8B\xE8\xAF\x95") != 0) {
rv = 21;
fail("%s | Title ini value incorrect (check 3)", TEST_NAME);
}
if (strcmp(testStrings.info, "Info Test - \xD0\x98\xD1\x81\xD0\xBF\xD1\x8B" \
"\xD1\x82\xD0\xB0\xD0\xBD\xD0\xB8\xD0\xB5 " \
"\xCE\x94\xCE\xBF\xCE\xBA\xCE\xB9\xCE\xBC\xCE\xAE " \
"\xE3\x83\x86\xE3\x82\xB9\xE3\x83\x88 " \
"\xE6\xB8\xAC\xE8\xA9\xA6 " \
"\xE6\xB5\x8B\xE8\xAF\x95\xE2\x80\xA6") != 0) {
rv = 22;
fail("%s | Info ini value incorrect (check 4)", TEST_NAME);
}
}
else {
fail("%s | ReadStrings returned %i (check 2)", TEST_NAME, retval);
rv = 23;
}
// Test failure when the ini file exists without Title and with Info in the
// Strings section.
NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings2.ini"), argv[0]);
retval = ReadStrings(inifile, &testStrings);
if (retval != PARSE_ERROR) {
rv = 24;
fail("%s | ReadStrings returned %i (check 5)", TEST_NAME, retval);
}
// Test failure when the ini file exists with Title and without Info in the
// Strings section.
NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings3.ini"), argv[0]);
retval = ReadStrings(inifile, &testStrings);
if (retval != PARSE_ERROR) {
rv = 25;
fail("%s | ReadStrings returned %i (check 6)", TEST_NAME, retval);
}
// Test failure when the ini file doesn't exist
NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStringsBogus.ini"), argv[0]);
retval = ReadStrings(inifile, &testStrings);
if (retval != READ_ERROR) {
rv = 26;
fail("%s | ini file doesn't exist (check 7)", TEST_NAME);
}
// Test reading a non-default section name
NS_tsnprintf(inifile, ArrayLength(inifile), NS_T("%sTestAUSReadStrings3.ini"), argv[0]);
retval = ReadStrings(inifile, "Title\0", 1, &testStrings.title, "BogusSection2");
if (retval == OK) {
if (strcmp(testStrings.title, "Bogus Title") != 0) {
rv = 27;
fail("%s | Title ini value incorrect (check 9)", TEST_NAME);
}
}
else {
fail("%s | ReadStrings returned %i (check 8)", TEST_NAME, retval);
rv = 28;
}
if (rv == 0) {
printf("TEST-PASS | %s | all checks passed\n", TEST_NAME);
} else {
fail("%s | %i out of 9 checks failed", TEST_NAME, gFailCount);
}
return rv;
}
| apache-2.0 |
svagionitis/aws-sdk-cpp | aws-cpp-sdk-events/source/model/PutEventsRequest.cpp | 2 | 1570 | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/events/model/PutEventsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::CloudWatchEvents::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
PutEventsRequest::PutEventsRequest() :
m_entriesHasBeenSet(false)
{
}
Aws::String PutEventsRequest::SerializePayload() const
{
JsonValue payload;
if(m_entriesHasBeenSet)
{
Array<JsonValue> entriesJsonList(m_entries.size());
for(unsigned entriesIndex = 0; entriesIndex < entriesJsonList.GetLength(); ++entriesIndex)
{
entriesJsonList[entriesIndex].AsObject(m_entries[entriesIndex].Jsonize());
}
payload.WithArray("Entries", std::move(entriesJsonList));
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection PutEventsRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSEvents.PutEvents"));
return headers;
}
| apache-2.0 |
iree-org/iree | compiler/src/iree/compiler/Codegen/Interfaces/PartitionableLoopsInterface.cpp | 2 | 9172 | // Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Codegen/Interfaces/PartitionableLoopsInterface.h"
#include "iree-dialects/Dialect/LinalgExt/IR/LinalgExtDialect.h"
#include "iree-dialects/Dialect/LinalgExt/IR/LinalgExtOps.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/IR/BuiltinTypes.h"
// clang-format off
#include "iree/compiler/Codegen/Interfaces/PartitionableLoopsInterface.cpp.inc" // IWYU pragma: export
// clang-format on
namespace mlir {
namespace iree_compiler {
/// Filters out dimensions in `parallelLoops` that have unit range in
/// `loopRanges`.
static llvm::SmallVector<unsigned> pruneUnitTripParallelLoops(
llvm::ArrayRef<unsigned> parallelLoops,
llvm::ArrayRef<int64_t> loopRanges) {
return llvm::to_vector(llvm::make_filter_range(
parallelLoops,
[&loopRanges](unsigned loopDim) { return loopRanges[loopDim] != 1; }));
}
/// Returns the partitionable loops for all Linalg ops.
llvm::SmallVector<unsigned> getPartitionableLoopsImpl(
linalg::LinalgOp linalgOp, unsigned maxNumPartitionedLoops) {
llvm::SmallVector<unsigned> parallelLoops;
linalgOp.getParallelDims(parallelLoops);
// Get the static loop ranges.
llvm::SmallVector<int64_t, 4> staticLoopRanges =
linalgOp.getStaticLoopRanges();
parallelLoops = pruneUnitTripParallelLoops(parallelLoops, staticLoopRanges);
// TODO(ravishankarm): For now the outer parallel loops are dropped. This is
// a pragmatic choice for now but might need to be revisited.
if (parallelLoops.size() > maxNumPartitionedLoops) {
parallelLoops = llvm::to_vector(llvm::ArrayRef<unsigned>(parallelLoops)
.take_back(maxNumPartitionedLoops));
}
return parallelLoops;
}
static llvm::SmallVector<utils::IteratorType> getIteratorTypesFromAttr(
ArrayAttr iteratorTypesAttr) {
return llvm::to_vector(llvm::map_range(iteratorTypesAttr, [](Attribute attr) {
return utils::symbolizeIteratorType(attr.cast<StringAttr>().getValue())
.value();
}));
}
/// External model implementation for all LinalgOps.
template <typename OpTy>
struct LinalgOpPartitionableLoops
: public PartitionableLoopsInterface::ExternalModel<
LinalgOpPartitionableLoops<OpTy>, OpTy> {
llvm::SmallVector<unsigned> getPartitionableLoops(
Operation *op, unsigned maxNumPartitionedLoops) const {
auto linalgOp = cast<linalg::LinalgOp>(op);
return getPartitionableLoopsImpl(linalgOp, maxNumPartitionedLoops);
}
};
/// External model implementation for linalg::Mmt4DOp.
struct Mmt4DOpPartitionableLoops
: public PartitionableLoopsInterface::ExternalModel<
Mmt4DOpPartitionableLoops, linalg::Mmt4DOp> {
llvm::SmallVector<unsigned> getPartitionableLoops(
Operation *op, unsigned maxNumPartitionedLoops) const {
return {0, 1};
}
};
/// External model implementation for all operations to make only
/// the outer parallel loops as partitionable.
template <typename OpTy>
struct OuterParallelAsPartitionableLoops
: public PartitionableLoopsInterface::ExternalModel<
OuterParallelAsPartitionableLoops<OpTy>, OpTy> {
llvm::SmallVector<unsigned> getPartitionableLoops(
Operation *op, unsigned maxNumPartitionedLoops) const {
// For now just return the loops that are returned by the
// `TiledOpInterface`. This needs to be further pruned to remove unit-dim
// loops, but that needs the interface to return the static sizes of the
// loops.
SmallVector<unsigned> partitionableLoops;
auto interfaceOp = cast<OpTy>(op);
for (auto iteratorType :
llvm::enumerate(interfaceOp.getLoopIteratorTypes())) {
if (iteratorType.value() != utils::IteratorType::parallel) {
break;
}
partitionableLoops.push_back(iteratorType.index());
}
if (partitionableLoops.size() > maxNumPartitionedLoops) {
partitionableLoops.erase(
partitionableLoops.begin(),
std::next(partitionableLoops.begin(),
partitionableLoops.size() - maxNumPartitionedLoops));
}
return partitionableLoops;
}
};
/// External model implementation for operations that are to be executed
/// sequentially.
template <typename OpTy>
struct NoPartitionableLoops : public PartitionableLoopsInterface::ExternalModel<
NoPartitionableLoops<OpTy>, OpTy> {
llvm::SmallVector<unsigned> getPartitionableLoops(
Operation *op, unsigned maxNumPartitionedLoops) const {
return {};
}
};
/// External model implementation for specifying partitionable loops of FftOp.
struct FftOpPartitionableLoops
: public PartitionableLoopsInterface::ExternalModel<
FftOpPartitionableLoops, IREE::LinalgExt::FftOp> {
llvm::SmallVector<unsigned> getPartitionableLoops(
Operation *op, unsigned maxNumPartitionedLoops) const {
auto fftOp = cast<IREE::LinalgExt::FftOp>(op);
auto range = llvm::seq<unsigned>(0, fftOp.getOperandRank());
SmallVector<unsigned> partitionableLoops(range.begin(), range.end());
// Indices matter for coeff computation.
if (!fftOp.hasCoeff()) {
partitionableLoops.pop_back();
}
if (partitionableLoops.size() > maxNumPartitionedLoops) {
partitionableLoops.erase(
partitionableLoops.begin(),
std::next(partitionableLoops.begin(),
partitionableLoops.size() - maxNumPartitionedLoops));
}
return partitionableLoops;
}
};
/// External model implementation for making all parallel loops as
/// partitionable.
template <typename OpTy>
struct AllParallelAsPartitionableLoops
: public PartitionableLoopsInterface::ExternalModel<
AllParallelAsPartitionableLoops<OpTy>, OpTy> {
llvm::SmallVector<unsigned> getPartitionableLoops(
Operation *op, unsigned maxNumPartitionedLoops) const {
SmallVector<unsigned> partitionableLoops;
auto interfaceOp = cast<OpTy>(op);
for (auto iteratorType :
llvm::enumerate(interfaceOp.getLoopIteratorTypes())) {
if (iteratorType.value() != utils::IteratorType::parallel) {
continue;
}
partitionableLoops.push_back(iteratorType.index());
}
if (partitionableLoops.size() > maxNumPartitionedLoops) {
partitionableLoops.erase(
partitionableLoops.begin(),
std::next(partitionableLoops.begin(),
partitionableLoops.size() - maxNumPartitionedLoops));
}
return partitionableLoops;
}
};
/// Registers the `LinalgOpPartitionableLoops` model for all Linalg ops. This
/// needs to be done on a op-by-op basis since registration is on an op-by-op
/// basis.
template <typename OpTy>
static void registerInterfaceForLinalgOps(MLIRContext *ctx) {
OpTy::template attachInterface<LinalgOpPartitionableLoops<OpTy>>(*ctx);
}
/// Specializations of the registration method to use a different external model
/// instead of the generic external model for Linalg ops.
template <>
void registerInterfaceForLinalgOps<linalg::Mmt4DOp>(MLIRContext *ctx) {
linalg::Mmt4DOp::attachInterface<Mmt4DOpPartitionableLoops>(*ctx);
}
/// Registers the external models for all Linalg operations.
template <typename OpTy1, typename OpTy2, typename... More>
static void registerInterfaceForLinalgOps(MLIRContext *ctx) {
registerInterfaceForLinalgOps<OpTy1>(ctx);
registerInterfaceForLinalgOps<OpTy2, More...>(ctx);
}
void registerPartitionableLoopsInterfaceModels(DialectRegistry ®istry) {
registry.insert<linalg::LinalgDialect>();
#define GET_OP_LIST
registry.addExtension(+[](MLIRContext *ctx, linalg::LinalgDialect *dialect) {
registerInterfaceForLinalgOps<
#include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
>(ctx);
});
registry.insert<IREE::LinalgExt::IREELinalgExtDialect>();
registry.addExtension(+[](MLIRContext *ctx,
IREE::LinalgExt::IREELinalgExtDialect *dialect) {
IREE::LinalgExt::FftOp::attachInterface<FftOpPartitionableLoops>(*ctx);
IREE::LinalgExt::PackOp::attachInterface<
OuterParallelAsPartitionableLoops<IREE::LinalgExt::PackOp>>(*ctx);
IREE::LinalgExt::UnPackOp::attachInterface<
OuterParallelAsPartitionableLoops<IREE::LinalgExt::UnPackOp>>(*ctx);
IREE::LinalgExt::ScanOp::attachInterface<
AllParallelAsPartitionableLoops<IREE::LinalgExt::ScanOp>>(*ctx);
IREE::LinalgExt::ScatterOp::attachInterface<
OuterParallelAsPartitionableLoops<IREE::LinalgExt::ScatterOp>>(*ctx);
IREE::LinalgExt::SortOp::attachInterface<
AllParallelAsPartitionableLoops<IREE::LinalgExt::SortOp>>(*ctx);
IREE::LinalgExt::ReverseOp::attachInterface<
OuterParallelAsPartitionableLoops<IREE::LinalgExt::ReverseOp>>(*ctx);
IREE::LinalgExt::TopkOp::attachInterface<
AllParallelAsPartitionableLoops<IREE::LinalgExt::TopkOp>>(*ctx);
});
}
} // namespace iree_compiler
} // namespace mlir
| apache-2.0 |
aws/aws-sdk-cpp | aws-cpp-sdk-mediaconvert/source/model/XavcFramerateControl.cpp | 3 | 2158 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/mediaconvert/model/XavcFramerateControl.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace MediaConvert
{
namespace Model
{
namespace XavcFramerateControlMapper
{
static const int INITIALIZE_FROM_SOURCE_HASH = HashingUtils::HashString("INITIALIZE_FROM_SOURCE");
static const int SPECIFIED_HASH = HashingUtils::HashString("SPECIFIED");
XavcFramerateControl GetXavcFramerateControlForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == INITIALIZE_FROM_SOURCE_HASH)
{
return XavcFramerateControl::INITIALIZE_FROM_SOURCE;
}
else if (hashCode == SPECIFIED_HASH)
{
return XavcFramerateControl::SPECIFIED;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<XavcFramerateControl>(hashCode);
}
return XavcFramerateControl::NOT_SET;
}
Aws::String GetNameForXavcFramerateControl(XavcFramerateControl enumValue)
{
switch(enumValue)
{
case XavcFramerateControl::INITIALIZE_FROM_SOURCE:
return "INITIALIZE_FROM_SOURCE";
case XavcFramerateControl::SPECIFIED:
return "SPECIFIED";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace XavcFramerateControlMapper
} // namespace Model
} // namespace MediaConvert
} // namespace Aws
| apache-2.0 |
veritas-shine/minix3-rpi | external/bsd/libc++/dist/libcxx/test/containers/sequences/array/iterators.pass.cpp | 3 | 1826 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <array>
// iterator, const_iterator
#include <array>
#include <iterator>
#include <cassert>
int main()
{
{
typedef std::array<int, 5> C;
C c;
C::iterator i;
i = c.begin();
C::const_iterator j;
j = c.cbegin();
assert(i == j);
}
{
typedef std::array<int, 0> C;
C c;
C::iterator i;
i = c.begin();
C::const_iterator j;
j = c.cbegin();
assert(i == j);
}
#if _LIBCPP_STD_VER > 11
{ // N3644 testing
{
typedef std::array<int, 5> C;
C::iterator ii1{}, ii2{};
C::iterator ii4 = ii1;
C::const_iterator cii{};
assert ( ii1 == ii2 );
assert ( ii1 == ii4 );
assert ( ii1 == cii );
assert ( !(ii1 != ii2 ));
assert ( !(ii1 != cii ));
// C c;
// assert ( ii1 != c.cbegin());
// assert ( cii != c.begin());
// assert ( cii != c.cend());
// assert ( ii1 != c.end());
}
{
typedef std::array<int, 0> C;
C::iterator ii1{}, ii2{};
C::iterator ii4 = ii1;
C::const_iterator cii{};
assert ( ii1 == ii2 );
assert ( ii1 == ii4 );
assert ( ii1 == cii );
assert ( !(ii1 != ii2 ));
assert ( !(ii1 != cii ));
// C c;
// assert ( ii1 != c.cbegin());
// assert ( cii != c.begin());
// assert ( cii != c.cend());
// assert ( ii1 != c.end());
}
}
#endif
}
| apache-2.0 |
gpu/CLBlast | src/routines/level2/xsyr2.cpp | 3 | 2099 |
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This file implements the Xsyr2 class (see the header for information about the class).
//
// =================================================================================================
#include "routines/level2/xsyr2.hpp"
#include <string>
namespace clblast {
// =================================================================================================
// Constructor: forwards to base class constructor
template <typename T>
Xsyr2<T>::Xsyr2(Queue &queue, EventPointer event, const std::string &name):
Xher2<T>(queue, event, name) {
}
// =================================================================================================
// The main routine
template <typename T>
void Xsyr2<T>::DoSyr2(const Layout layout, const Triangle triangle,
const size_t n,
const T alpha,
const Buffer<T> &x_buffer, const size_t x_offset, const size_t x_inc,
const Buffer<T> &y_buffer, const size_t y_offset, const size_t y_inc,
const Buffer<T> &a_buffer, const size_t a_offset, const size_t a_ld) {
// Specific Xsyr2 functionality is implemented in the kernel using defines
DoHer2(layout, triangle, n, alpha,
x_buffer, x_offset, x_inc,
y_buffer, y_offset, y_inc,
a_buffer, a_offset, a_ld);
}
// =================================================================================================
// Compiles the templated class
template class Xsyr2<half>;
template class Xsyr2<float>;
template class Xsyr2<double>;
// =================================================================================================
} // namespace clblast
| apache-2.0 |
frootloops/swift | lib/SIL/LoopInfo.cpp | 4 | 2867 | //===--- LoopInfo.cpp - SIL Loop Analysis ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/LoopInfo.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/CFG.h"
#include "llvm/Analysis/LoopInfoImpl.h"
#include "llvm/Support/Debug.h"
using namespace swift;
// Instantiate template members.
template class llvm::LoopBase<SILBasicBlock, SILLoop>;
template class llvm::LoopInfoBase<SILBasicBlock, SILLoop>;
void SILLoop::dump() const {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
print(llvm::dbgs());
#endif
}
SILLoopInfo::SILLoopInfo(SILFunction *F, DominanceInfo *DT) : Dominance(DT) {
LI.analyze(*Dominance);
}
bool SILLoop::canDuplicate(SILInstruction *I) const {
// The deallocation of a stack allocation must be in the loop, otherwise the
// deallocation will be fed by a phi node of two allocations.
if (I->isAllocatingStack()) {
for (auto *UI : cast<SingleValueInstruction>(I)->getUses()) {
if (UI->getUser()->isDeallocatingStack()) {
if (!contains(UI->getUser()->getParent()))
return false;
}
}
return true;
}
// CodeGen can't build ssa for objc methods.
if (auto *Method = dyn_cast<MethodInst>(I)) {
if (Method->getMember().isForeign) {
for (auto *UI : Method->getUses()) {
if (!contains(UI->getUser()))
return false;
}
}
return true;
}
// We can't have a phi of two openexistential instructions of different UUID.
if (isa<OpenExistentialAddrInst>(I) || isa<OpenExistentialRefInst>(I) ||
isa<OpenExistentialMetatypeInst>(I) ||
isa<OpenExistentialValueInst>(I) || isa<OpenExistentialBoxInst>(I) ||
isa<OpenExistentialBoxValueInst>(I)) {
SingleValueInstruction *OI = cast<SingleValueInstruction>(I);
for (auto *UI : OI->getUses())
if (!contains(UI->getUser()))
return false;
return true;
}
if (auto *Dealloc = dyn_cast<DeallocStackInst>(I)) {
// The matching alloc_stack must be in the loop.
if (auto *Alloc = dyn_cast<AllocStackInst>(Dealloc->getOperand()))
return contains(Alloc->getParent());
return false;
}
if (isa<ThrowInst>(I))
return false;
assert(I->isTriviallyDuplicatable() &&
"Code here must match isTriviallyDuplicatable in SILInstruction");
return true;
}
void SILLoopInfo::verify() const {
LI.verify(*Dominance);
}
| apache-2.0 |
hsnlab/escape | OpenYuma/libtecla/homedir.c | 4 | 15140 | /*
* Copyright (c) 2000, 2001, 2002, 2003, 2004 by Martin C. Shepherd.
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
* OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder
* shall not be used in advertising or otherwise to promote the sale, use
* or other dealings in this Software without prior written authorization
* of the copyright holder.
*/
/*
* If file-system access is to be excluded, this module has no function,
* so all of its code should be excluded.
*/
#ifndef WITHOUT_FILE_SYSTEM
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#include "pathutil.h"
#include "homedir.h"
#include "errmsg.h"
/*
* Use the reentrant POSIX threads versions of the password lookup functions?
*/
#if defined(PREFER_REENTRANT) && defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199506L
#define THREAD_COMPATIBLE 1
/*
* Under Solaris we can use thr_main() to determine whether
* threads are actually running, and thus when it is necessary
* to avoid non-reentrant features.
*/
#if defined __sun && defined __SVR4
#include <thread.h> /* Solaris thr_main() */
#endif
#endif
/*
* Provide a password buffer size fallback in case the max size reported
* by sysconf() is said to be indeterminate.
*/
#define DEF_GETPW_R_SIZE_MAX 1024
/*
* The resources needed to lookup and record a home directory are
* maintained in objects of the following type.
*/
struct HomeDir {
ErrMsg *err; /* The error message report buffer */
char *buffer; /* A buffer for reading password entries and */
/* directory paths. */
int buflen; /* The allocated size of buffer[] */
#ifdef THREAD_COMPATIBLE
struct passwd pwd; /* The password entry of a user */
#endif
};
static const char *hd_getpwd(HomeDir *home);
/*.......................................................................
* Create a new HomeDir object.
*
* Output:
* return HomeDir * The new object, or NULL on error.
*/
HomeDir *_new_HomeDir(void)
{
HomeDir *home; /* The object to be returned */
size_t pathlen; /* The estimated maximum size of a pathname */
/*
* Allocate the container.
*/
home = (HomeDir *) malloc(sizeof(HomeDir));
if(!home) {
errno = ENOMEM;
return NULL;
};
/*
* Before attempting any operation that might fail, initialize the
* container at least up to the point at which it can safely be passed
* to _del_HomeDir().
*/
home->err = NULL;
home->buffer = NULL;
home->buflen = 0;
/*
* Allocate a place to record error messages.
*/
home->err = _new_ErrMsg();
if(!home->err)
return _del_HomeDir(home);
/*
* Allocate the buffer that is used by the reentrant POSIX password-entry
* lookup functions.
*/
#ifdef THREAD_COMPATIBLE
/*
* Get the length of the buffer needed by the reentrant version
* of getpwnam().
*/
#ifndef _SC_GETPW_R_SIZE_MAX
home->buflen = DEF_GETPW_R_SIZE_MAX;
#else
errno = 0;
home->buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
/*
* If the limit isn't available, substitute a suitably large fallback value.
*/
if(home->buflen < 0 || errno)
home->buflen = DEF_GETPW_R_SIZE_MAX;
#endif
#endif
/*
* If the existing buffer length requirement is too restrictive to record
* a pathname, increase its length.
*/
pathlen = _pu_pathname_dim();
if(pathlen > home->buflen)
home->buflen = pathlen;
/*
* Allocate a work buffer.
*/
home->buffer = (char *) malloc(home->buflen);
if(!home->buffer) {
errno = ENOMEM;
return _del_HomeDir(home);
};
return home;
}
/*.......................................................................
* Delete a HomeDir object.
*
* Input:
* home HomeDir * The object to be deleted.
* Output:
* return HomeDir * The deleted object (always NULL).
*/
HomeDir *_del_HomeDir(HomeDir *home)
{
if(home) {
home->err = _del_ErrMsg(home->err);
if(home->buffer)
free(home->buffer);
free(home);
};
return NULL;
}
/*.......................................................................
* Lookup the home directory of a given user in the password file.
*
* Input:
* home HomeDir * The resources needed to lookup the home directory.
* user const char * The name of the user to lookup, or "" to lookup
* the home directory of the person running the
* program.
* Output:
* return const char * The home directory. If the library was compiled
* with threads, this string is part of the HomeDir
* object and will change on subsequent calls. If
* the library wasn't compiled to be reentrant,
* then the string is a pointer into a static string
* in the C library and will change not only on
* subsequent calls to this function, but also if
* any calls are made to the C library password
* file lookup functions. Thus to be safe, you should
* make a copy of this string before calling any
* other function that might do a password file
* lookup.
*
* On error, NULL is returned and a description
* of the error can be acquired by calling
* _hd_last_home_dir_error().
*/
const char *_hd_lookup_home_dir(HomeDir *home, const char *user)
{
const char *home_dir; /* A pointer to the home directory of the user */
/*
* If no username has been specified, arrange to lookup the current
* user.
*/
int login_user = !user || *user=='\0';
/*
* Check the arguments.
*/
if(!home) {
errno = EINVAL;
return NULL;
};
/*
* Handle the ksh "~+". This expands to the absolute path of the
* current working directory.
*/
if(!login_user && strcmp(user, "+") == 0) {
home_dir = hd_getpwd(home);
if(!home_dir) {
_err_record_msg(home->err, "Can't determine current directory",
END_ERR_MSG);
return NULL;
}
return home_dir;
};
/*
* When looking up the home directory of the current user, see if the
* HOME environment variable is set, and if so, return its value.
*/
if(login_user) {
home_dir = getenv("HOME");
if(home_dir)
return home_dir;
};
/*
* Look up the password entry of the user.
* First the POSIX threads version - this is painful!
*/
#ifdef THREAD_COMPATIBLE
{
struct passwd *ret; /* The returned pointer to pwd */
int status; /* The return value of getpwnam_r() */
/*
* Look up the password entry of the specified user.
*/
if(login_user)
status = getpwuid_r(geteuid(), &home->pwd, home->buffer, home->buflen,
&ret);
else
status = getpwnam_r(user, &home->pwd, home->buffer, home->buflen, &ret);
if(status || !ret) {
_err_record_msg(home->err, "User '", user, "' doesn't exist.",
END_ERR_MSG);
return NULL;
};
/*
* Get a pointer to the string that holds the home directory.
*/
home_dir = home->pwd.pw_dir;
};
/*
* Now the classic unix version.
*/
#else
{
struct passwd *pwd = login_user ? getpwuid(geteuid()) : getpwnam(user);
if(!pwd) {
_err_record_msg(home->err, "User '", user, "' doesn't exist.",
END_ERR_MSG);
return NULL;
};
/*
* Get a pointer to the home directory.
*/
home_dir = pwd->pw_dir;
};
#endif
return home_dir;
}
/*.......................................................................
* Return a description of the last error that caused _hd_lookup_home_dir()
* to return NULL.
*
* Input:
* home HomeDir * The resources needed to record the home directory.
* Output:
* return char * The description of the last error.
*/
const char *_hd_last_home_dir_error(HomeDir *home)
{
return home ? _err_get_msg(home->err) : "NULL HomeDir argument";
}
/*.......................................................................
* The _hd_scan_user_home_dirs() function calls a user-provided function
* for each username known by the system, passing the function both
* the name and the home directory of the user.
*
* Input:
* home HomeDir * The resource object for reading home
* directories.
* prefix const char * Only information for usernames that
* start with this prefix will be
* returned. Note that the empty
& string "", matches all usernames.
* data void * Anonymous data to be passed to the
* callback function.
* callback_fn HOME_DIR_FN(*) The function to call for each user.
* Output:
* return int 0 - Successful completion.
* 1 - An error occurred. A description
* of the error can be obtained by
* calling _hd_last_home_dir_error().
*/
int _hd_scan_user_home_dirs(HomeDir *home, const char *prefix,
void *data, HOME_DIR_FN(*callback_fn))
{
int waserr = 0; /* True after errors */
int prefix_len; /* The length of prefix[] */
/*
* Check the arguments.
*/
if(!home || !prefix || !callback_fn) {
if(home) {
_err_record_msg(home->err,
"_hd_scan_user_home_dirs: Missing callback function",
END_ERR_MSG);
};
return 1;
};
/*
* Get the length of the username prefix.
*/
prefix_len = strlen(prefix);
/*
* There are no reentrant versions of getpwent() etc for scanning
* the password file, so disable username completion when the
* library is compiled to be reentrant.
*/
#if defined(PREFER_REENTRANT) && defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199506L
#if defined __sun && defined __SVR4
if(thr_main() >= 0) /* thread library is linked in */
#else
if(1)
#endif
{
struct passwd pwd_buffer; /* A returned password entry */
struct passwd *pwd; /* A pointer to pwd_buffer */
char buffer[512]; /* The buffer in which the string members of */
/* pwd_buffer are stored. */
/*
* See if the prefix that is being completed is a complete username.
*/
if(!waserr && getpwnam_r(prefix, &pwd_buffer, buffer, sizeof(buffer),
&pwd) == 0 && pwd != NULL) {
waserr = callback_fn(data, pwd->pw_name, pwd->pw_dir,
_err_get_msg(home->err), ERR_MSG_LEN);
};
/*
* See if the username of the current user minimally matches the prefix.
*/
if(!waserr && getpwuid_r(getuid(), &pwd_buffer, buffer, sizeof(buffer),
&pwd) == 0 && pwd != NULL &&
strncmp(prefix, pwd->pw_name, prefix_len)==0) {
waserr = callback_fn(data, pwd->pw_name, pwd->pw_dir,
_err_get_msg(home->err), ERR_MSG_LEN);
};
/*
* Reentrancy not required?
*/
} else
#endif
{
struct passwd *pwd; /* The pointer to the latest password entry */
/*
* Open the password file.
*/
setpwent();
/*
* Read the contents of the password file, looking for usernames
* that start with the specified prefix, and adding them to the
* list of matches.
*/
while((pwd = getpwent()) != NULL && !waserr) {
if(strncmp(prefix, pwd->pw_name, prefix_len) == 0) {
waserr = callback_fn(data, pwd->pw_name, pwd->pw_dir,
_err_get_msg(home->err), ERR_MSG_LEN);
};
};
/*
* Close the password file.
*/
endpwent();
};
/*
* Under ksh ~+ stands for the absolute pathname of the current working
* directory.
*/
if(!waserr && strncmp(prefix, "+", prefix_len) == 0) {
const char *pwd = hd_getpwd(home);
if(pwd) {
waserr = callback_fn(data, "+", pwd, _err_get_msg(home->err),ERR_MSG_LEN);
} else {
waserr = 1;
_err_record_msg(home->err, "Can't determine current directory.",
END_ERR_MSG);
};
};
return waserr;
}
/*.......................................................................
* Return the value of getenv("PWD") if this points to the current
* directory, or the return value of getcwd() otherwise. The reason for
* prefering PWD over getcwd() is that the former preserves the history
* of symbolic links that have been traversed to reach the current
* directory. This function is designed to provide the equivalent
* expansion of the ksh ~+ directive, which normally returns its value
* of PWD.
*
* Input:
* home HomeDir * The resource object for reading home directories.
* Output:
* return const char * A pointer to either home->buffer, where the
* pathname is recorded, the string returned by
* getenv("PWD"), or NULL on error.
*/
static const char *hd_getpwd(HomeDir *home)
{
/*
* Get the absolute path of the current working directory.
*/
char *cwd = getcwd(home->buffer, home->buflen);
/*
* Some shells set PWD with the path of the current working directory.
* This will differ from cwd in that it won't have had symbolic links
* expanded.
*/
const char *pwd = getenv("PWD");
/*
* If PWD was set, and it points to the same directory as cwd, return
* its value. Note that it won't be the same if the current shell or
* the current program has changed directories, after inheriting PWD
* from a parent shell.
*/
struct stat cwdstat, pwdstat;
if(pwd && cwd && stat(cwd, &cwdstat)==0 && stat(pwd, &pwdstat)==0 &&
cwdstat.st_dev == pwdstat.st_dev && cwdstat.st_ino == pwdstat.st_ino)
return pwd;
/*
* Also return pwd if getcwd() failed, since it represents the best
* information that we have access to.
*/
if(!cwd)
return pwd;
/*
* In the absence of a valid PWD, return cwd.
*/
return cwd;
}
#endif /* ifndef WITHOUT_FILE_SYSTEM */
| apache-2.0 |
modocache/swift | lib/SILOptimizer/Transforms/RedundantLoadElimination.cpp | 4 | 56907 | //===--- RedundantLoadElimination.cpp - SIL Load Forwarding ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This pass eliminates redundant loads.
///
/// A load can be eliminated if its value has already been held somewhere,
/// i.e. generated by a previous load, LSLocation stored by a known value.
///
/// In this case, one can replace the load instruction with the previous
/// results.
///
/// Redundant Load Elimination (RLE) eliminates such loads by:
///
/// 1. Introducing a notion of a LSLocation that is used to model object
/// fields. (See below for more details).
///
/// 2. Introducing a notion of a LSValue that is used to model the value
/// that currently resides in the associated LSLocation on the particular
/// program path. (See below for more details).
///
/// 3. Performing a RPO walk over the control flow graph, tracking any
/// LSLocations that are read from or stored into in each basic block. The
/// read or stored value, kept in a map between LSLocation and LSValue,
/// becomes the available value for the LSLocation.
///
/// 4. An optimistic iterative intersection-based dataflow is performed on the
/// gensets until convergence.
///
/// At the core of RLE, there is the LSLocation class. A LSLocation is an
/// abstraction of an object field in program. It consists of a base and a
/// projection path to the field accessed.
///
/// In SIL, one can access an aggregate as a whole, i.e. store to a struct with
/// 2 Int fields. A store like this will generate 2 *indivisible* LSLocations,
/// 1 for each field and in addition to keeping a list of LSLocation, RLE also
/// keeps their available LSValues. We call it *indivisible* because it
/// cannot be broken down to more LSLocations.
///
/// LSValue consists of a base - a SILValue from the load or store inst,
/// as well as a projection path to which the field it represents. So, a
/// store to an 2-field struct as mentioned above will generate 2 LSLocations
/// and 2 LSValues.
///
/// Every basic block keeps a map between LSLocation and LSValue. By
/// keeping the LSLocation and LSValue in their indivisible form, one
/// can easily find which part of the load is redundant and how to compute its
/// forwarding value.
///
/// Given the case which the 2 fields of the struct both have available values,
/// RLE can find their LSValues (maybe by struct_extract from a larger
/// value) and then aggregate them.
///
/// However, this may introduce a lot of extraction and aggregation which may
/// not be necessary. i.e. a store the struct followed by a load from the
/// struct. To solve this problem, when RLE detects that a load instruction
/// can be replaced by forwarded value, it will try to find minimum # of
/// extractions necessary to form the forwarded value. It will group the
/// available value's by the LSValue base, i.e. the LSValues come from the
/// same instruction, and then use extraction to obtain the needed components
/// of the base.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-redundant-load-elim"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
#include "swift/SILOptimizer/Analysis/ValueTracking.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFG.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/Utils/LoadStoreOptUtils.h"
#include "swift/SILOptimizer/Utils/SILSSAUpdater.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace swift;
STATISTIC(NumForwardedLoads, "Number of loads forwarded");
/// Return the deallocate stack instructions corresponding to the given
/// AllocStackInst.
static SILInstruction *findAllocStackInst(SILInstruction *I) {
if (DeallocStackInst *DSI = dyn_cast<DeallocStackInst>(I))
return dyn_cast<SILInstruction>(DSI->getOperand());
return nullptr;
}
/// ComputeAvailSetMax - If we ignore all unknown writes, what is the max
/// available set that can reach the a certain point in a basic block. This
/// helps generating the genset and killset. i.e. if there is no downward visible
/// value that can reach the end of a basic block, then we know that the genset
/// and killset for the location need not be set.
///
/// ComputeAvailGenKillSet - Build the genset and killset of the basic block.
///
/// ComputeAvailValue - Compute the available value at the end of the basic
/// block.
///
/// PerformRLE - Perform the actual redundant load elimination.
enum class RLEKind : unsigned {
ComputeAvailSetMax = 0,
ComputeAvailGenKillSet = 1,
ComputeAvailValue = 2,
PerformRLE = 3,
};
//===----------------------------------------------------------------------===//
// Utility Functions
//===----------------------------------------------------------------------===//
static bool inline isComputeAvailSetMax(RLEKind Kind) {
return Kind == RLEKind::ComputeAvailSetMax;
}
static bool inline isComputeAvailGenKillSet(RLEKind Kind) {
return Kind == RLEKind::ComputeAvailGenKillSet;
}
static bool inline isComputeAvailValue(RLEKind Kind) {
return Kind == RLEKind::ComputeAvailValue;
}
static bool inline isPerformingRLE(RLEKind Kind) {
return Kind == RLEKind::PerformRLE;
}
/// Returns true if this is an instruction that may have side effects in a
/// general sense but are inert from a load store perspective.
static bool isRLEInertInstruction(SILInstruction *Inst) {
switch (Inst->getKind()) {
case ValueKind::StrongRetainInst:
case ValueKind::StrongRetainUnownedInst:
case ValueKind::UnownedRetainInst:
case ValueKind::RetainValueInst:
case ValueKind::DeallocStackInst:
case ValueKind::CondFailInst:
case ValueKind::IsUniqueInst:
case ValueKind::IsUniqueOrPinnedInst:
case ValueKind::FixLifetimeInst:
return true;
default:
return false;
}
}
//===----------------------------------------------------------------------===//
// Basic Block Location State
//===----------------------------------------------------------------------===//
namespace {
/// If this function has too many basic blocks or too many locations, it may
/// take a long time to compute the genset and killset. The number of memory
/// behavior or alias query we need to do in worst case is roughly linear to
/// # of BBs x(times) # of locations.
///
/// we could run RLE on functions with 128 basic blocks and 128 locations,
/// which is a large function.
constexpr unsigned MaxLSLocationBBMultiplicationNone = 128*128;
/// we could run optimistic RLE on functions with less than 64 basic blocks
/// and 64 locations which is a sizable function.
constexpr unsigned MaxLSLocationBBMultiplicationPessimistic = 64*64;
/// forward declaration.
class RLEContext;
/// State of the load store in one basic block which allows for forwarding from
/// loads, stores -> loads
class BlockState {
public:
enum class ValueState : unsigned {
CoverValues = 0,
ConcreteValues = 1,
CoverAndConcreteValues = 2,
};
private:
/// # of locations in the LocationVault.
unsigned LocationNum;
/// The basic block that we are optimizing.
SILBasicBlock *BB;
/// A bit vector for which the ith bit represents the ith LSLocation in
/// LocationVault. If the bit is set, then the location currently has an
/// downward visible value at the beginning of the basic block.
llvm::SmallBitVector ForwardSetIn;
/// A bit vector for which the ith bit represents the ith LSLocation in
/// LocationVault. If the bit is set, then the location currently has an
/// downward visible value at the end of the basic block.
llvm::SmallBitVector ForwardSetOut;
/// A bit vector for which the ith bit represents the ith LSLocation in
/// LocationVault. If we ignore all unknown write, what's the maximum set
/// of available locations at the current position in the basic block.
llvm::SmallBitVector ForwardSetMax;
/// A bit vector for which the ith bit represents the ith LSLocation in
/// LocationVault. If the bit is set, then the basic block generates a
/// value for the location.
llvm::SmallBitVector BBGenSet;
/// A bit vector for which the ith bit represents the ith LSLocation in
/// LocationVault. If the bit is set, then the basic block kills the
/// value for the location.
llvm::SmallBitVector BBKillSet;
/// This is map between LSLocations and their available values at the
/// beginning of this basic block.
ValueTableMap ForwardValIn;
/// This is map between LSLocations and their available values at the end of
/// this basic block.
ValueTableMap ForwardValOut;
/// Keeps a list of replaceable instructions in the current basic block as
/// well as their SILValue replacement.
llvm::DenseMap<SILInstruction *, SILValue> RedundantLoads;
/// LSLocation read or written has been extracted, expanded and mapped to the
/// bit position in the bitvector. Update it in the ForwardSetIn of the
/// current basic block.
void updateForwardSetForRead(RLEContext &Ctx, unsigned B);
void updateForwardSetForWrite(RLEContext &Ctx, unsigned B);
/// LSLocation read or written has been extracted, expanded and mapped to the
/// B position in the Bvector. Update it in the genset and killset of the
/// current basic block.
void updateGenKillSetForRead(RLEContext &Ctx, unsigned B);
void updateGenKillSetForWrite(RLEContext &Ctx, unsigned B);
/// LSLocation read or written has been extracted, expanded and mapped to the
/// B position in the Bvector. Update it in the MaxAvailForwardSet of the
/// current basic block.
void updateMaxAvailSetForRead(RLEContext &Ctx, unsigned B);
void updateMaxAvailSetForWrite(RLEContext &Ctx, unsigned B);
/// LSLocation written has been extracted, expanded and mapped to the bit
/// position in the bitvector. process it using the bit position.
void updateForwardSetAndValForRead(RLEContext &Ctx, unsigned L, unsigned V);
void updateForwardSetAndValForWrite(RLEContext &Ctx, unsigned L, unsigned V);
/// There is a read to a LSLocation, expand the LSLocation into individual
/// fields before processing them.
void processRead(RLEContext &Ctx, SILInstruction *I, SILValue Mem,
SILValue Val, RLEKind Kind);
/// There is a write to a LSLocation, expand the LSLocation into individual
/// fields before processing them.
void processWrite(RLEContext &Ctx, SILInstruction *I, SILValue Mem,
SILValue Val, RLEKind Kind);
/// BitVector manipulation functions.
void startTrackingLocation(llvm::SmallBitVector &BV, unsigned B);
void stopTrackingLocation(llvm::SmallBitVector &BV, unsigned B);
bool isTrackingLocation(llvm::SmallBitVector &BV, unsigned B);
void startTrackingValue(ValueTableMap &VM, unsigned L, unsigned V);
void stopTrackingValue(ValueTableMap &VM, unsigned B);
public:
BlockState() = default;
void init(SILBasicBlock *NewBB, unsigned bitcnt, bool optimistic) {
BB = NewBB;
LocationNum = bitcnt;
// For reachable basic blocks, the initial state of ForwardSetOut should be
// all 1's. Otherwise the dataflow solution could be too conservative.
//
// Consider this case, the forwardable value by var a = 10 before the loop
// will not be forwarded if the ForwardSetOut is set to 0 initially.
//
// var a = 10
// for _ in 0...1024 {}
// use(a);
//
// However, by doing so, we can only do the data forwarding after the
// data flow stabilizes.
//
// We set the initial state of unreachable block to 0, as we do not have
// a value for the location.
//
// This is a bit conservative as we could be missing forwarding
// opportunities. i.e. a joint block with 1 predecessor being an
// unreachable block.
//
// we rely on other passes to clean up unreachable block.
ForwardSetIn.resize(LocationNum, false);
ForwardSetOut.resize(LocationNum, optimistic);
// If we are running an optimistic data flow, set forward max to true
// initially.
ForwardSetMax.resize(LocationNum, optimistic);
BBGenSet.resize(LocationNum, false);
BBKillSet.resize(LocationNum, false);
}
/// Initialize the AvailSetMax by intersecting this basic block's
/// predecessors' AvailSetMax.
void mergePredecessorsAvailSetMax(RLEContext &Ctx);
/// Initialize the AvailSet by intersecting this basic block' predecessors'
/// AvailSet.
void mergePredecessorAvailSet(RLEContext &Ctx);
/// Initialize the AvailSet and AvailVal of the current basic block.
void mergePredecessorAvailSetAndValue(RLEContext &Ctx);
/// Reached the end of the basic block, update the ForwardValOut with the
/// ForwardValIn.
void updateForwardValOut() { ForwardValOut = ForwardValIn; }
/// Check whether the ForwardSetOut has changed. If it does, we need to
/// rerun the data flow to reach fixed point.
bool updateForwardSetOut() {
if (ForwardSetIn == ForwardSetOut)
return false;
ForwardSetOut = ForwardSetIn;
return true;
}
/// Returns the current basic block we are processing.
SILBasicBlock *getBB() const { return BB; }
/// Returns the ForwardValIn for the current basic block.
ValueTableMap &getForwardValIn() { return ForwardValIn; }
/// Returns the ForwardValOut for the current basic block.
ValueTableMap &getForwardValOut() { return ForwardValOut; }
/// Returns the redundant loads and their replacement in the currently basic
/// block.
llvm::DenseMap<SILInstruction *, SILValue> &getRL() { return RedundantLoads; }
/// Look into the value for the given LSLocation at end of the basic block,
/// return one of the three ValueState type.
ValueState getValueStateAtEndOfBlock(RLEContext &Ctx, LSLocation &L);
/// Wrappers to query the value state of the location in this BlockState.
bool isCoverValues(RLEContext &Ctx, LSLocation &L) {
return getValueStateAtEndOfBlock(Ctx, L) == ValueState::CoverValues;
}
bool isConcreteValues(RLEContext &Ctx, LSLocation &L) {
return getValueStateAtEndOfBlock(Ctx, L) == ValueState::ConcreteValues;
}
/// Iterate over the instructions in the basic block in forward order and
/// process them w.r.t. the given \p Kind.
void processInstructionWithKind(RLEContext &Ctx, SILInstruction *I,
RLEKind Kind);
void processBasicBlockWithKind(RLEContext &Ctx, RLEKind Kind);
/// Process the current basic block with the genset and killset. Return true
/// if the ForwardSetOut changes.
bool processBasicBlockWithGenKillSet();
/// Set up the value for redundant load elimination.
bool setupRLE(RLEContext &Ctx, SILInstruction *I, SILValue Mem);
/// Process Instruction which writes to memory in an unknown way.
void processUnknownWriteInst(RLEContext &Ctx, SILInstruction *I,
RLEKind Kind);
void processUnknownWriteInstForGenKillSet(RLEContext &Ctx, SILInstruction *I);
void processUnknownWriteInstForRLE(RLEContext &Ctx, SILInstruction *I);
void processDeallocStackInst(RLEContext &Ctx, SILInstruction *I,
RLEKind Kind);
void processDeallocStackInstForGenKillSet(RLEContext &Ctx, SILInstruction *I);
void processDeallocStackInstForRLE(RLEContext &Ctx, SILInstruction *I);
/// Process LoadInst. Extract LSLocations from LoadInst.
void processLoadInst(RLEContext &Ctx, LoadInst *LI, RLEKind Kind);
/// Process LoadInst. Extract LSLocations from StoreInst.
void processStoreInst(RLEContext &Ctx, StoreInst *SI, RLEKind Kind);
/// Returns a *single* forwardable SILValue for the given LSLocation right
/// before the InsertPt instruction.
SILValue reduceValuesAtEndOfBlock(RLEContext &Ctx, LSLocation &L);
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// RLEContext Interface
//===----------------------------------------------------------------------===//
namespace {
using BBValueMap = llvm::DenseMap<SILBasicBlock *, SILValue>;
/// This class stores global state that we use when computing redundant load and
/// their replacement in each basic block.
class RLEContext {
enum class ProcessKind {
ProcessMultipleIterations = 0,
ProcessOneIteration = 1,
ProcessNone = 2,
};
private:
/// Function currently processing.
SILFunction *Fn;
/// The passmanager we are using.
SILPassManager *PM;
/// The alias analysis that we will use during all computations.
AliasAnalysis *AA;
/// The type expansion analysis we will use during all computations.
TypeExpansionAnalysis *TE;
/// The SSA updater we use to materialize covering values.
SILSSAUpdater Updater;
/// The range that we use to iterate over the post order and reverse post
/// order of the given function.
PostOrderFunctionInfo *PO;
/// Epilogue release analysis.
EpilogueARCFunctionInfo *EAFI;
/// Keeps all the locations for the current function. The BitVector in each
/// BlockState is then laid on top of it to keep track of which LSLocation
/// has a downward available value.
std::vector<LSLocation> LocationVault;
/// Contains a map between LSLocation to their index in the LocationVault.
/// Use for fast lookup.
LSLocationIndexMap LocToBitIndex;
/// Keeps a map between the accessed SILValue and the location.
LSLocationBaseMap BaseToLocIndex;
/// Keeps all the loadstorevalues for the current function. The BitVector in
/// each g is then laid on top of it to keep track of which LSLocation
/// has a downward available value.
std::vector<LSValue> LSValueVault;
/// Contains a map between LSLocation to their index in the LocationVault.
/// Use for fast lookup.
llvm::DenseMap<LSValue, unsigned> ValToBitIndex;
/// A map from each BasicBlock to its BlockState.
llvm::SmallDenseMap<SILBasicBlock *, BlockState, 16> BBToLocState;
/// Keeps a list of basic blocks that have LoadInsts. If a basic block does
/// not have LoadInst, we do not actually perform the last iteration where
/// RLE is actually performed on the basic block.
///
/// NOTE: This is never populated for functions which will only require 1
/// data flow iteration. For function that requires more than 1 iteration of
/// the data flow this is populated when the first time the functions is
/// walked, i.e. when the we generate the genset and killset.
llvm::DenseSet<SILBasicBlock *> BBWithLoads;
public:
RLEContext(SILFunction *F, SILPassManager *PM, AliasAnalysis *AA,
TypeExpansionAnalysis *TE, PostOrderFunctionInfo *PO,
EpilogueARCFunctionInfo *EAFI);
RLEContext(const RLEContext &) = delete;
RLEContext(RLEContext &&) = default;
~RLEContext() = default;
/// Entry point to redundant load elimination.
bool run();
/// Use a set of ad hoc rules to tell whether we should run a pessimistic
/// one iteration data flow on the function.
ProcessKind getProcessFunctionKind(unsigned LoadCount, unsigned StoreCount);
/// Run the iterative data flow until convergence.
void runIterativeRLE();
/// Process the basic blocks for the gen and kill set.
void processBasicBlocksForGenKillSet();
/// Process the basic blocks with the gen and kill set.
void processBasicBlocksWithGenKillSet();
/// Process the basic block for values generated in the current basic
/// block.
void processBasicBlocksForAvailValue();
/// Process basic blocks to perform the redundant load elimination.
void processBasicBlocksForRLE(bool Optimistic);
/// Returns the alias analysis we will use during all computations.
AliasAnalysis *getAA() const { return AA; }
/// Returns the current type expansion analysis we are .
TypeExpansionAnalysis *getTE() const { return TE; }
/// Returns current epilogue release function info we are using.
EpilogueARCFunctionInfo *getEAFI() const { return EAFI; }
/// Returns the SILValue base to bit index.
LSLocationBaseMap &getBM() { return BaseToLocIndex; }
/// Return the BlockState for the basic block this basic block belongs to.
BlockState &getBlockState(SILBasicBlock *B) { return BBToLocState[B]; }
/// Get the bit representing the LSLocation in the LocationVault.
unsigned getLocationBit(const LSLocation &L);
/// Given the bit, get the LSLocation from the LocationVault.
LSLocation &getLocation(const unsigned index);
/// Get the bit representing the LSValue in the LSValueVault.
unsigned getValueBit(const LSValue &L);
/// Given the bit, get the LSValue from the LSValueVault.
LSValue &getValue(const unsigned index);
/// Given a LSLocation, try to collect all the LSValues for this LSLocation
/// in the given basic block. If part of the locations have covering values,
/// find the values in its predecessors.
bool collectLocationValues(SILBasicBlock *BB, LSLocation &L,
LSLocationValueMap &Values, ValueTableMap &VM);
/// Transitively collect all the values that make up this location and
/// create a SILArgument out of them.
SILValue computePredecessorLocationValue(SILBasicBlock *BB, LSLocation &L);
};
} // end anonymous namespace
void BlockState::startTrackingValue(ValueTableMap &VM, unsigned L, unsigned V) {
VM[L] = V;
}
void BlockState::stopTrackingValue(ValueTableMap &VM, unsigned B) {
VM.erase(B);
}
bool BlockState::isTrackingLocation(llvm::SmallBitVector &BV, unsigned B) {
return BV.test(B);
}
void BlockState::startTrackingLocation(llvm::SmallBitVector &BV, unsigned B) {
BV.set(B);
}
void BlockState::stopTrackingLocation(llvm::SmallBitVector &BV, unsigned B) {
BV.reset(B);
}
void BlockState::mergePredecessorsAvailSetMax(RLEContext &Ctx) {
if (BB->pred_empty()) {
ForwardSetMax.reset();
return;
}
auto Iter = BB->pred_begin();
ForwardSetMax = Ctx.getBlockState(*Iter).ForwardSetMax;
Iter = std::next(Iter);
for (auto EndIter = BB->pred_end(); Iter != EndIter; ++Iter) {
ForwardSetMax &= Ctx.getBlockState(*Iter).ForwardSetMax;
}
}
void BlockState::mergePredecessorAvailSet(RLEContext &Ctx) {
// Clear the state if the basic block has no predecessor.
if (BB->getPreds().begin() == BB->getPreds().end()) {
ForwardSetIn.reset();
return;
}
auto Iter = BB->pred_begin();
ForwardSetIn = Ctx.getBlockState(*Iter).ForwardSetOut;
Iter = std::next(Iter);
for (auto EndIter = BB->pred_end(); Iter != EndIter; ++Iter) {
ForwardSetIn &= Ctx.getBlockState(*Iter).ForwardSetOut;
}
}
void BlockState::mergePredecessorAvailSetAndValue(RLEContext &Ctx) {
// Clear the state if the basic block has no predecessor.
if (BB->getPreds().begin() == BB->getPreds().end()) {
ForwardSetIn.reset();
ForwardValIn.clear();
return;
}
auto Iter = BB->pred_begin();
ForwardSetIn = Ctx.getBlockState(*Iter).ForwardSetOut;
ForwardValIn = Ctx.getBlockState(*Iter).ForwardValOut;
Iter = std::next(Iter);
for (auto EndIter = BB->pred_end(); Iter != EndIter; ++Iter) {
BlockState &OtherState = Ctx.getBlockState(*Iter);
ForwardSetIn &= OtherState.ForwardSetOut;
// Merge in the predecessor state.
for (unsigned i = 0; i < LocationNum; ++i) {
if (OtherState.ForwardSetOut[i]) {
// There are multiple values from multiple predecessors, set this as
// a covering value. We do not need to track the value itself, as we
// can always go to the predecessors BlockState to find it.
ForwardValIn[i] = Ctx.getValueBit(LSValue(true));
continue;
}
// If this location does have an available value, then clear it.
stopTrackingValue(ForwardValIn, i);
stopTrackingLocation(ForwardSetIn, i);
}
}
}
void BlockState::processBasicBlockWithKind(RLEContext &Ctx, RLEKind Kind) {
// Iterate over instructions in forward order.
for (auto &II : *BB) {
processInstructionWithKind(Ctx, &II, Kind);
}
}
bool BlockState::processBasicBlockWithGenKillSet() {
ForwardSetIn.reset(BBKillSet);
ForwardSetIn |= BBGenSet;
return updateForwardSetOut();
}
SILValue BlockState::reduceValuesAtEndOfBlock(RLEContext &Ctx, LSLocation &L) {
// First, collect current available locations and their corresponding values
// into a map.
LSLocationValueMap Values;
LSLocationList Locs;
LSLocation::expand(L, &BB->getModule(), Locs, Ctx.getTE());
// Find the values that this basic block defines and the locations which
// we do not have a concrete value in the current basic block.
ValueTableMap &OTM = getForwardValOut();
for (unsigned i = 0; i < Locs.size(); ++i) {
Values[Locs[i]] = Ctx.getValue(OTM[Ctx.getLocationBit(Locs[i])]);
}
// Second, reduce the available values into a single SILValue we can use to
// forward.
SILValue TheForwardingValue;
TheForwardingValue = LSValue::reduce(L, &BB->getModule(), Values,
BB->getTerminator());
/// Return the forwarding value.
return TheForwardingValue;
}
bool BlockState::setupRLE(RLEContext &Ctx, SILInstruction *I, SILValue Mem) {
// Try to construct a SILValue for the current LSLocation.
//
// Collect the locations and their corresponding values into a map.
LSLocation L;
LSLocationBaseMap &BaseToLocIndex = Ctx.getBM();
if (BaseToLocIndex.find(Mem) != BaseToLocIndex.end()) {
L = BaseToLocIndex[Mem];
} else {
SILValue UO = getUnderlyingObject(Mem);
L = LSLocation(UO, ProjectionPath::getProjectionPath(UO, Mem));
}
LSLocationValueMap Values;
// Use the ForwardValIn as we are currently processing the basic block.
if (!Ctx.collectLocationValues(I->getParent(), L, Values, getForwardValIn()))
return false;
// Reduce the available values into a single SILValue we can use to forward.
SILModule *Mod = &I->getModule();
SILValue TheForwardingValue = LSValue::reduce(L, Mod, Values, I);
if (!TheForwardingValue)
return false;
// Now we have the forwarding value, record it for forwarding!.
//
// NOTE: we do not perform the RLE right here because doing so could introduce
// new LSLocations.
//
// e.g.
// %0 = load %x
// %1 = load %x
// %2 = extract_struct %1, #a
// %3 = load %2
//
// If we perform the RLE and replace %1 with %0, we end up having a memory
// location we do not have before, i.e. Base == %0, and Path == #a.
//
// We may be able to add the LSLocation to the vault, but it gets
// complicated very quickly, e.g. we need to resize the bit vectors size,
// etc.
//
// However, since we already know the instruction to replace and the value to
// replace it with, we can record it for now and forwarded it after all the
// forwardable values are recorded in the function.
//
RedundantLoads[I] = TheForwardingValue;
return true;
}
void BlockState::updateForwardSetForRead(RLEContext &Ctx, unsigned B) {
startTrackingLocation(ForwardSetIn, B);
}
void BlockState::updateGenKillSetForRead(RLEContext &Ctx, unsigned B) {
startTrackingLocation(BBGenSet, B);
stopTrackingLocation(BBKillSet, B);
}
void BlockState::updateForwardSetAndValForRead(RLEContext &Ctx, unsigned L,
unsigned V) {
// Track the new location and value.
startTrackingValue(ForwardValIn, L, V);
startTrackingLocation(ForwardSetIn, L);
}
void BlockState::updateGenKillSetForWrite(RLEContext &Ctx, unsigned B) {
// This is a store, invalidate any location that this location may alias, as
// their values can no longer be forwarded.
LSLocation &R = Ctx.getLocation(B);
for (unsigned i = 0; i < LocationNum; ++i) {
if (!isTrackingLocation(ForwardSetMax, i))
continue;
LSLocation &L = Ctx.getLocation(i);
if (!L.isMayAliasLSLocation(R, Ctx.getAA()))
continue;
// MayAlias, invalidate the location.
stopTrackingLocation(BBGenSet, i);
startTrackingLocation(BBKillSet, i);
}
// Start tracking this location.
startTrackingLocation(BBGenSet, B);
stopTrackingLocation(BBKillSet, B);
}
void BlockState::updateMaxAvailSetForWrite(RLEContext &Ctx, unsigned B) {
startTrackingLocation(ForwardSetMax, B);
}
void BlockState::updateMaxAvailSetForRead(RLEContext &Ctx, unsigned B) {
startTrackingLocation(ForwardSetMax, B);
}
void BlockState::updateForwardSetForWrite(RLEContext &Ctx, unsigned B) {
// This is a store, invalidate any location that this location may alias, as
// their values can no longer be forwarded.
LSLocation &R = Ctx.getLocation(B);
for (unsigned i = 0; i < LocationNum; ++i) {
if (!isTrackingLocation(ForwardSetIn, i))
continue;
LSLocation &L = Ctx.getLocation(i);
if (!L.isMayAliasLSLocation(R, Ctx.getAA()))
continue;
// MayAlias, invalidate the location.
stopTrackingLocation(ForwardSetIn, i);
}
// Start tracking this location.
startTrackingLocation(ForwardSetIn, B);
}
void BlockState::updateForwardSetAndValForWrite(RLEContext &Ctx, unsigned L,
unsigned V) {
// This is a store, invalidate any location that this location may alias, as
// their values can no longer be forwarded.
LSLocation &R = Ctx.getLocation(L);
for (unsigned i = 0; i < LocationNum; ++i) {
if (!isTrackingLocation(ForwardSetIn, i))
continue;
LSLocation &L = Ctx.getLocation(i);
if (!L.isMayAliasLSLocation(R, Ctx.getAA()))
continue;
// MayAlias, invalidate the location and value.
stopTrackingValue(ForwardValIn, i);
stopTrackingLocation(ForwardSetIn, i);
}
// Start tracking this location and value.
startTrackingLocation(ForwardSetIn, L);
startTrackingValue(ForwardValIn, L, V);
}
void BlockState::processWrite(RLEContext &Ctx, SILInstruction *I, SILValue Mem,
SILValue Val, RLEKind Kind) {
// Initialize the LSLocation.
LSLocation L;
LSLocationBaseMap &BaseToLocIndex = Ctx.getBM();
if (BaseToLocIndex.find(Mem) != BaseToLocIndex.end()) {
L = BaseToLocIndex[Mem];
} else {
SILValue UO = getUnderlyingObject(Mem);
L = LSLocation(UO, ProjectionPath::getProjectionPath(UO, Mem));
}
// If we can't figure out the Base or Projection Path for the write,
// process it as an unknown memory instruction.
if (!L.isValid()) {
// we can ignore unknown store instructions if we are computing the
// AvailSetMax.
if (!isComputeAvailSetMax(Kind)) {
processUnknownWriteInst(Ctx, I, Kind);
}
return;
}
// Expand the given location and val into individual fields and process
// them as separate writes.
LSLocationList Locs;
LSLocation::expand(L, &I->getModule(), Locs, Ctx.getTE());
if (isComputeAvailSetMax(Kind)) {
for (unsigned i = 0; i < Locs.size(); ++i) {
updateMaxAvailSetForWrite(Ctx, Ctx.getLocationBit(Locs[i]));
}
return;
}
// Are we computing the genset and killset ?
if (isComputeAvailGenKillSet(Kind)) {
for (unsigned i = 0; i < Locs.size(); ++i) {
updateGenKillSetForWrite(Ctx, Ctx.getLocationBit(Locs[i]));
}
return;
}
// Are we computing available value or performing RLE?
LSValueList Vals;
LSValue::expand(Val, &I->getModule(), Vals, Ctx.getTE());
if (isComputeAvailValue(Kind) || isPerformingRLE(Kind)) {
for (unsigned i = 0; i < Locs.size(); ++i) {
updateForwardSetAndValForWrite(Ctx, Ctx.getLocationBit(Locs[i]),
Ctx.getValueBit(Vals[i]));
}
return;
}
llvm_unreachable("Unknown RLE compute kind");
}
void BlockState::processRead(RLEContext &Ctx, SILInstruction *I, SILValue Mem,
SILValue Val, RLEKind Kind) {
// Initialize the LSLocation.
LSLocation L;
LSLocationBaseMap &BaseToLocIndex = Ctx.getBM();
if (BaseToLocIndex.find(Mem) != BaseToLocIndex.end()) {
L = BaseToLocIndex[Mem];
} else {
SILValue UO = getUnderlyingObject(Mem);
L = LSLocation(UO, ProjectionPath::getProjectionPath(UO, Mem));
}
// If we can't figure out the Base or Projection Path for the read, simply
// ignore it for now.
if (!L.isValid())
return;
// Expand the given LSLocation and Val into individual fields and process
// them as separate reads.
LSLocationList Locs;
LSLocation::expand(L, &I->getModule(), Locs, Ctx.getTE());
if (isComputeAvailSetMax(Kind)) {
for (unsigned i = 0; i < Locs.size(); ++i) {
updateMaxAvailSetForRead(Ctx, Ctx.getLocationBit(Locs[i]));
}
return;
}
// Are we computing the genset and killset.
if (isComputeAvailGenKillSet(Kind)) {
for (unsigned i = 0; i < Locs.size(); ++i) {
updateGenKillSetForRead(Ctx, Ctx.getLocationBit(Locs[i]));
}
return;
}
// Are we computing available values ?.
bool CanForward = true;
LSValueList Vals;
LSValue::expand(Val, &I->getModule(), Vals, Ctx.getTE());
if (isComputeAvailValue(Kind) || isPerformingRLE(Kind)) {
for (unsigned i = 0; i < Locs.size(); ++i) {
if (isTrackingLocation(ForwardSetIn, Ctx.getLocationBit(Locs[i])))
continue;
updateForwardSetAndValForRead(Ctx, Ctx.getLocationBit(Locs[i]),
Ctx.getValueBit(Vals[i]));
// We can not perform the forwarding as we are at least missing
// some pieces of the read location.
CanForward = false;
}
}
// Simply return if we are not performing RLE or we do not have all the
// values available to perform RLE.
if (!isPerformingRLE(Kind) || !CanForward)
return;
// Lastly, forward value to the load.
setupRLE(Ctx, I, Mem);
}
void BlockState::processStoreInst(RLEContext &Ctx, StoreInst *SI, RLEKind Kind) {
processWrite(Ctx, SI, SI->getDest(), SI->getSrc(), Kind);
}
void BlockState::processLoadInst(RLEContext &Ctx, LoadInst *LI, RLEKind Kind) {
processRead(Ctx, LI, LI->getOperand(), SILValue(LI), Kind);
}
void BlockState::processUnknownWriteInstForGenKillSet(RLEContext &Ctx,
SILInstruction *I) {
auto *AA = Ctx.getAA();
for (unsigned i = 0; i < LocationNum; ++i) {
if (!isTrackingLocation(ForwardSetMax, i))
continue;
// Invalidate any location this instruction may write to.
//
// TODO: checking may alias with Base is overly conservative,
// we should check may alias with base plus projection path.
LSLocation &R = Ctx.getLocation(i);
if (!AA->mayWriteToMemory(I, R.getBase()))
continue;
// MayAlias.
stopTrackingLocation(BBGenSet, i);
startTrackingLocation(BBKillSet, i);
}
}
void BlockState::processUnknownWriteInstForRLE(RLEContext &Ctx,
SILInstruction *I) {
auto *AA = Ctx.getAA();
for (unsigned i = 0; i < LocationNum; ++i) {
if (!isTrackingLocation(ForwardSetIn, i))
continue;
// Invalidate any location this instruction may write to.
//
// TODO: checking may alias with Base is overly conservative,
// we should check may alias with base plus projection path.
LSLocation &R = Ctx.getLocation(i);
if (!AA->mayWriteToMemory(I, R.getBase()))
continue;
// MayAlias.
stopTrackingLocation(ForwardSetIn, i);
stopTrackingValue(ForwardValIn, i);
}
}
void BlockState::processUnknownWriteInst(RLEContext &Ctx, SILInstruction *I,
RLEKind Kind) {
// If this is a release on a guaranteed parameter, it can not call deinit,
// which might read or write memory.
if (isIntermediateRelease(I, Ctx.getEAFI()))
return;
// Are we computing the genset and killset ?
if (isComputeAvailGenKillSet(Kind)) {
processUnknownWriteInstForGenKillSet(Ctx, I);
return;
}
// Are we computing the available value or doing RLE ?
if (isComputeAvailValue(Kind) || isPerformingRLE(Kind)) {
processUnknownWriteInstForRLE(Ctx, I);
return;
}
llvm_unreachable("Unknown RLE compute kind");
}
void BlockState::
processDeallocStackInstForGenKillSet(RLEContext &Ctx, SILInstruction *I) {
SILValue ASI = findAllocStackInst(I);
for (unsigned i = 0; i < LocationNum; ++i) {
LSLocation &R = Ctx.getLocation(i);
if (R.getBase() != ASI)
continue;
// MayAlias.
stopTrackingLocation(BBGenSet, i);
startTrackingLocation(BBKillSet, i);
}
}
void BlockState::
processDeallocStackInstForRLE(RLEContext &Ctx, SILInstruction *I) {
SILValue ASI = findAllocStackInst(I);
for (unsigned i = 0; i < LocationNum; ++i) {
LSLocation &R = Ctx.getLocation(i);
if (R.getBase() != ASI)
continue;
// MayAlias.
stopTrackingLocation(ForwardSetIn, i);
stopTrackingValue(ForwardValIn, i);
}
}
void BlockState::
processDeallocStackInst(RLEContext &Ctx, SILInstruction *I, RLEKind Kind) {
// Are we computing the genset and killset ?
if (isComputeAvailGenKillSet(Kind)) {
processDeallocStackInstForGenKillSet(Ctx, I);
return;
}
// Are we computing the available value or doing RLE ?
if (isComputeAvailValue(Kind) || isPerformingRLE(Kind)) {
processDeallocStackInstForRLE(Ctx, I);
return;
}
llvm_unreachable("Unknown RLE compute kind");
}
void BlockState::processInstructionWithKind(RLEContext &Ctx,
SILInstruction *Inst,
RLEKind Kind) {
// This is a StoreInst, try to see whether it clobbers any forwarding value
if (auto *SI = dyn_cast<StoreInst>(Inst)) {
processStoreInst(Ctx, SI, Kind);
return;
}
// This is a LoadInst. Let's see if we can find a previous loaded, stored
// value to use instead of this load.
if (auto *LI = dyn_cast<LoadInst>(Inst)) {
processLoadInst(Ctx, LI, Kind);
return;
}
if (auto *DSI = dyn_cast<DeallocStackInst>(Inst)) {
processDeallocStackInst(Ctx, DSI, Kind);
return;
}
// If this instruction has side effects, but is inert from a load store
// perspective, skip it.
if (isRLEInertInstruction(Inst))
return;
// If this instruction does not read or write memory, we can skip it.
if (!Inst->mayReadOrWriteMemory())
return;
// If we have an instruction that may write to memory and we cannot prove
// that it and its operands cannot alias a load we have visited,
// invalidate that load.
if (Inst->mayWriteToMemory()) {
processUnknownWriteInst(Ctx, Inst, Kind);
return;
}
}
RLEContext::ProcessKind
RLEContext::
getProcessFunctionKind(unsigned LoadCount, unsigned StoreCount) {
// Don't optimize function that are marked as 'no.optimize'.
if (!Fn->shouldOptimize())
return ProcessKind::ProcessNone;
// Really no point optimizing here as there is no forwardable loads.
if (LoadCount + StoreCount < 2)
return ProcessKind::ProcessNone;
bool RunOneIteration = true;
unsigned BBCount = 0;
unsigned LocationCount = LocationVault.size();
if (LocationCount == 0)
return ProcessKind::ProcessNone;
// If all basic blocks will have their predecessors processed if
// the basic blocks in the functions are iterated in post order.
// Then this function can be processed in one iteration, i.e. no
// need to generate the genset and killset.
auto *PO = PM->getAnalysis<PostOrderAnalysis>()->get(Fn);
llvm::DenseSet<SILBasicBlock *> HandledBBs;
for (SILBasicBlock *B : PO->getReversePostOrder()) {
++BBCount;
for (auto X : B->getPreds()) {
if (HandledBBs.find(X) == HandledBBs.end()) {
RunOneIteration = false;
break;
}
}
HandledBBs.insert(B);
}
// Data flow may take too long to run.
if (BBCount * LocationCount > MaxLSLocationBBMultiplicationNone)
return ProcessKind::ProcessNone;
// This function's data flow would converge in 1 iteration.
if (RunOneIteration)
return ProcessKind::ProcessOneIteration;
// We run one pessimistic data flow to do dead store elimination on
// the function.
if (BBCount * LocationCount > MaxLSLocationBBMultiplicationPessimistic)
return ProcessKind::ProcessOneIteration;
return ProcessKind::ProcessMultipleIterations;
}
//===----------------------------------------------------------------------===//
// RLEContext Implementation
//===----------------------------------------------------------------------===//
RLEContext::RLEContext(SILFunction *F, SILPassManager *PM, AliasAnalysis *AA,
TypeExpansionAnalysis *TE, PostOrderFunctionInfo *PO,
EpilogueARCFunctionInfo *EAFI)
: Fn(F), PM(PM), AA(AA), TE(TE), PO(PO), EAFI(EAFI) {
}
LSLocation &RLEContext::getLocation(const unsigned index) {
return LocationVault[index];
}
unsigned RLEContext::getLocationBit(const LSLocation &Loc) {
// Return the bit position of the given Loc in the LocationVault. The bit
// position is then used to set/reset the bitvector kept by each BlockState.
//
// We should have the location populated by the enumerateLSLocation at this
// point.
auto Iter = LocToBitIndex.find(Loc);
assert(Iter != LocToBitIndex.end() && "Location should have been enum'ed");
return Iter->second;
}
LSValue &RLEContext::getValue(const unsigned index) {
return LSValueVault[index];
}
unsigned RLEContext::getValueBit(const LSValue &Val) {
// Return the bit position of the given Val in the LSValueVault. The bit
// position is then used to set/reset the bitvector kept by each g.
auto Iter = ValToBitIndex.find(Val);
// We do not walk over the function and find all the possible LSValues
// in this function, as some of the these values will not be used, i.e.
// if the LoadInst that generates this value is actually RLE'ed.
// Instead, we create the LSValues when we need them.
if (Iter == ValToBitIndex.end()) {
ValToBitIndex[Val] = LSValueVault.size();
LSValueVault.push_back(Val);
return ValToBitIndex[Val];
}
return Iter->second;
}
BlockState::ValueState BlockState::getValueStateAtEndOfBlock(RLEContext &Ctx,
LSLocation &L) {
// Find number of covering value and concrete values for the locations
// expanded from the given location.
unsigned CSCount = 0, CTCount = 0;
LSLocationList Locs;
LSLocation::expand(L, &BB->getModule(), Locs, Ctx.getTE());
ValueTableMap &OTM = getForwardValOut();
for (auto &X : Locs) {
LSValue &V = Ctx.getValue(OTM[Ctx.getLocationBit(X)]);
if (V.isCoveringValue()) {
++CSCount;
continue;
}
++CTCount;
}
if (CSCount == Locs.size())
return ValueState::CoverValues;
if (CTCount == Locs.size())
return ValueState::ConcreteValues;
return ValueState::CoverAndConcreteValues;
}
SILValue RLEContext::computePredecessorLocationValue(SILBasicBlock *BB,
LSLocation &L) {
BBValueMap Values;
llvm::DenseSet<SILBasicBlock *> HandledBBs;
llvm::SmallVector<SILBasicBlock *, 8> WorkList;
// Push in all the predecessors to get started.
for (auto Pred : BB->getPreds()) {
WorkList.push_back(Pred);
}
while (!WorkList.empty()) {
auto *CurBB = WorkList.pop_back_val();
BlockState &Forwarder = getBlockState(CurBB);
// Mark this basic block as processed.
HandledBBs.insert(CurBB);
// There are 3 cases that can happen here.
//
// 1. The current basic block contains concrete values for the entire
// location.
// 2. The current basic block contains covering values for the entire
// location.
// 3. The current basic block contains concrete value for part of the
// location and covering values for the rest.
//
// This BlockState contains concrete values for all the expanded
// locations, collect and reduce them into a single value in the current
// basic block.
if (Forwarder.isConcreteValues(*this, L)) {
Values[CurBB] = Forwarder.reduceValuesAtEndOfBlock(*this, L);
continue;
}
// This BlockState does not contain concrete value for any of the expanded
// locations, collect in this block's predecessors.
if (Forwarder.isCoverValues(*this, L)) {
for (auto Pred : CurBB->getPreds()) {
if (HandledBBs.find(Pred) != HandledBBs.end())
continue;
WorkList.push_back(Pred);
}
continue;
}
// This block contains concrete values for some but not all the expanded
// locations, recursively call collectLocationValues to materialize the
// value that reaches this basic block.
LSLocationValueMap LSValues;
if (!collectLocationValues(CurBB, L, LSValues, Forwarder.getForwardValOut()))
return SILValue();
// Reduce the available values into a single SILValue we can use to forward
SILInstruction *IPt = CurBB->getTerminator();
Values[CurBB] = LSValue::reduce(L, &BB->getModule(), LSValues, IPt);
}
// Finally, collect all the values for the SILArgument, materialize it using
// the SSAUpdater.
Updater.Initialize(L.getType(&BB->getModule()).getObjectType());
for (auto V : Values) {
Updater.AddAvailableValue(V.first, V.second);
}
return Updater.GetValueInMiddleOfBlock(BB);
}
bool RLEContext::collectLocationValues(SILBasicBlock *BB, LSLocation &L,
LSLocationValueMap &Values,
ValueTableMap &VM) {
LSLocationSet CSLocs;
LSLocationList Locs;
LSLocation::expand(L, &BB->getModule(), Locs, TE);
auto *Mod = &BB->getModule();
// Find the locations that this basic block defines and the locations which
// we do not have a concrete value in the current basic block.
for (auto &X : Locs) {
Values[X] = getValue(VM[getLocationBit(X)]);
if (!Values[X].isCoveringValue())
continue;
CSLocs.insert(X);
}
// For locations which we do not have concrete values for in this basic
// block, try to reduce it to the minimum # of locations possible, this
// will help us to generate as few SILArguments as possible.
LSLocation::reduce(L, Mod, CSLocs);
// To handle covering value, we need to go to the predecessors and
// materialize them there.
for (auto &X : CSLocs) {
SILValue V = computePredecessorLocationValue(BB, X);
if (!V)
return false;
// We've constructed a concrete value for the covering value. Expand and
// collect the newly created forwardable values.
LSLocationList Locs;
LSValueList Vals;
LSLocation::expand(X, Mod, Locs, TE);
LSValue::expand(V, Mod, Vals, TE);
for (unsigned i = 0; i < Locs.size(); ++i) {
Values[Locs[i]] = Vals[i];
assert(Values[Locs[i]].isValid() && "Invalid load store value");
}
}
return true;
}
void RLEContext::processBasicBlocksForGenKillSet() {
for (SILBasicBlock *BB : PO->getReversePostOrder()) {
BlockState &S = getBlockState(BB);
// Compute the AvailSetMax at the beginning of the basic block.
S.mergePredecessorsAvailSetMax(*this);
// Compute the genset and killset.
//
// To optimize this process, we also compute the AvailSetMax at particular
// point in the basic block.
for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
if (auto *LI = dyn_cast<LoadInst>(&*I)) {
if (BBWithLoads.find(BB) == BBWithLoads.end())
BBWithLoads.insert(BB);
S.processLoadInst(*this, LI, RLEKind::ComputeAvailSetMax);
}
if (auto *SI = dyn_cast<StoreInst>(&*I)) {
S.processStoreInst(*this, SI, RLEKind::ComputeAvailSetMax);
}
S.processInstructionWithKind(*this, &*I, RLEKind::ComputeAvailGenKillSet);
}
}
}
void RLEContext::processBasicBlocksWithGenKillSet() {
// Process each basic block with the gen and kill set. Every time the
// ForwardSetOut of a basic block changes, the optimization is rerun on its
// successors.
llvm::SmallVector<SILBasicBlock *, 16> WorkList;
llvm::DenseSet<SILBasicBlock *> HandledBBs;
// Push into the worklist in post order so that we can pop from the back and
// get reverse post order.
for (SILBasicBlock *BB : PO->getPostOrder()) {
WorkList.push_back(BB);
HandledBBs.insert(BB);
}
while (!WorkList.empty()) {
SILBasicBlock *BB = WorkList.pop_back_val();
HandledBBs.erase(BB);
// Intersection.
BlockState &Forwarder = getBlockState(BB);
// Compute the ForwardSetIn at the beginning of the basic block.
Forwarder.mergePredecessorAvailSet(*this);
if (Forwarder.processBasicBlockWithGenKillSet()) {
for (auto &X : BB->getSuccessors()) {
// We do not push basic block into the worklist if its already
// in the worklist.
if (HandledBBs.find(X) != HandledBBs.end())
continue;
WorkList.push_back(X);
}
}
}
}
void RLEContext::processBasicBlocksForAvailValue() {
for (SILBasicBlock *BB : PO->getReversePostOrder()) {
BlockState &Forwarder = getBlockState(BB);
// Merge the predecessors. After merging, BlockState now contains
// lists of available LSLocations and their values that reach the
// beginning of the basic block along all paths.
Forwarder.mergePredecessorAvailSetAndValue(*this);
// Merge duplicate loads, and forward stores to
// loads. We also update lists of stores|loads to reflect the end
// of the basic block.
Forwarder.processBasicBlockWithKind(*this, RLEKind::ComputeAvailValue);
// Update the locations with available values. We do not need to update
// the available BitVector here as they should have been initialized and
// stabilized in the processBasicBlocksWithGenKillSet.
Forwarder.updateForwardValOut();
}
}
void RLEContext::processBasicBlocksForRLE(bool Optimistic) {
for (SILBasicBlock *BB : PO->getReversePostOrder()) {
// If we know this is not a one iteration function which means its
// forward sets have been computed and converged,
// and this basic block does not even have LoadInsts, there is no point
// in processing every instruction in the basic block again as no store
// will be eliminated.
if (Optimistic && BBWithLoads.find(BB) == BBWithLoads.end())
continue;
BlockState &Forwarder = getBlockState(BB);
// Merge the predecessors. After merging, BlockState now contains
// lists of available LSLocations and their values that reach the
// beginning of the basic block along all paths.
Forwarder.mergePredecessorAvailSetAndValue(*this);
// Perform the actual redundant load elimination.
Forwarder.processBasicBlockWithKind(*this, RLEKind::PerformRLE);
// If this is not a one iteration data flow, then the forward sets
// have been computed.
if (Optimistic)
continue;
// Update the locations with available values and their values.
Forwarder.updateForwardSetOut();
Forwarder.updateForwardValOut();
}
}
void RLEContext::runIterativeRLE() {
// Generate the genset and killset for every basic block.
processBasicBlocksForGenKillSet();
// Process basic blocks in RPO. After the data flow converges, run last
// iteration and perform load forwarding.
processBasicBlocksWithGenKillSet();
// We have computed the available value bit, now go through every basic
// block and compute the forwarding value locally. This is necessary as
// when we perform the RLE in the last iteration, we must handle loops, i.e.
// predecessor blocks which have not been processed when a basic block is
// processed.
processBasicBlocksForAvailValue();
}
bool RLEContext::run() {
// We perform redundant load elimination in the following phases.
//
// Phase 1. Compute the genset and killset for every basic block.
//
// Phase 2. Use an iterative data flow to compute whether there is an
// available value at a given point, we do not yet care about what the value
// is.
//
// Phase 3. we compute the real forwardable value at a given point.
//
// Phase 4. we perform the redundant load elimination.
// Walk over the function and find all the locations accessed by
// this function.
std::pair<int, int> LSCount = std::make_pair(0, 0);
LSLocation::enumerateLSLocations(*Fn, LocationVault,
LocToBitIndex,
BaseToLocIndex, TE,
LSCount);
// Check how to optimize this function.
ProcessKind Kind = getProcessFunctionKind(LSCount.first, LSCount.second);
// We do not optimize this function at all.
if (Kind == ProcessKind::ProcessNone)
return false;
// Do we run a multi-iteration data flow ?
bool Optimistic = Kind == ProcessKind::ProcessMultipleIterations ?
true : false;
// These are a list of basic blocks that we actually processed.
// We do not process unreachable block, instead we set their liveouts to nil.
llvm::DenseSet<SILBasicBlock *> BBToProcess;
for (auto X : PO->getPostOrder())
BBToProcess.insert(X);
// For all basic blocks in the function, initialize a BB state. Since we
// know all the locations accessed in this function, we can resize the bit
// vector to the appropriate size.
for (auto &B : *Fn) {
BBToLocState[&B] = BlockState();
BBToLocState[&B].init(&B, LocationVault.size(), Optimistic &&
BBToProcess.find(&B) != BBToProcess.end());
}
if (Optimistic)
runIterativeRLE();
// We have the available value bit computed and the local forwarding value.
// Set up the load forwarding.
processBasicBlocksForRLE(Optimistic);
// Finally, perform the redundant load replacements.
llvm::DenseSet<SILInstruction *> InstsToDelete;
bool SILChanged = false;
for (auto &B : *Fn) {
auto &State = BBToLocState[&B];
auto &Loads = State.getRL();
// Nothing to forward.
if (Loads.empty())
continue;
// We iterate the instructions in the basic block in a deterministic order
// and use this order to perform the load forwarding.
//
// NOTE: we could end up with different SIL depending on the ordering load
// forwarding is performed.
for (auto I = B.rbegin(), E = B.rend(); I != E; ++I) {
auto Iter = Loads.find(&*I);
if (Iter == Loads.end())
continue;
DEBUG(llvm::dbgs() << "Replacing " << SILValue(Iter->first) << "With "
<< Iter->second);
SILChanged = true;
Iter->first->replaceAllUsesWith(Iter->second);
InstsToDelete.insert(Iter->first);
++NumForwardedLoads;
}
}
// Erase the instructions recursively, this way, we get rid of pass
// dependence on DCE.
for (auto &X : InstsToDelete) {
// It is possible that the instruction still has uses, because it could be
// used as the replacement Value, i.e. F.second, for some other RLE pairs.
//
// TODO: we should fix this, otherwise we are missing RLE opportunities.
if (!X->use_empty())
continue;
recursivelyDeleteTriviallyDeadInstructions(X, true);
}
return SILChanged;
}
//===----------------------------------------------------------------------===//
// Top Level Entry Point
//===----------------------------------------------------------------------===//
namespace {
class RedundantLoadElimination : public SILFunctionTransform {
StringRef getName() override { return "SIL Redundant Load Elimination"; }
/// The entry point to the transformation.
void run() override {
SILFunction *F = getFunction();
DEBUG(llvm::dbgs() << "*** RLE on function: " << F->getName() << " ***\n");
auto *AA = PM->getAnalysis<AliasAnalysis>();
auto *TE = PM->getAnalysis<TypeExpansionAnalysis>();
auto *PO = PM->getAnalysis<PostOrderAnalysis>()->get(F);
auto *EAFI = PM->getAnalysis<EpilogueARCAnalysis>()->get(F);
RLEContext RLE(F, PM, AA, TE, PO, EAFI);
if (RLE.run()) {
invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
}
}
};
} // end anonymous namespace
SILTransform *swift::createRedundantLoadElimination() {
return new RedundantLoadElimination();
}
| apache-2.0 |
jeromerg/NSix | src/Version/Resource/Assembly.cpp | 4 | 1276 | #include "stdafx.h"
#include "../../../NGitVersion/Generated/GlobalAssemblyInfo.h" // TODO: Fix the path!
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
// ----------------------------------------------------------------------
// LOCAL
// ----------------------------------------------------------------------
[assembly:AssemblyTitleAttribute("TODO Title")];
[assembly:AssemblyDescriptionAttribute("TODO Description")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
// ----------------------------------------------------------------------
// GLOBAL
// ----------------------------------------------------------------------
[assembly:AssemblyCompanyAttribute(COMPANY)];
[assembly:AssemblyProductAttribute(PRODUCT)];
[assembly:AssemblyCopyrightAttribute(COPYRIGHT)];
[assembly:AssemblyTrademarkAttribute(TRADEMARK)];
[assembly:AssemblyConfigurationAttribute(CONFIGURATION)];
[assembly:AssemblyCultureAttribute(CULTURE)];
[assembly:AssemblyVersionAttribute(VERSION)];
[assembly:AssemblyFileVersionAttribute(VERSION)];
[assembly:AssemblyInformationalVersionAttribute(FULL_VERSION)];
| apache-2.0 |
vldpyatkov/ignite | modules/platforms/cpp/core/src/impl/interop/interop_target.cpp | 5 | 6811 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ignite/impl/interop/interop_target.h"
#include "ignite/impl/binary/binary_type_updater_impl.h"
using namespace ignite::common::concurrent;
using namespace ignite::jni::java;
using namespace ignite::java;
using namespace ignite::impl::interop;
using namespace ignite::impl::binary;
using namespace ignite::binary;
namespace ignite
{
namespace impl
{
namespace interop
{
/**
* Operation result.
*/
enum OperationResult
{
/** Null. */
ResultNull = 0,
/** Object. */
ResultObject = 1,
/** Error. */
ResultError = -1
};
InteropTarget::InteropTarget(SharedPointer<IgniteEnvironment> env, jobject javaRef) :
env(env), javaRef(javaRef)
{
// No-op.
}
InteropTarget::~InteropTarget()
{
JniContext::Release(javaRef);
}
int64_t InteropTarget::WriteTo(InteropMemory* mem, InputOperation& inOp, IgniteError* err)
{
BinaryTypeManager* metaMgr = env.Get()->GetTypeManager();
int32_t metaVer = metaMgr->GetVersion();
InteropOutputStream out(mem);
BinaryWriterImpl writer(&out, metaMgr);
inOp.ProcessInput(writer);
out.Synchronize();
if (metaMgr->IsUpdatedSince(metaVer))
{
if (!metaMgr->ProcessPendingUpdates(env.Get()->GetTypeUpdater(), err))
return 0;
}
return mem->PointerLong();
}
void InteropTarget::ReadFrom(InteropMemory* mem, OutputOperation& outOp)
{
InteropInputStream in(mem);
BinaryReaderImpl reader(&in);
outOp.ProcessOutput(reader);
}
bool InteropTarget::OutOp(int32_t opType, InputOperation& inOp, IgniteError* err)
{
JniErrorInfo jniErr;
SharedPointer<InteropMemory> mem = env.Get()->AllocateMemory();
int64_t outPtr = WriteTo(mem.Get(), inOp, err);
if (outPtr)
{
long long res = env.Get()->Context()->TargetInStreamOutLong(javaRef, opType, outPtr, &jniErr);
IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
if (jniErr.code == IGNITE_JNI_ERR_SUCCESS)
return res == 1;
}
return false;
}
bool InteropTarget::OutOp(int32_t opType, IgniteError* err)
{
JniErrorInfo jniErr;
long long res = env.Get()->Context()->TargetInLongOutLong(javaRef, opType, 0, &jniErr);
IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
if (jniErr.code == IGNITE_JNI_ERR_SUCCESS)
return res == 1;
return false;
}
bool InteropTarget::InOp(int32_t opType, OutputOperation& outOp, IgniteError* err)
{
JniErrorInfo jniErr;
SharedPointer<InteropMemory> mem = env.Get()->AllocateMemory();
env.Get()->Context()->TargetOutStream(javaRef, opType, mem.Get()->PointerLong(), &jniErr);
IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
if (jniErr.code == IGNITE_JNI_ERR_SUCCESS)
{
ReadFrom(mem.Get(), outOp);
return true;
}
return false;
}
void InteropTarget::OutInOp(int32_t opType, InputOperation& inOp, OutputOperation& outOp, IgniteError* err)
{
JniErrorInfo jniErr;
SharedPointer<InteropMemory> outMem = env.Get()->AllocateMemory();
SharedPointer<InteropMemory> inMem = env.Get()->AllocateMemory();
int64_t outPtr = WriteTo(outMem.Get(), inOp, err);
if (outPtr)
{
env.Get()->Context()->TargetInStreamOutStream(javaRef, opType, outPtr,
inMem.Get()->PointerLong(), &jniErr);
IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
if (jniErr.code == IGNITE_JNI_ERR_SUCCESS)
ReadFrom(inMem.Get(), outOp);
}
}
void InteropTarget::OutInOpX(int32_t opType, InputOperation& inOp, OutputOperation& outOp, IgniteError* err)
{
JniErrorInfo jniErr;
SharedPointer<InteropMemory> outInMem = env.Get()->AllocateMemory();
int64_t outInPtr = WriteTo(outInMem.Get(), inOp, err);
if (outInPtr)
{
int64_t res = env.Get()->Context()->TargetInStreamOutLong(javaRef, opType, outInPtr, &jniErr);
IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
if (jniErr.code == IGNITE_JNI_ERR_SUCCESS && res == ResultObject)
ReadFrom(outInMem.Get(), outOp);
else if (res == ResultNull)
outOp.SetNull();
//Read and process error if res == ResultError here.
}
}
int64_t InteropTarget::OutInOpLong(int32_t opType, int64_t val, IgniteError* err)
{
JniErrorInfo jniErr;
long long res = env.Get()->Context()->TargetInLongOutLong(javaRef, opType, val, &jniErr);
IgniteError::SetError(jniErr.code, jniErr.errCls, jniErr.errMsg, err);
return res;
}
}
}
} | apache-2.0 |
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Modules/_json.c | 6 | 81565 | #include "Python.h"
#include "structmember.h"
#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#define PyInt_FromSsize_t PyInt_FromLong
#define PyInt_AsSsize_t PyInt_AsLong
#endif
#ifndef Py_IS_FINITE
#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
#endif
#ifdef __GNUC__
#define UNUSED __attribute__((__unused__))
#else
#define UNUSED
#endif
#define DEFAULT_ENCODING "utf-8"
#define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType)
#define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType)
#define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType)
#define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType)
static PyTypeObject PyScannerType;
static PyTypeObject PyEncoderType;
typedef struct _PyScannerObject {
PyObject_HEAD
PyObject *encoding;
PyObject *strict;
PyObject *object_hook;
PyObject *pairs_hook;
PyObject *parse_float;
PyObject *parse_int;
PyObject *parse_constant;
} PyScannerObject;
static PyMemberDef scanner_members[] = {
{"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"},
{"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"},
{"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"},
{"object_pairs_hook", T_OBJECT, offsetof(PyScannerObject, pairs_hook), READONLY, "object_pairs_hook"},
{"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"},
{"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"},
{"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"},
{NULL}
};
typedef struct _PyEncoderObject {
PyObject_HEAD
PyObject *markers;
PyObject *defaultfn;
PyObject *encoder;
PyObject *indent;
PyObject *key_separator;
PyObject *item_separator;
PyObject *sort_keys;
PyObject *skipkeys;
int fast_encode;
int allow_nan;
} PyEncoderObject;
static PyMemberDef encoder_members[] = {
{"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"},
{"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"},
{"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"},
{"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"},
{"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"},
{"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"},
{"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"},
{"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"},
{NULL}
};
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars);
static PyObject *
ascii_escape_unicode(PyObject *pystr);
static PyObject *
ascii_escape_str(PyObject *pystr);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr);
void init_json(void);
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx);
static PyObject *
scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
scanner_dealloc(PyObject *self);
static int
scanner_clear(PyObject *self);
static PyObject *
encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
encoder_dealloc(PyObject *self);
static int
encoder_clear(PyObject *self);
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level);
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level);
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level);
static PyObject *
_encoded_const(PyObject *obj);
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end);
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj);
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr);
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr);
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj);
#define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
#define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))
#define MIN_EXPANSION 6
#ifdef Py_UNICODE_WIDE
#define MAX_EXPANSION (2 * MIN_EXPANSION)
#else
#define MAX_EXPANSION MIN_EXPANSION
#endif
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr)
{
/* PyObject to Py_ssize_t converter */
*size_ptr = PyInt_AsSsize_t(o);
if (*size_ptr == -1 && PyErr_Occurred())
return 0;
return 1;
}
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr)
{
/* Py_ssize_t to PyObject converter */
return PyInt_FromSsize_t(*size_ptr);
}
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars)
{
/* Escape unicode code point c to ASCII escape sequences
in char *output. output must have at least 12 bytes unused to
accommodate an escaped surrogate pair "\uXXXX\uXXXX" */
output[chars++] = '\\';
switch (c) {
case '\\': output[chars++] = (char)c; break;
case '"': output[chars++] = (char)c; break;
case '\b': output[chars++] = 'b'; break;
case '\f': output[chars++] = 'f'; break;
case '\n': output[chars++] = 'n'; break;
case '\r': output[chars++] = 'r'; break;
case '\t': output[chars++] = 't'; break;
default:
#ifdef Py_UNICODE_WIDE
if (c >= 0x10000) {
/* UTF-16 surrogate pair */
Py_UNICODE v = c - 0x10000;
c = 0xd800 | ((v >> 10) & 0x3ff);
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
c = 0xdc00 | (v & 0x3ff);
output[chars++] = '\\';
}
#endif
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
}
return chars;
}
static PyObject *
ascii_escape_unicode(PyObject *pystr)
{
/* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t max_output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
Py_UNICODE *input_unicode;
input_chars = PyUnicode_GET_SIZE(pystr);
input_unicode = PyUnicode_AS_UNICODE(pystr);
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
max_output_size = 2 + (input_chars * MAX_EXPANSION);
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
chars = 0;
output[chars++] = '"';
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = input_unicode[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
if (output_size - chars < (1 + MAX_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
Py_ssize_t new_output_size = output_size * 2;
/* This is an upper bound */
if (new_output_size > max_output_size) {
new_output_size = max_output_size;
}
/* Make sure that the output size changed before resizing */
if (new_output_size != output_size) {
output_size = new_output_size;
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static PyObject *
ascii_escape_str(PyObject *pystr)
{
/* Take a PyString pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
char *input_str;
input_chars = PyString_GET_SIZE(pystr);
input_str = PyString_AS_STRING(pystr);
/* Fast path for a string that's already ASCII */
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (!S_CHAR(c)) {
/* If we have to escape something, scan the string for unicode */
Py_ssize_t j;
for (j = i; j < input_chars; j++) {
c = (Py_UNICODE)(unsigned char)input_str[j];
if (c > 0x7f) {
/* We hit a non-ASCII character, bail to unicode mode */
PyObject *uni;
uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict");
if (uni == NULL) {
return NULL;
}
rval = ascii_escape_unicode(uni);
Py_DECREF(uni);
return rval;
}
}
break;
}
}
if (i == input_chars) {
/* Input is already ASCII */
output_size = 2 + input_chars;
}
else {
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
}
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
output[0] = '"';
/* We know that everything up to i is ASCII already */
chars = i + 1;
memcpy(&output[1], input_str, i);
for (; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
/* An ASCII char can't possibly expand to a surrogate! */
if (output_size - chars < (1 + MIN_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
output_size *= 2;
if (output_size > 2 + (input_chars * MIN_EXPANSION)) {
output_size = 2 + (input_chars * MIN_EXPANSION);
}
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
{
/* Use the Python function json.decoder.errmsg to raise a nice
looking ValueError exception */
static PyObject *errmsg_fn = NULL;
PyObject *pymsg;
if (errmsg_fn == NULL) {
PyObject *decoder = PyImport_ImportModule("json.decoder");
if (decoder == NULL)
return;
errmsg_fn = PyObject_GetAttrString(decoder, "errmsg");
Py_DECREF(decoder);
if (errmsg_fn == NULL)
return;
}
pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end);
if (pymsg) {
PyErr_SetObject(PyExc_ValueError, pymsg);
Py_DECREF(pymsg);
}
}
static PyObject *
join_list_unicode(PyObject *lst)
{
/* return u''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyUnicode_FromUnicode(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
/* return (rval, idx) tuple, stealing reference to rval */
PyObject *tpl;
PyObject *pyidx;
/*
steal a reference to rval, returns (rval, idx)
*/
if (rval == NULL) {
return NULL;
}
pyidx = PyInt_FromSsize_t(idx);
if (pyidx == NULL) {
Py_DECREF(rval);
return NULL;
}
tpl = PyTuple_New(2);
if (tpl == NULL) {
Py_DECREF(pyidx);
Py_DECREF(rval);
return NULL;
}
PyTuple_SET_ITEM(tpl, 0, rval);
PyTuple_SET_ITEM(tpl, 1, pyidx);
return tpl;
}
static PyObject *
scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyString pystr.
end is the index of the first character after the quote.
encoding is the encoding of pystr (must be an ASCII superset)
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyString (if ASCII-only) or PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyString_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next;
char *buf = PyString_AS_STRING(pystr);
PyObject *chunks = PyList_New(0);
if (chunks == NULL) {
goto bail;
}
if (end < 0 || len <= end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
PyObject *chunk = NULL;
for (next = end; next < len; next++) {
c = (unsigned char)buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
PyObject *strchunk = PyString_FromStringAndSize(&buf[end], next - end);
if (strchunk == NULL) {
goto bail;
}
chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL);
Py_DECREF(strchunk);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c2 <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
rval = join_list_unicode(chunks);
if (rval == NULL) {
goto bail;
}
Py_CLEAR(chunks);
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunks);
return NULL;
}
static PyObject *
scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyUnicode pystr.
end is the index of the first character after the quote.
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next;
const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
PyObject *chunks = PyList_New(0);
if (chunks == NULL) {
goto bail;
}
if (end < 0 || len <= end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
PyObject *chunk = NULL;
for (next = end; next < len; next++) {
c = buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
chunk = PyUnicode_FromUnicode(&buf[end], next - end);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c2 <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
rval = join_list_unicode(chunks);
if (rval == NULL) {
goto bail;
}
Py_DECREF(chunks);
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunks);
return NULL;
}
PyDoc_STRVAR(pydoc_scanstring,
"scanstring(basestring, end, encoding, strict=True) -> (str, end)\n"
"\n"
"Scan the string s for a JSON string. End is the index of the\n"
"character in s after the quote that started the JSON string.\n"
"Unescapes all valid JSON string escape sequences and raises ValueError\n"
"on attempt to decode an invalid string. If strict is False then literal\n"
"control characters are allowed in the string.\n"
"\n"
"Returns a tuple of the decoded string and the index of the character in s\n"
"after the end quote."
);
static PyObject *
py_scanstring(PyObject* self UNUSED, PyObject *args)
{
PyObject *pystr;
PyObject *rval;
Py_ssize_t end;
Py_ssize_t next_end = -1;
char *encoding = NULL;
int strict = 1;
if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) {
return NULL;
}
if (encoding == NULL) {
encoding = DEFAULT_ENCODING;
}
if (PyString_Check(pystr)) {
rval = scanstring_str(pystr, end, encoding, strict, &next_end);
}
else if (PyUnicode_Check(pystr)) {
rval = scanstring_unicode(pystr, end, strict, &next_end);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_end);
}
PyDoc_STRVAR(pydoc_encode_basestring_ascii,
"encode_basestring_ascii(basestring) -> str\n"
"\n"
"Return an ASCII-only JSON representation of a Python string"
);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr)
{
/* Return an ASCII-only JSON representation of a Python string */
/* METH_O */
if (PyString_Check(pystr)) {
return ascii_escape_str(pystr);
}
else if (PyUnicode_Check(pystr)) {
return ascii_escape_unicode(pystr);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
}
static void
scanner_dealloc(PyObject *self)
{
/* Deallocate scanner object */
scanner_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
scanner_traverse(PyObject *self, visitproc visit, void *arg)
{
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
Py_VISIT(s->encoding);
Py_VISIT(s->strict);
Py_VISIT(s->object_hook);
Py_VISIT(s->pairs_hook);
Py_VISIT(s->parse_float);
Py_VISIT(s->parse_int);
Py_VISIT(s->parse_constant);
return 0;
}
static int
scanner_clear(PyObject *self)
{
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->pairs_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
return 0;
}
static PyObject *
_parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyString pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *rval;
PyObject *pairs;
PyObject *item;
PyObject *key = NULL;
PyObject *val = NULL;
char *encoding = PyString_AS_STRING(s->encoding);
int strict = PyObject_IsTrue(s->strict);
Py_ssize_t next_idx;
pairs = PyList_New(0);
if (pairs == NULL)
return NULL;
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
/* read key */
if (str[idx] != '"') {
raise_errmsg("Expecting property name", pystr, idx);
goto bail;
}
key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx);
if (key == NULL)
goto bail;
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting : delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON data type */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
item = PyTuple_Pack(2, key, val);
if (item == NULL)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
if (PyList_Append(pairs, item) == -1) {
Py_DECREF(item);
goto bail;
}
Py_DECREF(item);
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if pairs_hook is not None: rval = object_pairs_hook(pairs) */
if (s->pairs_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->pairs_hook, pairs, NULL);
if (val == NULL)
goto bail;
Py_DECREF(pairs);
*next_idx_ptr = idx + 1;
return val;
}
rval = PyObject_CallFunctionObjArgs((PyObject *)(&PyDict_Type),
pairs, NULL);
if (rval == NULL)
goto bail;
Py_CLEAR(pairs);
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(key);
Py_XDECREF(val);
Py_XDECREF(pairs);
return NULL;
}
static PyObject *
_parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyUnicode pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *rval;
PyObject *pairs;
PyObject *item;
PyObject *key = NULL;
PyObject *val = NULL;
int strict = PyObject_IsTrue(s->strict);
Py_ssize_t next_idx;
pairs = PyList_New(0);
if (pairs == NULL)
return NULL;
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
/* read key */
if (str[idx] != '"') {
raise_errmsg("Expecting property name", pystr, idx);
goto bail;
}
key = scanstring_unicode(pystr, idx + 1, strict, &next_idx);
if (key == NULL)
goto bail;
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting : delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
item = PyTuple_Pack(2, key, val);
if (item == NULL)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
if (PyList_Append(pairs, item) == -1) {
Py_DECREF(item);
goto bail;
}
Py_DECREF(item);
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if pairs_hook is not None: rval = object_pairs_hook(pairs) */
if (s->pairs_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->pairs_hook, pairs, NULL);
if (val == NULL)
goto bail;
Py_DECREF(pairs);
*next_idx_ptr = idx + 1;
return val;
}
rval = PyObject_CallFunctionObjArgs((PyObject *)(&PyDict_Type),
pairs, NULL);
if (rval == NULL)
goto bail;
Py_CLEAR(pairs);
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(key);
Py_XDECREF(val);
Py_XDECREF(pairs);
return NULL;
}
static PyObject *
_parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term and de-tuplefy the (rval, idx) */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON constant from PyString pystr.
constant is the constant string that was found
("NaN", "Infinity", "-Infinity").
idx is the index of the first character of the constant
*next_idx_ptr is a return-by-reference index to the first character after
the constant.
Returns the result of parse_constant
*/
PyObject *cstr;
PyObject *rval;
/* constant is "NaN", "Infinity", or "-Infinity" */
cstr = PyString_InternFromString(constant);
if (cstr == NULL)
return NULL;
/* rval = parse_constant(constant) */
rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL);
idx += PyString_GET_SIZE(cstr);
Py_DECREF(cstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyString pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
/* save the index of the 'e' or 'E' just in case we need to backtrack */
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyString_FromStringAndSize(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
double d = PyOS_string_to_double(PyString_AS_STRING(numstr),
NULL, NULL);
if (d == -1.0 && PyErr_Occurred())
return NULL;
rval = PyFloat_FromDouble(d);
}
}
else {
/* parse as an int using a fast path if available, otherwise call user defined method */
if (s->parse_int != (PyObject *)&PyInt_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
else {
rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10);
}
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyUnicode pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyUnicode_FromUnicode(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
rval = PyFloat_FromString(numstr, NULL);
}
}
else {
/* no fast path for unicode -> int, just call */
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyString pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
PyObject *res;
char *str = PyString_AS_STRING(pystr);
Py_ssize_t length = PyString_GET_SIZE(pystr);
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
switch (str[idx]) {
case '"':
/* string */
return scanstring_str(pystr, idx + 1,
PyString_AS_STRING(s->encoding),
PyObject_IsTrue(s->strict),
next_idx_ptr);
case '{':
/* object */
if (Py_EnterRecursiveCall(" while decoding a JSON object "
"from a byte string"))
return NULL;
res = _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
Py_LeaveRecursiveCall();
return res;
case '[':
/* array */
if (Py_EnterRecursiveCall(" while decoding a JSON array "
"from a byte string"))
return NULL;
res = _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
Py_LeaveRecursiveCall();
return res;
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
return Py_None;
}
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
return Py_True;
}
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
return Py_False;
}
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
return _parse_constant(s, "NaN", idx, next_idx_ptr);
}
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
return _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
break;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
return _match_number_str(s, pystr, idx, next_idx_ptr);
}
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyUnicode pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
PyObject *res;
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
switch (str[idx]) {
case '"':
/* string */
return scanstring_unicode(pystr, idx + 1,
PyObject_IsTrue(s->strict),
next_idx_ptr);
case '{':
/* object */
if (Py_EnterRecursiveCall(" while decoding a JSON object "
"from a unicode string"))
return NULL;
res = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
Py_LeaveRecursiveCall();
return res;
case '[':
/* array */
if (Py_EnterRecursiveCall(" while decoding a JSON array "
"from a unicode string"))
return NULL;
res = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
Py_LeaveRecursiveCall();
return res;
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
return Py_None;
}
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
return Py_True;
}
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
return Py_False;
}
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
return _parse_constant(s, "NaN", idx, next_idx_ptr);
}
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
return _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
break;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
return _match_number_unicode(s, pystr, idx, next_idx_ptr);
}
static PyObject *
scanner_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to scan_once_{str,unicode} */
PyObject *pystr;
PyObject *rval;
Py_ssize_t idx;
Py_ssize_t next_idx = -1;
static char *kwlist[] = {"string", "idx", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx))
return NULL;
if (PyString_Check(pystr)) {
rval = scan_once_str(s, pystr, idx, &next_idx);
}
else if (PyUnicode_Check(pystr)) {
rval = scan_once_unicode(s, pystr, idx, &next_idx);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_idx);
}
static PyObject *
scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyScannerObject *s;
s = (PyScannerObject *)type->tp_alloc(type, 0);
if (s != NULL) {
s->encoding = NULL;
s->strict = NULL;
s->object_hook = NULL;
s->pairs_hook = NULL;
s->parse_float = NULL;
s->parse_int = NULL;
s->parse_constant = NULL;
}
return (PyObject *)s;
}
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Initialize Scanner object */
PyObject *ctx;
static char *kwlist[] = {"context", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx))
return -1;
/* PyString_AS_STRING is used on encoding */
s->encoding = PyObject_GetAttrString(ctx, "encoding");
if (s->encoding == NULL)
goto bail;
if (s->encoding == Py_None) {
Py_DECREF(Py_None);
s->encoding = PyString_InternFromString(DEFAULT_ENCODING);
}
else if (PyUnicode_Check(s->encoding)) {
PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL);
Py_DECREF(s->encoding);
s->encoding = tmp;
}
if (s->encoding == NULL || !PyString_Check(s->encoding))
goto bail;
/* All of these will fail "gracefully" so we don't need to verify them */
s->strict = PyObject_GetAttrString(ctx, "strict");
if (s->strict == NULL)
goto bail;
s->object_hook = PyObject_GetAttrString(ctx, "object_hook");
if (s->object_hook == NULL)
goto bail;
s->pairs_hook = PyObject_GetAttrString(ctx, "object_pairs_hook");
if (s->pairs_hook == NULL)
goto bail;
s->parse_float = PyObject_GetAttrString(ctx, "parse_float");
if (s->parse_float == NULL)
goto bail;
s->parse_int = PyObject_GetAttrString(ctx, "parse_int");
if (s->parse_int == NULL)
goto bail;
s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant");
if (s->parse_constant == NULL)
goto bail;
return 0;
bail:
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->pairs_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
return -1;
}
PyDoc_STRVAR(scanner_doc, "JSON scanner object");
static
PyTypeObject PyScannerType = {
PyObject_HEAD_INIT(NULL)
0, /* tp_internal */
"_json.Scanner", /* tp_name */
sizeof(PyScannerObject), /* tp_basicsize */
0, /* tp_itemsize */
scanner_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
scanner_call, /* tp_call */
0, /* tp_str */
0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
scanner_doc, /* tp_doc */
scanner_traverse, /* tp_traverse */
scanner_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
scanner_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
scanner_init, /* tp_init */
0,/* PyType_GenericAlloc, */ /* tp_alloc */
scanner_new, /* tp_new */
0,/* PyObject_GC_Del, */ /* tp_free */
};
static PyObject *
encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyEncoderObject *s;
s = (PyEncoderObject *)type->tp_alloc(type, 0);
if (s != NULL) {
s->markers = NULL;
s->defaultfn = NULL;
s->encoder = NULL;
s->indent = NULL;
s->key_separator = NULL;
s->item_separator = NULL;
s->sort_keys = NULL;
s->skipkeys = NULL;
}
return (PyObject *)s;
}
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* initialize Encoder object */
static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL};
PyEncoderObject *s;
PyObject *markers, *defaultfn, *encoder, *indent, *key_separator;
PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist,
&markers, &defaultfn, &encoder, &indent, &key_separator, &item_separator,
&sort_keys, &skipkeys, &allow_nan))
return -1;
s->markers = markers;
s->defaultfn = defaultfn;
s->encoder = encoder;
s->indent = indent;
s->key_separator = key_separator;
s->item_separator = item_separator;
s->sort_keys = sort_keys;
s->skipkeys = skipkeys;
s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii);
s->allow_nan = PyObject_IsTrue(allow_nan);
Py_INCREF(s->markers);
Py_INCREF(s->defaultfn);
Py_INCREF(s->encoder);
Py_INCREF(s->indent);
Py_INCREF(s->key_separator);
Py_INCREF(s->item_separator);
Py_INCREF(s->sort_keys);
Py_INCREF(s->skipkeys);
return 0;
}
static PyObject *
encoder_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to encode_listencode_obj */
static char *kwlist[] = {"obj", "_current_indent_level", NULL};
PyObject *obj;
PyObject *rval;
Py_ssize_t indent_level;
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist,
&obj, _convertPyInt_AsSsize_t, &indent_level))
return NULL;
rval = PyList_New(0);
if (rval == NULL)
return NULL;
if (encoder_listencode_obj(s, rval, obj, indent_level)) {
Py_DECREF(rval);
return NULL;
}
return rval;
}
static PyObject *
_encoded_const(PyObject *obj)
{
/* Return the JSON string representation of None, True, False */
if (obj == Py_None) {
static PyObject *s_null = NULL;
if (s_null == NULL) {
s_null = PyString_InternFromString("null");
}
Py_INCREF(s_null);
return s_null;
}
else if (obj == Py_True) {
static PyObject *s_true = NULL;
if (s_true == NULL) {
s_true = PyString_InternFromString("true");
}
Py_INCREF(s_true);
return s_true;
}
else if (obj == Py_False) {
static PyObject *s_false = NULL;
if (s_false == NULL) {
s_false = PyString_InternFromString("false");
}
Py_INCREF(s_false);
return s_false;
}
else {
PyErr_SetString(PyExc_ValueError, "not a const");
return NULL;
}
}
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a PyFloat */
double i = PyFloat_AS_DOUBLE(obj);
if (!Py_IS_FINITE(i)) {
if (!s->allow_nan) {
PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant");
return NULL;
}
if (i > 0) {
return PyString_FromString("Infinity");
}
else if (i < 0) {
return PyString_FromString("-Infinity");
}
else {
return PyString_FromString("NaN");
}
}
/* Use a better float format here? */
return PyObject_Repr(obj);
}
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a string */
if (s->fast_encode)
return py_encode_basestring_ascii(NULL, obj);
else
return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL);
}
static int
_steal_list_append(PyObject *lst, PyObject *stolen)
{
/* Append stolen and then decrement its reference count */
int rval = PyList_Append(lst, stolen);
Py_DECREF(stolen);
return rval;
}
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level)
{
/* Encode Python object obj to a JSON term, rval is a PyList */
PyObject *newobj;
int rv;
if (obj == Py_None || obj == Py_True || obj == Py_False) {
PyObject *cstr = _encoded_const(obj);
if (cstr == NULL)
return -1;
return _steal_list_append(rval, cstr);
}
else if (PyString_Check(obj) || PyUnicode_Check(obj))
{
PyObject *encoded = encoder_encode_string(s, obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyInt_Check(obj) || PyLong_Check(obj)) {
PyObject *encoded = PyObject_Str(obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyFloat_Check(obj)) {
PyObject *encoded = encoder_encode_float(s, obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyList_Check(obj) || PyTuple_Check(obj)) {
if (Py_EnterRecursiveCall(" while encoding a JSON object"))
return -1;
rv = encoder_listencode_list(s, rval, obj, indent_level);
Py_LeaveRecursiveCall();
return rv;
}
else if (PyDict_Check(obj)) {
if (Py_EnterRecursiveCall(" while encoding a JSON object"))
return -1;
rv = encoder_listencode_dict(s, rval, obj, indent_level);
Py_LeaveRecursiveCall();
return rv;
}
else {
PyObject *ident = NULL;
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(obj);
if (ident == NULL)
return -1;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
Py_DECREF(ident);
return -1;
}
if (PyDict_SetItem(s->markers, ident, obj)) {
Py_DECREF(ident);
return -1;
}
}
newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL);
if (newobj == NULL) {
Py_XDECREF(ident);
return -1;
}
if (Py_EnterRecursiveCall(" while encoding a JSON object"))
return -1;
rv = encoder_listencode_obj(s, rval, newobj, indent_level);
Py_LeaveRecursiveCall();
Py_DECREF(newobj);
if (rv) {
Py_XDECREF(ident);
return -1;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident)) {
Py_XDECREF(ident);
return -1;
}
Py_XDECREF(ident);
}
return rv;
}
}
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level)
{
/* Encode Python dict dct a JSON term, rval is a PyList */
static PyObject *open_dict = NULL;
static PyObject *close_dict = NULL;
static PyObject *empty_dict = NULL;
PyObject *kstr = NULL;
PyObject *ident = NULL;
PyObject *key = NULL;
PyObject *value = NULL;
PyObject *it = NULL;
int skipkeys;
Py_ssize_t idx;
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) {
open_dict = PyString_InternFromString("{");
close_dict = PyString_InternFromString("}");
empty_dict = PyString_InternFromString("{}");
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL)
return -1;
}
if (Py_SIZE(dct) == 0)
return PyList_Append(rval, empty_dict);
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(dct);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, dct)) {
goto bail;
}
}
if (PyList_Append(rval, open_dict))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
/* TODO: C speedup not implemented for sort_keys */
it = PyObject_GetIter(dct);
if (it == NULL)
goto bail;
skipkeys = PyObject_IsTrue(s->skipkeys);
idx = 0;
while ((key = PyIter_Next(it)) != NULL) {
PyObject *encoded;
if (PyString_Check(key) || PyUnicode_Check(key)) {
Py_INCREF(key);
kstr = key;
}
else if (PyFloat_Check(key)) {
kstr = encoder_encode_float(s, key);
if (kstr == NULL)
goto bail;
}
else if (PyInt_Check(key) || PyLong_Check(key)) {
kstr = PyObject_Str(key);
if (kstr == NULL)
goto bail;
}
else if (key == Py_True || key == Py_False || key == Py_None) {
kstr = _encoded_const(key);
if (kstr == NULL)
goto bail;
}
else if (skipkeys) {
Py_DECREF(key);
continue;
}
else {
/* TODO: include repr of key */
PyErr_SetString(PyExc_TypeError, "keys must be a string");
goto bail;
}
if (idx) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
value = PyObject_GetItem(dct, key);
if (value == NULL)
goto bail;
encoded = encoder_encode_string(s, kstr);
Py_CLEAR(kstr);
if (encoded == NULL)
goto bail;
if (PyList_Append(rval, encoded)) {
Py_DECREF(encoded);
goto bail;
}
Py_DECREF(encoded);
if (PyList_Append(rval, s->key_separator))
goto bail;
if (encoder_listencode_obj(s, rval, value, indent_level))
goto bail;
idx += 1;
Py_CLEAR(value);
Py_DECREF(key);
}
if (PyErr_Occurred())
goto bail;
Py_CLEAR(it);
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
/*
indent_level -= 1;
yield '\n' + (' ' * (_indent * _current_indent_level))
*/
}
if (PyList_Append(rval, close_dict))
goto bail;
return 0;
bail:
Py_XDECREF(it);
Py_XDECREF(key);
Py_XDECREF(value);
Py_XDECREF(kstr);
Py_XDECREF(ident);
return -1;
}
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level)
{
/* Encode Python list seq to a JSON term, rval is a PyList */
static PyObject *open_array = NULL;
static PyObject *close_array = NULL;
static PyObject *empty_array = NULL;
PyObject *ident = NULL;
PyObject *s_fast = NULL;
Py_ssize_t num_items;
PyObject **seq_items;
Py_ssize_t i;
if (open_array == NULL || close_array == NULL || empty_array == NULL) {
open_array = PyString_InternFromString("[");
close_array = PyString_InternFromString("]");
empty_array = PyString_InternFromString("[]");
if (open_array == NULL || close_array == NULL || empty_array == NULL)
return -1;
}
ident = NULL;
s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence");
if (s_fast == NULL)
return -1;
num_items = PySequence_Fast_GET_SIZE(s_fast);
if (num_items == 0) {
Py_DECREF(s_fast);
return PyList_Append(rval, empty_array);
}
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(seq);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, seq)) {
goto bail;
}
}
seq_items = PySequence_Fast_ITEMS(s_fast);
if (PyList_Append(rval, open_array))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
for (i = 0; i < num_items; i++) {
PyObject *obj = seq_items[i];
if (i) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
if (encoder_listencode_obj(s, rval, obj, indent_level))
goto bail;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
/*
indent_level -= 1;
yield '\n' + (' ' * (_indent * _current_indent_level))
*/
}
if (PyList_Append(rval, close_array))
goto bail;
Py_DECREF(s_fast);
return 0;
bail:
Py_XDECREF(ident);
Py_DECREF(s_fast);
return -1;
}
static void
encoder_dealloc(PyObject *self)
{
/* Deallocate Encoder */
encoder_clear(self);
Py_TYPE(self)->tp_free(self);
}
static int
encoder_traverse(PyObject *self, visitproc visit, void *arg)
{
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
Py_VISIT(s->markers);
Py_VISIT(s->defaultfn);
Py_VISIT(s->encoder);
Py_VISIT(s->indent);
Py_VISIT(s->key_separator);
Py_VISIT(s->item_separator);
Py_VISIT(s->sort_keys);
Py_VISIT(s->skipkeys);
return 0;
}
static int
encoder_clear(PyObject *self)
{
/* Deallocate Encoder */
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
Py_CLEAR(s->markers);
Py_CLEAR(s->defaultfn);
Py_CLEAR(s->encoder);
Py_CLEAR(s->indent);
Py_CLEAR(s->key_separator);
Py_CLEAR(s->item_separator);
Py_CLEAR(s->sort_keys);
Py_CLEAR(s->skipkeys);
return 0;
}
PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable");
static
PyTypeObject PyEncoderType = {
PyObject_HEAD_INIT(NULL)
0, /* tp_internal */
"_json.Encoder", /* tp_name */
sizeof(PyEncoderObject), /* tp_basicsize */
0, /* tp_itemsize */
encoder_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
encoder_call, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
encoder_doc, /* tp_doc */
encoder_traverse, /* tp_traverse */
encoder_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
encoder_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
encoder_init, /* tp_init */
0, /* tp_alloc */
encoder_new, /* tp_new */
0, /* tp_free */
};
static PyMethodDef speedups_methods[] = {
{"encode_basestring_ascii",
(PyCFunction)py_encode_basestring_ascii,
METH_O,
pydoc_encode_basestring_ascii},
{"scanstring",
(PyCFunction)py_scanstring,
METH_VARARGS,
pydoc_scanstring},
{NULL, NULL, 0, NULL}
};
PyDoc_STRVAR(module_doc,
"json speedups\n");
void
init_json(void)
{
PyObject *m;
PyScannerType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PyScannerType) < 0)
return;
PyEncoderType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PyEncoderType) < 0)
return;
m = Py_InitModule3("_json", speedups_methods, module_doc);
Py_INCREF((PyObject*)&PyScannerType);
PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType);
Py_INCREF((PyObject*)&PyEncoderType);
PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType);
}
| apache-2.0 |
veritas-shine/minix3-rpi | external/bsd/libc++/dist/libcxx/test/language.support/support.limits/limits/numeric.limits.members/traps.pass.cpp | 6 | 1414 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test numeric_limits
// traps
#include <limits>
template <class T, bool expected>
void
test()
{
static_assert(std::numeric_limits<T>::traps == expected, "traps test 1");
static_assert(std::numeric_limits<const T>::traps == expected, "traps test 2");
static_assert(std::numeric_limits<volatile T>::traps == expected, "traps test 3");
static_assert(std::numeric_limits<const volatile T>::traps == expected, "traps test 4");
}
int main()
{
test<bool, false>();
test<char, true>();
test<signed char, true>();
test<unsigned char, true>();
test<wchar_t, true>();
#ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
test<char16_t, true>();
test<char32_t, true>();
#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
test<short, true>();
test<unsigned short, true>();
test<int, true>();
test<unsigned int, true>();
test<long, true>();
test<unsigned long, true>();
test<long long, true>();
test<unsigned long long, true>();
test<float, false>();
test<double, false>();
test<long double, false>();
}
| apache-2.0 |
awakecoding/FreeRDP | winpr/libwinpr/file/pattern.c | 6 | 8891 | /**
* WinPR: Windows Portable Runtime
* File Functions
*
* Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <winpr/config.h>
#include <winpr/crt.h>
#include <winpr/handle.h>
#include <winpr/file.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include "../log.h"
#define TAG WINPR_TAG("file")
/**
* File System Behavior in the Microsoft Windows Environment:
* http://download.microsoft.com/download/4/3/8/43889780-8d45-4b2e-9d3a-c696a890309f/File%20System%20Behavior%20Overview.pdf
*/
LPSTR FilePatternFindNextWildcardA(LPCSTR lpPattern, DWORD* pFlags)
{
LPSTR lpWildcard;
*pFlags = 0;
lpWildcard = strpbrk(lpPattern, "*?~");
if (lpWildcard)
{
if (*lpWildcard == '*')
{
*pFlags = WILDCARD_STAR;
return lpWildcard;
}
else if (*lpWildcard == '?')
{
*pFlags = WILDCARD_QM;
return lpWildcard;
}
else if (*lpWildcard == '~')
{
if (lpWildcard[1] == '*')
{
*pFlags = WILDCARD_DOS_STAR;
return lpWildcard;
}
else if (lpWildcard[1] == '?')
{
*pFlags = WILDCARD_DOS_QM;
return lpWildcard;
}
else if (lpWildcard[1] == '.')
{
*pFlags = WILDCARD_DOS_DOT;
return lpWildcard;
}
}
}
return NULL;
}
static BOOL FilePatternMatchSubExpressionA(LPCSTR lpFileName, size_t cchFileName, LPCSTR lpX,
size_t cchX, LPCSTR lpY, size_t cchY, LPCSTR lpWildcard,
LPCSTR* ppMatchEnd)
{
LPCSTR lpMatch;
if (!lpFileName)
return FALSE;
if (*lpWildcard == '*')
{
/*
* S
* <-----<
* X | | e Y
* X * Y == (0)----->-(1)->-----(2)-----(3)
*/
/*
* State 0: match 'X'
*/
if (_strnicmp(lpFileName, lpX, cchX) != 0)
return FALSE;
/*
* State 1: match 'S' or 'e'
*
* We use 'e' to transition to state 2
*/
/**
* State 2: match Y
*/
if (cchY != 0)
{
/* TODO: case insensitive character search */
lpMatch = strchr(&lpFileName[cchX], *lpY);
if (!lpMatch)
return FALSE;
if (_strnicmp(lpMatch, lpY, cchY) != 0)
return FALSE;
}
else
{
lpMatch = &lpFileName[cchFileName];
}
/**
* State 3: final state
*/
*ppMatchEnd = &lpMatch[cchY];
return TRUE;
}
else if (*lpWildcard == '?')
{
/**
* X S Y
* X ? Y == (0)---(1)---(2)---(3)
*/
/*
* State 0: match 'X'
*/
if (cchFileName < cchX)
return FALSE;
if (_strnicmp(lpFileName, lpX, cchX) != 0)
return FALSE;
/*
* State 1: match 'S'
*/
/**
* State 2: match Y
*/
if (cchY != 0)
{
/* TODO: case insensitive character search */
lpMatch = strchr(&lpFileName[cchX + 1], *lpY);
if (!lpMatch)
return FALSE;
if (_strnicmp(lpMatch, lpY, cchY) != 0)
return FALSE;
}
else
{
if ((cchX + 1) > cchFileName)
return FALSE;
lpMatch = &lpFileName[cchX + 1];
}
/**
* State 3: final state
*/
*ppMatchEnd = &lpMatch[cchY];
return TRUE;
}
else if (*lpWildcard == '~')
{
WLog_ERR(TAG, "warning: unimplemented '~' pattern match");
return TRUE;
}
return FALSE;
}
BOOL FilePatternMatchA(LPCSTR lpFileName, LPCSTR lpPattern)
{
BOOL match;
LPCSTR lpTail;
size_t cchTail;
size_t cchPattern;
size_t cchFileName;
DWORD dwFlags;
DWORD dwNextFlags;
LPSTR lpWildcard;
LPSTR lpNextWildcard;
/**
* Wild Card Matching
*
* '*' matches 0 or more characters
* '?' matches exactly one character
*
* '~*' DOS_STAR - matches 0 or more characters until encountering and matching final '.'
*
* '~?' DOS_QM - matches any single character, or upon encountering a period or end of name
* string, advances the expresssion to the end of the set of contiguous DOS_QMs.
*
* '~.' DOS_DOT - matches either a '.' or zero characters beyond name string.
*/
if (!lpPattern)
return FALSE;
if (!lpFileName)
return FALSE;
cchPattern = strlen(lpPattern);
cchFileName = strlen(lpFileName);
/**
* First and foremost the file system starts off name matching with the expression “*”.
* If the expression contains a single wild card character ‘*’ all matches are satisfied
* immediately. This is the most common wild card character used in Windows and expression
* evaluation is optimized by looking for this character first.
*/
if ((lpPattern[0] == '*') && (cchPattern == 1))
return TRUE;
/**
* Subsequently evaluation of the “*X” expression is performed. This is a case where
* the expression starts off with a wild card character and contains some non-wild card
* characters towards the tail end of the name. This is evaluated by making sure the
* expression starts off with the character ‘*’ and does not contain any wildcards in
* the latter part of the expression. The tail part of the expression beyond the first
* character ‘*’ is matched against the file name at the end uppercasing each character
* if necessary during the comparison.
*/
if (lpPattern[0] == '*')
{
lpTail = &lpPattern[1];
cchTail = strlen(lpTail);
if (!FilePatternFindNextWildcardA(lpTail, &dwFlags))
{
/* tail contains no wildcards */
if (cchFileName < cchTail)
return FALSE;
if (_stricmp(&lpFileName[cchFileName - cchTail], lpTail) == 0)
return TRUE;
return FALSE;
}
}
/**
* The remaining expressions are evaluated in a non deterministic
* finite order as listed below, where:
*
* 'S' is any single character
* 'S-.' is any single character except the final '.'
* 'e' is a null character transition
* 'EOF' is the end of the name string
*
* S
* <-----<
* X | | e Y
* X * Y == (0)----->-(1)->-----(2)-----(3)
*
*
* S-.
* <-----<
* X | | e Y
* X ~* Y == (0)----->-(1)->-----(2)-----(3)
*
*
* X S S Y
* X ?? Y == (0)---(1)---(2)---(3)---(4)
*
*
* X S-. S-. Y
* X ~?~? == (0)---(1)-----(2)-----(3)---(4)
* | |_______|
* | ^ |
* |_______________|
* ^EOF of .^
*
*/
lpWildcard = FilePatternFindNextWildcardA(lpPattern, &dwFlags);
if (lpWildcard)
{
LPCSTR lpX;
LPCSTR lpY;
size_t cchX;
size_t cchY;
LPCSTR lpMatchEnd = NULL;
LPCSTR lpSubPattern;
size_t cchSubPattern;
LPCSTR lpSubFileName;
size_t cchSubFileName;
size_t cchWildcard;
size_t cchNextWildcard;
cchSubPattern = cchPattern;
lpSubPattern = lpPattern;
cchSubFileName = cchFileName;
lpSubFileName = lpFileName;
cchWildcard = ((dwFlags & WILDCARD_DOS) ? 2 : 1);
lpNextWildcard = FilePatternFindNextWildcardA(&lpWildcard[cchWildcard], &dwNextFlags);
if (!lpNextWildcard)
{
lpX = lpSubPattern;
cchX = (lpWildcard - lpSubPattern);
lpY = &lpSubPattern[cchX + cchWildcard];
cchY = (cchSubPattern - (lpY - lpSubPattern));
match = FilePatternMatchSubExpressionA(lpSubFileName, cchSubFileName, lpX, cchX, lpY,
cchY, lpWildcard, &lpMatchEnd);
return match;
}
else
{
while (lpNextWildcard)
{
cchSubFileName = cchFileName - (lpSubFileName - lpFileName);
cchNextWildcard = ((dwNextFlags & WILDCARD_DOS) ? 2 : 1);
lpX = lpSubPattern;
cchX = (lpWildcard - lpSubPattern);
lpY = &lpSubPattern[cchX + cchWildcard];
cchY = (lpNextWildcard - lpWildcard) - cchWildcard;
match = FilePatternMatchSubExpressionA(lpSubFileName, cchSubFileName, lpX, cchX,
lpY, cchY, lpWildcard, &lpMatchEnd);
if (!match)
return FALSE;
lpSubFileName = lpMatchEnd;
cchWildcard = cchNextWildcard;
lpWildcard = lpNextWildcard;
dwFlags = dwNextFlags;
lpNextWildcard =
FilePatternFindNextWildcardA(&lpWildcard[cchWildcard], &dwNextFlags);
}
return TRUE;
}
}
else
{
/* no wildcard characters */
if (_stricmp(lpFileName, lpPattern) == 0)
return TRUE;
}
return FALSE;
}
| apache-2.0 |
raphaelchang/quadthingy-software | base_station/ChibiOS_16.1.4/ext/stdperiph_stm32f4/src/stm32f4xx_dsi.c | 6 | 61738 | /**
******************************************************************************
* @file stm32f4xx_dsi.c
* @author MCD Application Team
* @version V1.6.1
* @date 21-October-2015
* @brief This file provides firmware functions to manage the following
* functionalities of the Display Serial Interface (DSI):
* + Initialization and Configuration
* + Data transfers management functions
* + Low Power functions
* + Interrupts and flags management
*
@verbatim
===================================================================
##### How to use this driver #####
===================================================================
[..]
@endverbatim
*
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2015 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.st.com/software_license_agreement_liberty_v2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_dsi.h"
/** @addtogroup STM32F4xx_StdPeriph_Driver
* @{
*/
/** @addtogroup DSI
* @brief DSI driver modules
* @{
*/
#if defined(STM32F469_479xx)
/* Private types -------------------------------------------------------------*/
/* Private defines -----------------------------------------------------------*/
/** @addtogroup DSI_Private_Constants
* @{
*/
#define DSI_TIMEOUT_VALUE ((uint32_t)1000) /* 1s */
#define DSI_ERROR_ACK_MASK (DSI_ISR0_AE0 | DSI_ISR0_AE1 | DSI_ISR0_AE2 | DSI_ISR0_AE3 | \
DSI_ISR0_AE4 | DSI_ISR0_AE5 | DSI_ISR0_AE6 | DSI_ISR0_AE7 | \
DSI_ISR0_AE8 | DSI_ISR0_AE9 | DSI_ISR0_AE10 | DSI_ISR0_AE11 | \
DSI_ISR0_AE12 | DSI_ISR0_AE13 | DSI_ISR0_AE14 | DSI_ISR0_AE15)
#define DSI_ERROR_PHY_MASK (DSI_ISR0_PE0 | DSI_ISR0_PE1 | DSI_ISR0_PE2 | DSI_ISR0_PE3 | DSI_ISR0_PE4)
#define DSI_ERROR_TX_MASK DSI_ISR1_TOHSTX
#define DSI_ERROR_RX_MASK DSI_ISR1_TOLPRX
#define DSI_ERROR_ECC_MASK (DSI_ISR1_ECCSE | DSI_ISR1_ECCME)
#define DSI_ERROR_CRC_MASK DSI_ISR1_CRCE
#define DSI_ERROR_PSE_MASK DSI_ISR1_PSE
#define DSI_ERROR_EOT_MASK DSI_ISR1_EOTPE
#define DSI_ERROR_OVF_MASK DSI_ISR1_LPWRE
#define DSI_ERROR_GEN_MASK (DSI_ISR1_GCWRE | DSI_ISR1_GPWRE | DSI_ISR1_GPTXE | DSI_ISR1_GPRDE | DSI_ISR1_GPRXE)
#define DSI_MAX_RETURN_PKT_SIZE ((uint32_t)0x00000037) /*!< Maximum return packet configuration */
/**
* @}
*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void DSI_ConfigPacketHeader(DSI_TypeDef *DSIx, uint32_t ChannelID, uint32_t DataType, uint32_t Data0, uint32_t Data1);
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup DSI_Exported_Functions
* @{
*/
/** @defgroup DSI_Group1 Initialization and Configuration functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and Configuration functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize and configure the DSI
(+) De-initialize the DSI
@endverbatim
* @{
*/
/**
* @brief De-initializes the DSI peripheral registers to their default reset
* values.
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @retval None
*/
void DSI_DeInit(DSI_TypeDef *DSIx)
{
/* Disable the DSI wrapper */
DSIx->WCR &= ~DSI_WCR_DSIEN;
/* Disable the DSI host */
DSIx->CR &= ~DSI_CR_EN;
/* D-PHY clock and digital disable */
DSIx->PCTLR &= ~(DSI_PCTLR_CKE | DSI_PCTLR_DEN);
/* Turn off the DSI PLL */
DSIx->WRPCR &= ~DSI_WRPCR_PLLEN;
/* Disable the regulator */
DSIx->WRPCR &= ~DSI_WRPCR_REGEN;
/* Check the parameters */
assert_param(IS_DSI_ALL_PERIPH(DSIx));
if(DSIx == DSI)
{
/* Enable DSI reset state */
RCC_APB2PeriphResetCmd(RCC_APB2Periph_DSI, ENABLE);
/* Release DSI from reset state */
RCC_APB2PeriphResetCmd(RCC_APB2Periph_DSI, DISABLE);
}
}
/**
* @brief Deinitialize the DSIx peripheral registers to their default reset values.
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param DSI_InitStruct: pointer to a DSI_InitTypeDef structure that
* contains the configuration information for the specified DSI peripheral.
* @param DSI_InitTIMStruct: pointer to a DSI_TIMTypeDef structure that
* contains the configuration information for the specified DSI Timings.
* @retval None
*/
void DSI_Init(DSI_TypeDef *DSIx,DSI_InitTypeDef* DSI_InitStruct, DSI_PLLInitTypeDef *PLLInit)
{
uint32_t unitIntervalx4 = 0;
uint32_t tempIDF = 0;
/* Check function parameters */
assert_param(IS_DSI_PLL_NDIV(PLLInit->PLLNDIV));
assert_param(IS_DSI_PLL_IDF(PLLInit->PLLIDF));
assert_param(IS_DSI_PLL_ODF(PLLInit->PLLODF));
assert_param(IS_DSI_AUTO_CLKLANE_CONTROL(DSI_InitStruct->AutomaticClockLaneControl));
assert_param(IS_DSI_NUMBER_OF_LANES(DSI_InitStruct->NumberOfLanes));
/**************** Turn on the regulator and enable the DSI PLL ****************/
/* Enable the regulator */
DSIx->WRPCR |= DSI_WRPCR_REGEN;
/* Wait until the regulator is ready */
while(DSI_GetFlagStatus(DSIx, DSI_FLAG_RRS) == RESET )
{}
/* Set the PLL division factors */
DSIx->WRPCR &= ~(DSI_WRPCR_PLL_NDIV | DSI_WRPCR_PLL_IDF | DSI_WRPCR_PLL_ODF);
DSIx->WRPCR |= (((PLLInit->PLLNDIV)<<2) | ((PLLInit->PLLIDF)<<11) | ((PLLInit->PLLODF)<<16));
/* Enable the DSI PLL */
DSIx->WRPCR |= DSI_WRPCR_PLLEN;
/* Wait for the lock of the PLL */
while(DSI_GetFlagStatus(DSIx, DSI_FLAG_PLLLS) == RESET)
{}
/*************************** Set the PHY parameters ***************************/
/* D-PHY clock and digital enable*/
DSIx->PCTLR |= (DSI_PCTLR_CKE | DSI_PCTLR_DEN);
/* Clock lane configuration */
DSIx->CLCR &= ~(DSI_CLCR_DPCC | DSI_CLCR_ACR);
DSIx->CLCR |= (DSI_CLCR_DPCC | DSI_InitStruct->AutomaticClockLaneControl);
/* Configure the number of active data lanes */
DSIx->PCONFR &= ~DSI_PCONFR_NL;
DSIx->PCONFR |= DSI_InitStruct->NumberOfLanes;
/************************ Set the DSI clock parameters ************************/
/* Set the TX escape clock division factor */
DSIx->CCR &= ~DSI_CCR_TXECKDIV;
DSIx->CCR = DSI_InitStruct->TXEscapeCkdiv;
/* Calculate the bit period in high-speed mode in unit of 0.25 ns (UIX4) */
/* The equation is : UIX4 = IntegerPart( (1000/F_PHY_Mhz) * 4 ) */
/* Where : F_PHY_Mhz = (NDIV * HSE_Mhz) / (IDF * ODF) */
tempIDF = (PLLInit->PLLIDF > 0) ? PLLInit->PLLIDF : 1;
unitIntervalx4 = (4000000 * tempIDF * (1 << PLLInit->PLLODF)) / ((HSE_VALUE/1000) * PLLInit->PLLNDIV);
/* Set the bit period in high-speed mode */
DSIx->WPCR[0] &= ~DSI_WPCR0_UIX4;
DSIx->WPCR[0] |= unitIntervalx4;
/****************************** Error management *****************************/
/* Disable all error interrupts */
DSIx->IER[0] = 0;
DSIx->IER[1] = 0;
}
/**
* @brief Fills each DSI_InitStruct member with its default value.
* @param DSI_InitStruct: pointer to a DSI_InitTypeDef structure which will be initialized.
* @retval None
*/
void DSI_StructInit(DSI_InitTypeDef* DSI_InitStruct, DSI_HOST_TimeoutTypeDef* DSI_HOST_TimeoutInitStruct)
{
/*--------------- Reset DSI init structure parameters values ---------------*/
/* Initialize the AutomaticClockLaneControl member */
DSI_InitStruct->AutomaticClockLaneControl = DSI_AUTO_CLK_LANE_CTRL_DISABLE;
/* Initialize the NumberOfLanes member */
DSI_InitStruct->NumberOfLanes = DSI_ONE_DATA_LANE;
/* Initialize the TX Escape clock division */
DSI_InitStruct->TXEscapeCkdiv = 0;
/*--------------- Reset DSI timings init structure parameters values -------*/
/* Initialize the TimeoutCkdiv member */
DSI_HOST_TimeoutInitStruct->TimeoutCkdiv = 0;
/* Initialize the HighSpeedTransmissionTimeout member */
DSI_HOST_TimeoutInitStruct->HighSpeedTransmissionTimeout = 0;
/* Initialize the LowPowerReceptionTimeout member */
DSI_HOST_TimeoutInitStruct->LowPowerReceptionTimeout = 0;
/* Initialize the HighSpeedReadTimeout member */
DSI_HOST_TimeoutInitStruct->HighSpeedReadTimeout = 0;
/* Initialize the LowPowerReadTimeout member */
DSI_HOST_TimeoutInitStruct->LowPowerReadTimeout = 0;
/* Initialize the HighSpeedWriteTimeout member */
DSI_HOST_TimeoutInitStruct->HighSpeedWriteTimeout = 0;
/* Initialize the HighSpeedWritePrespMode member */
DSI_HOST_TimeoutInitStruct->HighSpeedWritePrespMode = 0;
/* Initialize the LowPowerWriteTimeout member */
DSI_HOST_TimeoutInitStruct->LowPowerWriteTimeout = 0;
/* Initialize the BTATimeout member */
DSI_HOST_TimeoutInitStruct->BTATimeout = 0;
}
/**
* @brief Configure the Generic interface read-back Virtual Channel ID.
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param VirtualChannelID: Virtual channel ID
* @retval None
*/
void DSI_SetGenericVCID(DSI_TypeDef *DSIx, uint32_t VirtualChannelID)
{
/* Update the GVCID register */
DSIx->GVCIDR &= ~DSI_GVCIDR_VCID;
DSIx->GVCIDR |= VirtualChannelID;
}
/**
* @brief Select video mode and configure the corresponding parameters
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param VidCfg: pointer to a DSI_VidCfgTypeDef structure that contains
* the DSI video mode configuration parameters
* @retval None
*/
void DSI_ConfigVideoMode(DSI_TypeDef *DSIx, DSI_VidCfgTypeDef *VidCfg)
{
/* Check the parameters */
assert_param(IS_DSI_COLOR_CODING(VidCfg->ColorCoding));
assert_param(IS_DSI_VIDEO_MODE_TYPE(VidCfg->Mode));
assert_param(IS_DSI_LP_COMMAND(VidCfg->LPCommandEnable));
assert_param(IS_DSI_LP_HFP(VidCfg->LPHorizontalFrontPorchEnable));
assert_param(IS_DSI_LP_HBP(VidCfg->LPHorizontalBackPorchEnable));
assert_param(IS_DSI_LP_VACTIVE(VidCfg->LPVerticalActiveEnable));
assert_param(IS_DSI_LP_VFP(VidCfg->LPVerticalFrontPorchEnable));
assert_param(IS_DSI_LP_VBP(VidCfg->LPVerticalBackPorchEnable));
assert_param(IS_DSI_LP_VSYNC(VidCfg->LPVerticalSyncActiveEnable));
assert_param(IS_DSI_FBTAA(VidCfg->FrameBTAAcknowledgeEnable));
assert_param(IS_DSI_DE_POLARITY(VidCfg->DEPolarity));
assert_param(IS_DSI_VSYNC_POLARITY(VidCfg->VSPolarity));
assert_param(IS_DSI_HSYNC_POLARITY(VidCfg->HSPolarity));
/* Check the LooselyPacked variant only in 18-bit mode */
if(VidCfg->ColorCoding == DSI_RGB666)
{
assert_param(IS_DSI_LOOSELY_PACKED(VidCfg->LooselyPacked));
}
/* Select video mode by resetting CMDM and DSIM bits */
DSIx->MCR &= ~DSI_MCR_CMDM;
DSIx->WCFGR &= ~DSI_WCFGR_DSIM;
/* Configure the video mode transmission type */
DSIx->VMCR &= ~DSI_VMCR_VMT;
DSIx->VMCR |= VidCfg->Mode;
/* Configure the video packet size */
DSIx->VPCR &= ~DSI_VPCR_VPSIZE;
DSIx->VPCR |= VidCfg->PacketSize;
/* Set the chunks number to be transmitted through the DSI link */
DSIx->VCCR &= ~DSI_VCCR_NUMC;
DSIx->VCCR |= VidCfg->NumberOfChunks;
/* Set the size of the null packet */
DSIx->VNPCR &= ~DSI_VNPCR_NPSIZE;
DSIx->VNPCR |= VidCfg->NullPacketSize;
/* Select the virtual channel for the LTDC interface traffic */
DSIx->LVCIDR &= ~DSI_LVCIDR_VCID;
DSIx->LVCIDR |= VidCfg->VirtualChannelID;
/* Configure the polarity of control signals */
DSIx->LPCR &= ~(DSI_LPCR_DEP | DSI_LPCR_VSP | DSI_LPCR_HSP);
DSIx->LPCR |= (VidCfg->DEPolarity | VidCfg->VSPolarity | VidCfg->HSPolarity);
/* Select the color coding for the host */
DSIx->LCOLCR &= ~DSI_LCOLCR_COLC;
DSIx->LCOLCR |= VidCfg->ColorCoding;
/* Select the color coding for the wrapper */
DSIx->WCFGR &= ~DSI_WCFGR_COLMUX;
DSIx->WCFGR |= ((VidCfg->ColorCoding)<<1);
/* Enable/disable the loosely packed variant to 18-bit configuration */
if(VidCfg->ColorCoding == DSI_RGB666)
{
DSIx->LCOLCR &= ~DSI_LCOLCR_LPE;
DSIx->LCOLCR |= VidCfg->LooselyPacked;
}
/* Set the Horizontal Synchronization Active (HSA) in lane byte clock cycles */
DSIx->VHSACR &= ~DSI_VHSACR_HSA;
DSIx->VHSACR |= VidCfg->HorizontalSyncActive;
/* Set the Horizontal Back Porch (HBP) in lane byte clock cycles */
DSIx->VHBPCR &= ~DSI_VHBPCR_HBP;
DSIx->VHBPCR |= VidCfg->HorizontalBackPorch;
/* Set the total line time (HLINE=HSA+HBP+HACT+HFP) in lane byte clock cycles */
DSIx->VLCR &= ~DSI_VLCR_HLINE;
DSIx->VLCR |= VidCfg->HorizontalLine;
/* Set the Vertical Synchronization Active (VSA) */
DSIx->VVSACR &= ~DSI_VVSACR_VSA;
DSIx->VVSACR |= VidCfg->VerticalSyncActive;
/* Set the Vertical Back Porch (VBP)*/
DSIx->VVBPCR &= ~DSI_VVBPCR_VBP;
DSIx->VVBPCR |= VidCfg->VerticalBackPorch;
/* Set the Vertical Front Porch (VFP)*/
DSIx->VVFPCR &= ~DSI_VVFPCR_VFP;
DSIx->VVFPCR |= VidCfg->VerticalFrontPorch;
/* Set the Vertical Active period*/
DSIx->VVACR &= ~DSI_VVACR_VA;
DSIx->VVACR |= VidCfg->VerticalActive;
/* Configure the command transmission mode */
DSIx->VMCR &= ~DSI_VMCR_LPCE;
DSIx->VMCR |= VidCfg->LPCommandEnable;
/* Low power largest packet size */
DSIx->LPMCR &= ~DSI_LPMCR_LPSIZE;
DSIx->LPMCR |= ((VidCfg->LPLargestPacketSize)<<16);
/* Low power VACT largest packet size */
DSIx->LPMCR &= ~DSI_LPMCR_VLPSIZE;
DSIx->LPMCR |= VidCfg->LPVACTLargestPacketSize;
/* Enable LP transition in HFP period */
DSIx->VMCR &= ~DSI_VMCR_LPHFPE;
DSIx->VMCR |= VidCfg->LPHorizontalFrontPorchEnable;
/* Enable LP transition in HBP period */
DSIx->VMCR &= ~DSI_VMCR_LPHBPE;
DSIx->VMCR |= VidCfg->LPHorizontalBackPorchEnable;
/* Enable LP transition in VACT period */
DSIx->VMCR &= ~DSI_VMCR_LPVAE;
DSIx->VMCR |= VidCfg->LPVerticalActiveEnable;
/* Enable LP transition in VFP period */
DSIx->VMCR &= ~DSI_VMCR_LPVFPE;
DSIx->VMCR |= VidCfg->LPVerticalFrontPorchEnable;
/* Enable LP transition in VBP period */
DSIx->VMCR &= ~DSI_VMCR_LPVBPE;
DSIx->VMCR |= VidCfg->LPVerticalBackPorchEnable;
/* Enable LP transition in vertical sync period */
DSIx->VMCR &= ~DSI_VMCR_LPVSAE;
DSIx->VMCR |= VidCfg->LPVerticalSyncActiveEnable;
/* Enable the request for an acknowledge response at the end of a frame */
DSIx->VMCR &= ~DSI_VMCR_FBTAAE;
DSIx->VMCR |= VidCfg->FrameBTAAcknowledgeEnable;
}
/**
* @brief Select adapted command mode and configure the corresponding parameters
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param CmdCfg: pointer to a DSI_CmdCfgTypeDef structure that contains
* the DSI command mode configuration parameters
* @retval None
*/
void DSI_ConfigAdaptedCommandMode(DSI_TypeDef *DSIx, DSI_CmdCfgTypeDef *CmdCfg)
{
/* Check the parameters */
assert_param(IS_DSI_COLOR_CODING(CmdCfg->ColorCoding));
assert_param(IS_DSI_TE_SOURCE(CmdCfg->TearingEffectSource));
assert_param(IS_DSI_TE_POLARITY(CmdCfg->TearingEffectPolarity));
assert_param(IS_DSI_AUTOMATIC_REFRESH(CmdCfg->AutomaticRefresh));
assert_param(IS_DSI_VS_POLARITY(CmdCfg->VSyncPol));
assert_param(IS_DSI_TE_ACK_REQUEST(CmdCfg->TEAcknowledgeRequest));
assert_param(IS_DSI_DE_POLARITY(CmdCfg->DEPolarity));
assert_param(IS_DSI_VSYNC_POLARITY(CmdCfg->VSPolarity));
assert_param(IS_DSI_HSYNC_POLARITY(CmdCfg->HSPolarity));
/* Select command mode by setting CMDM and DSIM bits */
DSIx->MCR |= DSI_MCR_CMDM;
DSIx->WCFGR &= ~DSI_WCFGR_DSIM;
DSIx->WCFGR |= DSI_WCFGR_DSIM;
/* Select the virtual channel for the LTDC interface traffic */
DSIx->LVCIDR &= ~DSI_LVCIDR_VCID;
DSIx->LVCIDR |= CmdCfg->VirtualChannelID;
/* Configure the polarity of control signals */
DSIx->LPCR &= ~(DSI_LPCR_DEP | DSI_LPCR_VSP | DSI_LPCR_HSP);
DSIx->LPCR |= (CmdCfg->DEPolarity | CmdCfg->VSPolarity | CmdCfg->HSPolarity);
/* Select the color coding for the host */
DSIx->LCOLCR &= ~DSI_LCOLCR_COLC;
DSIx->LCOLCR |= CmdCfg->ColorCoding;
/* Select the color coding for the wrapper */
DSIx->WCFGR &= ~DSI_WCFGR_COLMUX;
DSIx->WCFGR |= ((CmdCfg->ColorCoding)<<1);
/* Configure the maximum allowed size for write memory command */
DSIx->LCCR &= ~DSI_LCCR_CMDSIZE;
DSIx->LCCR |= CmdCfg->CommandSize;
/* Configure the tearing effect source and polarity and select the refresh mode */
DSIx->WCFGR &= ~(DSI_WCFGR_TESRC | DSI_WCFGR_TEPOL | DSI_WCFGR_AR | DSI_WCFGR_VSPOL);
DSIx->WCFGR |= (CmdCfg->TearingEffectSource | CmdCfg->TearingEffectPolarity | CmdCfg->AutomaticRefresh | CmdCfg->VSyncPol);
/* Configure the tearing effect acknowledge request */
DSIx->CMCR &= ~DSI_CMCR_TEARE;
DSIx->CMCR |= CmdCfg->TEAcknowledgeRequest;
/* Enable the Tearing Effect interrupt */
DSI_ITConfig(DSIx, DSI_IT_TE, ENABLE);
/* Enable the End of Refresh interrupt */
DSI_ITConfig(DSIx, DSI_IT_ER, ENABLE);
}
/**
* @brief Configure command transmission mode: High-speed or Low-power
* and enable/disable acknowledge request after packet transmission
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param LPCmd: pointer to a DSI_LPCmdTypeDef structure that contains
* the DSI command transmission mode configuration parameters
* @retval None
*/
void DSI_ConfigCommand(DSI_TypeDef *DSIx, DSI_LPCmdTypeDef *LPCmd)
{
assert_param(IS_DSI_LP_GSW0P(LPCmd->LPGenShortWriteNoP));
assert_param(IS_DSI_LP_GSW1P(LPCmd->LPGenShortWriteOneP));
assert_param(IS_DSI_LP_GSW2P(LPCmd->LPGenShortWriteTwoP));
assert_param(IS_DSI_LP_GSR0P(LPCmd->LPGenShortReadNoP));
assert_param(IS_DSI_LP_GSR1P(LPCmd->LPGenShortReadOneP));
assert_param(IS_DSI_LP_GSR2P(LPCmd->LPGenShortReadTwoP));
assert_param(IS_DSI_LP_GLW(LPCmd->LPGenLongWrite));
assert_param(IS_DSI_LP_DSW0P(LPCmd->LPDcsShortWriteNoP));
assert_param(IS_DSI_LP_DSW1P(LPCmd->LPDcsShortWriteOneP));
assert_param(IS_DSI_LP_DSR0P(LPCmd->LPDcsShortReadNoP));
assert_param(IS_DSI_LP_DLW(LPCmd->LPDcsLongWrite));
assert_param(IS_DSI_LP_MRDP(LPCmd->LPMaxReadPacket));
assert_param(IS_DSI_ACK_REQUEST(LPCmd->AcknowledgeRequest));
/* Select High-speed or Low-power for command transmission */
DSIx->CMCR &= ~(DSI_CMCR_GSW0TX |\
DSI_CMCR_GSW1TX |\
DSI_CMCR_GSW2TX |\
DSI_CMCR_GSR0TX |\
DSI_CMCR_GSR1TX |\
DSI_CMCR_GSR2TX |\
DSI_CMCR_GLWTX |\
DSI_CMCR_DSW0TX |\
DSI_CMCR_DSW1TX |\
DSI_CMCR_DSR0TX |\
DSI_CMCR_DLWTX |\
DSI_CMCR_MRDPS);
DSIx->CMCR |= (LPCmd->LPGenShortWriteNoP |\
LPCmd->LPGenShortWriteOneP |\
LPCmd->LPGenShortWriteTwoP |\
LPCmd->LPGenShortReadNoP |\
LPCmd->LPGenShortReadOneP |\
LPCmd->LPGenShortReadTwoP |\
LPCmd->LPGenLongWrite |\
LPCmd->LPDcsShortWriteNoP |\
LPCmd->LPDcsShortWriteOneP |\
LPCmd->LPDcsShortReadNoP |\
LPCmd->LPDcsLongWrite |\
LPCmd->LPMaxReadPacket);
/* Configure the acknowledge request after each packet transmission */
DSIx->CMCR &= ~DSI_CMCR_ARE;
DSIx->CMCR |= LPCmd->AcknowledgeRequest;
}
/**
* @brief Configure the flow control parameters
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param FlowControl: flow control feature(s) to be enabled.
* This parameter can be any combination of @ref DSI_FlowControl.
* @retval None
*/
void DSI_ConfigFlowControl(DSI_TypeDef *DSIx, uint32_t FlowControl)
{
/* Check the parameters */
assert_param(IS_DSI_FLOW_CONTROL(FlowControl));
/* Set the DSI Host Protocol Configuration Register */
DSIx->PCR &= ~DSI_FLOW_CONTROL_ALL;
DSIx->PCR |= FlowControl;
}
/**
* @brief Configure the DSI PHY timer parameters
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param PhyTimers: DSI_PHY_TimerTypeDef structure that contains
* the DSI PHY timing parameters
* @retval None
*/
void DSI_ConfigPhyTimer(DSI_TypeDef *DSIx, DSI_PHY_TimerTypeDef *PhyTimers)
{
uint32_t maxTime = 0;
maxTime = (PhyTimers->ClockLaneLP2HSTime > PhyTimers->ClockLaneHS2LPTime)? PhyTimers->ClockLaneLP2HSTime: PhyTimers->ClockLaneHS2LPTime;
/* Clock lane timer configuration */
/* In Automatic Clock Lane control mode, the DSI Host can turn off the clock lane between two
High-Speed transmission.
To do so, the DSI Host calculates the time required for the clock lane to change from HighSpeed
to Low-Power and from Low-Power to High-Speed.
This timings are configured by the HS2LP_TIME and LP2HS_TIME in the DSI Host Clock Lane Timer Configuration Register (DSI_CLTCR).
But the DSI Host is not calculating LP2HS_TIME + HS2LP_TIME but 2 x HS2LP_TIME.
Workaround : Configure HS2LP_TIME and LP2HS_TIME with the same value being the max of HS2LP_TIME or LP2HS_TIME.
*/
DSIx->CLTCR &= ~(DSI_CLTCR_LP2HS_TIME | DSI_CLTCR_HS2LP_TIME);
DSIx->CLTCR |= (maxTime | ((maxTime)<<16));
/* Data lane timer configuration */
DSIx->DLTCR &= ~(DSI_DLTCR_MRD_TIME | DSI_DLTCR_LP2HS_TIME | DSI_DLTCR_HS2LP_TIME);
DSIx->DLTCR |= (PhyTimers->DataLaneMaxReadTime | ((PhyTimers->DataLaneLP2HSTime)<<16) | ((PhyTimers->DataLaneHS2LPTime)<<24));
/* Configure the wait period to request HS transmission after a stop state */
DSIx->PCONFR &= ~DSI_PCONFR_SW_TIME;
DSIx->PCONFR |= ((PhyTimers->StopWaitTime)<<8);
}
/**
* @brief Configure the DSI HOST timeout parameters
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param HostTimeouts: DSI_HOST_TimeoutTypeDef structure that contains
* the DSI host timeout parameters
* @retval None
*/
void DSI_ConfigHostTimeouts(DSI_TypeDef *DSIx, DSI_HOST_TimeoutTypeDef *HostTimeouts)
{
/* Set the timeout clock division factor */
DSIx->CCR &= ~DSI_CCR_TOCKDIV;
DSIx->CCR = ((HostTimeouts->TimeoutCkdiv)<<8);
/* High-speed transmission timeout */
DSIx->TCCR[0] &= ~DSI_TCCR0_HSTX_TOCNT;
DSIx->TCCR[0] |= ((HostTimeouts->HighSpeedTransmissionTimeout)<<16);
/* Low-power reception timeout */
DSIx->TCCR[0] &= ~DSI_TCCR0_LPRX_TOCNT;
DSIx->TCCR[0] |= HostTimeouts->LowPowerReceptionTimeout;
/* High-speed read timeout */
DSIx->TCCR[1] &= ~DSI_TCCR1_HSRD_TOCNT;
DSIx->TCCR[1] |= HostTimeouts->HighSpeedReadTimeout;
/* Low-power read timeout */
DSIx->TCCR[2] &= ~DSI_TCCR2_LPRD_TOCNT;
DSIx->TCCR[2] |= HostTimeouts->LowPowerReadTimeout;
/* High-speed write timeout */
DSIx->TCCR[3] &= ~DSI_TCCR3_HSWR_TOCNT;
DSIx->TCCR[3] |= HostTimeouts->HighSpeedWriteTimeout;
/* High-speed write presp mode */
DSIx->TCCR[3] &= ~DSI_TCCR3_PM;
DSIx->TCCR[3] |= HostTimeouts->HighSpeedWritePrespMode;
/* Low-speed write timeout */
DSIx->TCCR[4] &= ~DSI_TCCR4_LPWR_TOCNT;
DSIx->TCCR[4] |= HostTimeouts->LowPowerWriteTimeout;
/* BTA timeout */
DSIx->TCCR[5] &= ~DSI_TCCR5_BTA_TOCNT;
DSIx->TCCR[5] |= HostTimeouts->BTATimeout;
}
/**
* @brief Start the DSI module
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* the configuration information for the DSI.
* @retval None
*/
void DSI_Start(DSI_TypeDef *DSIx)
{
/* Enable the DSI host */
DSIx->CR |= DSI_CR_EN;
/* Enable the DSI wrapper */
DSIx->WCR |= DSI_WCR_DSIEN;
}
/**
* @brief Stop the DSI module
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @retval None
*/
void DSI_Stop(DSI_TypeDef *DSIx)
{
/* Disable the DSI host */
DSIx->CR &= ~DSI_CR_EN;
/* Disable the DSI wrapper */
DSIx->WCR &= ~DSI_WCR_DSIEN;
}
/**
* @brief Refresh the display in command mode
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* the configuration information for the DSI.
* @retval None
*/
void DSI_Refresh(DSI_TypeDef *DSIx)
{
/* Update the display */
DSIx->WCR |= DSI_WCR_LTDCEN;
}
/**
* @brief Controls the display color mode in Video mode
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param ColorMode: Color mode (full or 8-colors).
* This parameter can be any value of @ref DSI_Color_Mode
* @retval None
*/
void DSI_ColorMode(DSI_TypeDef *DSIx, uint32_t ColorMode)
{
/* Check the parameters */
assert_param(IS_DSI_COLOR_MODE(ColorMode));
/* Update the display color mode */
DSIx->WCR &= ~DSI_WCR_COLM;
DSIx->WCR |= ColorMode;
}
/**
* @brief Control the display shutdown in Video mode
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param Shutdown: Shut-down (Display-ON or Display-OFF).
* This parameter can be any value of @ref DSI_ShutDown
* @retval None
*/
void DSI_Shutdown(DSI_TypeDef *DSIx, uint32_t Shutdown)
{
/* Check the parameters */
assert_param(IS_DSI_SHUT_DOWN(Shutdown));
/* Update the display Shutdown */
DSIx->WCR &= ~DSI_WCR_SHTDN;
DSIx->WCR |= Shutdown;
}
/**
* @}
*/
/** @defgroup Data transfers management functions
* @brief DSI data transfers management functions
*
@verbatim
===============================================================================
##### Data transfers management functions #####
===============================================================================
@endverbatim
* @{
*/
/**
* @brief DCS or Generic short write command
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param ChannelID: Virtual channel ID.
* @param Mode: DSI short packet data type.
* This parameter can be any value of @ref DSI_SHORT_WRITE_PKT_Data_Type.
* @param Param1: DSC command or first generic parameter.
* This parameter can be any value of @ref DSI_DCS_Command or a
* generic command code.
* @param Param2: DSC parameter or second generic parameter.
* @retval None
*/
void DSI_ShortWrite(DSI_TypeDef *DSIx,
uint32_t ChannelID,
uint32_t Mode,
uint32_t Param1,
uint32_t Param2)
{
/* Check the parameters */
assert_param(IS_DSI_SHORT_WRITE_PACKET_TYPE(Mode));
/* Wait for Command FIFO Empty */
while((DSIx->GPSR & DSI_GPSR_CMDFE) == 0)
{}
/* Configure the packet to send a short DCS command with 0 or 1 parameter */
DSI_ConfigPacketHeader(DSIx,
ChannelID,
Mode,
Param1,
Param2);
}
/**
* @brief DCS or Generic long write command
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param ChannelID: Virtual channel ID.
* @param Mode: DSI long packet data type.
* This parameter can be any value of @ref DSI_LONG_WRITE_PKT_Data_Type.
* @param NbParams: Number of parameters.
* @param Param1: DSC command or first generic parameter.
* This parameter can be any value of @ref DSI_DCS_Command or a
* generic command code
* @param ParametersTable: Pointer to parameter values table.
* @retval None
*/
void DSI_LongWrite(DSI_TypeDef *DSIx,
uint32_t ChannelID,
uint32_t Mode,
uint32_t NbParams,
uint32_t Param1,
uint8_t* ParametersTable)
{
uint32_t uicounter = 0;
/* Check the parameters */
assert_param(IS_DSI_LONG_WRITE_PACKET_TYPE(Mode));
/* Wait for Command FIFO Empty */
while((DSIx->GPSR & DSI_GPSR_CMDFE) == 0)
{}
/* Set the DCS code hexadecimal on payload byte 1, and the other parameters on the write FIFO command*/
while(uicounter < NbParams)
{
if(uicounter == 0x00)
{
DSIx->GPDR=(Param1 | \
((*(ParametersTable+uicounter))<<8) | \
((*(ParametersTable+uicounter+1))<<16) | \
((*(ParametersTable+uicounter+2))<<24));
uicounter += 3;
}
else
{
DSIx->GPDR=((*(ParametersTable+uicounter)) | \
((*(ParametersTable+uicounter+1))<<8) | \
((*(ParametersTable+uicounter+2))<<16) | \
((*(ParametersTable+uicounter+3))<<24));
uicounter+=4;
}
}
/* Configure the packet to send a long DCS command */
DSI_ConfigPacketHeader(DSIx,
ChannelID,
Mode,
((NbParams+1)&0x00FF),
(((NbParams+1)&0xFF00)>>8));
}
/**
* @brief Read command (DCS or generic)
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param ChannelNbr: Virtual channel ID
* @param Array: pointer to a buffer to store the payload of a read back operation.
* @param Size: Data size to be read (in byte).
* @param Mode: DSI read packet data type.
* This parameter can be any value of @ref DSI_SHORT_READ_PKT_Data_Type.
* @param DCSCmd: DCS get/read command.
* @param ParametersTable: Pointer to parameter values table.
* @retval None
*/
void DSI_Read(DSI_TypeDef *DSIx,
uint32_t ChannelNbr,
uint8_t* Array,
uint32_t Size,
uint32_t Mode,
uint32_t DCSCmd,
uint8_t* ParametersTable)
{
/* Check the parameters */
assert_param(IS_DSI_READ_PACKET_TYPE(Mode));
if(Size > 2)
{
/* set max return packet size */
DSI_ShortWrite(DSIx, ChannelNbr, DSI_MAX_RETURN_PKT_SIZE, ((Size)&0xFF), (((Size)>>8)&0xFF));
}
/* Configure the packet to read command */
if (Mode == DSI_DCS_SHORT_PKT_READ)
{
DSI_ConfigPacketHeader(DSIx, ChannelNbr, Mode, DCSCmd, 0);
}
else if (Mode == DSI_GEN_SHORT_PKT_READ_P0)
{
DSI_ConfigPacketHeader(DSIx, ChannelNbr, Mode, 0, 0);
}
else if (Mode == DSI_GEN_SHORT_PKT_READ_P1)
{
DSI_ConfigPacketHeader(DSIx, ChannelNbr, Mode, ParametersTable[0], 0);
}
else if (Mode == DSI_GEN_SHORT_PKT_READ_P2)
{
DSI_ConfigPacketHeader(DSIx, ChannelNbr, Mode, ParametersTable[0], ParametersTable[1]);
}
/* Check that the payload read FIFO is not empty */
while((DSIx->GPSR & DSI_GPSR_PRDFE) == DSI_GPSR_PRDFE)
{}
/* Get the first byte */
*((uint32_t *)Array) = (DSIx->GPDR);
if (Size > 4)
{
Size -= 4;
Array += 4;
}
/* Get the remaining bytes if any */
while(((int)(Size)) > 0)
{
if((DSIx->GPSR & DSI_GPSR_PRDFE) == 0)
{
*((uint32_t *)Array) = (DSIx->GPDR);
Size -= 4;
Array += 4;
}
}
}
/**
* @brief Generic DSI packet header configuration
* @param DSIx: Pointer to DSI register base
* @param ChannelID: Virtual channel ID of the header packet
* @param DataType: Packet data type of the header packet
* This parameter can be any value of :
* @ref DSI_SHORT_WRITE_PKT_Data_Type
* or @ref DSI_LONG_WRITE_PKT_Data_Type
* or @ref DSI_SHORT_READ_PKT_Data_Type
* or DSI_MAX_RETURN_PKT_SIZE
* @param Data0: Word count LSB
* @param Data1: Word count MSB
* @retval None
*/
static void DSI_ConfigPacketHeader(DSI_TypeDef *DSIx,
uint32_t ChannelID,
uint32_t DataType,
uint32_t Data0,
uint32_t Data1)
{
/* Update the DSI packet header with new information */
DSIx->GHCR = (DataType | (ChannelID<<6) | (Data0<<8) | (Data1<<16));
}
/**
* @}
*/
/** @defgroup DSI_Group3 Low Power functions
* @brief DSI Low Power management functions
*
@verbatim
===============================================================================
##### DSI Low Power functions #####
===============================================================================
@endverbatim
* @{
*/
/**
* @brief Enter the ULPM (Ultra Low Power Mode) with the D-PHY PLL running
* (only data lanes are in ULPM)
* @param DSIx: Pointer to DSI register base
* @retval None
*/
void DSI_EnterULPMData(DSI_TypeDef *DSIx)
{
/* ULPS Request on Data Lanes */
DSIx->PUCR |= DSI_PUCR_URDL;
/* Wait until the D-PHY active lanes enter into ULPM */
if((DSIx->PCONFR & DSI_PCONFR_NL) == DSI_ONE_DATA_LANE)
{
while((DSIx->PSR & DSI_PSR_UAN0) != 0)
{}
}
else if ((DSIx->PCONFR & DSI_PCONFR_NL) == DSI_TWO_DATA_LANES)
{
while((DSIx->PSR & (DSI_PSR_UAN0 | DSI_PSR_UAN1)) != 0)
{}
}
}
/**
* @brief Exit the ULPM (Ultra Low Power Mode) with the D-PHY PLL running
* (only data lanes are in ULPM)
* @param DSIx: Pointer to DSI register base
* @retval None
*/
void DSI_ExitULPMData(DSI_TypeDef *DSIx)
{
/* Exit ULPS on Data Lanes */
DSIx->PUCR |= DSI_PUCR_UEDL;
/* Wait until all active lanes exit ULPM */
if((DSIx->PCONFR & DSI_PCONFR_NL) == DSI_ONE_DATA_LANE)
{
while((DSIx->PSR & DSI_PSR_UAN0) != DSI_PSR_UAN0)
{}
}
else if ((DSIx->PCONFR & DSI_PCONFR_NL) == DSI_TWO_DATA_LANES)
{
while((DSIx->PSR & (DSI_PSR_UAN0 | DSI_PSR_UAN1)) != (DSI_PSR_UAN0 | DSI_PSR_UAN1))
{}
}
/* De-assert the ULPM requests and the ULPM exit bits */
DSIx->PUCR = 0;
}
/**
* @brief Enter the ULPM (Ultra Low Power Mode) with the D-PHY PLL turned off
* (both data and clock lanes are in ULPM)
* @param DSIx: Pointer to DSI register base
* @retval None
*/
void DSI_EnterULPM(DSI_TypeDef *DSIx)
{
/* Clock lane configuration: no more HS request */
DSIx->CLCR &= ~DSI_CLCR_DPCC;
/* Use system PLL as byte lane clock source before stopping DSIPHY clock source */
RCC_DSIClockSourceConfig(RCC_DSICLKSource_PLLR);
/* ULPS Request on Clock and Data Lanes */
DSIx->PUCR |= (DSI_PUCR_URCL | DSI_PUCR_URDL);
/* Wait until all active lanes exit ULPM */
if((DSIx->PCONFR & DSI_PCONFR_NL) == DSI_ONE_DATA_LANE)
{
while((DSIx->PSR & (DSI_PSR_UAN0 | DSI_PSR_UANC)) != 0)
{}
}
else if ((DSIx->PCONFR & DSI_PCONFR_NL) == DSI_TWO_DATA_LANES)
{
while((DSIx->PSR & (DSI_PSR_UAN0 | DSI_PSR_UAN1 | DSI_PSR_UANC)) != 0)
{}
}
/* Turn off the DSI PLL */
DSIx->WRPCR &= ~DSI_WRPCR_PLLEN;
}
/**
* @brief Exit the ULPM (Ultra Low Power Mode) with the D-PHY PLL turned off
* (both data and clock lanes are in ULPM)
* @param DSIx: Pointer to DSI register base
* @retval None
*/
void DSI_ExitULPM(DSI_TypeDef *DSIx)
{
/* Turn on the DSI PLL */
DSIx->WRPCR |= DSI_WRPCR_PLLEN;
/* Wait for the lock of the PLL */
while(DSI_GetFlagStatus(DSIx, DSI_FLAG_PLLLS) == RESET)
{}
/* Exit ULPS on Clock and Data Lanes */
DSIx->PUCR |= (DSI_PUCR_UECL | DSI_PUCR_UEDL);
/* Wait until all active lanes exit ULPM */
if((DSIx->PCONFR & DSI_PCONFR_NL) == DSI_ONE_DATA_LANE)
{
while((DSIx->PSR & (DSI_PSR_UAN0 | DSI_PSR_UANC)) != (DSI_PSR_UAN0 | DSI_PSR_UANC))
{}
}
else if ((DSIx->PCONFR & DSI_PCONFR_NL) == DSI_TWO_DATA_LANES)
{
while((DSIx->PSR & (DSI_PSR_UAN0 | DSI_PSR_UAN1 | DSI_PSR_UANC)) != (DSI_PSR_UAN0 | DSI_PSR_UAN1 | DSI_PSR_UANC))
{}
}
/* De-assert the ULPM requests and the ULPM exit bits */
DSIx->PUCR = 0;
/* Switch the lanbyteclock source in the RCC from system PLL to D-PHY */
RCC_DSIClockSourceConfig(RCC_DSICLKSource_PHY);
/* Restore clock lane configuration to HS */
DSIx->CLCR |= DSI_CLCR_DPCC;
}
/**
* @brief Start test pattern generation
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param Mode: Pattern generator mode
* This parameter can be one of the following values:
* 0 : Color bars (horizontal or vertical)
* 1 : BER pattern (vertical only)
* @param Orientation: Pattern generator orientation
* This parameter can be one of the following values:
* 0 : Vertical color bars
* 1 : Horizontal color bars
* @retval None
*/
void DSI_PatternGeneratorStart(DSI_TypeDef *DSIx, uint32_t Mode, uint32_t Orientation)
{
/* Configure pattern generator mode and orientation */
DSIx->VMCR &= ~(DSI_VMCR_PGM | DSI_VMCR_PGO);
DSIx->VMCR |= ((Mode<<20) | (Orientation<<24));
/* Enable pattern generator by setting PGE bit */
DSIx->VMCR |= DSI_VMCR_PGE;
}
/**
* @brief Stop test pattern generation
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @retval None
*/
void DSI_PatternGeneratorStop(DSI_TypeDef *DSIx)
{
/* Disable pattern generator by clearing PGE bit */
DSIx->VMCR &= ~DSI_VMCR_PGE;
}
/**
* @brief Set Slew-Rate And Delay Tuning
* @param DSIx: Pointer to DSI register base
* @param CommDelay: Communication delay to be adjusted.
* This parameter can be any value of @ref DSI_Communication_Delay
* @param Lane: select between clock or data lanes.
* This parameter can be any value of @ref DSI_Lane_Group
* @param Value: Custom value of the slew-rate or delay
* @retval None
*/
void DSI_SetSlewRateAndDelayTuning(DSI_TypeDef *DSIx, uint32_t CommDelay, uint32_t Lane, uint32_t Value)
{
/* Check function parameters */
assert_param(IS_DSI_COMMUNICATION_DELAY(CommDelay));
assert_param(IS_DSI_LANE_GROUP(Lane));
switch(CommDelay)
{
case DSI_SLEW_RATE_HSTX:
if(Lane == DSI_CLOCK_LANE)
{
/* High-Speed Transmission Slew Rate Control on Clock Lane */
DSIx->WPCR[1] &= ~DSI_WPCR1_HSTXSRCCL;
DSIx->WPCR[1] |= Value<<16;
}
else if(Lane == DSI_DATA_LANES)
{
/* High-Speed Transmission Slew Rate Control on Data Lanes */
DSIx->WPCR[1] &= ~DSI_WPCR1_HSTXSRCDL;
DSIx->WPCR[1] |= Value<<18;
}
break;
case DSI_SLEW_RATE_LPTX:
if(Lane == DSI_CLOCK_LANE)
{
/* Low-Power transmission Slew Rate Compensation on Clock Lane */
DSIx->WPCR[1] &= ~DSI_WPCR1_LPSRCCL;
DSIx->WPCR[1] |= Value<<6;
}
else if(Lane == DSI_DATA_LANES)
{
/* Low-Power transmission Slew Rate Compensation on Data Lanes */
DSIx->WPCR[1] &= ~DSI_WPCR1_LPSRCDL;
DSIx->WPCR[1] |= Value<<8;
}
break;
case DSI_HS_DELAY:
if(Lane == DSI_CLOCK_LANE)
{
/* High-Speed Transmission Delay on Clock Lane */
DSIx->WPCR[1] &= ~DSI_WPCR1_HSTXDCL;
DSIx->WPCR[1] |= Value;
}
else if(Lane == DSI_DATA_LANES)
{
/* High-Speed Transmission Delay on Data Lanes */
DSIx->WPCR[1] &= ~DSI_WPCR1_HSTXDDL;
DSIx->WPCR[1] |= Value<<2;
}
break;
default:
break;
}
}
/**
* @brief Low-Power Reception Filter Tuning
* @param DSIx: Pointer to DSI register base
* @param Frequency: cutoff frequency of low-pass filter at the input of LPRX
* @retval None
*/
void DSI_SetLowPowerRXFilter(DSI_TypeDef *DSIx, uint32_t Frequency)
{
/* Low-Power RX low-pass Filtering Tuning */
DSIx->WPCR[1] &= ~DSI_WPCR1_LPRXFT;
DSIx->WPCR[1] |= Frequency<<25;
}
/**
* @brief Activate an additional current path on all lanes to meet the SDDTx parameter
* defined in the MIPI D-PHY specification
* @param hdsi: pointer to a DSI_HandleTypeDef structure that contains
* the configuration information for the DSI.
* @param State: ENABLE or DISABLE
* @retval None
*/
void DSI_SetSDD(DSI_TypeDef *DSIx, FunctionalState State)
{
/* Check function parameters */
assert_param(IS_FUNCTIONAL_STATE(State));
/* Activate/Disactivate additional current path on all lanes */
DSIx->WPCR[1] &= ~DSI_WPCR1_SDDC;
DSIx->WPCR[1] |= State<<12;
}
/**
* @brief Custom lane pins configuration
* @param DSIx: Pointer to DSI register base
* @param CustomLane: Function to be applyed on selected lane.
* This parameter can be any value of @ref DSI_CustomLane
* @param Lane: select between clock or data lane 0 or data lane 1.
* This parameter can be any value of @ref DSI_Lane_Select
* @param State: ENABLE or DISABLE
* @retval None
*/
void DSI_SetLanePinsConfiguration(DSI_TypeDef *DSIx, uint32_t CustomLane, uint32_t Lane, FunctionalState State)
{
/* Check function parameters */
assert_param(IS_DSI_CUSTOM_LANE(CustomLane));
assert_param(IS_DSI_LANE(Lane));
assert_param(IS_FUNCTIONAL_STATE(State));
switch(CustomLane)
{
case DSI_SWAP_LANE_PINS:
if(Lane == DSI_CLOCK_LANE)
{
/* Swap pins on clock lane */
DSIx->WPCR[0] &= ~DSI_WPCR0_SWCL;
DSIx->WPCR[0] |= (State<<6);
}
else if(Lane == DSI_DATA_LANE0)
{
/* Swap pins on data lane 0 */
DSIx->WPCR[0] &= ~DSI_WPCR0_SWDL0;
DSIx->WPCR[0] |= (State<<7);
}
else if(Lane == DSI_DATA_LANE1)
{
/* Swap pins on data lane 1 */
DSIx->WPCR[0] &= ~DSI_WPCR0_SWDL1;
DSIx->WPCR[0] |= (State<<8);
}
break;
case DSI_INVERT_HS_SIGNAL:
if(Lane == DSI_CLOCK_LANE)
{
/* Invert HS signal on clock lane */
DSIx->WPCR[0] &= ~DSI_WPCR0_HSICL;
DSIx->WPCR[0] |= (State<<9);
}
else if(Lane == DSI_DATA_LANE0)
{
/* Invert HS signal on data lane 0 */
DSIx->WPCR[0] &= ~DSI_WPCR0_HSIDL0;
DSIx->WPCR[0] |= (State<<10);
}
else if(Lane == DSI_DATA_LANE1)
{
/* Invert HS signal on data lane 1 */
DSIx->WPCR[0] &= ~DSI_WPCR0_HSIDL1;
DSIx->WPCR[0] |= (State<<11);
}
break;
default:
break;
}
}
/**
* @brief Set custom timing for the PHY
* @param DSIx: Pointer to DSI register base
* @param Timing: PHY timing to be adjusted.
* This parameter can be any value of @ref DSI_PHY_Timing
* @param State: ENABLE or DISABLE
* @param Value: Custom value of the timing
* @retval None
*/
void DSI_SetPHYTimings(DSI_TypeDef *DSIx, uint32_t Timing, FunctionalState State, uint32_t Value)
{
/* Check function parameters */
assert_param(IS_DSI_PHY_TIMING(Timing));
assert_param(IS_FUNCTIONAL_STATE(State));
switch(Timing)
{
case DSI_TCLK_POST:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_TCLKPOSTEN;
DSIx->WPCR[0] |= (State<<27);
if(State)
{
/* Set custom value */
DSIx->WPCR[4] &= ~DSI_WPCR4_TCLKPOST;
DSIx->WPCR[4] |= Value;
}
break;
case DSI_TLPX_CLK:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_TLPXCEN;
DSIx->WPCR[0] |= (State<<26);
if(State)
{
/* Set custom value */
DSIx->WPCR[3] &= ~DSI_WPCR3_TLPXC;
DSIx->WPCR[3] |= Value;
}
break;
case DSI_THS_EXIT:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_THSEXITEN;
DSIx->WPCR[0] |= (State<<25);
if(State)
{
/* Set custom value */
DSIx->WPCR[3] &= ~DSI_WPCR3_THSEXIT;
DSIx->WPCR[3] |= Value;
}
break;
case DSI_TLPX_DATA:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_TLPXDEN;
DSIx->WPCR[0] |= (State<<24);
if(State)
{
/* Set custom value */
DSIx->WPCR[3] &= ~DSI_WPCR3_TLPXD;
DSIx->WPCR[3] |= Value;
}
break;
case DSI_THS_ZERO:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_THSZEROEN;
DSIx->WPCR[0] |= (State<<23);
if(State)
{
/* Set custom value */
DSIx->WPCR[3] &= ~DSI_WPCR3_THSZERO;
DSIx->WPCR[3] |= Value;
}
break;
case DSI_THS_TRAIL:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_THSTRAILEN;
DSIx->WPCR[0] |= (State<<22);
if(State)
{
/* Set custom value */
DSIx->WPCR[2] &= ~DSI_WPCR2_THSTRAIL;
DSIx->WPCR[2] |= Value;
}
break;
case DSI_THS_PREPARE:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_THSPREPEN;
DSIx->WPCR[0] |= (State<<21);
if(State)
{
/* Set custom value */
DSIx->WPCR[2] &= ~DSI_WPCR2_THSPREP;
DSIx->WPCR[2] |= Value;
}
break;
case DSI_TCLK_ZERO:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_TCLKZEROEN;
DSIx->WPCR[0] |= (State<<20);
if(State)
{
/* Set custom value */
DSIx->WPCR[2] &= ~DSI_WPCR2_TCLKZERO;
DSIx->WPCR[2] |= Value;
}
break;
case DSI_TCLK_PREPARE:
/* Enable/Disable custom timing setting */
DSIx->WPCR[0] &= ~DSI_WPCR0_TCLKPREPEN;
DSIx->WPCR[0] |= (State<<19);
if(State)
{
/* Set custom value */
DSIx->WPCR[2] &= ~DSI_WPCR2_TCLKPREP;
DSIx->WPCR[2] |= Value;
}
break;
default:
break;
}
}
/**
* @brief Force the Clock/Data Lane in TX Stop Mode
* @param DSIx: Pointer to DSI register base
* @param Lane: select between clock or data lanes.
* This parameter can be any value of @ref DSI_Lane_Group
* @param State: ENABLE or DISABLE
* @retval None
*/
void DSI_ForceTXStopMode(DSI_TypeDef *DSIx, uint32_t Lane, FunctionalState State)
{
/* Check function parameters */
assert_param(IS_DSI_LANE_GROUP(Lane));
assert_param(IS_FUNCTIONAL_STATE(State));
if(Lane == DSI_CLOCK_LANE)
{
/* Force/Unforce the Clock Lane in TX Stop Mode */
DSIx->WPCR[0] &= ~DSI_WPCR0_FTXSMCL;
DSIx->WPCR[0] |= (State<<12);
}
else if(Lane == DSI_DATA_LANES)
{
/* Force/Unforce the Data Lanes in TX Stop Mode */
DSIx->WPCR[0] &= ~DSI_WPCR0_FTXSMDL;
DSIx->WPCR[0] |= (State<<13);
}
}
/**
* @brief Forces LP Receiver in Low-Power Mode
* @param hdsi: pointer to a DSI_HandleTypeDef structure that contains
* the configuration information for the DSI.
* @param State: ENABLE or DISABLE
* @retval None
*/
void DSI_ForceRXLowPower(DSI_TypeDef *DSIx, FunctionalState State)
{
/* Check function parameters */
assert_param(IS_FUNCTIONAL_STATE(State));
/* Force/Unforce LP Receiver in Low-Power Mode */
DSIx->WPCR[1] &= ~DSI_WPCR1_FLPRXLPM;
DSIx->WPCR[1] |= State<<22;
}
/**
* @brief Force Data Lanes in RX Mode after a BTA
* @param hdsi: pointer to a DSI_HandleTypeDef structure that contains
* the configuration information for the DSI.
* @param State: ENABLE or DISABLE
* @retval None
*/
void DSI_ForceDataLanesInRX(DSI_TypeDef *DSIx, FunctionalState State)
{
/* Check function parameters */
assert_param(IS_FUNCTIONAL_STATE(State));
/* Force Data Lanes in RX Mode */
DSIx->WPCR[0] &= ~DSI_WPCR0_TDDL;
DSIx->WPCR[0] |= State<<16;
}
/**
* @brief Enable a pull-down on the lanes to prevent from floating states when unused
* @param hdsi: pointer to a DSI_HandleTypeDef structure that contains
* the configuration information for the DSI.
* @param State: ENABLE or DISABLE
* @retval None
*/
void DSI_SetPullDown(DSI_TypeDef *DSIx, FunctionalState State)
{
/* Check function parameters */
assert_param(IS_FUNCTIONAL_STATE(State));
/* Enable/Disable pull-down on lanes */
DSIx->WPCR[0] &= ~DSI_WPCR0_PDEN;
DSIx->WPCR[0] |= State<<18;
}
/**
* @brief Switch off the contention detection on data lanes
* @param hdsi: pointer to a DSI_HandleTypeDef structure that contains
* the configuration information for the DSI.
* @param State: ENABLE or DISABLE
* @retval None
*/
void DSI_SetContentionDetectionOff(DSI_TypeDef *DSIx, FunctionalState State)
{
/* Check function parameters */
assert_param(IS_FUNCTIONAL_STATE(State));
/* Contention Detection on Data Lanes OFF */
DSIx->WPCR[0] &= ~DSI_WPCR0_CDOFFDL;
DSIx->WPCR[0] |= State<<14;
}
/**
* @}
*/
/** @defgroup DSI_Group4 Interrupts and flags management functions
* @brief Interrupts and flags management functions
*
@verbatim
===============================================================================
##### Interrupts and flags management functions #####
===============================================================================
[..] This section provides a set of functions allowing to configure the DSI Interrupts
sources and check or clear the flags or pending bits status.
The user should identify which mode will be used in his application to manage
the communication: Polling mode or Interrupt mode.
*** Polling Mode ***
====================
[..] In Polling Mode, the DSI communication can be managed by 8 flags:
(#) DSI_FLAG_TE : Tearing Effect Interrupt Flag
(#) DSI_FLAG_ER : End of Refresh Interrupt Flag
(#) DSI_FLAG_BUSY : Busy Flag
(#) DSI_FLAG_PLLLS : PLL Lock Status
(#) DSI_FLAG_PLLL : PLL Lock Interrupt Flag
(#) DSI_FLAG_PLLU : PLL Unlock Interrupt Flag
(#) DSI_FLAG_RRS: Regulator Ready Status.
(#) DSI_FLAG_RR: Regulator Ready Interrupt Flag.
[..] In this Mode it is advised to use the following functions:
(+) FlagStatus DSI_GetFlagStatus(DSI_TypeDef* DSIx, uint32_t DSI_FLAG);
(+) void DSI_ClearFlag(DSI_TypeDef* DSIx, uint32_t DSI_FLAG);
*** Interrupt Mode ***
======================
[..] In Interrupt Mode, the SPI communication can be managed by 3 interrupt sources
and 7 pending bits:
(+) Pending Bits:
(##) DSI_IT_TE : Tearing Effect Interrupt Flag
(##) DSI_IT_ER : End of Refresh Interrupt Flag
(##) DSI_IT_PLLL : PLL Lock Interrupt Flag
(##) DSI_IT_PLLU : PLL Unlock Interrupt Flag
(##) DSI_IT_RR: Regulator Ready Interrupt Flag.
(+) Interrupt Source:
(##) DSI_IT_TE : Tearing Effect Interrupt Enable
(##) DSI_IT_ER : End of Refresh Interrupt Enable
(##) DSI_IT_PLLL : PLL Lock Interrupt Enable
(##) DSI_IT_PLLU : PLL Unlock Interrupt Enable
(##) DSI_IT_RR: Regulator Ready Interrupt Enable
[..] In this Mode it is advised to use the following functions:
(+) void DSI_ITConfig(DSI_TypeDef* DSIx, uint32_t DSI_IT, FunctionalState NewState);
(+) ITStatus DSI_GetITStatus(DSI_TypeDef* DSIx, uint32_t DSI_IT);
(+) void DSI_ClearITPendingBit(DSI_TypeDef* DSIx, uint32_t DSI_IT);
@endverbatim
* @{
*/
/**
* @brief Enables or disables the specified DSI interrupts.
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param DSI_IT: specifies the DSI interrupt sources to be enabled or disabled.
* This parameter can be any combination of the following values:
* @arg DSI_IT_TE : Tearing Effect Interrupt
* @arg DSI_IT_ER : End of Refresh Interrupt
* @arg DSI_IT_PLLL: PLL Lock Interrupt
* @arg DSI_IT_PLLU: PLL Unlock Interrupt
* @arg DSI_IT_RR : Regulator Ready Interrupt
* @param NewState: new state of the specified DSI interrupt.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void DSI_ITConfig(DSI_TypeDef* DSIx, uint32_t DSI_IT, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_DSI_ALL_PERIPH(DSIx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
assert_param(IS_DSI_IT(DSI_IT));
if(NewState != DISABLE)
{
/* Enable the selected DSI interrupt */
DSIx->WIER |= DSI_IT;
}
else
{
/* Disable the selected DSI interrupt */
DSIx->WIER &= ~DSI_IT;
}
}
/**
* @brief Checks whether the specified DSI flag is set or not.
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param DSI_FLAG: specifies the SPI flag to be checked.
* This parameter can be one of the following values:
* @arg DSI_FLAG_TE : Tearing Effect Interrupt Flag
* @arg DSI_FLAG_ER : End of Refresh Interrupt Flag
* @arg DSI_FLAG_BUSY : Busy Flag
* @arg DSI_FLAG_PLLLS: PLL Lock Status
* @arg DSI_FLAG_PLLL : PLL Lock Interrupt Flag
* @arg DSI_FLAG_PLLU : PLL Unlock Interrupt Flag
* @arg DSI_FLAG_RRS : Regulator Ready Flag
* @arg DSI_FLAG_RR : Regulator Ready Interrupt Flag
* @retval The new state of DSI_FLAG (SET or RESET).
*/
FlagStatus DSI_GetFlagStatus(DSI_TypeDef* DSIx, uint16_t DSI_FLAG)
{
FlagStatus bitstatus = RESET;
/* Check the parameters */
assert_param(IS_DSI_ALL_PERIPH(DSIx));
assert_param(IS_DSI_GET_FLAG(DSI_FLAG));
/* Check the status of the specified DSI flag */
if((DSIx->WISR & DSI_FLAG) != (uint32_t)RESET)
{
/* DSI_FLAG is set */
bitstatus = SET;
}
else
{
/* DSI_FLAG is reset */
bitstatus = RESET;
}
/* Return the DSI_FLAG status */
return bitstatus;
}
/**
* @brief Clears the specified DSI flag.
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param DSI_FLAG: specifies the SPI flag to be cleared.
* This parameter can be one of the following values:
* @arg DSI_FLAG_TE : Tearing Effect Interrupt Flag
* @arg DSI_FLAG_ER : End of Refresh Interrupt Flag
* @arg DSI_FLAG_PLLL : PLL Lock Interrupt Flag
* @arg DSI_FLAG_PLLU : PLL Unlock Interrupt Flag
* @arg DSI_FLAG_RR : Regulator Ready Interrupt Flag
* @retval None
*/
void DSI_ClearFlag(DSI_TypeDef* DSIx, uint16_t DSI_FLAG)
{
/* Check the parameters */
assert_param(IS_DSI_ALL_PERIPH(DSIx));
assert_param(IS_DSI_CLEAR_FLAG(DSI_FLAG));
/* Clear the selected DSI flag */
DSIx->WIFCR = (uint32_t)DSI_FLAG;
}
/**
* @brief Checks whether the specified DSIx interrupt has occurred or not.
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param DSI_IT: specifies the DSI interrupt sources to be checked.
* This parameter can be one of the following values:
* @arg DSI_IT_TE : Tearing Effect Interrupt
* @arg DSI_IT_ER : End of Refresh Interrupt
* @arg DSI_IT_PLLL: PLL Lock Interrupt
* @arg DSI_IT_PLLU: PLL Unlock Interrupt
* @arg DSI_IT_RR : Regulator Ready Interrupt
* @retval The new state of SPI_I2S_IT (SET or RESET).
*/
ITStatus DSI_GetITStatus(DSI_TypeDef* DSIx, uint32_t DSI_IT)
{
ITStatus bitstatus = RESET;
uint32_t enablestatus = 0;
/* Check the parameters */
assert_param(IS_DSI_ALL_PERIPH(DSIx));
assert_param(IS_DSI_IT(DSI_IT));
/* Get the DSI_IT enable bit status */
enablestatus = (DSIx->WIER & DSI_IT);
/* Check the status of the specified SPI interrupt */
if (((DSIx->WISR & DSI_IT) != (uint32_t)RESET) && enablestatus)
{
/* DSI_IT is set */
bitstatus = SET;
}
else
{
/* DSI_IT is reset */
bitstatus = RESET;
}
/* Return the DSI_IT status */
return bitstatus;
}
/**
* @brief Clears the DSIx interrupt pending bit.
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param DSI_IT: specifies the DSI interrupt sources to be cleared.
* This parameter can be one of the following values:
* @arg DSI_IT_TE : Tearing Effect Interrupt
* @arg DSI_IT_ER : End of Refresh Interrupt
* @arg DSI_IT_PLLL: PLL Lock Interrupt
* @arg DSI_IT_PLLU: PLL Unlock Interrupt
* @arg DSI_IT_RR : Regulator Ready Interrupt
* @retval None
*/
void DSI_ClearITPendingBit(DSI_TypeDef* DSIx, uint32_t DSI_IT)
{
/* Check the parameters */
assert_param(IS_DSI_ALL_PERIPH(DSIx));
assert_param(IS_DSI_IT(DSI_IT));
/* Clear the selected DSI interrupt pending bit */
DSIx->WIFCR = (uint32_t)DSI_IT;
}
/**
* @brief Enable the error monitor flags
* @param DSIx: To select the DSIx peripheral, where x can be the different DSI instances
* @param ActiveErrors: indicates which error interrupts will be enabled.
* This parameter can be any combination of @ref DSI_Error_Data_Type.
* @retval None
*/
void DSI_ConfigErrorMonitor(DSI_TypeDef *DSIx, uint32_t ActiveErrors)
{
DSIx->IER[0] = 0;
DSIx->IER[1] = 0;
if(ActiveErrors & DSI_ERROR_ACK)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[0] |= DSI_ERROR_ACK_MASK;
}
if(ActiveErrors & DSI_ERROR_PHY)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[0] |= DSI_ERROR_PHY_MASK;
}
if(ActiveErrors & DSI_ERROR_TX)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[1] |= DSI_ERROR_TX_MASK;
}
if(ActiveErrors & DSI_ERROR_RX)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[1] |= DSI_ERROR_RX_MASK;
}
if(ActiveErrors & DSI_ERROR_ECC)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[1] |= DSI_ERROR_ECC_MASK;
}
if(ActiveErrors & DSI_ERROR_CRC)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[1] |= DSI_ERROR_CRC_MASK;
}
if(ActiveErrors & DSI_ERROR_PSE)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[1] |= DSI_ERROR_PSE_MASK;
}
if(ActiveErrors & DSI_ERROR_EOT)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[1] |= DSI_ERROR_EOT_MASK;
}
if(ActiveErrors & DSI_ERROR_OVF)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[1] |= DSI_ERROR_OVF_MASK;
}
if(ActiveErrors & DSI_ERROR_GEN)
{
/* Enable the interrupt generation on selected errors */
DSIx->IER[1] |= DSI_ERROR_GEN_MASK;
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* STM32F469_479xx */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
wallamejorge/WirelessSensorGas | rtl/wirelessUSBDrivers/Linux/2011_0719_RT3070_RT3370_RT5370_RT5372_Linux_STA_V2.5.0.3_DPO/os/linux/rt_linux.c | 8 | 116696 | /*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2010, Ralink Technology, Inc.
*
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*************************************************************************/
#define RTMP_MODULE_OS
#define RTMP_MODULE_OS_UTIL
/*#include "rt_config.h" */
#include "rtmp_comm.h"
#include "rtmp_osabl.h"
#include "rt_os_util.h"
#if defined (CONFIG_RA_HW_NAT) || defined (CONFIG_RA_HW_NAT_MODULE)
#include "../../../../../../net/nat/hw_nat/ra_nat.h"
#include "../../../../../../net/nat/hw_nat/frame_engine.h"
#endif
/* TODO */
#undef RT_CONFIG_IF_OPMODE_ON_AP
#undef RT_CONFIG_IF_OPMODE_ON_STA
#if defined(CONFIG_AP_SUPPORT) && defined(CONFIG_STA_SUPPORT)
#define RT_CONFIG_IF_OPMODE_ON_AP(__OpMode) if (__OpMode == OPMODE_AP)
#define RT_CONFIG_IF_OPMODE_ON_STA(__OpMode) if (__OpMode == OPMODE_STA)
#else
#define RT_CONFIG_IF_OPMODE_ON_AP(__OpMode)
#define RT_CONFIG_IF_OPMODE_ON_STA(__OpMode)
#endif
ULONG RTDebugLevel = RT_DEBUG_ERROR;
#ifdef OS_ABL_FUNC_SUPPORT
ULONG RTPktOffsetData = 0, RTPktOffsetLen = 0, RTPktOffsetCB = 0;
#endif /* OS_ABL_FUNC_SUPPORT */
#ifdef VENDOR_FEATURE4_SUPPORT
ULONG OS_NumOfMemAlloc = 0, OS_NumOfMemFree = 0;
#endif /* VENDOR_FEATURE4_SUPPORT */
#ifdef VENDOR_FEATURE2_SUPPORT
ULONG OS_NumOfPktAlloc = 0, OS_NumOfPktFree = 0;
#endif /* VENDOR_FEATURE2_SUPPORT */
/*
* the lock will not be used in TX/RX
* path so throughput should not be impacted
*/
BOOLEAN FlgIsUtilInit = FALSE;
OS_NDIS_SPIN_LOCK UtilSemLock;
/*
========================================================================
Routine Description:
Initialize something in UTIL module.
Arguments:
None
Return Value:
None
Note:
========================================================================
*/
VOID RtmpUtilInit(
VOID)
{
if (FlgIsUtilInit == FALSE) {
OS_NdisAllocateSpinLock(&UtilSemLock);
FlgIsUtilInit = TRUE;
}
}
/* timeout -- ms */
static inline VOID __RTMP_SetPeriodicTimer(
IN OS_NDIS_MINIPORT_TIMER * pTimer,
IN unsigned long timeout)
{
timeout = ((timeout * OS_HZ) / 1000);
pTimer->expires = jiffies + timeout;
add_timer(pTimer);
}
/* convert NdisMInitializeTimer --> RTMP_OS_Init_Timer */
static inline VOID __RTMP_OS_Init_Timer(
IN VOID *pReserved,
IN OS_NDIS_MINIPORT_TIMER * pTimer,
IN TIMER_FUNCTION function,
IN PVOID data)
{
if (!timer_pending(pTimer)) {
init_timer(pTimer);
pTimer->data = (unsigned long)data;
pTimer->function = function;
}
}
static inline VOID __RTMP_OS_Add_Timer(
IN OS_NDIS_MINIPORT_TIMER * pTimer,
IN unsigned long timeout)
{
if (timer_pending(pTimer))
return;
timeout = ((timeout * OS_HZ) / 1000);
pTimer->expires = jiffies + timeout;
add_timer(pTimer);
}
static inline VOID __RTMP_OS_Mod_Timer(
IN OS_NDIS_MINIPORT_TIMER * pTimer,
IN unsigned long timeout)
{
timeout = ((timeout * OS_HZ) / 1000);
mod_timer(pTimer, jiffies + timeout);
}
static inline VOID __RTMP_OS_Del_Timer(
IN OS_NDIS_MINIPORT_TIMER * pTimer,
OUT BOOLEAN *pCancelled)
{
if (timer_pending(pTimer))
*pCancelled = del_timer_sync(pTimer);
else
*pCancelled = TRUE;
}
static inline VOID __RTMP_OS_Release_Timer(
IN OS_NDIS_MINIPORT_TIMER * pTimer)
{
/* nothing to do */
}
/* Unify all delay routine by using udelay */
VOID RTMPusecDelay(
IN ULONG usec)
{
ULONG i;
for (i = 0; i < (usec / 50); i++)
udelay(50);
if (usec % 50)
udelay(usec % 50);
}
VOID RtmpOsMsDelay(
IN ULONG msec)
{
mdelay(msec);
}
void RTMP_GetCurrentSystemTime(
LARGE_INTEGER * time)
{
time->u.LowPart = jiffies;
}
void RTMP_GetCurrentSystemTick(
ULONG *pNow)
{
*pNow = jiffies;
}
/* pAd MUST allow to be NULL */
NDIS_STATUS os_alloc_mem(
IN VOID *pReserved,
OUT UCHAR **mem,
IN ULONG size)
{
*mem = (PUCHAR) kmalloc(size, GFP_ATOMIC);
if (*mem) {
#ifdef VENDOR_FEATURE4_SUPPORT
OS_NumOfMemAlloc++;
#endif /* VENDOR_FEATURE4_SUPPORT */
return (NDIS_STATUS_SUCCESS);
} else
return (NDIS_STATUS_FAILURE);
}
NDIS_STATUS os_alloc_mem_suspend(
IN VOID *pReserved,
OUT UCHAR **mem,
IN ULONG size)
{
*mem = (PUCHAR) kmalloc(size, GFP_KERNEL);
if (*mem) {
#ifdef VENDOR_FEATURE4_SUPPORT
OS_NumOfMemAlloc++;
#endif /* VENDOR_FEATURE4_SUPPORT */
return (NDIS_STATUS_SUCCESS);
} else
return (NDIS_STATUS_FAILURE);
}
/* pAd MUST allow to be NULL */
NDIS_STATUS os_free_mem(
IN VOID *pReserved,
IN PVOID mem)
{
ASSERT(mem);
kfree(mem);
#ifdef VENDOR_FEATURE4_SUPPORT
OS_NumOfMemFree++;
#endif /* VENDOR_FEATURE4_SUPPORT */
return (NDIS_STATUS_SUCCESS);
}
#if defined(RTMP_RBUS_SUPPORT) || defined (RTMP_FLASH_SUPPORT)
/* The flag "CONFIG_RALINK_FLASH_API" is used for APSoC Linux SDK */
#ifdef CONFIG_RALINK_FLASH_API
int32_t FlashRead(
uint32_t *dst,
uint32_t *src,
uint32_t count);
int32_t FlashWrite(
uint16_t *source,
uint16_t *destination,
uint32_t numBytes);
#define NVRAM_OFFSET 0x30000
#if defined (CONFIG_RT2880_FLASH_32M)
#define RF_OFFSET 0x1FE0000
#else
#ifdef RTMP_FLASH_SUPPORT
#define RF_OFFSET 0x48000
#else
#define RF_OFFSET 0x40000
#endif /* RTMP_FLASH_SUPPORT */
#endif
#else /* CONFIG_RALINK_FLASH_API */
#ifdef RA_MTD_RW_BY_NUM
#if defined (CONFIG_RT2880_FLASH_32M)
#define MTD_NUM_FACTORY 5
#else
#define MTD_NUM_FACTORY 2
#endif
extern int ra_mtd_write(
int num,
loff_t to,
size_t len,
const u_char *buf);
extern int ra_mtd_read(
int num,
loff_t from,
size_t len,
u_char *buf);
#else
extern int ra_mtd_write_nm(
char *name,
loff_t to,
size_t len,
const u_char *buf);
extern int ra_mtd_read_nm(
char *name,
loff_t from,
size_t len,
u_char *buf);
#endif
#endif /* CONFIG_RALINK_FLASH_API */
void RtmpFlashRead(
UCHAR * p,
ULONG a,
ULONG b)
{
#ifdef CONFIG_RALINK_FLASH_API
FlashRead((uint32_t *) p, (uint32_t *) a, (uint32_t) b);
#else
#ifdef RA_MTD_RW_BY_NUM
ra_mtd_read(MTD_NUM_FACTORY, 0, (size_t) b, p);
#else
ra_mtd_read_nm("Factory", a&0xFFFF, (size_t) b, p);
#endif
#endif /* CONFIG_RALINK_FLASH_API */
}
void RtmpFlashWrite(
UCHAR * p,
ULONG a,
ULONG b)
{
#ifdef CONFIG_RALINK_FLASH_API
FlashWrite((uint16_t *) p, (uint16_t *) a, (uint32_t) b);
#else
#ifdef RA_MTD_RW_BY_NUM
ra_mtd_write(MTD_NUM_FACTORY, 0, (size_t) b, p);
#else
ra_mtd_write_nm("Factory", a&0xFFFF, (size_t) b, p);
#endif
#endif /* CONFIG_RALINK_FLASH_API */
}
#endif /* defined(RTMP_RBUS_SUPPORT) || defined (RTMP_FLASH_SUPPORT) */
PNDIS_PACKET RtmpOSNetPktAlloc(
IN VOID *pReserved,
IN int size)
{
struct sk_buff *skb;
/* Add 2 more bytes for ip header alignment */
skb = dev_alloc_skb(size + 2);
if (skb != NULL)
MEM_DBG_PKT_ALLOC_INC(skb);
return ((PNDIS_PACKET) skb);
}
PNDIS_PACKET RTMP_AllocateFragPacketBuffer(
IN VOID *pReserved,
IN ULONG Length)
{
struct sk_buff *pkt;
pkt = dev_alloc_skb(Length);
if (pkt == NULL) {
DBGPRINT(RT_DEBUG_ERROR,
("can't allocate frag rx %ld size packet\n", Length));
}
if (pkt) {
MEM_DBG_PKT_ALLOC_INC(pkt);
RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pkt), PKTSRC_NDIS);
}
return (PNDIS_PACKET) pkt;
}
/* the allocated NDIS PACKET must be freed via RTMPFreeNdisPacket() */
NDIS_STATUS RTMPAllocateNdisPacket(
IN VOID *pReserved,
OUT PNDIS_PACKET *ppPacket,
IN PUCHAR pHeader,
IN UINT HeaderLen,
IN PUCHAR pData,
IN UINT DataLen)
{
PNDIS_PACKET pPacket;
ASSERT(pData);
ASSERT(DataLen);
/* 1. Allocate a packet */
pPacket =
(PNDIS_PACKET) dev_alloc_skb(HeaderLen + DataLen +
RTMP_PKT_TAIL_PADDING);
if (pPacket == NULL) {
*ppPacket = NULL;
#ifdef DEBUG
printk(KERN_ERR "RTMPAllocateNdisPacket Fail\n\n");
#endif
return NDIS_STATUS_FAILURE;
}
MEM_DBG_PKT_ALLOC_INC(pPacket);
/* 2. clone the frame content */
if (HeaderLen > 0)
NdisMoveMemory(GET_OS_PKT_DATAPTR(pPacket), pHeader, HeaderLen);
if (DataLen > 0)
NdisMoveMemory(GET_OS_PKT_DATAPTR(pPacket) + HeaderLen, pData,
DataLen);
/* 3. update length of packet */
skb_put(GET_OS_PKT_TYPE(pPacket), HeaderLen + DataLen);
RTMP_SET_PACKET_SOURCE(pPacket, PKTSRC_NDIS);
/* printk(KERN_ERR "%s : pPacket = %p, len = %d\n", __FUNCTION__,
pPacket, GET_OS_PKT_LEN(pPacket));*/
*ppPacket = pPacket;
return NDIS_STATUS_SUCCESS;
}
/*
========================================================================
Description:
This routine frees a miniport internally allocated NDIS_PACKET and its
corresponding NDIS_BUFFER and allocated memory.
========================================================================
*/
VOID RTMPFreeNdisPacket(
IN VOID *pReserved,
IN PNDIS_PACKET pPacket)
{
dev_kfree_skb_any(RTPKT_TO_OSPKT(pPacket));
MEM_DBG_PKT_FREE_INC(pPacket);
}
/* IRQL = DISPATCH_LEVEL */
/* NOTE: we do have an assumption here, that Byte0 and Byte1
* always reasid at the same scatter gather buffer
*/
NDIS_STATUS Sniff2BytesFromNdisBuffer(
IN PNDIS_BUFFER pFirstBuffer,
IN UCHAR DesiredOffset,
OUT PUCHAR pByte0,
OUT PUCHAR pByte1)
{
*pByte0 = *(PUCHAR) (pFirstBuffer + DesiredOffset);
*pByte1 = *(PUCHAR) (pFirstBuffer + DesiredOffset + 1);
return NDIS_STATUS_SUCCESS;
}
void RTMP_QueryPacketInfo(
IN PNDIS_PACKET pPacket,
OUT PACKET_INFO * pPacketInfo,
OUT PUCHAR * pSrcBufVA,
OUT UINT * pSrcBufLen)
{
pPacketInfo->BufferCount = 1;
pPacketInfo->pFirstBuffer = (PNDIS_BUFFER) GET_OS_PKT_DATAPTR(pPacket);
pPacketInfo->PhysicalBufferCount = 1;
pPacketInfo->TotalPacketLength = GET_OS_PKT_LEN(pPacket);
*pSrcBufVA = GET_OS_PKT_DATAPTR(pPacket);
*pSrcBufLen = GET_OS_PKT_LEN(pPacket);
}
PNDIS_PACKET DuplicatePacket(
IN PNET_DEV pNetDev,
IN PNDIS_PACKET pPacket,
IN UCHAR FromWhichBSSID)
{
struct sk_buff *skb;
PNDIS_PACKET pRetPacket = NULL;
USHORT DataSize;
UCHAR *pData;
DataSize = (USHORT) GET_OS_PKT_LEN(pPacket);
pData = (PUCHAR) GET_OS_PKT_DATAPTR(pPacket);
skb = skb_clone(RTPKT_TO_OSPKT(pPacket), MEM_ALLOC_FLAG);
if (skb) {
MEM_DBG_PKT_ALLOC_INC(skb);
skb->dev = pNetDev; /*get_netdev_from_bssid(pAd, FromWhichBSSID); */
pRetPacket = OSPKT_TO_RTPKT(skb);
}
return pRetPacket;
}
PNDIS_PACKET duplicate_pkt(
IN PNET_DEV pNetDev,
IN PUCHAR pHeader802_3,
IN UINT HdrLen,
IN PUCHAR pData,
IN ULONG DataSize,
IN UCHAR FromWhichBSSID)
{
struct sk_buff *skb;
PNDIS_PACKET pPacket = NULL;
if ((skb =
__dev_alloc_skb(HdrLen + DataSize + 2, MEM_ALLOC_FLAG)) != NULL) {
MEM_DBG_PKT_ALLOC_INC(skb);
skb_reserve(skb, 2);
NdisMoveMemory(skb->tail, pHeader802_3, HdrLen);
skb_put(skb, HdrLen);
NdisMoveMemory(skb->tail, pData, DataSize);
skb_put(skb, DataSize);
skb->dev = pNetDev; /*get_netdev_from_bssid(pAd, FromWhichBSSID); */
pPacket = OSPKT_TO_RTPKT(skb);
}
return pPacket;
}
#define TKIP_TX_MIC_SIZE 8
PNDIS_PACKET duplicate_pkt_with_TKIP_MIC(
IN VOID *pReserved,
IN PNDIS_PACKET pPacket)
{
struct sk_buff *skb, *newskb;
skb = RTPKT_TO_OSPKT(pPacket);
if (skb_tailroom(skb) < TKIP_TX_MIC_SIZE) {
/* alloc a new skb and copy the packet */
newskb =
skb_copy_expand(skb, skb_headroom(skb), TKIP_TX_MIC_SIZE,
GFP_ATOMIC);
dev_kfree_skb_any(skb);
MEM_DBG_PKT_FREE_INC(skb);
if (newskb == NULL) {
DBGPRINT(RT_DEBUG_ERROR,
("Extend Tx.MIC for packet failed!, dropping packet!\n"));
return NULL;
}
skb = newskb;
MEM_DBG_PKT_ALLOC_INC(skb);
}
return OSPKT_TO_RTPKT(skb);
}
/*
========================================================================
Routine Description:
Send a L2 frame to upper daemon to trigger state machine
Arguments:
pAd - pointer to our pAdapter context
Return Value:
Note:
========================================================================
*/
BOOLEAN RTMPL2FrameTxAction(
IN VOID * pCtrlBkPtr,
IN PNET_DEV pNetDev,
IN RTMP_CB_8023_PACKET_ANNOUNCE _announce_802_3_packet,
IN UCHAR apidx,
IN PUCHAR pData,
IN UINT32 data_len,
IN UCHAR OpMode)
{
struct sk_buff *skb = dev_alloc_skb(data_len + 2);
if (!skb) {
DBGPRINT(RT_DEBUG_ERROR,
("%s : Error! Can't allocate a skb.\n", __FUNCTION__));
return FALSE;
}
MEM_DBG_PKT_ALLOC_INC(skb);
/*get_netdev_from_bssid(pAd, apidx)); */
SET_OS_PKT_NETDEV(skb, pNetDev);
/* 16 byte align the IP header */
skb_reserve(skb, 2);
/* Insert the frame content */
NdisMoveMemory(GET_OS_PKT_DATAPTR(skb), pData, data_len);
/* End this frame */
skb_put(GET_OS_PKT_TYPE(skb), data_len);
DBGPRINT(RT_DEBUG_TRACE, ("%s doen\n", __FUNCTION__));
_announce_802_3_packet(pCtrlBkPtr, skb, OpMode);
return TRUE;
}
PNDIS_PACKET ExpandPacket(
IN VOID *pReserved,
IN PNDIS_PACKET pPacket,
IN UINT32 ext_head_len,
IN UINT32 ext_tail_len)
{
struct sk_buff *skb, *newskb;
skb = RTPKT_TO_OSPKT(pPacket);
if (skb_cloned(skb) || (skb_headroom(skb) < ext_head_len)
|| (skb_tailroom(skb) < ext_tail_len)) {
UINT32 head_len =
(skb_headroom(skb) <
ext_head_len) ? ext_head_len : skb_headroom(skb);
UINT32 tail_len =
(skb_tailroom(skb) <
ext_tail_len) ? ext_tail_len : skb_tailroom(skb);
/* alloc a new skb and copy the packet */
newskb = skb_copy_expand(skb, head_len, tail_len, GFP_ATOMIC);
dev_kfree_skb_any(skb);
MEM_DBG_PKT_FREE_INC(skb);
if (newskb == NULL) {
DBGPRINT(RT_DEBUG_ERROR,
("Extend Tx buffer for WPI failed!, dropping packet!\n"));
return NULL;
}
skb = newskb;
MEM_DBG_PKT_ALLOC_INC(skb);
}
return OSPKT_TO_RTPKT(skb);
}
PNDIS_PACKET ClonePacket(
IN VOID *pReserved,
IN PNDIS_PACKET pPacket,
IN PUCHAR pData,
IN ULONG DataSize)
{
struct sk_buff *pRxPkt;
struct sk_buff *pClonedPkt;
ASSERT(pPacket);
pRxPkt = RTPKT_TO_OSPKT(pPacket);
/* clone the packet */
pClonedPkt = skb_clone(pRxPkt, MEM_ALLOC_FLAG);
if (pClonedPkt) {
/* set the correct dataptr and data len */
MEM_DBG_PKT_ALLOC_INC(pClonedPkt);
pClonedPkt->dev = pRxPkt->dev;
pClonedPkt->data = pData;
pClonedPkt->len = DataSize;
pClonedPkt->tail = pClonedPkt->data + pClonedPkt->len;
ASSERT(DataSize < 1530);
}
return pClonedPkt;
}
VOID RtmpOsPktInit(
IN PNDIS_PACKET pNetPkt,
IN PNET_DEV pNetDev,
IN UCHAR *pData,
IN USHORT DataSize)
{
PNDIS_PACKET pRxPkt;
pRxPkt = RTPKT_TO_OSPKT(pNetPkt);
SET_OS_PKT_NETDEV(pRxPkt, pNetDev);
SET_OS_PKT_DATAPTR(pRxPkt, pData);
SET_OS_PKT_LEN(pRxPkt, DataSize);
SET_OS_PKT_DATATAIL(pRxPkt, pData, DataSize);
}
void wlan_802_11_to_802_3_packet(
IN PNET_DEV pNetDev,
IN UCHAR OpMode,
IN USHORT VLAN_VID,
IN USHORT VLAN_Priority,
IN PNDIS_PACKET pRxPacket,
IN UCHAR *pData,
IN ULONG DataSize,
IN PUCHAR pHeader802_3,
IN UCHAR FromWhichBSSID,
IN UCHAR *TPID)
{
struct sk_buff *pOSPkt;
/* ASSERT(pRxBlk->pRxPacket); */
ASSERT(pHeader802_3);
pOSPkt = RTPKT_TO_OSPKT(pRxPacket);
/*get_netdev_from_bssid(pAd, FromWhichBSSID); */
pOSPkt->dev = pNetDev;
pOSPkt->data = pData;
pOSPkt->len = DataSize;
pOSPkt->tail = pOSPkt->data + pOSPkt->len;
/* */
/* copy 802.3 header */
/* */
/* */
#ifdef CONFIG_STA_SUPPORT
RT_CONFIG_IF_OPMODE_ON_STA(OpMode)
{
NdisMoveMemory(skb_push(pOSPkt, LENGTH_802_3), pHeader802_3,
LENGTH_802_3);
}
#endif /* CONFIG_STA_SUPPORT */
}
void hex_dump(
char *str,
unsigned char *pSrcBufVA,
unsigned int SrcBufLen)
{
#ifdef DBG
unsigned char *pt;
int x;
if (RTDebugLevel < RT_DEBUG_TRACE)
return;
pt = pSrcBufVA;
printk("%s: %p, len = %d\n", str, pSrcBufVA, SrcBufLen);
for (x = 0; x < SrcBufLen; x++) {
if (x % 16 == 0)
printk("0x%04x : ", x);
printk("%02x ", ((unsigned char)pt[x]));
if (x % 16 == 15)
printk("\n");
}
printk("\n");
#endif /* DBG */
}
#ifdef SYSTEM_LOG_SUPPORT
/*
========================================================================
Routine Description:
Send log message through wireless event
Support standard iw_event with IWEVCUSTOM. It is used below.
iwreq_data.data.flags is used to store event_flag that is
defined by user. iwreq_data.data.length is the length of the
event log.
The format of the event log is composed of the entry's MAC
address and the desired log message (refer to
pWirelessEventText).
ex: 11:22:33:44:55:66 has associated successfully
p.s. The requirement of Wireless Extension is v15 or newer.
========================================================================
*/
VOID RtmpOsSendWirelessEvent(
IN VOID *pAd,
IN USHORT Event_flag,
IN PUCHAR pAddr,
IN UCHAR BssIdx,
IN CHAR Rssi,
IN RTMP_OS_SEND_WLAN_EVENT pFunc)
{
#if WIRELESS_EXT >= 15
pFunc(pAd, Event_flag, pAddr, BssIdx, Rssi);
#else
DBGPRINT(RT_DEBUG_ERROR,
("%s : The Wireless Extension MUST be v15 or newer.\n",
__FUNCTION__));
#endif /* WIRELESS_EXT >= 15 */
}
#endif /* SYSTEM_LOG_SUPPORT */
#ifdef CONFIG_STA_SUPPORT
INT32 ralinkrate[] = {
2, 4, 11, 22, /* CCK */
12, 18, 24, 36, 48, 72, 96, 108, /* OFDM */
/* 20MHz, 800ns GI, MCS: 0 ~ 15 */
13, 26, 39, 52, 78, 104, 117, 130, 26, 52, 78, 104, 156, 208, 234, 260,
39, 78, 117, 156, 234, 312, 351, 390, /* 20MHz, 800ns GI, MCS: 16 ~ 23 */
/* 40MHz, 800ns GI, MCS: 0 ~ 15 */
27, 54, 81, 108, 162, 216, 243, 270, 54, 108, 162, 216, 324, 432, 486, 540,
81, 162, 243, 324, 486, 648, 729, 810, /* 40MHz, 800ns GI, MCS: 16 ~ 23 */
/* 20MHz, 400ns GI, MCS: 0 ~ 15 */
14, 29, 43, 57, 87, 115, 130, 144, 29, 59, 87, 115, 173, 230, 260, 288,
43, 87, 130, 173, 260, 317, 390, 433, /* 20MHz, 400ns GI, MCS: 16 ~ 23 */
/* 40MHz, 400ns GI, MCS: 0 ~ 15 */
30, 60, 90, 120, 180, 240, 270, 300, 60, 120, 180, 240, 360, 480, 540, 600,
90, 180, 270, 360, 540, 720, 810, 900}; /* 40MHz, 400ns GI, MCS: 16 ~ 23 */
UINT32 RT_RateSize = sizeof (ralinkrate);
void send_monitor_packets(IN PNET_DEV pNetDev,
IN PNDIS_PACKET pRxPacket,
IN PHEADER_802_11 pHeader,
IN UCHAR * pData,
IN USHORT DataSize,
IN UCHAR L2PAD,
IN UCHAR PHYMODE,
IN UCHAR BW,
IN UCHAR ShortGI,
IN UCHAR MCS,
IN UCHAR AMPDU,
IN UCHAR STBC,
IN UCHAR RSSI1,
IN UCHAR BssMonitorFlag11n,
IN UCHAR * pDevName,
IN UCHAR Channel,
IN UCHAR CentralChannel,
IN UINT32 MaxRssi) {
struct sk_buff *pOSPkt;
wlan_ng_prism2_header *ph;
#ifdef MONITOR_FLAG_11N_SNIFFER_SUPPORT
ETHEREAL_RADIO h,
*ph_11n33; /* for new 11n sniffer format */
#endif /* MONITOR_FLAG_11N_SNIFFER_SUPPORT */
int rate_index = 0;
USHORT header_len = 0;
UCHAR temp_header[40] = {
0};
MEM_DBG_PKT_FREE_INC(pRxPacket);
pOSPkt = RTPKT_TO_OSPKT(pRxPacket); /*pRxBlk->pRxPacket); */
pOSPkt->dev = pNetDev; /*get_netdev_from_bssid(pAd, BSS0); */
if (pHeader->FC.Type == BTYPE_DATA) {
DataSize -= LENGTH_802_11;
if ((pHeader->FC.ToDs == 1) && (pHeader->FC.FrDs == 1))
header_len = LENGTH_802_11_WITH_ADDR4;
else
header_len = LENGTH_802_11;
/* QOS */
if (pHeader->FC.SubType & 0x08) {
header_len += 2;
/* Data skip QOS contorl field */
DataSize -= 2;
}
/* Order bit: A-Ralink or HTC+ */
if (pHeader->FC.Order) {
header_len += 4;
/* Data skip HTC contorl field */
DataSize -= 4;
}
/* Copy Header */
if (header_len <= 40)
NdisMoveMemory(temp_header, pData, header_len);
/* skip HW padding */
if (L2PAD)
pData += (header_len + 2);
else
pData += header_len;
}
/*end if */
if (DataSize < pOSPkt->len) {
skb_trim(pOSPkt, DataSize);
} else {
skb_put(pOSPkt, (DataSize - pOSPkt->len));
} /*end if */
if ((pData - pOSPkt->data) > 0) {
skb_put(pOSPkt, (pData - pOSPkt->data));
skb_pull(pOSPkt, (pData - pOSPkt->data));
}
/*end if */
if (skb_headroom(pOSPkt) <
(sizeof (wlan_ng_prism2_header) + header_len)) {
if (pskb_expand_head
(pOSPkt, (sizeof (wlan_ng_prism2_header) + header_len), 0,
GFP_ATOMIC)) {
DBGPRINT(RT_DEBUG_ERROR,
("%s : Reallocate header size of sk_buff fail!\n",
__FUNCTION__));
goto err_free_sk_buff;
} /*end if */
}
/*end if */
if (header_len > 0)
NdisMoveMemory(skb_push(pOSPkt, header_len), temp_header,
header_len);
#ifdef MONITOR_FLAG_11N_SNIFFER_SUPPORT
if (BssMonitorFlag11n == 0)
#endif /* MONITOR_FLAG_11N_SNIFFER_SUPPORT */
{
ph = (wlan_ng_prism2_header *) skb_push(pOSPkt,
sizeof
(wlan_ng_prism2_header));
NdisZeroMemory(ph, sizeof (wlan_ng_prism2_header));
ph->msgcode = DIDmsg_lnxind_wlansniffrm;
ph->msglen = sizeof (wlan_ng_prism2_header);
strcpy((PSTRING) ph->devname, (PSTRING) pDevName);
ph->hosttime.did = DIDmsg_lnxind_wlansniffrm_hosttime;
ph->hosttime.status = 0;
ph->hosttime.len = 4;
ph->hosttime.data = jiffies;
ph->mactime.did = DIDmsg_lnxind_wlansniffrm_mactime;
ph->mactime.status = 0;
ph->mactime.len = 0;
ph->mactime.data = 0;
ph->istx.did = DIDmsg_lnxind_wlansniffrm_istx;
ph->istx.status = 0;
ph->istx.len = 0;
ph->istx.data = 0;
ph->channel.did = DIDmsg_lnxind_wlansniffrm_channel;
ph->channel.status = 0;
ph->channel.len = 4;
ph->channel.data = (u_int32_t) Channel;
ph->rssi.did = DIDmsg_lnxind_wlansniffrm_rssi;
ph->rssi.status = 0;
ph->rssi.len = 4;
ph->rssi.data = MaxRssi;
ph->signal.did = DIDmsg_lnxind_wlansniffrm_signal;
ph->signal.status = 0;
ph->signal.len = 4;
ph->signal.data = 0; /*rssi + noise; */
ph->noise.did = DIDmsg_lnxind_wlansniffrm_noise;
ph->noise.status = 0;
ph->noise.len = 4;
ph->noise.data = 0;
#ifdef DOT11_N_SUPPORT
if (PHYMODE >= MODE_HTMIX) {
rate_index =
12 + ((UCHAR) BW * 24) + ((UCHAR) ShortGI * 48) +
((UCHAR) MCS);
} else
#endif /* DOT11_N_SUPPORT */
if (PHYMODE == MODE_OFDM)
rate_index = (UCHAR) (MCS) + 4;
else
rate_index = (UCHAR) (MCS);
if (rate_index < 0)
rate_index = 0;
if (rate_index >=
(sizeof (ralinkrate) / sizeof (ralinkrate[0])))
rate_index =
(sizeof (ralinkrate) / sizeof (ralinkrate[0])) - 1;
ph->rate.did = DIDmsg_lnxind_wlansniffrm_rate;
ph->rate.status = 0;
ph->rate.len = 4;
/* real rate = ralinkrate[rate_index] / 2 */
ph->rate.data = ralinkrate[rate_index];
ph->frmlen.did = DIDmsg_lnxind_wlansniffrm_frmlen;
ph->frmlen.status = 0;
ph->frmlen.len = 4;
ph->frmlen.data = (u_int32_t) DataSize;
}
#ifdef MONITOR_FLAG_11N_SNIFFER_SUPPORT
else {
ph_11n33 = &h;
NdisZeroMemory((unsigned char *)ph_11n33,
sizeof (ETHEREAL_RADIO));
/*802.11n fields */
if (MCS > 15)
ph_11n33->Flag_80211n |= WIRESHARK_11N_FLAG_3x3;
if (PHYMODE == MODE_HTGREENFIELD)
ph_11n33->Flag_80211n |= WIRESHARK_11N_FLAG_GF;
if (BW == 1) {
ph_11n33->Flag_80211n |= WIRESHARK_11N_FLAG_BW40;
} else if (Channel < CentralChannel) {
ph_11n33->Flag_80211n |= WIRESHARK_11N_FLAG_BW20U;
} else if (Channel > CentralChannel) {
ph_11n33->Flag_80211n |= WIRESHARK_11N_FLAG_BW20D;
} else {
ph_11n33->Flag_80211n |=
(WIRESHARK_11N_FLAG_BW20U |
WIRESHARK_11N_FLAG_BW20D);
}
if (ShortGI == 1)
ph_11n33->Flag_80211n |= WIRESHARK_11N_FLAG_SGI;
/* RXD_STRUC PRT28XX_RXD_STRUC pRxD = &(pRxBlk->RxD); */
if (AMPDU)
ph_11n33->Flag_80211n |= WIRESHARK_11N_FLAG_AMPDU;
if (STBC)
ph_11n33->Flag_80211n |= WIRESHARK_11N_FLAG_STBC;
ph_11n33->signal_level = (UCHAR) RSSI1;
/* data_rate is the rate index in the wireshark rate table */
if (PHYMODE >= MODE_HTMIX) {
if (MCS == 32) {
if (ShortGI)
ph_11n33->data_rate = 16;
else
ph_11n33->data_rate = 4;
} else if (MCS > 15)
ph_11n33->data_rate =
(16 * 4 + ((UCHAR) BW * 16) +
((UCHAR) ShortGI * 32) + ((UCHAR) MCS));
else
ph_11n33->data_rate =
16 + ((UCHAR) BW * 16) +
((UCHAR) ShortGI * 32) + ((UCHAR) MCS);
} else if (PHYMODE == MODE_OFDM)
ph_11n33->data_rate = (UCHAR) (MCS) + 4;
else
ph_11n33->data_rate = (UCHAR) (MCS);
/*channel field */
ph_11n33->channel = (UCHAR) Channel;
NdisMoveMemory(skb_put(pOSPkt, sizeof (ETHEREAL_RADIO)),
(UCHAR *) ph_11n33, sizeof (ETHEREAL_RADIO));
}
#endif /* MONITOR_FLAG_11N_SNIFFER_SUPPORT */
pOSPkt->pkt_type = PACKET_OTHERHOST;
pOSPkt->protocol = eth_type_trans(pOSPkt, pOSPkt->dev);
pOSPkt->ip_summed = CHECKSUM_NONE;
netif_rx(pOSPkt);
return;
err_free_sk_buff:
RELEASE_NDIS_PACKET(NULL, pRxPacket, NDIS_STATUS_FAILURE);
return;
}
#endif /* CONFIG_STA_SUPPORT */
/*******************************************************************************
File open/close related functions.
*******************************************************************************/
RTMP_OS_FD RtmpOSFileOpen(char *pPath,
int flag,
int mode) {
struct file *filePtr;
if (flag == RTMP_FILE_RDONLY)
flag = O_RDONLY;
else if (flag == RTMP_FILE_WRONLY)
flag = O_WRONLY;
else if (flag == RTMP_FILE_CREAT)
flag = O_CREAT;
else if (flag == RTMP_FILE_TRUNC)
flag = O_TRUNC;
filePtr = filp_open(pPath, flag, 0);
if (IS_ERR(filePtr)) {
DBGPRINT(RT_DEBUG_ERROR,
("%s(): Error %ld opening %s\n", __FUNCTION__,
-PTR_ERR(filePtr), pPath));
}
return (RTMP_OS_FD) filePtr;
}
int RtmpOSFileClose(RTMP_OS_FD osfd) {
filp_close(osfd, NULL);
return 0;
}
void RtmpOSFileSeek(RTMP_OS_FD osfd,
int offset) {
osfd->f_pos = offset;
}
int RtmpOSFileRead(RTMP_OS_FD osfd,
char *pDataPtr, int readLen) {
/* The object must have a read method */
if (osfd->f_op && osfd->f_op->read) {
return osfd->f_op->read(osfd, pDataPtr, readLen, &osfd->f_pos);
} else {
DBGPRINT(RT_DEBUG_ERROR, ("no file read method\n"));
return -1;
}
}
int RtmpOSFileWrite(RTMP_OS_FD osfd,
char *pDataPtr, int writeLen) {
return osfd->f_op->write(osfd,
pDataPtr,
(
size_t) writeLen,
&osfd->f_pos);
}
static inline void __RtmpOSFSInfoChange(OS_FS_INFO * pOSFSInfo,
BOOLEAN bSet) {
if (bSet) {
/* Save uid and gid used for filesystem access. */
/* Set user and group to 0 (root) */
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,29)
pOSFSInfo->fsuid = current->fsuid;
pOSFSInfo->fsgid = current->fsgid;
current->fsuid = current->fsgid = 0;
#else
pOSFSInfo->fsuid = current_fsuid();
pOSFSInfo->fsgid = current_fsgid();
#endif
pOSFSInfo->fs = get_fs();
set_fs(KERNEL_DS);
} else {
set_fs(pOSFSInfo->fs);
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,29)
current->fsuid = pOSFSInfo->fsuid;
current->fsgid = pOSFSInfo->fsgid;
#endif
}
}
/*******************************************************************************
Task create/management/kill related functions.
*******************************************************************************/
static inline NDIS_STATUS __RtmpOSTaskKill(IN OS_TASK *pTask) {
/* RTMP_ADAPTER *pAd; */
int ret = NDIS_STATUS_FAILURE;
/* pAd = (RTMP_ADAPTER *)pTask->priv; */
#ifdef KTHREAD_SUPPORT
if (pTask->kthread_task) {
kthread_stop(pTask->kthread_task);
ret = NDIS_STATUS_SUCCESS;
}
#else
CHECK_PID_LEGALITY(pTask->taskPID) {
DBGPRINT(RT_DEBUG_TRACE,
("Terminate the task(%s) with pid(%d)!\n",
pTask->taskName, GET_PID_NUMBER(pTask->taskPID)));
mb();
pTask->task_killed = 1;
mb();
ret = KILL_THREAD_PID(pTask->taskPID, SIGTERM, 1);
if (ret) {
printk(KERN_WARNING
"kill task(%s) with pid(%d) failed(retVal=%d)!\n",
pTask->taskName, GET_PID_NUMBER(pTask->taskPID),
ret);
} else {
wait_for_completion(&pTask->taskComplete);
pTask->taskPID = THREAD_PID_INIT_VALUE;
pTask->task_killed = 0;
RTMP_SEM_EVENT_DESTORY(&pTask->taskSema);
ret = NDIS_STATUS_SUCCESS;
}
}
#endif
return ret;
}
static inline INT __RtmpOSTaskNotifyToExit(IN OS_TASK *pTask) {
#ifndef KTHREAD_SUPPORT
pTask->taskPID = THREAD_PID_INIT_VALUE;
complete_and_exit(&pTask->taskComplete, 0);
#endif
return 0;
}
static inline void __RtmpOSTaskCustomize(IN OS_TASK *pTask) {
#ifndef KTHREAD_SUPPORT
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
daemonize((PSTRING) & pTask->taskName[0] /*"%s",pAd->net_dev->name */ );
allow_signal(SIGTERM);
allow_signal(SIGKILL);
current->flags |= PF_NOFREEZE;
#else
unsigned long flags;
daemonize();
reparent_to_init();
strcpy(current->comm, &pTask->taskName[0]);
siginitsetinv(¤t->blocked, sigmask(SIGTERM) | sigmask(SIGKILL));
/* Allow interception of SIGKILL only
* Don't allow other signals to interrupt the transmission */
#if LINUX_VERSION_CODE > KERNEL_VERSION(2,4,22)
spin_lock_irqsave(¤t->sigmask_lock, flags);
flush_signals(current);
recalc_sigpending(current);
spin_unlock_irqrestore(¤t->sigmask_lock, flags);
#endif
#endif
RTMP_GET_OS_PID(pTask->taskPID, current->pid);
/* signal that we've started the thread */
complete(&pTask->taskComplete);
#endif
}
static inline NDIS_STATUS __RtmpOSTaskAttach(IN OS_TASK *pTask,
IN RTMP_OS_TASK_CALLBACK fn,
IN ULONG arg) {
NDIS_STATUS status = NDIS_STATUS_SUCCESS;
#ifndef KTHREAD_SUPPORT
pid_t pid_number = -1;
#endif /* KTHREAD_SUPPORT */
#ifdef KTHREAD_SUPPORT
pTask->task_killed = 0;
pTask->kthread_task = NULL;
pTask->kthread_task =
kthread_run((cast_fn) fn, (void *)arg, pTask->taskName);
if (IS_ERR(pTask->kthread_task))
status = NDIS_STATUS_FAILURE;
#else
pid_number =
kernel_thread((cast_fn) fn, (void *)arg, RTMP_OS_MGMT_TASK_FLAGS);
if (pid_number < 0) {
DBGPRINT(RT_DEBUG_ERROR,
("Attach task(%s) failed!\n", pTask->taskName));
status = NDIS_STATUS_FAILURE;
} else {
/* Wait for the thread to start */
wait_for_completion(&pTask->taskComplete);
status = NDIS_STATUS_SUCCESS;
}
#endif
return status;
}
static inline NDIS_STATUS __RtmpOSTaskInit(IN OS_TASK *pTask,
IN PSTRING pTaskName,
IN VOID *pPriv,
IN LIST_HEADER *pSemList) {
int len;
ASSERT(pTask);
#ifndef KTHREAD_SUPPORT
NdisZeroMemory((PUCHAR) (pTask), sizeof (OS_TASK));
#endif
len = strlen(pTaskName);
len =
len >
(RTMP_OS_TASK_NAME_LEN - 1) ? (RTMP_OS_TASK_NAME_LEN - 1) : len;
NdisMoveMemory(&pTask->taskName[0], pTaskName, len);
pTask->priv = pPriv;
#ifndef KTHREAD_SUPPORT
RTMP_SEM_EVENT_INIT_LOCKED(&(pTask->taskSema), pSemList);
pTask->taskPID = THREAD_PID_INIT_VALUE;
init_completion(&pTask->taskComplete);
#endif
#ifdef KTHREAD_SUPPORT
init_waitqueue_head(&(pTask->kthread_q));
#endif /* KTHREAD_SUPPORT */
return NDIS_STATUS_SUCCESS;
}
BOOLEAN __RtmpOSTaskWait(IN VOID *pReserved,
IN OS_TASK *pTask,
IN INT32 *pStatus) {
#ifdef KTHREAD_SUPPORT
RTMP_WAIT_EVENT_INTERRUPTIBLE((*pStatus), pTask);
if ((pTask->task_killed == 1) || ((*pStatus) != 0))
return FALSE;
#else
RTMP_SEM_EVENT_WAIT(&(pTask->taskSema), (*pStatus));
/* unlock the device pointers */
if ((*pStatus) != 0) {
/* RTMP_SET_FLAG_(*pFlags, fRTMP_ADAPTER_HALT_IN_PROGRESS); */
return FALSE;
}
#endif /* KTHREAD_SUPPORT */
return TRUE;
}
#if LINUX_VERSION_CODE <= 0x20402 /* Red Hat 7.1 */
struct net_device *alloc_netdev(
int sizeof_priv,
const char *mask,
void (*setup) (struct net_device *))
{
struct net_device *dev;
INT alloc_size;
/* ensure 32-byte alignment of the private area */
alloc_size = sizeof (*dev) + sizeof_priv + 31;
dev = (struct net_device *)kmalloc(alloc_size, GFP_KERNEL);
if (dev == NULL) {
DBGPRINT(RT_DEBUG_ERROR,
("alloc_netdev: Unable to allocate device memory.\n"));
return NULL;
}
memset(dev, 0, alloc_size);
if (sizeof_priv)
dev->priv = (void *)(((long)(dev + 1) + 31) & ~31);
setup(dev);
strcpy(dev->name, mask);
return dev;
}
#endif /* LINUX_VERSION_CODE */
static UINT32 RtmpOSWirelessEventTranslate(IN UINT32 eventType) {
switch (eventType) {
case RT_WLAN_EVENT_CUSTOM:
eventType = IWEVCUSTOM;
break;
case RT_WLAN_EVENT_CGIWAP:
eventType = SIOCGIWAP;
break;
#if WIRELESS_EXT > 17
case RT_WLAN_EVENT_ASSOC_REQ_IE:
eventType = IWEVASSOCREQIE;
break;
#endif /* WIRELESS_EXT */
#if WIRELESS_EXT >= 14
case RT_WLAN_EVENT_SCAN:
eventType = SIOCGIWSCAN;
break;
#endif /* WIRELESS_EXT */
case RT_WLAN_EVENT_EXPIRED:
eventType = IWEVEXPIRED;
break;
default:
printk("Unknown event: %d\n", eventType);
break;
}
return eventType;
}
int RtmpOSWrielessEventSend(IN PNET_DEV pNetDev,
IN UINT32 eventType,
IN INT flags,
IN PUCHAR pSrcMac,
IN PUCHAR pData,
IN UINT32 dataLen) {
union iwreq_data wrqu;
/* translate event type */
eventType = RtmpOSWirelessEventTranslate(eventType);
memset(&wrqu, 0, sizeof (wrqu));
if (flags > -1)
wrqu.data.flags = flags;
if (pSrcMac)
memcpy(wrqu.ap_addr.sa_data, pSrcMac, MAC_ADDR_LEN);
if ((pData != NULL) && (dataLen > 0))
wrqu.data.length = dataLen;
wireless_send_event(pNetDev, eventType, &wrqu, (char *)pData);
return 0;
}
int RtmpOSWrielessEventSendExt(IN PNET_DEV pNetDev,
IN UINT32 eventType,
IN INT flags,
IN PUCHAR pSrcMac,
IN PUCHAR pData,
IN UINT32 dataLen,
IN UINT32 family) {
union iwreq_data wrqu;
/* translate event type */
eventType = RtmpOSWirelessEventTranslate(eventType);
/* translate event type */
memset(&wrqu, 0, sizeof (wrqu));
if (flags > -1)
wrqu.data.flags = flags;
if (pSrcMac)
memcpy(wrqu.ap_addr.sa_data, pSrcMac, MAC_ADDR_LEN);
if ((pData != NULL) && (dataLen > 0))
wrqu.data.length = dataLen;
wrqu.addr.sa_family = family;
wireless_send_event(pNetDev, eventType, &wrqu, (char *)pData);
return 0;
}
int RtmpOSNetDevAddrSet(IN UCHAR OpMode,
IN PNET_DEV pNetDev,
IN PUCHAR pMacAddr,
IN PUCHAR dev_name) {
struct net_device *net_dev;
/* RTMP_ADAPTER *pAd; */
net_dev = pNetDev;
/* GET_PAD_FROM_NET_DEV(pAd, net_dev); */
#ifdef CONFIG_STA_SUPPORT
/* work-around for the SuSE due to it has it's own interface name management system. */
RT_CONFIG_IF_OPMODE_ON_STA(OpMode) {
/* NdisZeroMemory(pAd->StaCfg.dev_name, 16); */
/* NdisMoveMemory(pAd->StaCfg.dev_name, net_dev->name, strlen(net_dev->name)); */
NdisZeroMemory(dev_name, 16);
NdisMoveMemory(dev_name, net_dev->name, strlen(net_dev->name));
}
#endif /* CONFIG_STA_SUPPORT */
NdisMoveMemory(net_dev->dev_addr, pMacAddr, 6);
return 0;
}
/*
* Assign the network dev name for created Ralink WiFi interface.
*/
static int RtmpOSNetDevRequestName(IN INT32 MC_RowID,
IN UINT32 *pIoctlIF,
IN PNET_DEV dev,
IN PSTRING pPrefixStr,
IN INT devIdx) {
PNET_DEV existNetDev;
STRING suffixName[IFNAMSIZ];
STRING desiredName[IFNAMSIZ];
int ifNameIdx,
prefixLen,
slotNameLen;
int Status;
prefixLen = strlen(pPrefixStr);
ASSERT((prefixLen < IFNAMSIZ));
for (ifNameIdx = devIdx; ifNameIdx < 32; ifNameIdx++) {
memset(suffixName, 0, IFNAMSIZ);
memset(desiredName, 0, IFNAMSIZ);
strncpy(&desiredName[0], pPrefixStr, prefixLen);
#ifdef MULTIPLE_CARD_SUPPORT
if (MC_RowID >= 0)
sprintf(suffixName, "%02d_%d", MC_RowID, ifNameIdx);
else
#endif /* MULTIPLE_CARD_SUPPORT */
sprintf(suffixName, "%d", ifNameIdx);
slotNameLen = strlen(suffixName);
ASSERT(((slotNameLen + prefixLen) < IFNAMSIZ));
strcat(desiredName, suffixName);
existNetDev = RtmpOSNetDevGetByName(dev, &desiredName[0]);
if (existNetDev == NULL)
break;
else
RtmpOSNetDeviceRefPut(existNetDev);
}
if (ifNameIdx < 32) {
#ifdef HOSTAPD_SUPPORT
*pIoctlIF = ifNameIdx;
#endif /*HOSTAPD_SUPPORT */
strcpy(&dev->name[0], &desiredName[0]);
Status = NDIS_STATUS_SUCCESS;
} else {
DBGPRINT(RT_DEBUG_ERROR,
("Cannot request DevName with preifx(%s) and in range(0~32) as suffix from OS!\n",
pPrefixStr));
Status = NDIS_STATUS_FAILURE;
}
return Status;
}
void RtmpOSNetDevClose(IN PNET_DEV pNetDev) {
dev_close(pNetDev);
}
void RtmpOSNetDevFree(PNET_DEV pNetDev) {
ASSERT(pNetDev);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
free_netdev(pNetDev);
#else
kfree(pNetDev);
#endif
}
INT RtmpOSNetDevAlloc(IN PNET_DEV *new_dev_p,
IN UINT32 privDataSize) {
/* assign it as null first. */
*new_dev_p = NULL;
DBGPRINT(RT_DEBUG_TRACE,
("Allocate a net device with private data size=%d!\n",
privDataSize));
#if LINUX_VERSION_CODE <= 0x20402 /* Red Hat 7.1 */
*new_dev_p = alloc_netdev(privDataSize, "eth%d", ether_setup);
#else
*new_dev_p = alloc_etherdev(privDataSize);
#endif /* LINUX_VERSION_CODE */
if (*new_dev_p)
return NDIS_STATUS_SUCCESS;
else
return NDIS_STATUS_FAILURE;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
INT RtmpOSNetDevOpsAlloc(IN PVOID *pNetDevOps) {
*pNetDevOps = (PVOID) vmalloc(sizeof (struct net_device_ops));
if (*pNetDevOps) {
NdisZeroMemory(*pNetDevOps, sizeof (struct net_device_ops));
return NDIS_STATUS_SUCCESS;
} else {
return NDIS_STATUS_FAILURE;
}
}
#endif
PNET_DEV RtmpOSNetDevGetByName(PNET_DEV pNetDev,
PSTRING pDevName) {
PNET_DEV pTargetNetDev = NULL;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26)
pTargetNetDev = dev_get_by_name(dev_net(pNetDev), pDevName);
#else
ASSERT(pNetDev);
pTargetNetDev = dev_get_by_name(pNetDev->nd_net, pDevName);
#endif
#else
pTargetNetDev = dev_get_by_name(pDevName);
#endif /* KERNEL_VERSION(2,6,24) */
#else
int devNameLen;
devNameLen = strlen(pDevName);
ASSERT((devNameLen <= IFNAMSIZ));
for (pTargetNetDev = dev_base; pTargetNetDev != NULL;
pTargetNetDev = pTargetNetDev->next) {
if (strncmp(pTargetNetDev->name, pDevName, devNameLen) == 0)
break;
}
#endif /* KERNEL_VERSION(2,5,0) */
return pTargetNetDev;
}
void RtmpOSNetDeviceRefPut(PNET_DEV pNetDev) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
/*
every time dev_get_by_name is called, and it has returned a valid struct
net_device*, dev_put should be called afterwards, because otherwise the
machine hangs when the device is unregistered (since dev->refcnt > 1).
*/
if (pNetDev)
dev_put(pNetDev);
#endif /* LINUX_VERSION_CODE */
}
INT RtmpOSNetDevDestory(IN VOID *pReserved,
IN PNET_DEV pNetDev) {
/* TODO: Need to fix this */
printk("WARNING: This function(%s) not implement yet!!!\n",
__FUNCTION__);
return 0;
}
void RtmpOSNetDevDetach(PNET_DEV pNetDev) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
struct net_device_ops *pNetDevOps = (struct net_device_ops *)pNetDev->netdev_ops;
#endif
unregister_netdev(pNetDev);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
vfree(pNetDevOps);
#endif
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18)
static void RALINK_ET_DrvInfoGet(IN struct net_device *pDev,
IN struct ethtool_drvinfo *pInfo) {
strcpy(pInfo->driver, "RALINK WLAN");
sprintf(pInfo->bus_info,
"CSR 0x%lx",
pDev->base_addr);
} static struct ethtool_ops RALINK_Ethtool_Ops = {
.get_drvinfo = RALINK_ET_DrvInfoGet,};
#endif /* LINUX_VERSION_CODE */
int RtmpOSNetDevAttach(IN UCHAR OpMode,
IN PNET_DEV pNetDev,
IN RTMP_OS_NETDEV_OP_HOOK *pDevOpHook) {
int ret,
rtnl_locked = FALSE;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
struct net_device_ops *pNetDevOps = (struct net_device_ops *)pNetDev->netdev_ops;
#endif
DBGPRINT(RT_DEBUG_TRACE, ("RtmpOSNetDevAttach()--->\n"));
/* If we need hook some callback function to the net device structrue, now do it. */
if (pDevOpHook) {
/* PRTMP_ADAPTER pAd = NULL; */
/* GET_PAD_FROM_NET_DEV(pAd, pNetDev); */
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
pNetDevOps->ndo_open = pDevOpHook->open;
pNetDevOps->ndo_stop = pDevOpHook->stop;
pNetDevOps->ndo_start_xmit =
(HARD_START_XMIT_FUNC) (pDevOpHook->xmit);
pNetDevOps->ndo_do_ioctl = pDevOpHook->ioctl;
#else
pNetDev->open = pDevOpHook->open;
pNetDev->stop = pDevOpHook->stop;
pNetDev->hard_start_xmit =
(HARD_START_XMIT_FUNC) (pDevOpHook->xmit);
pNetDev->do_ioctl = pDevOpHook->ioctl;
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,18)
pNetDev->ethtool_ops = &RALINK_Ethtool_Ops;
#endif
/* if you don't implement get_stats, just leave the callback function as NULL, a dummy
function will make kernel panic.
*/
if (pDevOpHook->get_stats)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
pNetDevOps->ndo_get_stats = pDevOpHook->get_stats;
#else
pNetDev->get_stats = pDevOpHook->get_stats;
#endif
/* OS specific flags, here we used to indicate if we are virtual interface */
pNetDev->priv_flags = pDevOpHook->priv_flags;
#if (WIRELESS_EXT < 21) && (WIRELESS_EXT >= 12)
/* pNetDev->get_wireless_stats = rt28xx_get_wireless_stats; */
pNetDev->get_wireless_stats = pDevOpHook->get_wstats;
#endif
#ifdef CONFIG_STA_SUPPORT
#if WIRELESS_EXT >= 12
if (OpMode == OPMODE_STA) {
/* pNetDev->wireless_handlers = &rt28xx_iw_handler_def; */
pNetDev->wireless_handlers = pDevOpHook->iw_handler;
}
#endif /*WIRELESS_EXT >= 12 */
#endif /* CONFIG_STA_SUPPORT */
#ifdef CONFIG_APSTA_MIXED_SUPPORT
#if WIRELESS_EXT >= 12
if (OpMode == OPMODE_AP) {
/* pNetDev->wireless_handlers = &rt28xx_ap_iw_handler_def; */
pNetDev->wireless_handlers = pDevOpHook->iw_handler;
}
#endif /*WIRELESS_EXT >= 12 */
#endif /* CONFIG_APSTA_MIXED_SUPPORT */
/* copy the net device mac address to the net_device structure. */
NdisMoveMemory(pNetDev->dev_addr, &pDevOpHook->devAddr[0],
MAC_ADDR_LEN);
rtnl_locked = pDevOpHook->needProtcted;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
pNetDevOps->ndo_validate_addr = NULL;
/*pNetDev->netdev_ops = ops; */
#else
pNetDev->validate_addr = NULL;
#endif
#endif
if (rtnl_locked)
ret = register_netdevice(pNetDev);
else
ret = register_netdev(pNetDev);
netif_stop_queue(pNetDev);
DBGPRINT(RT_DEBUG_TRACE, ("<---RtmpOSNetDevAttach(), ret=%d\n", ret));
if (ret == 0)
return NDIS_STATUS_SUCCESS;
else
return NDIS_STATUS_FAILURE;
}
PNET_DEV RtmpOSNetDevCreate(IN INT32 MC_RowID,
IN UINT32 *pIoctlIF,
IN INT devType,
IN INT devNum,
IN INT privMemSize,
IN PSTRING pNamePrefix) {
struct net_device *pNetDev = NULL;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
struct net_device_ops *pNetDevOps = NULL;
#endif
int status;
/* allocate a new network device */
status = RtmpOSNetDevAlloc(&pNetDev, 0 /*privMemSize */ );
if (status != NDIS_STATUS_SUCCESS) {
/* allocation fail, exit */
DBGPRINT(RT_DEBUG_ERROR,
("Allocate network device fail (%s)...\n",
pNamePrefix));
return NULL;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,31)
status = RtmpOSNetDevOpsAlloc((PVOID) & pNetDevOps);
if (status != NDIS_STATUS_SUCCESS) {
/* error! no any available ra name can be used! */
DBGPRINT(RT_DEBUG_TRACE, ("Allocate net device ops fail!\n"));
RtmpOSNetDevFree(pNetDev);
return NULL;
} else {
DBGPRINT(RT_DEBUG_TRACE,
("Allocate net device ops success!\n"));
pNetDev->netdev_ops = pNetDevOps;
}
#endif
/* find a available interface name, max 32 interfaces */
status =
RtmpOSNetDevRequestName(MC_RowID, pIoctlIF, pNetDev, pNamePrefix,
devNum);
if (status != NDIS_STATUS_SUCCESS) {
/* error! no any available ra name can be used! */
DBGPRINT(RT_DEBUG_ERROR,
("Assign interface name (%s with suffix 0~32) failed...\n",
pNamePrefix));
RtmpOSNetDevFree(pNetDev);
return NULL;
} else {
DBGPRINT(RT_DEBUG_TRACE,
("The name of the new %s interface is %s...\n",
pNamePrefix, pNetDev->name));
}
return pNetDev;
}
/*
========================================================================
Routine Description:
Allocate memory for adapter control block.
Arguments:
pAd Pointer to our adapter
Return Value:
NDIS_STATUS_SUCCESS
NDIS_STATUS_FAILURE
NDIS_STATUS_RESOURCES
Note:
========================================================================
*/
NDIS_STATUS AdapterBlockAllocateMemory(IN PVOID handle,
OUT PVOID *ppAd,
IN UINT32 SizeOfpAd) {
/* RTMP_ADAPTER *pAd; */
#ifdef WORKQUEUE_BH
/* POS_COOKIE cookie; */
#endif /* WORKQUEUE_BH */
#ifdef OS_ABL_FUNC_SUPPORT
/* get offset for sk_buff */
{
struct sk_buff *pPkt = NULL;
pPkt = kmalloc(sizeof (struct sk_buff), GFP_ATOMIC);
if (pPkt == NULL) {
*ppAd = NULL;
return (NDIS_STATUS_FAILURE);
}
RTPktOffsetData = (ULONG) (&(pPkt->data)) - (ULONG) pPkt;
RTPktOffsetLen = (ULONG) (&(pPkt->len)) - (ULONG) pPkt;
RTPktOffsetCB = (ULONG) (pPkt->cb) - (ULONG) pPkt;
kfree(pPkt);
DBGPRINT(RT_DEBUG_TRACE,
("packet> data offset = %lu\n", RTPktOffsetData));
DBGPRINT(RT_DEBUG_TRACE,
("packet> len offset = %lu\n", RTPktOffsetLen));
DBGPRINT(RT_DEBUG_TRACE,
("packet> cb offset = %lu\n", RTPktOffsetCB));
}
#endif /* OS_ABL_FUNC_SUPPORT */
/* *ppAd = (PVOID)vmalloc(sizeof(RTMP_ADAPTER)); //pci_alloc_consistent(pci_dev, sizeof(RTMP_ADAPTER), phy_addr); */
*ppAd = (PVOID) vmalloc(SizeOfpAd); /*pci_alloc_consistent(pci_dev, sizeof(RTMP_ADAPTER), phy_addr); */
/* pAd = (RTMP_ADAPTER *)(*ppAd); */
if (*ppAd) {
NdisZeroMemory(*ppAd, SizeOfpAd);
return (NDIS_STATUS_SUCCESS);
} else {
return (NDIS_STATUS_FAILURE);
}
}
/* ========================================================================== */
UINT RtmpOsWirelessExtVerGet(VOID) {
return WIRELESS_EXT;
}
VOID RtmpDrvAllMacPrint(IN VOID *pReserved,
IN UINT32 *pBufMac,
IN UINT32 AddrStart,
IN UINT32 AddrEnd,
IN UINT32 AddrStep) {
struct file *file_w;
PSTRING fileName = "MacDump.txt";
mm_segment_t orig_fs;
STRING *msg;//[1024];
ULONG macAddr = 0;
UINT32 macValue = 0;
os_alloc_mem(NULL, (UCHAR **)&msg, 1024);
if (msg)
{
orig_fs = get_fs();
set_fs(KERNEL_DS);
/* open file */
file_w = filp_open(fileName, O_WRONLY | O_CREAT, 0);
if (IS_ERR(file_w)) {
DBGPRINT(RT_DEBUG_TRACE,
("-->2) %s: Error %ld opening %s\n", __FUNCTION__,
-PTR_ERR(file_w), fileName));
} else {
if (file_w->f_op && file_w->f_op->write) {
file_w->f_pos = 0;
macAddr = AddrStart;
while (macAddr <= AddrEnd) {
/* RTMP_IO_READ32(pAd, macAddr, &macValue); // sample */
macValue = *pBufMac++;
sprintf(msg, "%08lx = %08X\n", macAddr,
macValue);
/* write data to file */
file_w->f_op->write(file_w, msg, strlen(msg),
&file_w->f_pos);
printk("%s", msg);
macAddr += AddrStep;
}
sprintf(msg, "\nDump all MAC values to %s\n", fileName);
}
filp_close(file_w, NULL);
}
set_fs(orig_fs);
os_free_mem(NULL, msg);
}
}
VOID RtmpDrvAllE2PPrint(IN VOID *pReserved,
IN USHORT *pMacContent,
IN UINT32 AddrEnd,
IN UINT32 AddrStep) {
struct file *file_w;
PSTRING fileName = "EEPROMDump.txt";
mm_segment_t orig_fs;
STRING *msg;//[1024];
USHORT eepAddr = 0;
USHORT eepValue;
os_alloc_mem(NULL, (UCHAR **)&msg, 1024);
if (msg)
{
orig_fs = get_fs();
set_fs(KERNEL_DS);
/* open file */
file_w = filp_open(fileName, O_WRONLY | O_CREAT, 0);
if (IS_ERR(file_w)) {
DBGPRINT(RT_DEBUG_TRACE,
("-->2) %s: Error %ld opening %s\n", __FUNCTION__,
-PTR_ERR(file_w), fileName));
} else {
if (file_w->f_op && file_w->f_op->write) {
file_w->f_pos = 0;
eepAddr = 0x00;
/* while (eepAddr <= 0xFE) */
while (eepAddr <= AddrEnd) {
/* RT28xx_EEPROM_READ16(pAd, eepAddr, eepValue); // sample */
eepValue = *pMacContent;
sprintf(msg, "%08x = %04x\n", eepAddr,
eepValue);
/* write data to file */
file_w->f_op->write(file_w, msg, strlen(msg),
&file_w->f_pos);
printk("%s", msg);
eepAddr += AddrStep;
pMacContent += (AddrStep/2);
}
sprintf(msg, "\nDump all EEPROM values to %s\n",
fileName);
}
filp_close(file_w, NULL);
}
set_fs(orig_fs);
os_free_mem(NULL, msg);
}
}
/*
========================================================================
Routine Description:
Check if the network interface is up.
Arguments:
*pDev - Network Interface
Return Value:
None
Note:
========================================================================
*/
BOOLEAN RtmpOSNetDevIsUp(IN VOID *pDev) {
struct net_device *pNetDev = (struct net_device *)pDev;
if ((pNetDev == NULL) || !(pNetDev->flags & IFF_UP))
return FALSE;
return TRUE;
}
/*
========================================================================
Routine Description:
Wake up the command thread.
Arguments:
pAd - WLAN control block pointer
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsCmdUp(IN RTMP_OS_TASK *pCmdQTask) {
#ifdef KTHREAD_SUPPORT
do {
OS_TASK *pTask = RTMP_OS_TASK_GET(pCmdQTask);
{
pTask->kthread_running = TRUE;
wake_up(&pTask->kthread_q);
}
} while (0);
#else
do {
OS_TASK *pTask = RTMP_OS_TASK_GET(pCmdQTask);
CHECK_PID_LEGALITY(pTask->taskPID) {
RTMP_SEM_EVENT_UP(&(pTask->taskSema));
}
} while (0);
#endif /* KTHREAD_SUPPORT */
}
/*
========================================================================
Routine Description:
Wake up USB Mlme thread.
Arguments:
pAd - WLAN control block pointer
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsMlmeUp(IN RTMP_OS_TASK *pMlmeQTask) {
#ifdef RTMP_USB_SUPPORT
/* OS_RTUSBMlmeUp(pMlmeQTask); */
#ifdef KTHREAD_SUPPORT
do {
OS_TASK *pTask = RTMP_OS_TASK_GET(pMlmeQTask);
if ((pTask != NULL) && (pTask->kthread_task)) {
pTask->kthread_running = TRUE;
wake_up(&pTask->kthread_q);
}
} while (0);
#else
do {
OS_TASK *pTask = RTMP_OS_TASK_GET(pMlmeQTask);
if (pTask != NULL) {
CHECK_PID_LEGALITY(pTask->taskPID) {
RTMP_SEM_EVENT_UP(&(pTask->taskSema));
}
}
} while (0);
#endif /* KTHREAD_SUPPORT */
#endif /* RTMP_USB_SUPPORT */
}
/*
========================================================================
Routine Description:
Check if the file is error.
Arguments:
pFile - the file
Return Value:
OK or any error
Note:
rt_linux.h, not rt_drv.h
========================================================================
*/
INT32 RtmpOsFileIsErr(IN VOID *pFile) {
return IS_FILE_OPEN_ERR(pFile);
}
int RtmpOSIRQRelease(IN PNET_DEV pNetDev,
IN UINT32 infType,
IN PPCI_DEV pci_dev,
IN BOOLEAN *pHaveMsi) {
struct net_device *net_dev = pNetDev;
/* PRTMP_ADAPTER pAd = NULL; */
/* GET_PAD_FROM_NET_DEV(pAd, net_dev); */
/* ASSERT(pAd); */
net_dev = net_dev; /* avoid compile warning */
return 0;
}
/*
========================================================================
Routine Description:
Enable or disable wireless event sent.
Arguments:
pReserved - Reserved
FlgIsWEntSup - TRUE or FALSE
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsWlanEventSet(IN VOID *pReserved,
IN BOOLEAN *pCfgWEnt,
IN BOOLEAN FlgIsWEntSup) {
#if WIRELESS_EXT >= 15
/* pAd->CommonCfg.bWirelessEvent = FlgIsWEntSup; */
*pCfgWEnt = FlgIsWEntSup;
#else
*pCfgWEnt = 0; /* disable */
#endif
}
/*
========================================================================
Routine Description:
vmalloc
Arguments:
Size - memory size
Return Value:
the memory
Note:
========================================================================
*/
VOID *RtmpOsVmalloc(IN ULONG Size) {
return vmalloc(Size);
}
/*
========================================================================
Routine Description:
vfree
Arguments:
pMem - the memory
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsVfree(IN VOID *pMem) {
if (pMem != NULL)
vfree(pMem);
}
/*
========================================================================
Routine Description:
Get network interface name.
Arguments:
pDev - the device
Return Value:
the name
Note:
========================================================================
*/
char *RtmpOsGetNetDevName(IN VOID *pDev) {
return ((PNET_DEV) pDev)->name;
}
/*
========================================================================
Routine Description:
Assign protocol to the packet.
Arguments:
pPkt - the packet
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsPktProtocolAssign(IN PNDIS_PACKET pNetPkt) {
struct sk_buff *pRxPkt = RTPKT_TO_OSPKT(pNetPkt);
pRxPkt->protocol = eth_type_trans(pRxPkt, pRxPkt->dev);
}
BOOLEAN RtmpOsStatsAlloc(IN VOID **ppStats,
IN VOID **ppIwStats) {
os_alloc_mem(NULL, (UCHAR **) ppStats,
sizeof (struct net_device_stats));
if ((*ppStats) == NULL)
return FALSE;
NdisZeroMemory((UCHAR *) *ppStats, sizeof (struct net_device_stats));
#if WIRELESS_EXT >= 12
os_alloc_mem(NULL, (UCHAR **) ppIwStats, sizeof (struct iw_statistics));
if ((*ppIwStats) == NULL) {
os_free_mem(NULL, *ppStats);
return FALSE;
}
NdisZeroMemory((UCHAR *)* ppIwStats, sizeof (struct iw_statistics));
#endif
return TRUE;
}
/*
========================================================================
Routine Description:
Pass the received packet to OS.
Arguments:
pPkt - the packet
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsPktRcvHandle(IN PNDIS_PACKET pNetPkt) {
struct sk_buff *pRxPkt = RTPKT_TO_OSPKT(pNetPkt);
netif_rx(pRxPkt);
}
VOID RtmpOsTaskPidInit(IN RTMP_OS_PID *pPid) {
*pPid = THREAD_PID_INIT_VALUE;
}
/*
========================================================================
Routine Description:
Get the network interface for the packet.
Arguments:
pPkt - the packet
Return Value:
None
Note:
========================================================================
*/
PNET_DEV RtmpOsPktNetDevGet(IN VOID *pPkt) {
return GET_OS_PKT_NETDEV(pPkt);
}
#ifdef IAPP_SUPPORT
/* Layer 2 Update frame to switch/bridge */
/* For any Layer2 devices, e.g., bridges, switches and other APs, the frame
can update their forwarding tables with the correct port to reach the new
location of the STA */
typedef struct GNU_PACKED _RT_IAPP_L2_UPDATE_FRAME {
UCHAR DA[ETH_ALEN]; /* broadcast MAC address */
UCHAR SA[ETH_ALEN]; /* the MAC address of the STA that has just associated
or reassociated */
USHORT Len; /* 8 octets */
UCHAR DSAP; /* null */
UCHAR SSAP; /* null */
UCHAR Control; /* reference to IEEE Std 802.2 */
UCHAR XIDInfo[3]; /* reference to IEEE Std 802.2 */
} RT_IAPP_L2_UPDATE_FRAME, *PRT_IAPP_L2_UPDATE_FRAME;
PNDIS_PACKET RtmpOsPktIappMakeUp(IN PNET_DEV pNetDev,
IN UINT8 *pMac) {
RT_IAPP_L2_UPDATE_FRAME frame_body;
INT size = sizeof (RT_IAPP_L2_UPDATE_FRAME);
PNDIS_PACKET pNetBuf;
if (pNetDev == NULL)
return NULL;
pNetBuf = RtmpOSNetPktAlloc(NULL, size);
if (!pNetBuf) {
DBGPRINT(RT_DEBUG_ERROR, ("Error! Can't allocate a skb.\n"));
return NULL;
}
/* init the update frame body */
NdisZeroMemory(&frame_body, size);
memset(frame_body.DA, 0xFF, ETH_ALEN);
memcpy(frame_body.SA, pMac, ETH_ALEN);
frame_body.Len = OS_HTONS(ETH_ALEN);
frame_body.DSAP = 0;
frame_body.SSAP = 0x01;
frame_body.Control = 0xAF;
frame_body.XIDInfo[0] = 0x81;
frame_body.XIDInfo[1] = 1;
frame_body.XIDInfo[2] = 1 << 1;
SET_OS_PKT_NETDEV(pNetBuf, pNetDev);
skb_reserve(pNetBuf, 2);
memcpy(skb_put(pNetBuf, size), &frame_body, size);
return pNetBuf;
}
#endif /* IAPP_SUPPORT */
VOID RtmpOsPktNatMagicTag(IN PNDIS_PACKET pNetPkt) {
}
VOID RtmpOsPktNatNone(IN PNDIS_PACKET pNetPkt) {
}
#ifdef RT_CFG80211_SUPPORT
/* all available channels */
UCHAR Cfg80211_Chan[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
/* 802.11 UNI / HyperLan 2 */
36, 38, 40, 44, 46, 48, 52, 54, 56, 60, 62, 64,
/* 802.11 HyperLan 2 */
100, 104, 108, 112, 116, 118, 120, 124, 126, 128, 132, 134, 136,
/* 802.11 UNII */
140, 149, 151, 153, 157, 159, 161, 165, 167, 169, 171, 173,
/* Japan */
184, 188, 192, 196, 208, 212, 216,
};
/*
Array of bitrates the hardware can operate with
in this band. Must be sorted to give a valid "supported
rates" IE, i.e. CCK rates first, then OFDM.
For HT, assign MCS in another structure, ieee80211_sta_ht_cap.
*/
const struct ieee80211_rate Cfg80211_SupRate[12] = {
{
.flags = IEEE80211_RATE_SHORT_PREAMBLE,
.bitrate = 10,
.hw_value = 0,
.hw_value_short = 0,
},
{
.flags = IEEE80211_RATE_SHORT_PREAMBLE,
.bitrate = 20,
.hw_value = 1,
.hw_value_short = 1,
},
{
.flags = IEEE80211_RATE_SHORT_PREAMBLE,
.bitrate = 55,
.hw_value = 2,
.hw_value_short = 2,
},
{
.flags = IEEE80211_RATE_SHORT_PREAMBLE,
.bitrate = 110,
.hw_value = 3,
.hw_value_short = 3,
},
{
.flags = 0,
.bitrate = 60,
.hw_value = 4,
.hw_value_short = 4,
},
{
.flags = 0,
.bitrate = 90,
.hw_value = 5,
.hw_value_short = 5,
},
{
.flags = 0,
.bitrate = 120,
.hw_value = 6,
.hw_value_short = 6,
},
{
.flags = 0,
.bitrate = 180,
.hw_value = 7,
.hw_value_short = 7,
},
{
.flags = 0,
.bitrate = 240,
.hw_value = 8,
.hw_value_short = 8,
},
{
.flags = 0,
.bitrate = 360,
.hw_value = 9,
.hw_value_short = 9,
},
{
.flags = 0,
.bitrate = 480,
.hw_value = 10,
.hw_value_short = 10,
},
{
.flags = 0,
.bitrate = 540,
.hw_value = 11,
.hw_value_short = 11,
},
};
static const UINT32 CipherSuites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
};
/*
========================================================================
Routine Description:
UnRegister MAC80211 Module.
Arguments:
pCB - CFG80211 control block pointer
pNetDev - Network device
Return Value:
NONE
Note:
========================================================================
*/
VOID CFG80211OS_UnRegister(
IN VOID *pCB,
IN VOID *pNetDevOrg)
{
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
struct net_device *pNetDev = (struct net_device *)pNetDevOrg;
/* unregister */
if (pCfg80211_CB->pCfg80211_Wdev != NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("80211> unregister/free wireless device\n"));
/*
Must unregister, or you will suffer problem when you change
regulatory domain by using iw.
*/
#ifdef RFKILL_HW_SUPPORT
wiphy_rfkill_stop_polling(pCfg80211_CB->pCfg80211_Wdev->wiphy);
#endif /* RFKILL_HW_SUPPORT */
wiphy_unregister(pCfg80211_CB->pCfg80211_Wdev->wiphy);
wiphy_free(pCfg80211_CB->pCfg80211_Wdev->wiphy);
os_free_mem(NULL, pCfg80211_CB->pCfg80211_Wdev);
if (pCfg80211_CB->pCfg80211_Channels != NULL)
os_free_mem(NULL, pCfg80211_CB->pCfg80211_Channels);
/* End of if */
if (pCfg80211_CB->pCfg80211_Rates != NULL)
os_free_mem(NULL, pCfg80211_CB->pCfg80211_Rates);
/* End of if */
pCfg80211_CB->pCfg80211_Wdev = NULL;
pCfg80211_CB->pCfg80211_Channels = NULL;
pCfg80211_CB->pCfg80211_Rates = NULL;
/* must reset to NULL; or kernel will panic in unregister_netdev */
pNetDev->ieee80211_ptr = NULL;
SET_NETDEV_DEV(pNetDev, NULL);
} /* End of if */
os_free_mem(NULL, pCfg80211_CB);
} /* End of CFG80211_UnRegister */
/*
========================================================================
Routine Description:
Initialize wireless channel in 2.4GHZ and 5GHZ.
Arguments:
pAd - WLAN control block pointer
pWiphy - WLAN PHY interface
pChannels - Current channel info
pRates - Current rate info
Return Value:
TRUE - init successfully
FALSE - init fail
Note:
TX Power related:
1. Suppose we can send power to 15dBm in the board.
2. A value 0x0 ~ 0x1F for a channel. We will adjust it based on 15dBm/
54Mbps. So if value == 0x07, the TX power of 54Mbps is 15dBm and
the value is 0x07 in the EEPROM.
3. Based on TX power value of 54Mbps/channel, adjust another value
0x0 ~ 0xF for other data rate. (-6dBm ~ +6dBm)
Other related factors:
1. TX power percentage from UI/users;
2. Maximum TX power limitation in the regulatory domain.
========================================================================
*/
BOOLEAN CFG80211_SupBandInit(
IN VOID *pCB,
IN CFG80211_BAND *pBandInfo,
IN VOID *pWiphyOrg,
IN VOID *pChannelsOrg,
IN VOID *pRatesOrg)
{
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
struct wiphy *pWiphy = (struct wiphy *)pWiphyOrg;
struct ieee80211_channel *pChannels = (struct ieee80211_channel *)pChannelsOrg;
struct ieee80211_rate *pRates = (struct ieee80211_rate *)pRatesOrg;
struct ieee80211_supported_band *pBand;
UINT32 NumOfChan, NumOfRate;
UINT32 IdLoop;
UINT32 CurTxPower;
/* sanity check */
if (pBandInfo->RFICType == 0)
pBandInfo->RFICType = RFIC_24GHZ | RFIC_5GHZ;
/* End of if */
CFG80211DBG(RT_DEBUG_ERROR, ("80211> RFICType = %d\n",
pBandInfo->RFICType));
/* init */
if (pBandInfo->RFICType & RFIC_5GHZ)
NumOfChan = CFG80211_NUM_OF_CHAN_2GHZ + CFG80211_NUM_OF_CHAN_5GHZ;
else
NumOfChan = CFG80211_NUM_OF_CHAN_2GHZ;
/* End of if */
if (pBandInfo->FlgIsBMode == TRUE)
NumOfRate = 4;
else
NumOfRate = 4 + 8;
/* End of if */
if (pChannels == NULL)
{
pChannels = kzalloc(sizeof(*pChannels) * NumOfChan, GFP_KERNEL);
if (!pChannels)
{
DBGPRINT(RT_DEBUG_ERROR, ("80211> ieee80211_channel allocation fail!\n"));
return FALSE;
} /* End of if */
} /* End of if */
CFG80211DBG(RT_DEBUG_ERROR, ("80211> Number of channel = %d\n",
CFG80211_NUM_OF_CHAN_5GHZ));
if (pRates == NULL)
{
pRates = kzalloc(sizeof(*pRates) * NumOfRate, GFP_KERNEL);
if (!pRates)
{
os_free_mem(NULL, pChannels);
DBGPRINT(RT_DEBUG_ERROR, ("80211> ieee80211_rate allocation fail!\n"));
return FALSE;
} /* End of if */
} /* End of if */
CFG80211DBG(RT_DEBUG_ERROR, ("80211> Number of rate = %d\n", NumOfRate));
/* get TX power */
#ifdef SINGLE_SKU
CurTxPower = pBandInfo->DefineMaxTxPwr; /* dBm */
#else
CurTxPower = 0; /* unknown */
#endif /* SINGLE_SKU */
CFG80211DBG(RT_DEBUG_ERROR, ("80211> CurTxPower = %d dBm\n", CurTxPower));
/* init channel */
for(IdLoop=0; IdLoop<NumOfChan; IdLoop++)
{
pChannels[IdLoop].center_freq = \
ieee80211_channel_to_frequency(Cfg80211_Chan[IdLoop]);
pChannels[IdLoop].hw_value = IdLoop;
if (IdLoop < CFG80211_NUM_OF_CHAN_2GHZ)
pChannels[IdLoop].max_power = CurTxPower;
else
pChannels[IdLoop].max_power = CurTxPower;
/* End of if */
pChannels[IdLoop].max_antenna_gain = 0xff;
} /* End of if */
/* init rate */
for(IdLoop=0; IdLoop<NumOfRate; IdLoop++)
memcpy(&pRates[IdLoop], &Cfg80211_SupRate[IdLoop], sizeof(*pRates));
/* End of for */
pBand = &pCfg80211_CB->Cfg80211_bands[IEEE80211_BAND_2GHZ];
if (pBandInfo->RFICType & RFIC_24GHZ)
{
pBand->n_channels = CFG80211_NUM_OF_CHAN_2GHZ;
pBand->n_bitrates = NumOfRate;
pBand->channels = pChannels;
pBand->bitrates = pRates;
#ifdef DOT11_N_SUPPORT
/* for HT, assign pBand->ht_cap */
pBand->ht_cap.ht_supported = true;
pBand->ht_cap.cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 |
IEEE80211_HT_CAP_SM_PS |
IEEE80211_HT_CAP_SGI_40 |
IEEE80211_HT_CAP_DSSSCCK40;
pBand->ht_cap.ampdu_factor = 3; /* 2 ^ 16 */
pBand->ht_cap.ampdu_density = pBandInfo->MpduDensity;
memset(&pBand->ht_cap.mcs, 0, sizeof(pBand->ht_cap.mcs));
CFG80211DBG(RT_DEBUG_ERROR,
("80211> TxStream = %d\n", pBandInfo->TxStream));
switch(pBandInfo->TxStream)
{
case 1:
default:
pBand->ht_cap.mcs.rx_mask[0] = 0xff;
break;
case 2:
pBand->ht_cap.mcs.rx_mask[0] = 0xff;
pBand->ht_cap.mcs.rx_mask[1] = 0xff;
break;
case 3:
pBand->ht_cap.mcs.rx_mask[0] = 0xff;
pBand->ht_cap.mcs.rx_mask[1] = 0xff;
pBand->ht_cap.mcs.rx_mask[2] = 0xff;
break;
} /* End of switch */
pBand->ht_cap.mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
#endif /* DOT11_N_SUPPORT */
pWiphy->bands[IEEE80211_BAND_2GHZ] = pBand;
}
else
{
pWiphy->bands[IEEE80211_BAND_2GHZ] = NULL;
pBand->channels = NULL;
pBand->bitrates = NULL;
} /* End of if */
pBand = &pCfg80211_CB->Cfg80211_bands[IEEE80211_BAND_5GHZ];
if (pBandInfo->RFICType & RFIC_5GHZ)
{
pBand->n_channels = CFG80211_NUM_OF_CHAN_5GHZ;
pBand->n_bitrates = NumOfRate - 4;
pBand->channels = &pChannels[CFG80211_NUM_OF_CHAN_2GHZ];
pBand->bitrates = &pRates[4];
/* for HT, assign pBand->ht_cap */
#ifdef DOT11_N_SUPPORT
/* for HT, assign pBand->ht_cap */
pBand->ht_cap.ht_supported = true;
pBand->ht_cap.cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 |
IEEE80211_HT_CAP_SM_PS |
IEEE80211_HT_CAP_SGI_40 |
IEEE80211_HT_CAP_DSSSCCK40;
pBand->ht_cap.ampdu_factor = 3; /* 2 ^ 16 */
pBand->ht_cap.ampdu_density = pBandInfo->MpduDensity;
memset(&pBand->ht_cap.mcs, 0, sizeof(pBand->ht_cap.mcs));
switch(pBandInfo->RxStream)
{
case 1:
default:
pBand->ht_cap.mcs.rx_mask[0] = 0xff;
break;
case 2:
pBand->ht_cap.mcs.rx_mask[0] = 0xff;
pBand->ht_cap.mcs.rx_mask[1] = 0xff;
break;
case 3:
pBand->ht_cap.mcs.rx_mask[0] = 0xff;
pBand->ht_cap.mcs.rx_mask[1] = 0xff;
pBand->ht_cap.mcs.rx_mask[2] = 0xff;
break;
} /* End of switch */
pBand->ht_cap.mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
#endif /* DOT11_N_SUPPORT */
pWiphy->bands[IEEE80211_BAND_5GHZ] = pBand;
}
else
{
pWiphy->bands[IEEE80211_BAND_5GHZ] = NULL;
pBand->channels = NULL;
pBand->bitrates = NULL;
} /* End of if */
pCfg80211_CB->pCfg80211_Channels = pChannels;
pCfg80211_CB->pCfg80211_Rates = pRates;
return TRUE;
} /* End of CFG80211_SupBandInit */
/*
========================================================================
Routine Description:
Re-Initialize wireless channel/PHY in 2.4GHZ and 5GHZ.
Arguments:
pCB - CFG80211 control block pointer
pBandInfo - Band information
Return Value:
TRUE - re-init successfully
FALSE - re-init fail
Note:
CFG80211_SupBandInit() is called in xx_probe().
But we do not have complete chip information in xx_probe() so we
need to re-init bands in xx_open().
========================================================================
*/
BOOLEAN CFG80211OS_SupBandReInit(
IN VOID *pCB,
IN CFG80211_BAND *pBandInfo)
{
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
struct wiphy *pWiphy;
/* sanity check */
if ((pCfg80211_CB == NULL) || (pCfg80211_CB->pCfg80211_Wdev == NULL))
return FALSE;
/* End of if */
pWiphy = pCfg80211_CB->pCfg80211_Wdev->wiphy;
if (pWiphy != NULL)
{
CFG80211DBG(RT_DEBUG_ERROR, ("80211> re-init bands...\n"));
/* re-init bands */
CFG80211_SupBandInit(pCfg80211_CB, pBandInfo, pWiphy,
pCfg80211_CB->pCfg80211_Channels,
pCfg80211_CB->pCfg80211_Rates);
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,32))
/* re-init PHY */
pWiphy->rts_threshold = pBandInfo->RtsThreshold;
pWiphy->frag_threshold = pBandInfo->FragmentThreshold;
pWiphy->retry_short = pBandInfo->RetryMaxCnt & 0xff;
pWiphy->retry_long = (pBandInfo->RetryMaxCnt & 0xff00)>>8;
#endif /* LINUX_VERSION_CODE */
return TRUE;
} /* End of if */
return FALSE;
} /* End of CFG80211OS_SupBandReInit */
/*
========================================================================
Routine Description:
Hint to the wireless core a regulatory domain from driver.
Arguments:
pAd - WLAN control block pointer
pCountryIe - pointer to the country IE
CountryIeLen - length of the country IE
Return Value:
NONE
Note:
Must call the function in kernel thread.
========================================================================
*/
VOID CFG80211OS_RegHint(
IN VOID *pCB,
IN UCHAR *pCountryIe,
IN ULONG CountryIeLen)
{
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
CFG80211DBG(RT_DEBUG_ERROR,
("crda> regulatory domain hint: %c%c\n",
pCountryIe[0], pCountryIe[1]));
if ((pCfg80211_CB->pCfg80211_Wdev == NULL) || (pCountryIe == NULL))
{
CFG80211DBG(RT_DEBUG_ERROR, ("crda> regulatory domain hint not support!\n"));
return;
} /* End of if */
/* hints a country IE as a regulatory domain "without" channel/power info. */
/* regulatory_hint(pCfg80211_CB->pMac80211_Hw->wiphy, pCountryIe); */
regulatory_hint(pCfg80211_CB->pCfg80211_Wdev->wiphy, (const char *)pCountryIe);
} /* End of CFG80211OS_RegHint */
/*
========================================================================
Routine Description:
Hint to the wireless core a regulatory domain from country element.
Arguments:
pAdCB - WLAN control block pointer
pCountryIe - pointer to the country IE
CountryIeLen - length of the country IE
Return Value:
NONE
Note:
Must call the function in kernel thread.
========================================================================
*/
VOID CFG80211OS_RegHint11D(
IN VOID *pCB,
IN UCHAR *pCountryIe,
IN ULONG CountryIeLen)
{
/* no regulatory_hint_11d() in 2.6.32 */
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,32))
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
if ((pCfg80211_CB->pCfg80211_Wdev == NULL) || (pCountryIe == NULL))
{
CFG80211DBG(RT_DEBUG_ERROR, ("crda> regulatory domain hint not support!\n"));
return;
} /* End of if */
CFG80211DBG(RT_DEBUG_ERROR,
("crda> regulatory domain hint: %c%c\n",
pCountryIe[0], pCountryIe[1]));
/*
hints a country IE as a regulatory domain "with" channel/power info.
but if you use regulatory_hint(), it only hint "regulatory domain".
*/
/* regulatory_hint_11d(pCfg80211_CB->pMac80211_Hw->wiphy, pCountryIe, CountryIeLen); */
regulatory_hint_11d(pCfg80211_CB->pCfg80211_Wdev->wiphy, pCountryIe, CountryIeLen);
#endif /* LINUX_VERSION_CODE */
} /* End of CFG80211_RegHint11D */
BOOLEAN CFG80211OS_BandInfoGet(
IN VOID *pCB,
IN VOID *pWiphyOrg,
OUT VOID **ppBand24,
OUT VOID **ppBand5)
{
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
struct wiphy *pWiphy = (struct wiphy *)pWiphyOrg;
/* sanity check */
if (pWiphy == NULL)
{
if ((pCfg80211_CB != NULL) && (pCfg80211_CB->pCfg80211_Wdev != NULL))
pWiphy = pCfg80211_CB->pCfg80211_Wdev->wiphy;
/* End of if */
} /* End of if */
if (pWiphy == NULL)
return FALSE;
*ppBand24 = pWiphy->bands[IEEE80211_BAND_2GHZ];
*ppBand5 = pWiphy->bands[IEEE80211_BAND_5GHZ];
return TRUE;
}
UINT32 CFG80211OS_ChanNumGet(
IN VOID *pCB,
IN VOID *pWiphyOrg,
IN UINT32 IdBand)
{
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
struct wiphy *pWiphy = (struct wiphy *)pWiphyOrg;
/* sanity check */
if (pWiphy == NULL)
{
if ((pCfg80211_CB != NULL) && (pCfg80211_CB->pCfg80211_Wdev != NULL))
pWiphy = pCfg80211_CB->pCfg80211_Wdev->wiphy;
/* End of if */
} /* End of if */
if (pWiphy == NULL)
return 0;
if (pWiphy->bands[IdBand] != NULL)
return pWiphy->bands[IdBand]->n_channels;
return 0;
}
BOOLEAN CFG80211OS_ChanInfoGet(
IN VOID *pCB,
IN VOID *pWiphyOrg,
IN UINT32 IdBand,
IN UINT32 IdChan,
OUT UINT32 *pChanId,
OUT UINT32 *pPower,
OUT BOOLEAN *pFlgIsRadar)
{
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
struct wiphy *pWiphy = (struct wiphy *)pWiphyOrg;
struct ieee80211_supported_band *pSband;
struct ieee80211_channel *pChan;
/* sanity check */
if (pWiphy == NULL)
{
if ((pCfg80211_CB != NULL) && (pCfg80211_CB->pCfg80211_Wdev != NULL))
pWiphy = pCfg80211_CB->pCfg80211_Wdev->wiphy;
/* End of if */
} /* End of if */
if (pWiphy == NULL)
return FALSE;
pSband = pWiphy->bands[IdBand];
pChan = &pSband->channels[IdChan];
*pChanId = ieee80211_frequency_to_channel(pChan->center_freq);
if (pChan->flags & IEEE80211_CHAN_DISABLED)
{
CFG80211DBG(RT_DEBUG_ERROR,
("Chan %03d (frq %d):\tnot allowed!\n",
(*pChanId), pChan->center_freq));
return FALSE;
}
*pPower = pChan->max_power;
if (pChan->flags & IEEE80211_CHAN_RADAR)
*pFlgIsRadar = TRUE;
else
*pFlgIsRadar = FALSE;
return TRUE;
}
/*
========================================================================
Routine Description:
Inform us that a scan is got.
Arguments:
pAdCB - WLAN control block pointer
Return Value:
NONE
Note:
Call RT_CFG80211_SCANNING_INFORM, not CFG80211_Scaning
========================================================================
*/
VOID CFG80211OS_Scaning(
IN VOID *pCB,
IN VOID **pChanOrg,
IN UINT32 ChanId,
IN UCHAR *pFrame,
IN UINT32 FrameLen,
IN INT32 RSSI,
IN BOOLEAN FlgIsNMode,
IN UINT8 BW)
{
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30))
#ifdef CONFIG_STA_SUPPORT
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
struct ieee80211_channel *pChan;
if ((*pChanOrg) == NULL)
{
os_alloc_mem(NULL, (UCHAR **)pChanOrg, sizeof(struct ieee80211_channel));
if ((*pChanOrg) == NULL)
{
DBGPRINT(RT_DEBUG_ERROR, ("80211> Allocate chan fail!\n"));
return;
}
}
pChan = (struct ieee80211_channel *)(*pChanOrg);
memset(pChan, 0, sizeof(*pChan));
if (ChanId > 14)
pChan->band = IEEE80211_BAND_5GHZ;
else
pChan->band = IEEE80211_BAND_2GHZ;
/* End of if */
pChan->center_freq = ieee80211_channel_to_frequency(ChanId);
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,32))
if (FlgIsNMode == TRUE)
{
if (BW == 0)
pChan->max_bandwidth = 20; /* 20MHz */
else
pChan->max_bandwidth = 40; /* 40MHz */
/* End of if */
}
else
pChan->max_bandwidth = 5; /* 5MHz for non-HT device */
/* End of if */
#endif /* LINUX_VERSION_CODE */
/* no use currently in 2.6.30 */
/* if (ieee80211_is_beacon(((struct ieee80211_mgmt *)pFrame)->frame_control)) */
/* pChan->beacon_found = 1; */
/* End of if */
/* inform 80211 a scan is got */
/* we can use cfg80211_inform_bss in 2.6.31, it is easy more than the one */
/* in cfg80211_inform_bss_frame(), it will memcpy pFrame but pChan */
cfg80211_inform_bss_frame(pCfg80211_CB->pCfg80211_Wdev->wiphy,
pChan,
(struct ieee80211_mgmt *)pFrame,
FrameLen,
RSSI,
GFP_ATOMIC);
CFG80211DBG(RT_DEBUG_ERROR, ("80211> cfg80211_inform_bss_frame\n"));
#endif /* CONFIG_STA_SUPPORT */
#endif /* LINUX_VERSION_CODE */
}
/*
========================================================================
Routine Description:
Inform us that scan ends.
Arguments:
pAdCB - WLAN control block pointer
FlgIsAborted - 1: scan is aborted
Return Value:
NONE
Note:
========================================================================
*/
VOID CFG80211OS_ScanEnd(
IN VOID *pCB,
IN BOOLEAN FlgIsAborted)
{
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30))
#ifdef CONFIG_STA_SUPPORT
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
CFG80211DBG(RT_DEBUG_ERROR, ("80211> cfg80211_scan_done\n"));
cfg80211_scan_done(pCfg80211_CB->pCfg80211_ScanReq, FlgIsAborted);
#endif /* CONFIG_STA_SUPPORT */
#endif /* LINUX_VERSION_CODE */
}
/*
========================================================================
Routine Description:
Inform CFG80211 about association status.
Arguments:
pAdCB - WLAN control block pointer
pBSSID - the BSSID of the AP
pReqIe - the element list in the association request frame
ReqIeLen - the request element length
pRspIe - the element list in the association response frame
RspIeLen - the response element length
FlgIsSuccess - 1: success; otherwise: fail
Return Value:
None
Note:
========================================================================
*/
void CFG80211OS_ConnectResultInform(
IN VOID *pCB,
IN UCHAR *pBSSID,
IN UCHAR *pReqIe,
IN UINT32 ReqIeLen,
IN UCHAR *pRspIe,
IN UINT32 RspIeLen,
IN UCHAR FlgIsSuccess)
{
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,32))
CFG80211_CB *pCfg80211_CB = (CFG80211_CB *)pCB;
if ((pCfg80211_CB->pCfg80211_Wdev->netdev == NULL) || (pBSSID == NULL))
return;
/* End of if */
if (FlgIsSuccess)
{
cfg80211_connect_result(pCfg80211_CB->pCfg80211_Wdev->netdev,
pBSSID,
pReqIe,
ReqIeLen,
pRspIe,
RspIeLen,
WLAN_STATUS_SUCCESS,
GFP_KERNEL);
}
else
{
cfg80211_connect_result(pCfg80211_CB->pCfg80211_Wdev->netdev,
pBSSID,
NULL, 0, NULL, 0,
WLAN_STATUS_UNSPECIFIED_FAILURE,
GFP_KERNEL);
} /* End of if */
#endif /* LINUX_VERSION_CODE */
} /* End of CFG80211_ConnectResultInform */
#endif /* RT_CFG80211_SUPPORT */
#ifdef OS_ABL_FUNC_SUPPORT
/*
========================================================================
Routine Description:
Change/Recover file UID/GID.
Arguments:
pOSFSInfoOrg - the file
bSet - Change (TRUE) or Recover (FALSE)
Return Value:
None
Note:
rt_linux.h, not rt_drv.h
========================================================================
*/
void RtmpOSFSInfoChange(IN RTMP_OS_FS_INFO *pOSFSInfoOrg,
IN BOOLEAN bSet) {
OS_FS_INFO *pOSFSInfo;
if (bSet == TRUE) {
os_alloc_mem(NULL, (UCHAR **) & (pOSFSInfoOrg->pContent),
sizeof (OS_FS_INFO));
if (pOSFSInfoOrg->pContent == NULL) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: alloc file info fail!\n", __FUNCTION__));
return;
} else
memset(pOSFSInfoOrg->pContent, 0, sizeof (OS_FS_INFO));
}
pOSFSInfo = (OS_FS_INFO *) (pOSFSInfoOrg->pContent);
if (pOSFSInfo == NULL) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: pOSFSInfo == NULL!\n", __FUNCTION__));
return;
}
__RtmpOSFSInfoChange(pOSFSInfo, bSet);
if (bSet == FALSE) {
if (pOSFSInfoOrg->pContent != NULL) {
os_free_mem(NULL, pOSFSInfoOrg->pContent);
pOSFSInfoOrg->pContent = NULL;
}
}
}
/*
========================================================================
Routine Description:
Activate a tasklet.
Arguments:
pTasklet - the tasklet
Return Value:
TRUE or FALSE
Note:
========================================================================
*/
BOOLEAN RtmpOsTaskletSche(IN RTMP_NET_TASK_STRUCT *pTasklet) {
if (pTasklet->pContent == NULL)
return FALSE;
#ifdef WORKQUEUE_BH
schedule_work((struct work_struct *)(pTasklet->pContent));
#else
tasklet_hi_schedule((OS_NET_TASK_STRUCT *) (pTasklet->pContent));
#endif /* WORKQUEUE_BH */
return TRUE;
}
/*
========================================================================
Routine Description:
Initialize a tasklet.
Arguments:
pTasklet - the tasklet
Return Value:
TRUE or FALSE
Note:
========================================================================
*/
BOOLEAN RtmpOsTaskletInit(IN RTMP_NET_TASK_STRUCT *pTasklet,
IN VOID (*pFunc) (unsigned long data),
IN ULONG Data,
IN LIST_HEADER * pTaskletList) {
#ifdef WORKQUEUE_BH
if (RTMP_OS_Alloc_Rsc(pTaskletList, pTasklet,
sizeof (struct work_struct)) == FALSE) {
return FALSE; /* allocate fail */
}
INIT_WORK((struct work_struct *)(pTasklet->pContent), pFunc);
#else
if (RTMP_OS_Alloc_Rsc(pTaskletList, pTasklet,
sizeof (OS_NET_TASK_STRUCT)) == FALSE) {
return FALSE; /* allocate fail */
}
tasklet_init((OS_NET_TASK_STRUCT *) (pTasklet->pContent), pFunc, Data);
#endif /* WORKQUEUE_BH */
return TRUE;
}
/*
========================================================================
Routine Description:
Delete a tasklet.
Arguments:
pTasklet - the tasklet
Return Value:
TRUE or FALSE
Note:
========================================================================
*/
BOOLEAN RtmpOsTaskletKill(IN RTMP_NET_TASK_STRUCT *pTasklet) {
if (pTasklet->pContent != NULL) {
#ifndef WORKQUEUE_BH
tasklet_kill((OS_NET_TASK_STRUCT *) (pTasklet->pContent));
#endif /* WORKQUEUE_BH */
/* we will free all tasks memory in RTMP_OS_FREE_TASKLET() */
/* os_free_mem(NULL, pTasklet->pContent); */
/* pTasklet->pContent = NULL; */
}
return TRUE;
}
VOID RtmpOsTaskletDataAssign(IN RTMP_NET_TASK_STRUCT *pTasklet,
IN ULONG Data) {
#ifndef WORKQUEUE_BH
if (pTasklet->pContent != NULL)
((OS_NET_TASK_STRUCT *) (pTasklet->pContent))->data =
(ULONG) Data;
#endif /* WORKQUEUE_BH */
}
INT32 RtmpOsTaskIsKilled(IN RTMP_OS_TASK *pTaskOrg) {
OS_TASK *pTask;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask == NULL)
return 1;
return pTask->task_killed;
}
VOID RtmpOsTaskWakeUp(IN RTMP_OS_TASK *pTaskOrg) {
OS_TASK *pTask;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask == NULL)
return;
#ifdef KTHREAD_SUPPORT
WAKE_UP(pTask);
#else
RTMP_SEM_EVENT_UP(&pTask->taskSema);
#endif
}
/*
========================================================================
Routine Description:
Check if the task is legal.
Arguments:
pPkt - the packet
pDev - the device
Return Value:
None
Note:
========================================================================
*/
BOOLEAN RtmpOsCheckTaskLegality(IN RTMP_OS_TASK *pTaskOrg) {
OS_TASK *pTask;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask == NULL)
return FALSE;
#ifdef KTHREAD_SUPPORT
if (pTask->kthread_task == NULL)
#else
CHECK_PID_LEGALITY(pTask->taskPID);
else
#endif
return FALSE;
return TRUE;
}
/* timeout -- ms */
VOID RTMP_SetPeriodicTimer(IN NDIS_MINIPORT_TIMER *pTimerOrg,
IN unsigned long timeout) {
OS_NDIS_MINIPORT_TIMER *pTimer;
pTimer = (OS_NDIS_MINIPORT_TIMER *) (pTimerOrg->pContent);
if (pTimer != NULL) {
__RTMP_SetPeriodicTimer(pTimer, timeout);
}
}
/* convert NdisMInitializeTimer --> RTMP_OS_Init_Timer */
VOID RTMP_OS_Init_Timer(IN VOID *pReserved,
IN NDIS_MINIPORT_TIMER *pTimerOrg,
IN TIMER_FUNCTION function,
IN PVOID data,
IN LIST_HEADER *pTimerList) {
OS_NDIS_MINIPORT_TIMER *pTimer;
if (RTMP_OS_Alloc_Rsc(pTimerList, pTimerOrg,
sizeof (OS_NDIS_MINIPORT_TIMER)) == FALSE) {
return; /* allocate fail */
}
pTimer = (OS_NDIS_MINIPORT_TIMER *) (pTimerOrg->pContent);
if (pTimer != NULL) {
__RTMP_OS_Init_Timer(pReserved, pTimer, function, data);
}
}
VOID RTMP_OS_Add_Timer(IN NDIS_MINIPORT_TIMER *pTimerOrg,
IN unsigned long timeout) {
OS_NDIS_MINIPORT_TIMER *pTimer;
pTimer = (OS_NDIS_MINIPORT_TIMER *) (pTimerOrg->pContent);
if (pTimer != NULL) {
if (timer_pending(pTimer))
return;
__RTMP_OS_Add_Timer(pTimer,
timeout);
}
}
VOID RTMP_OS_Mod_Timer(IN NDIS_MINIPORT_TIMER *pTimerOrg,
IN unsigned long timeout) {
OS_NDIS_MINIPORT_TIMER *pTimer;
pTimer = (OS_NDIS_MINIPORT_TIMER *) (pTimerOrg->pContent);
if (pTimer != NULL) {
__RTMP_OS_Mod_Timer(pTimer, timeout);
}
}
VOID RTMP_OS_Del_Timer(IN NDIS_MINIPORT_TIMER *pTimerOrg,
OUT BOOLEAN *pCancelled) {
OS_NDIS_MINIPORT_TIMER *pTimer;
pTimer = (OS_NDIS_MINIPORT_TIMER *) (pTimerOrg->pContent);
if (pTimer != NULL) {
__RTMP_OS_Del_Timer(pTimer, pCancelled);
}
}
VOID RTMP_OS_Release_Timer(IN NDIS_MINIPORT_TIMER *pTimerOrg) {
OS_NDIS_MINIPORT_TIMER *pTimer;
pTimer = (OS_NDIS_MINIPORT_TIMER *) (pTimerOrg->pContent);
if (pTimer != NULL) {
__RTMP_OS_Release_Timer(pTimer);
os_free_mem(NULL, pTimer);
pTimerOrg->pContent = NULL;
}
}
/*
========================================================================
Routine Description:
Allocate a OS resource.
Arguments:
pAd - WLAN control block pointer
pRsc - the resource
RscLen - resource length
Return Value:
TRUE or FALSE
Note:
========================================================================
*/
BOOLEAN RTMP_OS_Alloc_Rsc(IN LIST_HEADER *pRscList,
IN VOID *pRscSrc,
IN UINT32 RscLen) {
OS_RSTRUC *pRsc = (OS_RSTRUC *) pRscSrc;
if (pRsc->pContent == NULL) {
/* new entry */
os_alloc_mem(NULL, (UCHAR **) & (pRsc->pContent), RscLen);
if (pRsc->pContent == NULL) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: alloc timer fail!\n", __FUNCTION__));
return FALSE;
} else {
LIST_RESOURCE_OBJ_ENTRY *pObj;
/* allocate resource record entry */
os_alloc_mem(NULL, (UCHAR **) & (pObj),
sizeof (LIST_RESOURCE_OBJ_ENTRY));
if (pObj == NULL) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: alloc timer obj fail!\n",
__FUNCTION__));
os_free_mem(NULL, pRsc->pContent);
pRsc->pContent = NULL;
return FALSE;
} else {
memset(pRsc->pContent, 0, RscLen);
pObj->pRscObj = (VOID *) pRsc;
OS_SEM_LOCK(&UtilSemLock);
insertTailList(pRscList, (LIST_ENTRY *) pObj);
OS_SEM_UNLOCK(&UtilSemLock);
}
}
}
return TRUE;
}
/*
========================================================================
Routine Description:
Free all timers.
Arguments:
pAd - WLAN control block pointer
Return Value:
None
Note:
========================================================================
*/
VOID RTMP_OS_Free_Rscs(IN LIST_HEADER *pRscList) {
LIST_RESOURCE_OBJ_ENTRY *pObj;
OS_RSTRUC *pRsc;
OS_SEM_LOCK(&UtilSemLock);
while (TRUE) {
pObj = (LIST_RESOURCE_OBJ_ENTRY *) removeHeadList(pRscList);
if (pObj == NULL)
break;
pRsc = (OS_RSTRUC *) (pObj->pRscObj);
if (pRsc->pContent != NULL) {
/* free the timer memory */
os_free_mem(NULL, pRsc->pContent);
pRsc->pContent = NULL;
} else {
/*
The case is possible because some timers are released during
the driver life time, EX: we will release some timers in
MacTableDeleteEntry().
But we do not recommend the behavior, i.e. not to release
timers in the driver life time; Or we can not cancel the
timer for timer preemption problem.
*/
}
os_free_mem(NULL, pObj); /* free the timer record entry */
}
OS_SEM_UNLOCK(&UtilSemLock);
}
/*
========================================================================
Routine Description:
Allocate a kernel task.
Arguments:
pTask - the task
Return Value:
None
Note:
========================================================================
*/
BOOLEAN RtmpOSTaskAlloc(IN RTMP_OS_TASK *pTask,
IN LIST_HEADER *pTaskList) {
if (RTMP_OS_Alloc_Rsc(pTaskList, pTask, sizeof (OS_TASK)) == FALSE) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: alloc task fail!\n", __FUNCTION__));
return FALSE; /* allocate fail */
}
return TRUE;
}
/*
========================================================================
Routine Description:
Free a kernel task.
Arguments:
pTask - the task
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOSTaskFree(IN RTMP_OS_TASK *pTask) {
/* we will free all tasks memory in RTMP_OS_FREE_TASK() */
}
/*
========================================================================
Routine Description:
Kill a kernel task.
Arguments:
pTaskOrg - the task
Return Value:
None
Note:
========================================================================
*/
NDIS_STATUS RtmpOSTaskKill(IN RTMP_OS_TASK *pTaskOrg) {
OS_TASK *pTask;
NDIS_STATUS Status;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask != NULL) {
Status = __RtmpOSTaskKill(pTask);
RtmpOSTaskFree(pTaskOrg);
return Status;
}
return NDIS_STATUS_FAILURE;
}
/*
========================================================================
Routine Description:
Notify kernel the task exit.
Arguments:
pTaskOrg - the task
Return Value:
None
Note:
========================================================================
*/
INT RtmpOSTaskNotifyToExit(IN RTMP_OS_TASK *pTaskOrg) {
OS_TASK *pTask;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask == NULL)
return 0;
return __RtmpOSTaskNotifyToExit(pTask);
}
/*
========================================================================
Routine Description:
Customize the task.
Arguments:
pTaskOrg - the task
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOSTaskCustomize(IN RTMP_OS_TASK *pTaskOrg) {
OS_TASK *pTask;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask == NULL)
return;
__RtmpOSTaskCustomize(pTask);
}
/*
========================================================================
Routine Description:
Activate a kernel task.
Arguments:
pTaskOrg - the task
fn - task handler
arg - task input argument
Return Value:
None
Note:
========================================================================
*/
NDIS_STATUS RtmpOSTaskAttach(IN RTMP_OS_TASK *pTaskOrg,
IN RTMP_OS_TASK_CALLBACK fn,
IN ULONG arg) {
OS_TASK *pTask;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask == NULL)
return NDIS_STATUS_FAILURE;
return __RtmpOSTaskAttach(pTask, fn, arg);
}
/*
========================================================================
Routine Description:
Initialize a kernel task.
Arguments:
pTaskOrg - the task
pTaskName - task name
pPriv - task input argument
Return Value:
None
Note:
========================================================================
*/
NDIS_STATUS RtmpOSTaskInit(IN RTMP_OS_TASK *pTaskOrg,
IN PSTRING pTaskName,
IN VOID *pPriv,
IN LIST_HEADER *pTaskList,
IN LIST_HEADER *pSemList) {
OS_TASK *pTask;
if (RtmpOSTaskAlloc(pTaskOrg, pTaskList) == FALSE)
return NDIS_STATUS_FAILURE;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask == NULL)
return NDIS_STATUS_FAILURE;
return __RtmpOSTaskInit(pTask, pTaskName, pPriv, pSemList);
}
/*
========================================================================
Routine Description:
Wait for a event in the task.
Arguments:
pAd - WLAN control block pointer
pTaskOrg - the task
Return Value:
TRUE
FALSE
Note:
========================================================================
*/
BOOLEAN RtmpOSTaskWait(IN VOID *pReserved,
IN RTMP_OS_TASK *pTaskOrg,
IN INT32 *pStatus) {
OS_TASK *pTask;
pTask = (OS_TASK *) (pTaskOrg->pContent);
if (pTask == NULL)
return FALSE;
return __RtmpOSTaskWait(pReserved, pTask, pStatus);
}
/*
========================================================================
Routine Description:
Get private data for the task.
Arguments:
pTaskOrg - the task
Return Value:
None
Note:
========================================================================
*/
VOID *RtmpOsTaskDataGet(IN RTMP_OS_TASK *pTaskOrg) {
if (pTaskOrg->pContent == NULL)
return NULL;
return (((OS_TASK *) (pTaskOrg->pContent))->priv);
}
/*
========================================================================
Routine Description:
Allocate a lock.
Arguments:
pLock - the lock
Return Value:
None
Note:
========================================================================
*/
BOOLEAN RtmpOsAllocateLock(IN NDIS_SPIN_LOCK *pLock,
IN LIST_HEADER *pLockList) {
if (RTMP_OS_Alloc_Rsc(pLockList, pLock,
sizeof (OS_NDIS_SPIN_LOCK)) == FALSE) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: alloc lock fail!\n", __FUNCTION__));
return FALSE; /* allocate fail */
}
OS_NdisAllocateSpinLock(pLock->pContent);
return TRUE;
}
/*
========================================================================
Routine Description:
Free a lock.
Arguments:
pLockOrg - the lock
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsFreeSpinLock(IN NDIS_SPIN_LOCK *pLockOrg) {
OS_NdisFreeSpinLock(pLock);
/* we will free all locks memory in RTMP_OS_FREE_LOCK() */
}
/*
========================================================================
Routine Description:
Spin lock bh.
Arguments:
pLockOrg - the lock
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsSpinLockBh(IN NDIS_SPIN_LOCK *pLockOrg) {
OS_NDIS_SPIN_LOCK *pLock;
pLock = (OS_NDIS_SPIN_LOCK *) (pLockOrg->pContent);
if (pLock != NULL) {
OS_SEM_LOCK(pLock);
} else
printk("lock> warning! the lock was freed!\n");
}
/*
========================================================================
Routine Description:
Spin unlock bh.
Arguments:
pLockOrg - the lock
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsSpinUnLockBh(IN NDIS_SPIN_LOCK *pLockOrg) {
OS_NDIS_SPIN_LOCK *pLock;
pLock = (OS_NDIS_SPIN_LOCK *) (pLockOrg->pContent);
if (pLock != NULL) {
OS_SEM_UNLOCK(pLock);
} else
printk("lock> warning! the lock was freed!\n");
}
/*
========================================================================
Routine Description:
Interrupt lock.
Arguments:
pLockOrg - the lock
pIrqFlags - the lock flags
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsIntLock(IN NDIS_SPIN_LOCK *pLockOrg,
IN ULONG *pIrqFlags) {
OS_NDIS_SPIN_LOCK *pLock;
pLock = (OS_NDIS_SPIN_LOCK *) (pLockOrg->pContent);
if (pLock != NULL) {
OS_INT_LOCK(pLock, *pIrqFlags);
} else
printk("lock> warning! the lock was freed!\n");
}
/*
========================================================================
Routine Description:
Interrupt unlock.
Arguments:
pLockOrg - the lock
IrqFlags - the lock flags
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsIntUnLock(IN NDIS_SPIN_LOCK *pLockOrg,
IN ULONG IrqFlags) {
OS_NDIS_SPIN_LOCK *pLock;
pLock = (OS_NDIS_SPIN_LOCK *) (pLockOrg->pContent);
if (pLock != NULL) {
OS_INT_UNLOCK(pLock, IrqFlags);
} else
printk("lock> warning! the lock was freed!\n");
}
/*
========================================================================
Routine Description:
Get MAC address for the network interface.
Arguments:
pDev - the device
Return Value:
None
Note:
========================================================================
*/
unsigned char *RtmpOsNetDevGetPhyAddr(IN VOID *pDev) {
return RTMP_OS_NETDEV_GET_PHYADDR((PNET_DEV) pDev);
}
/*
========================================================================
Routine Description:
Start network interface TX queue.
Arguments:
pDev - the device
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsNetQueueStart(IN PNET_DEV pDev) {
RTMP_OS_NETDEV_START_QUEUE(pDev);
}
/*
========================================================================
Routine Description:
Stop network interface TX queue.
Arguments:
pDev - the device
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsNetQueueStop(IN PNET_DEV pDev) {
RTMP_OS_NETDEV_STOP_QUEUE(pDev);
}
/*
========================================================================
Routine Description:
Wake up network interface TX queue.
Arguments:
pDev - the device
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsNetQueueWake(IN PNET_DEV pDev) {
RTMP_OS_NETDEV_WAKE_QUEUE(pDev);
}
/*
========================================================================
Routine Description:
Assign network interface to the packet.
Arguments:
pPkt - the packet
pDev - the device
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsSetPktNetDev(IN VOID *pPkt,
IN VOID *pDev) {
SET_OS_PKT_NETDEV(pPkt, (PNET_DEV) pDev);
}
/*
========================================================================
Routine Description:
Assign private data pointer to the network interface.
Arguments:
pDev - the device
pPriv - the pointer
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsSetNetDevPriv(IN VOID *pDev,
IN VOID *pPriv) {
RTMP_OS_NETDEV_SET_PRIV((PNET_DEV) pDev, pPriv);
}
/*
========================================================================
Routine Description:
Get private data pointer from the network interface.
Arguments:
pDev - the device
pPriv - the pointer
Return Value:
None
Note:
========================================================================
*/
VOID *RtmpOsGetNetDevPriv(IN VOID *pDev) {
return (VOID *) RTMP_OS_NETDEV_GET_PRIV((PNET_DEV) pDev);
}
/*
========================================================================
Routine Description:
Assign network interface type.
Arguments:
pDev - the device
Type - the type
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsSetNetDevType(IN VOID *pDev,
IN USHORT Type) {
RTMP_OS_NETDEV_SET_TYPE((PNET_DEV) pDev, Type);
}
/*
========================================================================
Routine Description:
Assign network interface type for monitor mode.
Arguments:
pDev - the device
Type - the type
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsSetNetDevTypeMonitor(IN VOID *pDev) {
RTMP_OS_NETDEV_SET_TYPE((PNET_DEV) pDev, ARPHRD_IEEE80211_PRISM);
}
/*
========================================================================
Routine Description:
Get PID.
Arguments:
pPkt - the packet
pDev - the device
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsGetPid(IN ULONG *pDst,
IN ULONG PID) {
RT_GET_OS_PID(*pDst, PID);
}
/*
========================================================================
Routine Description:
Wait for a moment.
Arguments:
Time - micro second
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsWait(IN UINT32 Time) {
OS_WAIT(Time);
}
/*
========================================================================
Routine Description:
Check if b is smaller than a.
Arguments:
Time - micro second
Return Value:
None
Note:
========================================================================
*/
UINT32 RtmpOsTimerAfter(IN ULONG a,
IN ULONG b) {
return RTMP_TIME_AFTER(a, b);
}
/*
========================================================================
Routine Description:
Check if b is not smaller than a.
Arguments:
Time - micro second
Return Value:
None
Note:
========================================================================
*/
UINT32 RtmpOsTimerBefore(IN ULONG a,
IN ULONG b) {
return RTMP_TIME_BEFORE(a, b);
}
/*
========================================================================
Routine Description:
Get current system time.
Arguments:
pTime - system time (tick)
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsGetSystemUpTime(IN ULONG *pTime) {
NdisGetSystemUpTime(pTime);
}
/*
========================================================================
Routine Description:
Get OS tick unit.
Arguments:
pOps - Utility table
Return Value:
None
Note:
========================================================================
*/
UINT32 RtmpOsTickUnitGet(VOID) {
return HZ;
}
/*
========================================================================
Routine Description:
ntohs
Arguments:
Value - the value
Return Value:
the value
Note:
========================================================================
*/
UINT16 RtmpOsNtohs(IN UINT16 Value) {
return OS_NTOHS(Value);
}
/*
========================================================================
Routine Description:
htons
Arguments:
Value - the value
Return Value:
the value
Note:
========================================================================
*/
UINT16 RtmpOsHtons(IN UINT16 Value) {
return OS_HTONS(Value);
}
/*
========================================================================
Routine Description:
ntohl
Arguments:
Value - the value
Return Value:
the value
Note:
========================================================================
*/
UINT32 RtmpOsNtohl(IN UINT32 Value) {
return OS_NTOHL(Value);
}
/*
========================================================================
Routine Description:
htonl
Arguments:
Value - the value
Return Value:
the value
Note:
========================================================================
*/
UINT32 RtmpOsHtonl(IN UINT32 Value) {
return OS_HTONL(Value);
}
/*
========================================================================
Routine Description:
get_unaligned for 16-bit value.
Arguments:
pWord - the value
Return Value:
the value
Note:
========================================================================
*/
UINT16 RtmpOsGetUnaligned(IN UINT16 *pWord) {
return get_unaligned(pWord);
}
/*
========================================================================
Routine Description:
get_unaligned for 32-bit value.
Arguments:
pWord - the value
Return Value:
the value
Note:
========================================================================
*/
UINT32 RtmpOsGetUnaligned32(IN UINT32 *pWord) {
return get_unaligned(pWord);
}
/*
========================================================================
Routine Description:
get_unaligned for long-bit value.
Arguments:
pWord - the value
Return Value:
the value
Note:
========================================================================
*/
ULONG RtmpOsGetUnalignedlong(IN ULONG *pWord) {
return get_unaligned(pWord);
}
/*
========================================================================
Routine Description:
Get maximum scan data length.
Arguments:
None
Return Value:
length
Note:
Used in site servey.
========================================================================
*/
ULONG RtmpOsMaxScanDataGet(VOID) {
return IW_SCAN_MAX_DATA;
}
/*
========================================================================
Routine Description:
copy_from_user
Arguments:
to -
from -
n - size
Return Value:
copy size
Note:
========================================================================
*/
ULONG RtmpOsCopyFromUser(OUT VOID *to,
IN const void *from,
IN ULONG n) {
return (copy_from_user(to, from, n));
}
/*
========================================================================
Routine Description:
copy_to_user
Arguments:
to -
from -
n - size
Return Value:
copy size
Note:
========================================================================
*/
ULONG RtmpOsCopyToUser(OUT VOID *to,
IN const void *from,
IN ULONG n) {
return (copy_to_user(to, from, n));
}
/*
========================================================================
Routine Description:
Initialize a semaphore.
Arguments:
pSem - the semaphore
Return Value:
TRUE - Successfully
FALSE - Fail
Note:
========================================================================
*/
BOOLEAN RtmpOsSemaInitLocked(IN RTMP_OS_SEM *pSem,
IN LIST_HEADER *pSemList) {
if (RTMP_OS_Alloc_Rsc(pSemList, pSem, sizeof (OS_SEM)) == FALSE) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: alloc semaphore fail!\n", __FUNCTION__));
return FALSE; /* allocate fail */
}
OS_SEM_EVENT_INIT_LOCKED((OS_SEM *) (pSem->pContent));
return TRUE;
}
/*
========================================================================
Routine Description:
Initialize a semaphore.
Arguments:
pSemOrg - the semaphore
Return Value:
TRUE - Successfully
FALSE - Fail
Note:
========================================================================
*/
BOOLEAN RtmpOsSemaInit(IN RTMP_OS_SEM *pSem,
IN LIST_HEADER *pSemList) {
if (RTMP_OS_Alloc_Rsc(pSemList, pSem, sizeof (OS_SEM)) == FALSE) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: alloc semaphore fail!\n", __FUNCTION__));
return FALSE; /* allocate fail */
}
OS_SEM_EVENT_INIT((OS_SEM *) (pSem->pContent));
return TRUE;
}
/*
========================================================================
Routine Description:
Destroy a semaphore.
Arguments:
pSemOrg - the semaphore
Return Value:
TRUE - Successfully
FALSE - Fail
Note:
========================================================================
*/
BOOLEAN RtmpOsSemaDestory(IN RTMP_OS_SEM *pSemOrg) {
OS_SEM *pSem;
pSem = (OS_SEM *) (pSemOrg->pContent);
if (pSem != NULL) {
OS_SEM_EVENT_DESTORY(pSem);
/* we will free all tasks memory in RTMP_OS_FREE_SEM() */
/* os_free_mem(NULL, pSem); */
/* pSemOrg->pContent = NULL; */
} else
printk("sem> warning! double-free sem!\n");
return TRUE;
}
/*
========================================================================
Routine Description:
Wait a semaphore.
Arguments:
pSemOrg - the semaphore
Return Value:
0 - Successfully
Otherwise - Fail
Note:
========================================================================
*/
INT32 RtmpOsSemaWaitInterruptible(IN RTMP_OS_SEM *pSemOrg) {
OS_SEM *pSem;
INT32 Status = -1;
pSem = (OS_SEM *) (pSemOrg->pContent);
if (pSem != NULL)
OS_SEM_EVENT_WAIT(pSem, Status);
return Status;
}
/*
========================================================================
Routine Description:
Wake up a semaphore.
Arguments:
pSemOrg - the semaphore
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsSemaWakeUp(IN RTMP_OS_SEM *pSemOrg) {
OS_SEM *pSem;
pSem = (OS_SEM *) (pSemOrg->pContent);
if (pSem != NULL)
OS_SEM_EVENT_UP(pSem);
}
/*
========================================================================
Routine Description:
Check if we are in a interrupt.
Arguments:
None
Return Value:
0 - No
Otherwise - Yes
Note:
========================================================================
*/
INT32 RtmpOsIsInInterrupt(VOID) {
return (in_interrupt());
}
/*
========================================================================
Routine Description:
Copy the data buffer to the packet frame body.
Arguments:
pAd - WLAN control block pointer
pNetPkt - the packet
ThisFrameLen - copy length
pData - the data buffer
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsPktBodyCopy(IN PNET_DEV pNetDev,
IN PNDIS_PACKET pNetPkt,
IN ULONG ThisFrameLen,
IN PUCHAR pData) {
memcpy(skb_put(pNetPkt, ThisFrameLen), pData, ThisFrameLen);
SET_OS_PKT_NETDEV(pNetPkt, pNetDev);
RTMP_SET_PACKET_SOURCE(OSPKT_TO_RTPKT(pNetPkt), PKTSRC_NDIS);
}
/*
========================================================================
Routine Description:
Check if the packet is cloned.
Arguments:
pNetPkt - the packet
Return Value:
TRUE - Yes
Otherwise - No
Note:
========================================================================
*/
INT RtmpOsIsPktCloned(IN PNDIS_PACKET pNetPkt) {
return OS_PKT_CLONED(pNetPkt);
}
/*
========================================================================
Routine Description:
Duplicate a packet.
Arguments:
pNetPkt - the packet
Return Value:
the new packet
Note:
========================================================================
*/
PNDIS_PACKET RtmpOsPktCopy(IN PNDIS_PACKET pNetPkt) {
return skb_copy(RTPKT_TO_OSPKT(pNetPkt), GFP_ATOMIC);
}
/*
========================================================================
Routine Description:
Clone a packet.
Arguments:
pNetPkt - the packet
Return Value:
the cloned packet
Note:
========================================================================
*/
PNDIS_PACKET RtmpOsPktClone(IN PNDIS_PACKET pNetPkt) {
return skb_clone(RTPKT_TO_OSPKT(pNetPkt), MEM_ALLOC_FLAG);
}
/*
========================================================================
Routine Description:
Assign the data pointer for the packet.
Arguments:
pNetPkt - the packet
*pData - the data buffer
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsPktDataPtrAssign(IN PNDIS_PACKET pNetPkt,
IN UCHAR *pData) {
SET_OS_PKT_DATAPTR(pNetPkt, pData);
}
/*
========================================================================
Routine Description:
Assign the data length for the packet.
Arguments:
pNetPkt - the packet
Len - the data length
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsPktLenAssign(IN PNDIS_PACKET pNetPkt,
IN LONG Len) {
SET_OS_PKT_LEN(pNetPkt, Len);
}
/*
========================================================================
Routine Description:
Adjust the tail pointer for the packet.
Arguments:
pNetPkt - the packet
removedTagLen - the size for adjustment
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsPktTailAdjust(IN PNDIS_PACKET pNetPkt,
IN UINT removedTagLen) {
OS_PKT_TAIL_ADJUST(pNetPkt, removedTagLen);
}
/*
========================================================================
Routine Description:
Adjust the data pointer for the packet.
Arguments:
pNetPkt - the packet
Len - the size for adjustment
Return Value:
the new data pointer for the packet
Note:
========================================================================
*/
PUCHAR RtmpOsPktTailBufExtend(IN PNDIS_PACKET pNetPkt,
IN UINT Len) {
return OS_PKT_TAIL_BUF_EXTEND(pNetPkt, Len);
}
/*
========================================================================
Routine Description:
adjust headroom for the packet.
Arguments:
pNetPkt - the packet
Len - the size for adjustment
Return Value:
the new data pointer for the packet
Note:
========================================================================
*/
VOID RtmpOsPktReserve(IN PNDIS_PACKET pNetPkt,
IN UINT Len) {
OS_PKT_RESERVE(pNetPkt, Len);
}
/*
========================================================================
Routine Description:
Adjust the data pointer for the packet.
Arguments:
pNetPkt - the packet
Len - the size for adjustment
Return Value:
the new data pointer for the packet
Note:
========================================================================
*/
PUCHAR RtmpOsPktHeadBufExtend(IN PNDIS_PACKET pNetPkt,
IN UINT Len) {
return OS_PKT_HEAD_BUF_EXTEND(pNetPkt, Len);
}
/*
========================================================================
Routine Description:
Arguments:
pPkt - the packet
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsPktInfPpaSend(IN PNDIS_PACKET pNetPkt) {
#ifdef INF_PPA_SUPPORT
struct sk_buff *pRxPkt = RTPKT_TO_OSPKT(pNetPkt);
int ret = 0;
unsigned int ppa_flags = 0; /* reserved for now */
pRxPkt->protocol = eth_type_trans(pRxPkt, pRxPkt->dev);
memset(pRxPkt->head, 0, pRxPkt->data - pRxPkt->head - 14);
DBGPRINT(RT_DEBUG_TRACE,
("ppa_hook_directpath_send_fn rx :ret:%d headroom:%d dev:%s pktlen:%d<===\n",
ret, skb_headroom(pRxPkt)
, pRxPkt->dev->name, pRxPkt->len));
hex_dump("rx packet", pRxPkt->data, 32);
ret =
ppa_hook_directpath_send_fn(pAd->g_if_id, pRxPkt, pRxPkt->len,
ppa_flags);
#endif /* INF_PPA_SUPPORT */
}
INT32 RtmpThreadPidKill(IN RTMP_OS_PID PID) {
return KILL_THREAD_PID(PID, SIGTERM, 1);
}
long RtmpOsSimpleStrtol(IN const char *cp, IN char **endp, IN unsigned int base) {
return simple_strtol(cp,
endp,
base);
return simple_strtol(cp, endp, base);
}
BOOLEAN RtmpOsPktOffsetInit(VOID) {
struct sk_buff *pPkt = NULL;
if ((RTPktOffsetData == 0) && (RTPktOffsetLen == 0)
&& (RTPktOffsetCB == 0)) {
pPkt = kmalloc(sizeof (struct sk_buff), GFP_ATOMIC);
if (pPkt == NULL)
return FALSE;
RTPktOffsetData = (ULONG) (&(pPkt->data)) - (ULONG) pPkt;
RTPktOffsetLen = (ULONG) (&(pPkt->len)) - (ULONG) pPkt;
RTPktOffsetCB = (ULONG) (pPkt->cb) - (ULONG) pPkt;
kfree(pPkt);
DBGPRINT(RT_DEBUG_TRACE,
("packet> data offset = %lu\n", RTPktOffsetData));
DBGPRINT(RT_DEBUG_TRACE,
("packet> len offset = %lu\n", RTPktOffsetLen));
DBGPRINT(RT_DEBUG_TRACE,
("packet> cb offset = %lu\n", RTPktOffsetCB));
}
return TRUE;
}
/*
========================================================================
Routine Description:
Initialize the OS atomic_t.
Arguments:
pAtomic - the atomic
Return Value:
TRUE - allocation successfully
FALSE - allocation fail
Note:
========================================================================
*/
BOOLEAN RtmpOsAtomicInit(IN RTMP_OS_ATOMIC *pAtomic,
IN LIST_HEADER *pAtomicList) {
if (RTMP_OS_Alloc_Rsc(pAtomicList, pAtomic, sizeof (atomic_t)) == FALSE) {
DBGPRINT(RT_DEBUG_ERROR,
("%s: alloc atomic fail!\n", __FUNCTION__));
return FALSE; /* allocate fail */
}
return TRUE;
}
/*
========================================================================
Routine Description:
Atomic read a variable.
Arguments:
pAtomic - the atomic
Return Value:
content
Note:
========================================================================
*/
LONG RtmpOsAtomicRead(IN RTMP_OS_ATOMIC *pAtomicSrc) {
atomic_t *pAtomic;
if (pAtomicSrc->pContent == NULL)
return 0;
pAtomic = (atomic_t *) (pAtomicSrc->pContent);
return atomic_read(pAtomic);
}
/*
========================================================================
Routine Description:
Atomic dec a variable.
Arguments:
pAtomic - the atomic
Return Value:
content
Note:
========================================================================
*/
VOID RtmpOsAtomicDec(IN RTMP_OS_ATOMIC *pAtomicSrc) {
atomic_t *pAtomic;
if (pAtomicSrc->pContent == NULL)
return;
pAtomic = (atomic_t *) (pAtomicSrc->pContent);
atomic_dec(pAtomic);
}
/*
========================================================================
Routine Description:
Sets a 32-bit variable to the specified value as an atomic operation.
Arguments:
pAtomic - the atomic
Value - the value to be exchanged
Return Value:
the initial value of the pAtomicSrc parameter
Note:
========================================================================
*/
VOID RtmpOsAtomicInterlockedExchange(IN RTMP_OS_ATOMIC *pAtomicSrc,
IN LONG Value) {
atomic_t *pAtomic;
if (pAtomicSrc->pContent == NULL)
return;
pAtomic = (atomic_t *) (pAtomicSrc->pContent);
InterlockedExchange(pAtomic, Value);
}
/*
========================================================================
Routine Description:
Initialize the OS utilities.
Arguments:
pOps - Utility table
Return Value:
None
Note:
========================================================================
*/
VOID RtmpOsOpsInit(IN RTMP_OS_ABL_OPS *pOps) {
pOps->ra_printk = (RTMP_PRINTK)printk;
pOps->ra_snprintf = (RTMP_SNPRINTF)snprintf;
}
#else /* OS_ABL_FUNC_SUPPORT */
void RtmpOSFSInfoChange(IN RTMP_OS_FS_INFO *pOSFSInfoOrg,
IN BOOLEAN bSet) {
__RtmpOSFSInfoChange(pOSFSInfoOrg, bSet);
}
/* timeout -- ms */
VOID RTMP_SetPeriodicTimer(IN NDIS_MINIPORT_TIMER *pTimerOrg,
IN unsigned long timeout) {
__RTMP_SetPeriodicTimer(pTimerOrg,
timeout);
}
/* convert NdisMInitializeTimer --> RTMP_OS_Init_Timer */
VOID RTMP_OS_Init_Timer(
IN VOID *pReserved,
IN NDIS_MINIPORT_TIMER *pTimerOrg,
IN TIMER_FUNCTION function,
IN PVOID data,
IN LIST_HEADER *pTimerList) {
__RTMP_OS_Init_Timer(pReserved, pTimerOrg, function, data);
}
VOID RTMP_OS_Add_Timer(IN NDIS_MINIPORT_TIMER *pTimerOrg,
IN unsigned long timeout) {
__RTMP_OS_Add_Timer(pTimerOrg,
timeout);
}
VOID RTMP_OS_Mod_Timer(IN NDIS_MINIPORT_TIMER *pTimerOrg,
IN unsigned long timeout) {
__RTMP_OS_Mod_Timer(pTimerOrg,
timeout);
}
VOID RTMP_OS_Del_Timer(IN NDIS_MINIPORT_TIMER *pTimerOrg,
OUT BOOLEAN *pCancelled) {
__RTMP_OS_Del_Timer(pTimerOrg, pCancelled);
}
VOID RTMP_OS_Release_Timer(IN NDIS_MINIPORT_TIMER *pTimerOrg) {
__RTMP_OS_Release_Timer(pTimerOrg);
}
NDIS_STATUS RtmpOSTaskKill(IN RTMP_OS_TASK * pTask) {
return __RtmpOSTaskKill(pTask);
}
INT RtmpOSTaskNotifyToExit(IN RTMP_OS_TASK * pTask) {
return __RtmpOSTaskNotifyToExit(pTask);
}
void RtmpOSTaskCustomize(IN RTMP_OS_TASK * pTask) {
__RtmpOSTaskCustomize(pTask);
}
NDIS_STATUS RtmpOSTaskAttach(IN RTMP_OS_TASK * pTask,
IN RTMP_OS_TASK_CALLBACK fn,
IN ULONG arg) {
return __RtmpOSTaskAttach(pTask, fn, arg);
}
NDIS_STATUS RtmpOSTaskInit(IN RTMP_OS_TASK * pTask,
IN PSTRING pTaskName,
IN VOID *pPriv,
IN LIST_HEADER * pTaskList,
IN LIST_HEADER * pSemList) {
return __RtmpOSTaskInit(pTask, pTaskName, pPriv, pSemList);
}
BOOLEAN RtmpOSTaskWait(IN VOID *pReserved,
IN RTMP_OS_TASK * pTask,
IN INT32 *pStatus) {
return __RtmpOSTaskWait(pReserved, pTask, pStatus);
}
VOID RtmpOsTaskWakeUp(IN RTMP_OS_TASK * pTask) {
#ifdef KTHREAD_SUPPORT
WAKE_UP(pTask);
#else
RTMP_SEM_EVENT_UP(&pTask->taskSema);
#endif
}
#endif /* OS_ABL_FUNC_SUPPORT */
/* End of rt_linux.c */
| apache-2.0 |
leemichaelRazer/OSVR-Core | src/osvr/Connection/DeviceInitObject.cpp | 8 | 3691 | /** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/Connection/DeviceInitObject.h>
#include <osvr/PluginHost/PluginSpecificRegistrationContext.h>
#include <osvr/Connection/Connection.h>
// Library/third-party includes
// - none
// Standard includes
// - none
using osvr::pluginhost::PluginSpecificRegistrationContext;
using osvr::connection::Connection;
OSVR_DeviceInitObject::OSVR_DeviceInitObject(OSVR_PluginRegContext ctx)
: m_context(&PluginSpecificRegistrationContext::get(ctx)),
m_conn(Connection::retrieveConnection(m_context->getParent())),
m_analogIface(nullptr), m_buttonIface(nullptr), m_tracker(false) {}
OSVR_DeviceInitObject::OSVR_DeviceInitObject(
osvr::connection::ConnectionPtr conn)
: m_context(nullptr), m_conn(conn), m_tracker(false) {}
void OSVR_DeviceInitObject::setName(std::string const &n) {
m_name = n;
if (m_context) {
m_qualifiedName = m_context->getName() + "/" + m_name;
} else {
m_qualifiedName = m_name;
}
}
template <typename T>
inline bool setOptional(OSVR_ChannelCount input, T ptr,
boost::optional<OSVR_ChannelCount> &dest) {
if (0 == input || nullptr == ptr) {
dest.reset();
return false;
}
dest = input;
return true;
}
void OSVR_DeviceInitObject::setAnalogs(
OSVR_ChannelCount num, osvr::connection::AnalogServerInterface **iface) {
if (setOptional(num, iface, m_analogs)) {
m_analogIface = iface;
} else {
m_analogIface = nullptr;
}
}
void OSVR_DeviceInitObject::returnAnalogInterface(
osvr::connection::AnalogServerInterface &iface) {
*m_analogIface = &iface;
}
void OSVR_DeviceInitObject::setButtons(
OSVR_ChannelCount num, osvr::connection::ButtonServerInterface **iface) {
if (setOptional(num, iface, m_buttons)) {
m_buttonIface = iface;
} else {
m_buttonIface = nullptr;
}
}
void OSVR_DeviceInitObject::returnButtonInterface(
osvr::connection::ButtonServerInterface &iface) {
*m_buttonIface = &iface;
}
void OSVR_DeviceInitObject::setTracker(
osvr::connection::TrackerServerInterface **iface) {
if (nullptr != iface) {
m_tracker = true;
} else {
m_tracker = false;
}
m_trackerIface = iface;
}
void OSVR_DeviceInitObject::addServerInterface(
osvr::connection::ServerInterfacePtr const &iface) {
m_serverInterfaces.push_back(iface);
}
void OSVR_DeviceInitObject::addComponent(
osvr::common::DeviceComponentPtr const &comp) {
m_components.push_back(comp);
}
void OSVR_DeviceInitObject::returnTrackerInterface(
osvr::connection::TrackerServerInterface &iface) {
*m_trackerIface = &iface;
}
std::string OSVR_DeviceInitObject::getQualifiedName() const {
return m_qualifiedName;
}
osvr::connection::ConnectionPtr OSVR_DeviceInitObject::getConnection() {
return m_conn;
}
osvr::pluginhost::PluginSpecificRegistrationContext *
OSVR_DeviceInitObject::getContext() {
return m_context;
}
| apache-2.0 |
sharronliu/zephyr | ext/hal/ti/cc3200sdk/driverlib/spi.c | 9 | 39579 | //*****************************************************************************
//
// spi.c
//
// Driver for the SPI.
//
// Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// Neither the name of Texas Instruments Incorporated nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//*****************************************************************************
//*****************************************************************************
//
//! \addtogroup SPI_Serial_Peripheral_Interface_api
//! @{
//
//*****************************************************************************
#include "inc/hw_ints.h"
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_mcspi.h"
#include "inc/hw_apps_config.h"
#include "interrupt.h"
#include "spi.h"
//*****************************************************************************
//
// A mapping of SPI base address to interupt number.
//
//*****************************************************************************
static const unsigned long g_ppulSPIIntMap[][3] =
{
{ SSPI_BASE, INT_SSPI }, // Shared SPI
{ GSPI_BASE, INT_GSPI }, // Generic SPI
{ LSPI_BASE, INT_LSPI }, // LINK SPI
};
//*****************************************************************************
//
// A mapping of SPI base address to DMA done interrupt mask bit(s).
//
//*****************************************************************************
static const unsigned long g_ulSPIDmaMaskMap[][2]=
{
{SSPI_BASE,APPS_CONFIG_DMA_DONE_INT_MASK_SHSPI_WR_DMA_DONE_INT_MASK},
{LSPI_BASE,APPS_CONFIG_DMA_DONE_INT_MASK_HOSTSPI_WR_DMA_DONE_INT_MASK},
{GSPI_BASE,APPS_CONFIG_DMA_DONE_INT_MASK_APPS_SPI_WR_DMA_DONE_INT_MASK},
};
//*****************************************************************************
//
//! \internal
//! Transfer bytes over SPI channel
//!
//! \param ulBase is the base address of SPI module
//! \param ucDout is the pointer to Tx data buffer or 0.
//! \param ucDin is pointer to Rx data buffer or 0
//! \param ulCount is the size of data in bytes.
//!
//! This function transfers \e ulCount bytes of data over SPI channel.
//!
//! The function will not return until data has been transmitted
//!
//! \return Returns 0 on success, -1 otherwise.
//
//*****************************************************************************
static long SPITransfer8(unsigned long ulBase, unsigned char *ucDout,
unsigned char *ucDin, unsigned long ulCount,
unsigned long ulFlags)
{
unsigned long ulReadReg;
unsigned long ulWriteReg;
unsigned long ulStatReg;
unsigned long ulOutIncr;
unsigned long ulInIncr;
unsigned long ulTxDummy;
unsigned long ulRxDummy;
//
// Initialize the variables
//
ulOutIncr = 1;
ulInIncr = 1;
//
// Check if output buffer pointer is 0
//
if(ucDout == 0)
{
ulOutIncr = 0;
ulTxDummy = 0xFFFFFFFF;
ucDout = (unsigned char *)&ulTxDummy;
}
//
// Check if input buffer pointer is 0
//
if(ucDin == 0)
{
ulInIncr = 0;
ucDin = (unsigned char *)&ulRxDummy;
}
//
// Load the register addresses.
//
ulReadReg = (ulBase + MCSPI_O_RX0);
ulWriteReg = (ulBase + MCSPI_O_TX0);
ulStatReg = (ulBase + MCSPI_O_CH0STAT);
//
// Enable CS based on Flag
//
if( ulFlags & SPI_CS_ENABLE)
{
HWREG( ulBase + MCSPI_O_CH0CONF) |= MCSPI_CH0CONF_FORCE;
}
while(ulCount)
{
//
// Wait for space in output register/FIFO.
//
while( !(HWREG(ulStatReg) & MCSPI_CH0STAT_TXS) )
{
}
//
// Write the data
//
HWREG(ulWriteReg) = *ucDout;
//
// Wait for data in input register/FIFO.
//
while( !( HWREG(ulStatReg) & MCSPI_CH0STAT_RXS) )
{
}
//
// Read the data
//
*ucDin = HWREG(ulReadReg);
//
// Increment pointers.
//
ucDout = ucDout + ulOutIncr;
ucDin = ucDin + ulInIncr;
//
// Decrement the count.
//
ulCount--;
}
//
// Disable CS based on Flag
//
if( ulFlags & SPI_CS_DISABLE)
{
HWREG( ulBase + MCSPI_O_CH0CONF) &= ~MCSPI_CH0CONF_FORCE;
}
return 0;
}
//*****************************************************************************
//
//! \internal
//! Transfer half-words over SPI channel
//!
//! \param ulBase is the base address of SPI module
//! \param usDout is the pointer to Tx data buffer or 0.
//! \param usDin is pointer to Rx data buffer or 0
//! \param ulCount is the size of data in bytes.
//!
//! This function transfers \e ulCount bytes of data over SPI channel. Since
//! the API sends a half-word at a time \e ulCount should be a multiple
//! of two.
//!
//! The function will not return until data has been transmitted
//!
//! \return Returns 0 on success, -1 otherwise.
//
//*****************************************************************************
static long SPITransfer16(unsigned long ulBase, unsigned short *usDout,
unsigned short *usDin, unsigned long ulCount,
unsigned long ulFlags)
{
unsigned long ulReadReg;
unsigned long ulWriteReg;
unsigned long ulStatReg;
unsigned long ulOutIncr;
unsigned long ulInIncr;
unsigned long ulTxDummy;
unsigned long ulRxDummy;
//
// Initialize the variables.
//
ulOutIncr = 1;
ulInIncr = 1;
//
// Check if count is multiple of half-word
//
if(ulCount%2)
{
return -1;
}
//
// Compute number of half words.
//
ulCount = ulCount/2;
//
// Check if output buffer pointer is 0
//
if(usDout == 0)
{
ulOutIncr = 0;
ulTxDummy = 0xFFFFFFFF;
usDout = (unsigned short *)&ulTxDummy;
}
//
// Check if input buffer pointer is 0
//
if(usDin == 0)
{
ulInIncr = 0;
usDin = (unsigned short *)&ulRxDummy;
}
//
// Load the register addresses.
//
ulReadReg = (ulBase + MCSPI_O_RX0);
ulWriteReg = (ulBase + MCSPI_O_TX0);
ulStatReg = (ulBase + MCSPI_O_CH0STAT);
//
// Enable CS based on Flag
//
if( ulFlags & SPI_CS_ENABLE)
{
HWREG( ulBase + MCSPI_O_CH0CONF) |= MCSPI_CH0CONF_FORCE;
}
while(ulCount)
{
//
// Wait for space in output register/FIFO.
//
while( !(HWREG(ulStatReg) & MCSPI_CH0STAT_TXS) )
{
}
//
// Write the data
//
HWREG(ulWriteReg) = *usDout;
//
// Wait for data in input register/FIFO.
//
while( !( HWREG(ulStatReg) & MCSPI_CH0STAT_RXS) )
{
}
//
// Read the data
//
*usDin = HWREG(ulReadReg);
//
// Increment pointers.
//
usDout = usDout + ulOutIncr;
usDin = usDin + ulInIncr;
//
// Decrement the count.
//
ulCount--;
}
//
// Disable CS based on Flag
//
if( ulFlags & SPI_CS_DISABLE)
{
HWREG( ulBase + MCSPI_O_CH0CONF) &= ~MCSPI_CH0CONF_FORCE;
}
return 0;
}
//*****************************************************************************
//
//! \internal
//! Transfer words over SPI channel
//!
//! \param ulBase is the base address of SPI module
//! \param ulDout is the pointer to Tx data buffer or 0.
//! \param ulDin is pointer to Rx data buffer or 0
//! \param ulCount is the size of data in bytes.
//!
//! This function transfers \e ulCount bytes of data over SPI channel. Since
//! the API sends a word at a time \e ulCount should be a multiple of four.
//!
//! The function will not return until data has been transmitted
//!
//! \return Returns 0 on success, -1 otherwise.
//
//*****************************************************************************
static long SPITransfer32(unsigned long ulBase, unsigned long *ulDout,
unsigned long *ulDin, unsigned long ulCount,
unsigned long ulFlags)
{
unsigned long ulReadReg;
unsigned long ulWriteReg;
unsigned long ulStatReg;
unsigned long ulOutIncr;
unsigned long ulInIncr;
unsigned long ulTxDummy;
unsigned long ulRxDummy;
//
// Initialize the variables.
//
ulOutIncr = 1;
ulInIncr = 1;
//
// Check if count is multiple of word
//
if(ulCount%4)
{
return -1;
}
//
// Compute the number of words to be transferd
//
ulCount = ulCount/4;
//
// Check if output buffer pointer is 0
//
if(ulDout == 0)
{
ulOutIncr = 0;
ulTxDummy = 0xFFFFFFFF;
ulDout = &ulTxDummy;
}
//
// Check if input buffer pointer is 0
//
if(ulDin == 0)
{
ulInIncr = 0;
ulDin = &ulRxDummy;
}
//
// Load the register addresses.
//
ulReadReg = (ulBase + MCSPI_O_RX0);
ulWriteReg = (ulBase + MCSPI_O_TX0);
ulStatReg = (ulBase + MCSPI_O_CH0STAT);
//
// Enable CS based on Flag
//
if( ulFlags & SPI_CS_ENABLE)
{
HWREG( ulBase + MCSPI_O_CH0CONF) |= MCSPI_CH0CONF_FORCE;
}
while(ulCount)
{
//
// Wait for space in output register/FIFO.
//
while( !(HWREG(ulStatReg) & MCSPI_CH0STAT_TXS) )
{
}
//
// Write the data
//
HWREG(ulWriteReg) = *ulDout;
//
// Wait for data in input register/FIFO.
//
while( !( HWREG(ulStatReg) & MCSPI_CH0STAT_RXS) )
{
}
//
// Read the data
//
*ulDin = HWREG(ulReadReg);
//
// Increment pointers.
//
ulDout = ulDout + ulOutIncr;
ulDin = ulDin + ulInIncr;
//
// Decrement the count.
//
ulCount--;
}
//
// Disable CS based on Flag
//
if( ulFlags & SPI_CS_DISABLE)
{
HWREG( ulBase + MCSPI_O_CH0CONF) &= ~MCSPI_CH0CONF_FORCE;
}
return 0;
}
//*****************************************************************************
//
//! \internal
//! Gets the SPI interrupt number.
//!
//! \param ulBase is the base address of the SPI module
//!
//! Given a SPI base address, returns the corresponding interrupt number.
//!
//! \return Returns a SPI interrupt number, or -1 if \e ulBase is invalid.
//
//*****************************************************************************
static long
SPIIntNumberGet(unsigned long ulBase)
{
unsigned long ulIdx;
//
// Loop through the table that maps SPI base addresses to interrupt
// numbers.
//
for(ulIdx = 0; ulIdx < (sizeof(g_ppulSPIIntMap) /
sizeof(g_ppulSPIIntMap[0])); ulIdx++)
{
//
// See if this base address matches.
//
if(g_ppulSPIIntMap[ulIdx][0] == ulBase)
{
//
// Return the corresponding interrupt number.
//
return(g_ppulSPIIntMap[ulIdx][1]);
}
}
//
// The base address could not be found, so return an error.
//
return(-1);
}
//*****************************************************************************
//
//! \internal
//! Gets the SPI DMA interrupt mask bit.
//!
//! \param ulBase is the base address of the SPI module
//!
//! Given a SPI base address, DMA interrupt mask bit.
//!
//! \return Returns a DMA interrupt mask bit, or -1 if \e ulBase is invalid.
//
//*****************************************************************************
static long
SPIDmaMaskGet(unsigned long ulBase)
{
unsigned long ulIdx;
//
// Loop through the table that maps SPI base addresses to interrupt
// numbers.
//
for(ulIdx = 0; ulIdx < (sizeof(g_ulSPIDmaMaskMap) /
sizeof(g_ulSPIDmaMaskMap[0])); ulIdx++)
{
//
// See if this base address matches.
//
if(g_ulSPIDmaMaskMap[ulIdx][0] == ulBase)
{
//
// Return the corresponding interrupt number.
//
return(g_ulSPIDmaMaskMap[ulIdx][1]);
}
}
//
// The base address could not be found, so return an error.
//
return(-1);
}
//*****************************************************************************
//
//! Enables transmitting and receiving.
//!
//! \param ulBase is the base address of the SPI module
//!
//! This function enables the SPI channel for transmitting and receiving.
//!
//! \return None
//!
//
//*****************************************************************************
void
SPIEnable(unsigned long ulBase)
{
//
// Set Channel Enable Bit
//
HWREG(ulBase + MCSPI_O_CH0CTRL) |= MCSPI_CH0CTRL_EN;
}
//*****************************************************************************
//
//! Disables the transmitting and receiving.
//!
//! \param ulBase is the base address of the SPI module
//!
//! This function disables the SPI channel for transmitting and receiving.
//!
//! \return None
//!
//
//*****************************************************************************
void
SPIDisable(unsigned long ulBase)
{
//
// Reset Channel Enable Bit
//
HWREG(ulBase + MCSPI_O_CH0CTRL) &= ~MCSPI_CH0CTRL_EN;
}
//*****************************************************************************
//
//! Enables the SPI DMA operation for transmitting and/or receving.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulFlags selectes the DMA signal for transmit and/or receive.
//!
//! This function enables transmit and/or receive DMA request based on the
//! \e ulFlags parameter.
//!
//! The parameter \e ulFlags is the logical OR of one or more of
//! the following :
//! - \b SPI_RX_DMA
//! - \b SPI_TX_DMA
//!
//! \return None.
//
//*****************************************************************************
void
SPIDmaEnable(unsigned long ulBase, unsigned long ulFlags)
{
//
// Enable DMA based on ulFlags
//
HWREG(ulBase + MCSPI_O_CH0CONF) |= ulFlags;
}
//*****************************************************************************
//
//! Disables the SPI DMA operation for transmitting and/or receving.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulFlags selectes the DMA signal for transmit and/or receive.
//!
//! This function disables transmit and/or receive DMA request based on the
//! \e ulFlags parameter.
//!
//! The parameter \e ulFlags is the logical OR of one or more of
//! the following :
//! - \b SPI_RX_DMA
//! - \b SPI_TX_DMA
//!
//! \return None.
//
//*****************************************************************************
void
SPIDmaDisable(unsigned long ulBase, unsigned long ulFlags)
{
//
// Disable DMA based on ulFlags
//
HWREG(ulBase + MCSPI_O_CH0CONF) &= ~ulFlags;
}
//*****************************************************************************
//
//! Performs a software reset of the specified SPI module
//!
//! \param ulBase is the base address of the SPI module
//!
//! This function performs a software reset of the specified SPI module
//!
//! \return None.
//
//*****************************************************************************
void
SPIReset(unsigned long ulBase)
{
//
// Assert soft reset (auto clear)
//
HWREG(ulBase + MCSPI_O_SYSCONFIG) |= MCSPI_SYSCONFIG_SOFTRESET;
//
// wait until reset is done
//
while(!(HWREG(ulBase + MCSPI_O_SYSSTATUS)& MCSPI_SYSSTATUS_RESETDONE))
{
}
}
//*****************************************************************************
//
//! Sets the configuration of a SPI module
//!
//! \param ulBase is the base address of the SPI module
//! \param ulSPIClk is the rate of clock supplied to the SPI module.
//! \param ulBitRate is the desired bit rate.(master mode)
//! \param ulMode is the mode of operation.
//! \param ulSubMode is one of the valid sub-modes.
//! \param ulConfig is logical OR of configuration paramaters.
//!
//! This function configures SPI port for operation in specified sub-mode and
//! required bit rated as specified by \e ulMode and \e ulBitRate parameters
//! respectively.
//!
//! The SPI module can operate in either master or slave mode. The parameter
//! \e ulMode can be one of the following
//! -\b SPI_MODE_MASTER
//! -\b SPI_MODE_SLAVE
//!
//! The SPI module supports 4 sub modes based on SPI clock polarity and phase.
//!
//! <pre>
//! Polarity Phase Sub-Mode
//! 0 0 0
//! 0 1 1
//! 1 0 2
//! 1 1 3
//! </pre>
//!
//! Required sub mode can be select by setting \e ulSubMode parameter to one
//! of the following
//! - \b SPI_SUB_MODE_0
//! - \b SPI_SUB_MODE_1
//! - \b SPI_SUB_MODE_2
//! - \b SPI_SUB_MODE_3
//!
//! The parameter \e ulConfig is logical OR of five values: the word length,
//! active level for chip select, software or hardware controled chip select,
//! 3 or 4 pin mode and turbo mode.
//! mode.
//!
//! SPI support 8, 16 and 32 bit word lengths defined by:-
//! - \b SPI_WL_8
//! - \b SPI_WL_16
//! - \b SPI_WL_32
//!
//! Active state of Chip[ Selece can be defined by:-
//! - \b SPI_CS_ACTIVELOW
//! - \b SPI_CS_ACTIVEHIGH
//!
//! SPI chip select can be configured to be controlled either by hardware or
//! software:-
//! - \b SPI_SW_CS
//! - \b SPI_HW_CS
//!
//! The module can work in 3 or 4 pin mode defined by:-
//! - \b SPI_3PIN_MODE
//! - \b SPI_4PIN_MODE
//!
//! Turbo mode can be set on or turned off using:-
//! - \b SPI_TURBO_MODE_ON
//! - \b SPI_TURBO_MODE_OFF
//!
//! \return None.
//
//*****************************************************************************
void
SPIConfigSetExpClk(unsigned long ulBase,unsigned long ulSPIClk,
unsigned long ulBitRate, unsigned long ulMode,
unsigned long ulSubMode, unsigned long ulConfig)
{
unsigned long ulRegData;
unsigned long ulDivider;
//
// Read MODULCTRL register
//
ulRegData = HWREG(ulBase + MCSPI_O_MODULCTRL);
//
// Set Master mode with h/w chip select
//
ulRegData &= ~(MCSPI_MODULCTRL_MS |
MCSPI_MODULCTRL_SINGLE);
//
// Enable software control Chip Select, Init delay
// and 3-pin mode
//
ulRegData |= (((ulConfig >> 24) | ulMode) & 0xFF);
//
// Write the configuration
//
HWREG(ulBase + MCSPI_O_MODULCTRL) = ulRegData;
//
// Set IS, DPE0, DPE1 based on master or slave mode
//
if(ulMode == SPI_MODE_MASTER)
{
ulRegData = 0x1 << 16;
}
else
{
ulRegData = 0x6 << 16;
}
//
// Mask the configurations and set clock divider granularity
// to 1 cycle
//
ulRegData = (ulRegData & ~(MCSPI_CH0CONF_WL_M |
MCSPI_CH0CONF_EPOL |
MCSPI_CH0CONF_POL |
MCSPI_CH0CONF_PHA |
MCSPI_CH0CONF_TURBO ) |
MCSPI_CH0CONF_CLKG);
//
// Get the divider value
//
ulDivider = ((ulSPIClk/ulBitRate) - 1);
//
// The least significant four bits of the divider is used fo configure
// CLKD in MCSPI_CHCONF next eight least significant bits are used to
// configure the EXTCLK in MCSPI_CHCTRL
//
ulRegData |= ((ulDivider & 0x0000000F) << 2);
HWREG(ulBase + MCSPI_O_CH0CTRL) = ((ulDivider & 0x00000FF0) << 4);
//
// Set the protocol, CS polarity, word length
// and turbo mode
//
ulRegData = ((ulRegData |
ulSubMode) | (ulConfig & 0x0008FFFF));
//
// Write back the CONF register
//
HWREG(ulBase + MCSPI_O_CH0CONF) = ulRegData;
}
//*****************************************************************************
//
//! Receives a word from the specified port.
//!
//! \param ulBase is the base address of the SPI module.
//! \param pulData is pointer to receive data variable.
//!
//! This function gets a SPI word from the receive FIFO for the specified
//! port.
//!
//! \return Returns the number of elements read from the receive FIFO.
//
//*****************************************************************************
long
SPIDataGetNonBlocking(unsigned long ulBase, unsigned long *pulData)
{
unsigned long ulRegVal;
//
// Read register status register
//
ulRegVal = HWREG(ulBase + MCSPI_O_CH0STAT);
//
// Check is data is available
//
if(ulRegVal & MCSPI_CH0STAT_RXS)
{
*pulData = HWREG(ulBase + MCSPI_O_RX0);
return(1);
}
return(0);
}
//*****************************************************************************
//
//! Waits for the word to be received on the specified port.
//!
//! \param ulBase is the base address of the SPI module.
//! \param pulData is pointer to receive data variable.
//!
//! This function gets a SPI word from the receive FIFO for the specified
//! port. If there is no word available, this function waits until a
//! word is received before returning.
//!
//! \return Returns the word read from the specified port, cast as an
//! \e unsigned long.
//
//*****************************************************************************
void
SPIDataGet(unsigned long ulBase, unsigned long *pulData)
{
//
// Wait for Rx data
//
while(!(HWREG(ulBase + MCSPI_O_CH0STAT) & MCSPI_CH0STAT_RXS))
{
}
//
// Read the value
//
*pulData = HWREG(ulBase + MCSPI_O_RX0);
}
//*****************************************************************************
//
//! Transmits a word on the specified port.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulData is data to be transmitted.
//!
//! This function transmits a SPI word on the transmit FIFO for the specified
//! port.
//!
//! \return Returns the number of elements written to the transmit FIFO.
//!
//*****************************************************************************
long
SPIDataPutNonBlocking(unsigned long ulBase, unsigned long ulData)
{
unsigned long ulRegVal;
//
// Read status register
//
ulRegVal = HWREG(ulBase + MCSPI_O_CH0STAT);
//
// Write value into Tx register/FIFO
// if space is available
//
if(ulRegVal & MCSPI_CH0STAT_TXS)
{
HWREG(ulBase + MCSPI_O_TX0) = ulData;
return(1);
}
return(0);
}
//*****************************************************************************
//
//! Waits until the word is transmitted on the specified port.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulData is data to be transmitted.
//!
//! This function transmits a SPI word on the transmit FIFO for the specified
//! port. This function waits until the space is available on transmit FIFO
//!
//! \return None
//!
//*****************************************************************************
void
SPIDataPut(unsigned long ulBase, unsigned long ulData)
{
//
// Wait for space in FIFO
//
while(!(HWREG(ulBase + MCSPI_O_CH0STAT)&MCSPI_CH0STAT_TXS))
{
}
//
// Write the data
//
HWREG(ulBase + MCSPI_O_TX0) = ulData;
}
//*****************************************************************************
//
//! Enables the transmit and/or receive FIFOs.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulFlags selects the FIFO(s) to be enabled
//!
//! This function enables the transmit and/or receive FIFOs as specified by
//! \e ulFlags.
//! The parameter \e ulFlags shoulde be logical OR of one or more of the
//! following:
//! - \b SPI_TX_FIFO
//! - \b SPI_RX_FIFO
//!
//! \return None.
//
//*****************************************************************************
void
SPIFIFOEnable(unsigned long ulBase, unsigned long ulFlags)
{
//
// Set FIFO enable bits.
//
HWREG(ulBase + MCSPI_O_CH0CONF) |= ulFlags;
}
//*****************************************************************************
//
//! Disables the transmit and/or receive FIFOs.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulFlags selects the FIFO(s) to be enabled
//!
//! This function disables transmit and/or receive FIFOs. as specified by
//! \e ulFlags.
//! The parameter \e ulFlags shoulde be logical OR of one or more of the
//! following:
//! - \b SPI_TX_FIFO
//! - \b SPI_RX_FIFO
//!
//! \return None.
//
//*****************************************************************************
void
SPIFIFODisable(unsigned long ulBase, unsigned long ulFlags)
{
//
// Reset FIFO Enable bits.
//
HWREG(ulBase + MCSPI_O_CH0CONF) &= ~(ulFlags);
}
//*****************************************************************************
//
//! Sets the FIFO level at which DMA requests or interrupts are generated.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulTxLevel is the Almost Empty Level for transmit FIFO.
//! \param ulRxLevel is the Almost Full Level for the receive FIFO.
//!
//! This function Sets the FIFO level at which DMA requests or interrupts
//! are generated.
//!
//! \return None.
//
//*****************************************************************************
void SPIFIFOLevelSet(unsigned long ulBase, unsigned long ulTxLevel,
unsigned long ulRxLevel)
{
unsigned long ulRegVal;
//
// Read the current configuration
//
ulRegVal = HWREG(ulBase + MCSPI_O_XFERLEVEL);
//
// Mask and set new FIFO thresholds.
//
ulRegVal = ((ulRegVal & 0xFFFF0000) | (((ulRxLevel-1) << 8) | (ulTxLevel-1)));
//
// Set the transmit and receive FIFO thresholds.
//
HWREG(ulBase + MCSPI_O_XFERLEVEL) = ulRegVal;
}
//*****************************************************************************
//
//! Gets the FIFO level at which DMA requests or interrupts are generated.
//!
//! \param ulBase is the base address of the SPI module
//! \param pulTxLevel is a pointer to storage for the transmit FIFO level
//! \param pulRxLevel is a pointer to storage for the receive FIFO level
//!
//! This function gets the FIFO level at which DMA requests or interrupts
//! are generated.
//!
//! \return None.
//
//*****************************************************************************
void
SPIFIFOLevelGet(unsigned long ulBase, unsigned long *pulTxLevel,
unsigned long *pulRxLevel)
{
unsigned long ulRegVal;
//
// Read the current configuration
//
ulRegVal = HWREG(ulBase + MCSPI_O_XFERLEVEL);
*pulTxLevel = (ulRegVal & 0xFF);
*pulRxLevel = ((ulRegVal >> 8) & 0xFF);
}
//*****************************************************************************
//
//! Sets the word count.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulWordCount is number of SPI words to be transmitted.
//!
//! This function sets the word count, which is the number of SPI word to
//! be transferred on channel when using the FIFO buffer.
//!
//! \return None.
//
//*****************************************************************************
void
SPIWordCountSet(unsigned long ulBase, unsigned long ulWordCount)
{
unsigned long ulRegVal;
//
// Read the current configuration
//
ulRegVal = HWREG(ulBase + MCSPI_O_XFERLEVEL);
//
// Mask and set the word count
//
HWREG(ulBase + MCSPI_O_XFERLEVEL) = ((ulRegVal & 0x0000FFFF)|
(ulWordCount & 0xFFFF) << 16);
}
//*****************************************************************************
//
//! Registers an interrupt handler for a SPI interrupt.
//!
//! \param ulBase is the base address of the SPI module
//! \param pfnHandler is a pointer to the function to be called when the
//! SPI interrupt occurs.
//!
//! This function does the actual registering of the interrupt handler. This
//! function enables the global interrupt in the interrupt controller; specific
//! SPI interrupts must be enabled via SPIIntEnable(). It is the interrupt
//! handler's responsibility to clear the interrupt source.
//!
//! \sa IntRegister() for important information about registering interrupt
//! handlers.
//!
//! \return None.
//
//*****************************************************************************
void
SPIIntRegister(unsigned long ulBase, void(*pfnHandler)(void))
{
unsigned long ulInt;
//
// Determine the interrupt number based on the SPI module
//
ulInt = SPIIntNumberGet(ulBase);
//
// Register the interrupt handler.
//
IntRegister(ulInt, pfnHandler);
//
// Enable the SPI interrupt.
//
IntEnable(ulInt);
}
//*****************************************************************************
//
//! Unregisters an interrupt handler for a SPI interrupt.
//!
//! \param ulBase is the base address of the SPI module
//!
//! This function does the actual unregistering of the interrupt handler. It
//! clears the handler to be called when a SPI interrupt occurs. This
//! function also masks off the interrupt in the interrupt controller so that
//! the interrupt handler no longer is called.
//!
//! \sa IntRegister() for important information about registering interrupt
//! handlers.
//!
//! \return None.
//
//*****************************************************************************
void
SPIIntUnregister(unsigned long ulBase)
{
unsigned long ulInt;
//
// Determine the interrupt number based on the SPI module
//
ulInt = SPIIntNumberGet(ulBase);
//
// Disable the interrupt.
//
IntDisable(ulInt);
//
// Unregister the interrupt handler.
//
IntUnregister(ulInt);
}
//*****************************************************************************
//
//! Enables individual SPI interrupt sources.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulIntFlags is the bit mask of the interrupt sources to be enabled.
//!
//! This function enables the indicated SPI interrupt sources. Only the
//! sources that are enabled can be reflected to the processor interrupt;
//! disabled sources have no effect on the processor.
//!
//! The \e ulIntFlags parameter is the logical OR of any of the following:
//!
//! - \b SPI_INT_DMATX
//! - \b SPI_INT_DMARX
//! - \b SPI_INT_EOW
//! - \b SPI_INT_RX_OVRFLOW
//! - \b SPI_INT_RX_FULL
//! - \b SPI_INT_TX_UDRFLOW
//! - \b SPI_INT_TX_EMPTY
//!
//! \return None.
//
//*****************************************************************************
void
SPIIntEnable(unsigned long ulBase, unsigned long ulIntFlags)
{
unsigned long ulDmaMsk;
//
// Enable DMA Tx Interrupt
//
if(ulIntFlags & SPI_INT_DMATX)
{
ulDmaMsk = SPIDmaMaskGet(ulBase);
HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_MASK_CLR) = ulDmaMsk;
}
//
// Enable DMA Rx Interrupt
//
if(ulIntFlags & SPI_INT_DMARX)
{
ulDmaMsk = (SPIDmaMaskGet(ulBase) >> 1);
HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_MASK_CLR) = ulDmaMsk;
}
//
// Enable the specific Interrupts
//
HWREG(ulBase + MCSPI_O_IRQENABLE) |= (ulIntFlags & 0x0003000F);
}
//*****************************************************************************
//
//! Disables individual SPI interrupt sources.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulIntFlags is the bit mask of the interrupt sources to be disabled.
//!
//! This function disables the indicated SPI interrupt sources. Only the
//! sources that are enabled can be reflected to the processor interrupt;
//! disabled sources have no effect on the processor.
//!
//! The \e ulIntFlags parameter has the same definition as the \e ulIntFlags
//! parameter to SPIIntEnable().
//!
//! \return None.
//
//*****************************************************************************
void
SPIIntDisable(unsigned long ulBase, unsigned long ulIntFlags)
{
unsigned long ulDmaMsk;
//
// Disable DMA Tx Interrupt
//
if(ulIntFlags & SPI_INT_DMATX)
{
ulDmaMsk = SPIDmaMaskGet(ulBase);
HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_MASK_SET) = ulDmaMsk;
}
//
// Disable DMA Tx Interrupt
//
if(ulIntFlags & SPI_INT_DMARX)
{
ulDmaMsk = (SPIDmaMaskGet(ulBase) >> 1);
HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_MASK_SET) = ulDmaMsk;
}
//
// Disable the specific Interrupts
//
HWREG(ulBase + MCSPI_O_IRQENABLE) &= ~(ulIntFlags & 0x0003000F);
}
//*****************************************************************************
//
//! Gets the current interrupt status.
//!
//! \param ulBase is the base address of the SPI module
//! \param bMasked is \b false if the raw interrupt status is required and
//! \b true if the masked interrupt status is required.
//!
//! This function returns the interrupt status for the specified SPI.
//! The status of interrupts that are allowed to reflect to the processor can
//! be returned.
//!
//! \return Returns the current interrupt status, enumerated as a bit field of
//! values described in SPIIntEnable().
//
//*****************************************************************************
unsigned long
SPIIntStatus(unsigned long ulBase, tBoolean bMasked)
{
unsigned long ulIntStat;
unsigned long ulIntFlag;
unsigned long ulDmaMsk;
//
// Get SPI interrupt status
//
ulIntFlag = HWREG(ulBase + MCSPI_O_IRQSTATUS) & 0x0003000F;
if(bMasked)
{
ulIntFlag &= HWREG(ulBase + MCSPI_O_IRQENABLE);
}
//
// Get the interrupt bit
//
ulDmaMsk = SPIDmaMaskGet(ulBase);
//
// Get the DMA interrupt status
//
if(bMasked)
{
ulIntStat = HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_STS_MASKED);
}
else
{
ulIntStat = HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_STS_RAW);
}
//
// Get SPI Tx DMA done status
//
if(ulIntStat & ulDmaMsk)
{
ulIntFlag |= SPI_INT_DMATX;
}
//
// Get SPI Rx DMA done status
//
if(ulIntStat & (ulDmaMsk >> 1))
{
ulIntFlag |= SPI_INT_DMARX;
}
//
// Return status
//
return(ulIntFlag);
}
//*****************************************************************************
//
//! Clears SPI interrupt sources.
//!
//! \param ulBase is the base address of the SPI module
//! \param ulIntFlags is a bit mask of the interrupt sources to be cleared.
//!
//! The specified SPI interrupt sources are cleared, so that they no longer
//! assert. This function must be called in the interrupt handler to keep the
//! interrupt from being recognized again immediately upon exit.
//!
//! The \e ulIntFlags parameter has the same definition as the \e ulIntFlags
//! parameter to SPIIntEnable().
//!
//! \return None.
//
//*****************************************************************************
void
SPIIntClear(unsigned long ulBase, unsigned long ulIntFlags)
{
unsigned long ulDmaMsk;
//
// Disable DMA Tx Interrupt
//
if(ulIntFlags & SPI_INT_DMATX)
{
ulDmaMsk = SPIDmaMaskGet(ulBase);
HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_ACK) = ulDmaMsk;
}
//
// Disable DMA Tx Interrupt
//
if(ulIntFlags & SPI_INT_DMARX)
{
ulDmaMsk = (SPIDmaMaskGet(ulBase) >> 1);
HWREG(APPS_CONFIG_BASE + APPS_CONFIG_O_DMA_DONE_INT_ACK) = ulDmaMsk;
}
//
// Clear Interrupts
//
HWREG(ulBase + MCSPI_O_IRQSTATUS) = (ulIntFlags & 0x0003000F);
}
//*****************************************************************************
//
//! Enables the chip select in software controlled mode
//!
//! \param ulBase is the base address of the SPI module.
//!
//! This function enables the Chip select in software controlled mode. The
//! active state of CS will depend on the configuration done via
//! \sa SPIConfigExpClkSet().
//!
//! \return None.
//
//*****************************************************************************
void SPICSEnable(unsigned long ulBase)
{
//
// Set Chip Select enable bit.
//
HWREG( ulBase+MCSPI_O_CH0CONF) |= MCSPI_CH0CONF_FORCE;
}
//*****************************************************************************
//
//! Disables the chip select in software controlled mode
//!
//! \param ulBase is the base address of the SPI module.
//!
//! This function disables the Chip select in software controlled mode. The
//! active state of CS will depend on the configuration done via
//! sa SPIConfigSetExpClk().
//!
//! \return None.
//
//*****************************************************************************
void SPICSDisable(unsigned long ulBase)
{
//
// Reset Chip Select enable bit.
//
HWREG( ulBase+MCSPI_O_CH0CONF) &= ~MCSPI_CH0CONF_FORCE;
}
//*****************************************************************************
//
//! Send/Receive data buffer over SPI channel
//!
//! \param ulBase is the base address of SPI module
//! \param ucDout is the pointer to Tx data buffer or 0.
//! \param ucDin is pointer to Rx data buffer or 0
//! \param ulCount is the size of data in bytes.
//! \param ulFlags controlls chip select toggling.
//!
//! This function transfers \e ulCount bytes of data over SPI channel. Since
//! the API sends a SPI word at a time \e ulCount should be a multiple of
//! word length set using SPIConfigSetExpClk().
//!
//! If the \e ucDout parameter is set to 0, the function will send 0xFF over
//! the SPI MOSI line.
//!
//! If the \e ucDin parameter is set to 0, the function will ignore data on SPI
//! MISO line.
//!
//! The parameter \e ulFlags is logical OR of one or more of the following
//!
//! - \b SPI_CS_ENABLE if CS needs to be enabled at start of transfer.
//! - \b SPI_CS_DISABLE if CS need to be disabled at the end of transfer.
//!
//! This function will not return until data has been transmitted
//!
//! \return Returns 0 on success, -1 otherwise.
//
//*****************************************************************************
long SPITransfer(unsigned long ulBase, unsigned char *ucDout,
unsigned char *ucDin, unsigned long ulCount,
unsigned long ulFlags)
{
unsigned long ulWordLength;
long lRet;
//
// Get the word length
//
ulWordLength = (HWREG(ulBase + MCSPI_O_CH0CONF) & MCSPI_CH0CONF_WL_M);
//
// Check for word length.
//
if( !((ulWordLength == SPI_WL_8) || (ulWordLength == SPI_WL_16) ||
(ulWordLength == SPI_WL_32)) )
{
return -1;
}
if( ulWordLength == SPI_WL_8 )
{
//
// Do byte transfer
//
lRet = SPITransfer8(ulBase,ucDout,ucDin,ulCount,ulFlags);
}
else if( ulWordLength == SPI_WL_16 )
{
//
// Do half-word transfer
//
lRet = SPITransfer16(ulBase,(unsigned short *)ucDout,
(unsigned short *)ucDin,ulCount,ulFlags);
}
else
{
//
// Do word transfer
//
lRet = SPITransfer32(ulBase,(unsigned long *)ucDout,
(unsigned long *)ucDin,ulCount,ulFlags);
}
//
// return
//
return lRet;
}
//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************
| apache-2.0 |
Tao-Ma/incubator-hawq | src/backend/access/external/test_discard/hd_work_mgr_do_segment_clustering_by_host_test.c | 9 | 4945 | #include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include "cmockery.h"
#include "c.h"
#include "hd_work_mgr_mock.h"
/*
* check element list_index in segmenet_list
* has the expected hostip and segindex.
*/
void check_segment_info(List* segment_list, int list_index,
const char* expected_hostip,
int expected_segindex)
{
CdbComponentDatabaseInfo* seg_info =
(CdbComponentDatabaseInfo*)lfirst(list_nth_cell(segment_list, list_index));
assert_string_equal(seg_info->hostip, expected_hostip);
assert_int_equal(seg_info->segindex, expected_segindex);
}
/*
* Test clustering of segments to hosts.
* Environment: 10 segments over 3 hosts, all primary.
*/
void
test__do_segment_clustering_by_host__10SegmentsOn3Hosts(void **state)
{
List* groups = NIL;
ListCell* cell = NULL;
GpHost* gphost = NULL;
List* segs = NIL;
CdbComponentDatabaseInfo* seg_info = NULL;
char* array_of_segs[10] =
{"1.2.3.1", "1.2.3.1", "1.2.3.1", "1.2.3.1",
"1.2.3.2", "1.2.3.2", "1.2.3.2",
"1.2.3.3", "1.2.3.3", "1.2.3.3"
};
bool array_of_primaries[10] =
{
true, true, true, true,
true, true, true,
true, true, true
};
int number_of_segments = 10;
/* sanity */
assert_true(number_of_segments == (sizeof(array_of_segs) / sizeof(array_of_segs[0])));
assert_true(number_of_segments == (sizeof(array_of_primaries) / sizeof(array_of_primaries[0])));
buildCdbComponentDatabases(number_of_segments, array_of_segs, array_of_primaries);
CdbComponentDatabases *cdb = GpAliveSegmentsInfo.cdbComponentDatabases;
/* sanity for cdbComponentDatabases building*/
assert_int_equal(cdb->total_segment_dbs, number_of_segments);
assert_string_equal(cdb->segment_db_info[4].hostip, array_of_segs[4]);
/* test do_segment_clustering_by_host */
groups = do_segment_clustering_by_host();
assert_int_equal(list_length(groups), 3);
cell = list_nth_cell(groups, 0);
gphost = (GpHost*)lfirst(cell);
assert_string_equal(gphost->ip, array_of_segs[0]);
assert_int_equal(list_length(gphost->segs), 4);
for (int i = 0; i < 4; ++i)
{
check_segment_info(gphost->segs, i, "1.2.3.1", i);
}
cell = list_nth_cell(groups, 1);
gphost = (GpHost*)lfirst(cell);
assert_string_equal(gphost->ip, "1.2.3.2");
assert_int_equal(list_length(gphost->segs), 3);
for (int i = 0; i < 3; ++i)
{
check_segment_info(gphost->segs, i, "1.2.3.2", i+4);
}
cell = list_nth_cell(groups, 2);
gphost = (GpHost*)lfirst(cell);
assert_string_equal(gphost->ip, "1.2.3.3");
assert_int_equal(list_length(gphost->segs), 3);
for (int i = 0; i < 3; ++i)
{
check_segment_info(gphost->segs, i, "1.2.3.3", i+7);
}
restoreCdbComponentDatabases();
}
/*
* Test clustering of segments to hosts.
* Environment: 10 segments over 3 hosts, some of them mirrors.
*/
void
test__do_segment_clustering_by_host__10SegmentsOn3HostsWithMirrors(void **state)
{
List* groups = NIL;
ListCell* cell = NULL;
GpHost* gphost = NULL;
List* segs = NIL;
CdbComponentDatabaseInfo* seg_info = NULL;
CdbComponentDatabases *cdb = NULL;
char* array_of_segs[10] =
{
"1.2.3.1", "1.2.3.1", "1.2.3.1",
"1.2.3.2", "1.2.3.2", "1.2.3.2",
"1.2.3.3", "1.2.3.3", "1.2.3.3",
"1.2.3.1" /* another segment on the first host */
};
bool array_of_primaries[10] =
{
true, false, true,
true, true, true,
true, true, false,
true
};
int number_of_segments = 10;
/* sanity */
assert_true(number_of_segments == (sizeof(array_of_segs) / sizeof(array_of_segs[0])));
assert_true(number_of_segments == (sizeof(array_of_primaries) / sizeof(array_of_primaries[0])));
int array_for_host1[3] = {0, 2, 9};
int array_for_host2[3] = {3, 4, 5};
int array_for_host3[2] = {6, 7};
buildCdbComponentDatabases(number_of_segments, array_of_segs, array_of_primaries);
cdb = GpAliveSegmentsInfo.cdbComponentDatabases;
/* sanity for cdbComponentDatabases building*/
assert_int_equal(cdb->total_segment_dbs, number_of_segments);
assert_string_equal(cdb->segment_db_info[4].hostip, array_of_segs[4]);
/* test do_segment_clustering_by_host */
groups = do_segment_clustering_by_host();
assert_int_equal(list_length(groups), 3);
cell = list_nth_cell(groups, 0);
gphost = (GpHost*)lfirst(cell);
assert_string_equal(gphost->ip, "1.2.3.1");
assert_int_equal(list_length(gphost->segs), 3);
for (int i = 0; i < 3; ++i)
{
check_segment_info(gphost->segs, i, "1.2.3.1", array_for_host1[i]);
}
cell = list_nth_cell(groups, 1);
gphost = (GpHost*)lfirst(cell);
assert_string_equal(gphost->ip, "1.2.3.2");
assert_int_equal(list_length(gphost->segs), 3);
for (int i = 0; i < 3; ++i)
{
check_segment_info(gphost->segs, i, "1.2.3.2", array_for_host2[i]);
}
cell = list_nth_cell(groups, 2);
gphost = (GpHost*)lfirst(cell);
assert_string_equal(gphost->ip, "1.2.3.3");
assert_int_equal(list_length(gphost->segs), 2);
for (int i = 0; i < 2; ++i)
{
check_segment_info(gphost->segs, i, "1.2.3.3", array_for_host3[i]);
}
restoreCdbComponentDatabases();
}
| apache-2.0 |
vmcraft/RemotePrinter | 3rdparty/thrift-0.9.2/lib/cpp/src/thrift/transport/THttpTransport.cpp | 10 | 6025 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <sstream>
#include <thrift/transport/THttpTransport.h>
namespace apache { namespace thrift { namespace transport {
using namespace std;
// Yeah, yeah, hacky to put these here, I know.
const char* THttpTransport::CRLF = "\r\n";
const int THttpTransport::CRLF_LEN = 2;
THttpTransport::THttpTransport(boost::shared_ptr<TTransport> transport) :
transport_(transport),
origin_(""),
readHeaders_(true),
chunked_(false),
chunkedDone_(false),
chunkSize_(0),
contentLength_(0),
httpBuf_(NULL),
httpPos_(0),
httpBufLen_(0),
httpBufSize_(1024) {
init();
}
void THttpTransport::init() {
httpBuf_ = (char*)std::malloc(httpBufSize_+1);
if (httpBuf_ == NULL) {
throw std::bad_alloc();
}
httpBuf_[httpBufLen_] = '\0';
}
THttpTransport::~THttpTransport() {
if (httpBuf_ != NULL) {
std::free(httpBuf_);
}
}
uint32_t THttpTransport::read(uint8_t* buf, uint32_t len) {
if (readBuffer_.available_read() == 0) {
readBuffer_.resetBuffer();
uint32_t got = readMoreData();
if (got == 0) {
return 0;
}
}
return readBuffer_.read(buf, len);
}
uint32_t THttpTransport::readEnd() {
// Read any pending chunked data (footers etc.)
if (chunked_) {
while (!chunkedDone_) {
readChunked();
}
}
return 0;
}
uint32_t THttpTransport::readMoreData() {
uint32_t size;
// Get more data!
refill();
if (readHeaders_) {
readHeaders();
}
if (chunked_) {
size = readChunked();
} else {
size = readContent(contentLength_);
}
readHeaders_ = true;
return size;
}
uint32_t THttpTransport::readChunked() {
uint32_t length = 0;
char* line = readLine();
uint32_t chunkSize = parseChunkSize(line);
if (chunkSize == 0) {
readChunkedFooters();
} else {
// Read data content
length += readContent(chunkSize);
// Read trailing CRLF after content
readLine();
}
return length;
}
void THttpTransport::readChunkedFooters() {
// End of data, read footer lines until a blank one appears
while (true) {
char* line = readLine();
if (strlen(line) == 0) {
chunkedDone_ = true;
break;
}
}
}
uint32_t THttpTransport::parseChunkSize(char* line) {
char* semi = strchr(line, ';');
if (semi != NULL) {
*semi = '\0';
}
uint32_t size = 0;
sscanf(line, "%x", &size);
return size;
}
uint32_t THttpTransport::readContent(uint32_t size) {
uint32_t need = size;
while (need > 0) {
uint32_t avail = httpBufLen_ - httpPos_;
if (avail == 0) {
// We have given all the data, reset position to head of the buffer
httpPos_ = 0;
httpBufLen_ = 0;
refill();
// Now have available however much we read
avail = httpBufLen_;
}
uint32_t give = avail;
if (need < give) {
give = need;
}
readBuffer_.write((uint8_t*)(httpBuf_+httpPos_), give);
httpPos_ += give;
need -= give;
}
return size;
}
char* THttpTransport::readLine() {
while (true) {
char* eol = NULL;
eol = strstr(httpBuf_+httpPos_, CRLF);
// No CRLF yet?
if (eol == NULL) {
// Shift whatever we have now to front and refill
shift();
refill();
} else {
// Return pointer to next line
*eol = '\0';
char* line = httpBuf_+httpPos_;
httpPos_ = static_cast<uint32_t>((eol-httpBuf_) + CRLF_LEN);
return line;
}
}
}
void THttpTransport::shift() {
if (httpBufLen_ > httpPos_) {
// Shift down remaining data and read more
uint32_t length = httpBufLen_ - httpPos_;
memmove(httpBuf_, httpBuf_+httpPos_, length);
httpBufLen_ = length;
} else {
httpBufLen_ = 0;
}
httpPos_ = 0;
httpBuf_[httpBufLen_] = '\0';
}
void THttpTransport::refill() {
uint32_t avail = httpBufSize_ - httpBufLen_;
if (avail <= (httpBufSize_ / 4)) {
httpBufSize_ *= 2;
httpBuf_ = (char*)std::realloc(httpBuf_, httpBufSize_+1);
if (httpBuf_ == NULL) {
throw std::bad_alloc();
}
}
// Read more data
uint32_t got = transport_->read((uint8_t*)(httpBuf_+httpBufLen_), httpBufSize_-httpBufLen_);
httpBufLen_ += got;
httpBuf_[httpBufLen_] = '\0';
if (got == 0) {
throw TTransportException("Could not refill buffer");
}
}
void THttpTransport::readHeaders() {
// Initialize headers state variables
contentLength_ = 0;
chunked_ = false;
chunkedDone_ = false;
chunkSize_ = 0;
// Control state flow
bool statusLine = true;
bool finished = false;
// Loop until headers are finished
while (true) {
char* line = readLine();
if (strlen(line) == 0) {
if (finished) {
readHeaders_ = false;
return;
} else {
// Must have been an HTTP 100, keep going for another status line
statusLine = true;
}
} else {
if (statusLine) {
statusLine = false;
finished = parseStatusLine(line);
} else {
parseHeader(line);
}
}
}
}
void THttpTransport::write(const uint8_t* buf, uint32_t len) {
writeBuffer_.write(buf, len);
}
const std::string THttpTransport::getOrigin() {
std::ostringstream oss;
if ( !origin_.empty()) {
oss << origin_ << ", ";
}
oss << transport_->getOrigin();
return oss.str();
}
}}}
| apache-2.0 |
jqk6/s2n | utils/s2n_timer.c | 11 | 1852 | /*
* Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "utils/s2n_safety.h"
#include "utils/s2n_timer.h"
#if defined(__APPLE__) && defined(__MACH__)
#include <mach/clock.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
int s2n_timer_start(struct s2n_timer *timer)
{
timer->time = mach_absolute_time();
return 0;
}
int s2n_timer_reset(struct s2n_timer *timer, uint64_t *nanoseconds)
{
mach_timebase_info_data_t conversion_factor;
uint64_t previous_time = timer->time;
GUARD(s2n_timer_start(timer));
*nanoseconds = timer->time - previous_time;
GUARD(mach_timebase_info(&conversion_factor));
*nanoseconds *= conversion_factor.numer;
*nanoseconds /= conversion_factor.denom;
return 0;
}
#else
#if defined(CLOCK_MONOTONIC_RAW)
#define S2N_CLOCK CLOCK_MONOTONIC_RAW
#else
#define S2N_CLOCK CLOCK_MONOTONIC
#endif
int s2n_timer_start(struct s2n_timer *timer)
{
GUARD(clock_gettime(S2N_CLOCK, &timer->time));
return 0;
}
int s2n_timer_reset(struct s2n_timer *timer, uint64_t *nanoseconds)
{
struct timespec previous_time = timer->time;
GUARD(s2n_timer_start(timer));
*nanoseconds = (timer->time.tv_sec - previous_time.tv_sec) * 1000000000;
*nanoseconds += (timer->time.tv_nsec - previous_time.tv_nsec);
return 0;
}
#endif
| apache-2.0 |
roambotics/swift | lib/IDE/FuzzyStringMatcher.cpp | 13 | 17686 | //===--- FuzzyStringMatcher.cpp -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/FuzzyStringMatcher.h"
#include "clang/Basic/CharInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
using namespace swift;
using namespace swift::ide;
using clang::toUppercase;
using clang::toLowercase;
using clang::isUppercase;
using clang::isLowercase;
FuzzyStringMatcher::FuzzyStringMatcher(StringRef pattern_)
: pattern(pattern_), charactersInPattern(1 << (sizeof(char) * 8)) {
lowercasePattern.reserve(pattern.size());
unsigned upperCharCount = 0;
for (char c : pattern) {
char lower = toLowercase(c);
upperCharCount += (c == lower) ? 0 : 1;
lowercasePattern.push_back(lower);
charactersInPattern.set(static_cast<unsigned char>(lower));
charactersInPattern.set(static_cast<unsigned char>(toUppercase(c)));
}
assert(pattern.size() == lowercasePattern.size());
// FIXME: pull out the magic constants.
// This depends on the inner details of the matching algorithm and will need
// to be updated if we substantially alter it.
if (pattern.size() == 1) {
maxScore = 3.0 + // uppercase match
0.001; // size bonus
} else {
maxScore = 0.25 + // percent match bonus
2.5 + // match at start bonus
pattern.size() * pattern.size(); // max run length score
if (upperCharCount) // max uppercase match score
maxScore += (upperCharCount + 1) * (upperCharCount + 1);
maxScore *= 1.1 * 2.5 * 1.2; // exact prefix match bonus
}
}
bool FuzzyStringMatcher::matchesCandidate(StringRef candidate) const {
unsigned patternLength = pattern.size();
unsigned candidateLength = candidate.size();
if (patternLength > candidateLength)
return false;
// Do all of the pattern characters match the candidate in order?
unsigned pidx = 0, cidx = 0;
while (pidx < patternLength && cidx < candidateLength) {
char c = candidate[cidx];
char p = lowercasePattern[pidx];
if (p == c || p == toLowercase(c))
++pidx;
++cidx;
}
return pidx == patternLength;
}
static bool isTokenizingChar(char c) {
switch (c) {
case '/':
case '.':
case '_':
case '+':
case '-':
case ':':
case ',':
case ' ':
case '(':
case ')':
case '!':
case '?':
return true;
default:
return false;
}
}
namespace {
/// A simple index range.
struct Range {
unsigned location;
unsigned length;
};
} // end anonymous namespace
static void
populateTokenTable(SmallVectorImpl<Range> &tokens,
llvm::MutableArrayRef<unsigned> characterToTokenIndex,
StringRef candidate) {
unsigned start = 0;
characterToTokenIndex[0] = 0;
for (unsigned cidx = 1; cidx < candidate.size(); ++cidx) {
char current = candidate[cidx];
char prev = candidate[cidx - 1];
// Is this a special tokenizing character like '_', or the start of a camel
// case word? The uppercase character should start a new token.
if (isTokenizingChar(prev) ||
(isUppercase(current) && !isUppercase(prev)) ||
(clang::isDigit(current) && !clang::isDigit(prev))) {
tokens.push_back({start, cidx - start});
start = cidx;
} else if (isLowercase(current) && isUppercase(prev) && start != cidx - 1) {
// Or is this the end of a run of uppercase characters?
// E.g. in NSWindow, the 'W' should start a new token.
tokens.push_back({start, cidx - start - 1});
characterToTokenIndex[cidx - 1] = tokens.size();
start = cidx - 1;
}
characterToTokenIndex[cidx] = tokens.size();
}
tokens.push_back({start, static_cast<unsigned>(candidate.size() - start)});
}
static constexpr unsigned notFound = ~0U;
namespace {
/// The candidate-specific matching data and algorithms.
struct CandidateSpecificMatcher {
// The following StringRefs are owned by FuzzyStringMatcher and must outlive
// this object.
StringRef pattern;
StringRef lowercasePattern;
StringRef candidate;
SmallVector<char, 128> lowercaseCandidate;
SmallVector<unsigned, 128> jumpTable; ///< The next matching character index.
SmallVector<Range, 128> tokens; ///< Tokenized ranges from the candidate.
SmallVector<unsigned, 128> characterToTokenIndex;
SmallVector<Range, 128> runs;
CandidateSpecificMatcher(StringRef pattern, StringRef lowercasePattern,
StringRef candidate,
const llvm::BitVector &charactersInPattern,
unsigned &firstPatternPos);
/// Calculates the candidate's score, matching the candidate from
/// \p firstPatternPos or later.
///
/// This drives scoreCandidateTrial by trying the possible matches.
double scoreCandidate(unsigned firstPatternPos);
/// Calculates the candidate's score, matching the candidate from
/// exactly \p firstPatternPos.
double scoreCandidateTrial(unsigned firstPatternPos);
};
} // end anonymous namespace
double FuzzyStringMatcher::scoreCandidate(StringRef candidate) const {
double finalScore = 0.0;
if (candidate.empty() || pattern.empty() || candidate.size() < pattern.size())
return finalScore;
// Single character pattern matching should be simple and fast. Just look at
// the first character.
if (pattern.size() == 1) {
char c = candidate[0];
if (c == pattern[0] && isUppercase(c)) {
finalScore = 3.0;
} else if (toLowercase(c) == lowercasePattern[0]) {
finalScore = 2.0;
}
// Make sure shorter results come first;
if (finalScore)
finalScore += (1 / static_cast<double>(candidate.size())) * (1 / 1000.0);
if (normalize)
finalScore /= maxScore;
return finalScore;
}
// FIXME: path separators would be handled here, jumping straight to the last
// component if the pattern doesn't contain a separator.
unsigned firstPatternPos = 0;
CandidateSpecificMatcher CSM(pattern, lowercasePattern, candidate,
charactersInPattern, firstPatternPos);
finalScore = CSM.scoreCandidate(firstPatternPos);
if (normalize)
finalScore /= maxScore;
return finalScore;
}
CandidateSpecificMatcher::CandidateSpecificMatcher(
StringRef pattern, StringRef lowercasePattern, StringRef candidate,
const llvm::BitVector &charactersInPattern, unsigned &firstPatternPos)
: pattern(pattern), lowercasePattern(lowercasePattern),
candidate(candidate) {
assert(!pattern.empty() && pattern.size() <= candidate.size());
assert(pattern.size() == lowercasePattern.size());
// Build a table that points at the next pattern character so we skip
// through candidate faster.
unsigned candidateLength = candidate.size();
jumpTable.resize(candidateLength);
lowercaseCandidate.resize(candidateLength);
unsigned lastPatternPos = notFound;
for (unsigned cidx = candidateLength - 1;; --cidx) {
char c = candidate[cidx];
lowercaseCandidate[cidx] = toLowercase(c);
jumpTable[cidx] = lastPatternPos;
if (charactersInPattern[static_cast<unsigned char>(c)])
lastPatternPos = cidx;
if (!cidx)
break;
}
firstPatternPos = lastPatternPos;
// Build the token table.
characterToTokenIndex.resize(candidate.size());
populateTokenTable(tokens, characterToTokenIndex, candidate);
}
double CandidateSpecificMatcher::scoreCandidate(unsigned firstPatternPos) {
double finalScore = 0.0;
// The outer matching loop. We run multiple trials so that "a_b_c_abc"
// matching "abc" is matched on the "abc" part instead of the "a_b_c" part.
while (firstPatternPos != notFound) {
// Quickly skip to the first character that matches. We need
// the loop in case the first pattern-character in the
// candidate is not the first character in the pattern.
while (firstPatternPos != notFound) {
if (lowercasePattern[0] == lowercaseCandidate[firstPatternPos])
break;
firstPatternPos = jumpTable[firstPatternPos];
}
if (firstPatternPos == notFound)
break;
double trialScore = scoreCandidateTrial(firstPatternPos);
if (trialScore > finalScore) {
finalScore = trialScore;
// FIXME: update output ranges, if necessary
}
firstPatternPos = jumpTable[firstPatternPos];
}
return finalScore;
}
static double scoreRun(unsigned runStart, unsigned runLength,
unsigned prevTokenStart, unsigned tokenIndex,
unsigned uppercaseMatches, bool isTokenizingChar) {
if (runLength == 0)
return 0.0;
// We really don't like not matching at token starts, but if it's a long match
// give some credit.
if (runStart != prevTokenStart && !isTokenizingChar) {
if (runLength < 5) {
return (runLength < 3) ? 0.0 : runLength;
}
// For really long matches, we'll give a high score. Pretend it's a bit
// shorter.
runLength -= 2;
}
// Bonus if the match is the first or second token.
double prefixBonus = (runStart == 0) ? 2.5 : ((tokenIndex < 2) ? 1.0 : 0.0);
double uppercaseBonus =
uppercaseMatches ? (uppercaseMatches + 1) * (uppercaseMatches + 1) : 0.0;
return (runLength * runLength) + uppercaseBonus + prefixBonus;
}
double
CandidateSpecificMatcher::scoreCandidateTrial(unsigned firstPatternPos) {
double trialScore = 0.0; /// We run multiple trials so that "a_b_c_abc"
/// matching "abc" is matched on the "abc" part
/// instead of the "a_b_c" part.
unsigned uppercaseMatches = 0;
unsigned cidx = firstPatternPos;
unsigned pidx = 0;
unsigned runLength = 0;
unsigned runStart = cidx;
unsigned nonTokenRuns = 0;
unsigned camelCaseLen = 0;
unsigned camelCaseLastToken = 0;
double camelCaseStartBonus = 0.0;
unsigned camelCaseSkips = 0;
unsigned patternLength = pattern.size();
unsigned candidateLength = candidate.size();
while (pidx < patternLength && cidx < candidateLength) {
char lowerPatternChar = lowercasePattern[pidx];
char lowerCandidateChar = lowercaseCandidate[cidx];
unsigned nextCidx = jumpTable[cidx];
bool matched = lowerPatternChar == lowerCandidateChar;
if (matched) {
if (isUppercase(pattern[pidx]) && isUppercase(candidate[cidx])) {
++uppercaseMatches;
}
++runLength;
++pidx;
if (pidx < patternLength)
lowerPatternChar = lowercasePattern[pidx];
}
// If we're skipping forward and were running, the run ended.
if (((cidx + 1) != nextCidx) || !matched) {
if (runLength) {
double runValue =
scoreRun(runStart, runLength,
tokens[characterToTokenIndex[runStart]].location,
characterToTokenIndex[runStart], uppercaseMatches,
isTokenizingChar(candidate[runStart]));
// If it's a poor match in the middle of a token, see if the next char
// starts a token and also matches. If so, use it.
if (runLength == 1 && pidx > 1 && runValue == 0.0 &&
nextCidx != notFound &&
characterToTokenIndex[runStart] < tokens.size() - 1) {
bool foundIt = false;
unsigned charToCheck = matched ? nextCidx : cidx;
while (charToCheck != notFound) {
if (tokens[characterToTokenIndex[charToCheck]].location ==
charToCheck &&
lowercasePattern[pidx - 1] == lowercaseCandidate[charToCheck]) {
foundIt = true;
break;
}
charToCheck = jumpTable[charToCheck];
}
if (foundIt) {
--pidx;
lowerPatternChar = lowercasePattern[pidx];
runStart = cidx = charToCheck;
runLength = 0;
continue;
}
}
// We really don't like matches that don't start at a token.
if (runValue == 0.0) {
++nonTokenRuns;
} else {
unsigned tokenIndex = characterToTokenIndex[runStart];
if (runStart == tokens[tokenIndex].location ||
isTokenizingChar(lowerCandidateChar)) {
camelCaseLen += runLength;
// Bonus for matching the beginning of the candidate.
if (tokenIndex <= 1) {
camelCaseStartBonus = 2.0;
// Penalty for skipping a token.
} else if (tokenIndex != camelCaseLastToken + 1) {
camelCaseSkips += tokenIndex - camelCaseLastToken - 1;
}
camelCaseLastToken = tokenIndex;
if (isTokenizingChar(lowerCandidateChar) && runLength == 1) {
--camelCaseLastToken;
}
}
}
// Accumulate run and reset for next run.
trialScore += runValue;
runs.push_back({runStart, runLength});
uppercaseMatches = 0;
runLength = 0;
}
runStart = nextCidx;
}
cidx = nextCidx;
}
// The trial is done, did we find a match?
// FIXME: this can happen spuriously in foo => ufDownOb.
if (pidx != patternLength)
return 0.0;
// Okay, we found a match.
// FIXME: this code is largely duplicated with the previous block. There are
// some subtle differences that can be seen if you try to remove this one and
// check for pidx == patternLength for the other block.
if (runLength) {
double runValue = scoreRun(
runStart, runLength, tokens[characterToTokenIndex[runStart]].location,
characterToTokenIndex[runStart], uppercaseMatches,
isTokenizingChar(candidate[runStart]));
// If it's a poor match in the middle of a token, see if the next char
// starts a token and also matches. If so, use it.
if (runLength == 1 && runValue == 0.0) {
unsigned nextCidx = jumpTable[runStart];
if (nextCidx != notFound &&
characterToTokenIndex[runStart] < tokens.size() - 1) {
bool foundIt = false;
while (nextCidx != notFound) {
if (tokens[characterToTokenIndex[nextCidx]].location == nextCidx &&
lowercasePattern[pidx - 1] == lowercaseCandidate[nextCidx]) {
foundIt = true;
break;
}
nextCidx = jumpTable[nextCidx];
}
if (foundIt) {
runStart = nextCidx;
uppercaseMatches +=
(isUppercase(pattern[pidx - 1]) &&
isUppercase(candidate[runStart])) ? 1 : 0;
runValue = scoreRun(runStart, runLength,
tokens[characterToTokenIndex[runStart]].location,
characterToTokenIndex[runStart], uppercaseMatches,
isTokenizingChar(candidate[runStart]));
}
}
}
// We really don't like matches that don't start at a token.
if (runValue == 0.0) {
++nonTokenRuns;
} else {
unsigned tokenIndex = characterToTokenIndex[runStart];
if (runStart == tokens[tokenIndex].location ||
isTokenizingChar(lowercaseCandidate[runStart])) {
camelCaseLen += runLength;
if (tokenIndex <= 1) {
// Bonus for matching the beginning of the candidate.
camelCaseStartBonus = 2.0;
} else if (tokenIndex != camelCaseLastToken + 1) {
// Penalty for skipping a token.
camelCaseSkips += tokenIndex - camelCaseLastToken - 1;
}
}
}
// Accumulate run.
trialScore += runValue;
runs.push_back({runStart, runLength});
}
// Unless there were bad matches, prefer camel case matches.
if (nonTokenRuns == 0 && camelCaseSkips < 3) {
double camelCaseScore = (camelCaseLen * camelCaseLen) + camelCaseStartBonus;
if (camelCaseSkips == 1) {
camelCaseScore *= 0.9;
} else if (camelCaseSkips == 2) {
camelCaseScore *= 0.8;
}
if (trialScore < camelCaseScore) {
// Camel case matched better.
trialScore = camelCaseScore;
}
}
// FIXME: using the range up to a dot is silly when candidate isn't a file.
auto dotLoc = candidate.find_last_of('.');
unsigned baseNameLength =
dotLoc != StringRef::npos && dotLoc > 1 ? dotLoc : candidateLength;
// FIXME: file type bonus if we're checking a file path.
// Add a bit for the percentage of the candidate matched.
trialScore += patternLength / static_cast<double>(baseNameLength) * 0.25;
// Exact matches are even better.
if (patternLength >= baseNameLength && !runs.empty() &&
runs[0].location == 0) {
trialScore *= 1.1;
}
// Exact prefix matches are the best.
if (!runs.empty() && runs[0].location == 0 && runs[0].length == patternLength) {
trialScore *= 2.5;
// Case sensitive exact prefix matches are the best of the best.
if (candidate.startswith(pattern))
trialScore *= 1.2;
}
// FIXME: popular/unpopular API.
// We really don't like matches that don't start at a token.
switch (nonTokenRuns) {
case 0:
break;
case 1:
trialScore *= 0.8125;
break;
case 2:
trialScore *= 0.5;
break;
case 3:
trialScore *= 0.25;
break;
default:
trialScore *= 0.0625;
break;
}
// FIXME: matched ranges output.
return trialScore;
}
| apache-2.0 |
john-tornblom/mc | model/com.mentor.nucleus.bp.core/src418/ooaofooa_SR_M_class.c | 13 | 3757 | /*----------------------------------------------------------------------------
* File: ooaofooa_SR_M_class.c
*
* Class: Match (SR_M)
* Component: ooaofooa
*
* your copyright statement can go here (from te_copyright.body)
*--------------------------------------------------------------------------*/
#include "sys_sys_types.h"
#include "LOG_bridge.h"
#include "POP_bridge.h"
#include "T_bridge.h"
#include "ooaofooa_classes.h"
/*
* Instance Loader (from string data).
*/
Escher_iHandle_t
ooaofooa_SR_M_instanceloader( Escher_iHandle_t instance, const c_t * avlstring[] )
{
Escher_iHandle_t return_identifier = 0;
ooaofooa_SR_M * self = (ooaofooa_SR_M *) instance;
/* Initialize application analysis class attributes. */
self->Id = (Escher_iHandle_t) Escher_atoi( avlstring[ 1 ] );
return_identifier = self->Id;
self->Result_Id = (Escher_iHandle_t) Escher_atoi( avlstring[ 2 ] );
return return_identifier;
}
/*
* Select any where using referential/identifying attribute set.
* If not_empty, relate this instance to the selected instance.
*/
void ooaofooa_SR_M_batch_relate( Escher_iHandle_t instance )
{
ooaofooa_SR_M * ooaofooa_SR_M_instance = (ooaofooa_SR_M *) instance;
ooaofooa_SR_SR * ooaofooa_SR_SRrelated_instance1 = (ooaofooa_SR_SR *) Escher_instance_cache[ (intptr_t) ooaofooa_SR_M_instance->Result_Id ];
if ( ooaofooa_SR_SRrelated_instance1 ) {
ooaofooa_SR_M_R9800_Link_consists_of( ooaofooa_SR_SRrelated_instance1, ooaofooa_SR_M_instance );
}
}
/*
* Scan the extent for a matching instance.
*/
ooaofooa_SR_M *
ooaofooa_SR_M_AnyWhere1( Escher_UniqueID_t w_Id )
{
ooaofooa_SR_M * w;
Escher_Iterator_s iter_SR_M;
Escher_IteratorReset( &iter_SR_M, &pG_ooaofooa_SR_M_extent.active );
while ( (w = (ooaofooa_SR_M *) Escher_IteratorNext( &iter_SR_M )) != 0 ) {
if ( w->Id == w_Id ) {
return w;
}
}
return 0;
}
/*
* RELATE SR_SR TO SR_M ACROSS R9800
*/
void
ooaofooa_SR_M_R9800_Link_consists_of( ooaofooa_SR_SR * part, ooaofooa_SR_M * form )
{
/* Use TagEmptyHandleDetectionOn() to detect empty handle references. */
form->Result_Id = part->Id;
form->SR_SR_R9800_provides_for = part;
Escher_SetInsertElement( &part->SR_M_R9800_consists_of, (Escher_ObjectSet_s *) form );
}
/*
* UNRELATE SR_SR FROM SR_M ACROSS R9800
*/
void
ooaofooa_SR_M_R9800_Unlink_consists_of( ooaofooa_SR_SR * part, ooaofooa_SR_M * form )
{
/* Use TagEmptyHandleDetectionOn() to detect empty handle references. */
form->Result_Id = 0;
form->SR_SR_R9800_provides_for = 0;
Escher_SetRemoveElement( &part->SR_M_R9800_consists_of, (Escher_ObjectSet_s *) form );
}
/* Accessors to SR_M[R9801] subtypes */
/*
* Dump instances in SQL format.
*/
void
ooaofooa_SR_M_instancedumper( Escher_iHandle_t instance )
{
ooaofooa_SR_M * self = (ooaofooa_SR_M *) instance;
printf( "INSERT INTO SR_M VALUES ( %ld,%ld );\n",
((long)self->Id & ESCHER_IDDUMP_MASK),
((long)self->Result_Id & ESCHER_IDDUMP_MASK) );
}
/*
* Statically allocate space for the instance population for this class.
* Allocate space for the class instance and its attribute values.
* Depending upon the collection scheme, allocate containoids (collection
* nodes) for gathering instances into free and active extents.
*/
static Escher_SetElement_s ooaofooa_SR_M_container[ ooaofooa_SR_M_MAX_EXTENT_SIZE ];
static ooaofooa_SR_M ooaofooa_SR_M_instances[ ooaofooa_SR_M_MAX_EXTENT_SIZE ];
Escher_Extent_t pG_ooaofooa_SR_M_extent = {
{0,0}, {0,0}, &ooaofooa_SR_M_container[ 0 ],
(Escher_iHandle_t) &ooaofooa_SR_M_instances,
sizeof( ooaofooa_SR_M ), 0, ooaofooa_SR_M_MAX_EXTENT_SIZE
};
| apache-2.0 |
kubostech/KubOS | freertos/os/FreeRTOS/Demo/RX600_RX63N-RSK_Renesas/RTOSDemo/webserver/phy.c | 15 | 13529 | /******************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Technology Corp. and is only
* intended for use with Renesas products. No other uses are authorized.
* This software is owned by Renesas Technology Corp. and is protected under
* all applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES
* REGARDING THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY,
* INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY
* DISCLAIMED.
* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
* TECHNOLOGY CORP. NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
* FOR ANY REASON RELATED TO THE THIS SOFTWARE, EVEN IF RENESAS OR ITS
* AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this
* software and to discontinue the availability of this software.
* By using this software, you agree to the additional terms and
* conditions found by accessing the following link:
* http://www.renesas.com/disclaimer
******************************************************************************
* Copyright (C) 2008. Renesas Technology Corp., All Rights Reserved.
*******************************************************************************
* File Name : phy.c
* Version : 1.01
* Description : Ethernet PHY device driver
******************************************************************************
* History : DD.MM.YYYY Version Description
* : 15.02.2010 1.00 First Release
* : 06.04.2010 1.01 RX62N changes
******************************************************************************/
/******************************************************************************
Includes <System Includes> , "Project Includes"
******************************************************************************/
#include "iodefine.h"
#include "r_ether.h"
#include "phy.h"
#include "FreeRTOS.h"
#include "task.h"
/******************************************************************************
Typedef definitions
******************************************************************************/
/******************************************************************************
Macro definitions
******************************************************************************/
/******************************************************************************
Imported global variables and functions (from other files)
******************************************************************************/
/******************************************************************************
Exported global variables and functions (to be accessed by other files)
******************************************************************************/
/******************************************************************************
Private global variables and functions
******************************************************************************/
uint16_t _phy_read( uint16_t reg_addr );
void _phy_write( uint16_t reg_addr, uint16_t data );
void _phy_preamble( void );
void _phy_reg_set( uint16_t reg_addr, int32_t option );
void _phy_reg_read( uint16_t *data );
void _phy_reg_write( uint16_t data );
void _phy_ta_z0( void );
void _phy_ta_10( void );
void _phy_mii_write_1( void );
void _phy_mii_write_0( void );
/**
* External functions
*/
/******************************************************************************
* Function Name: phy_init
* Description : Resets Ethernet PHY device
* Arguments : none
* Return Value : none
******************************************************************************/
int16_t phy_init( void )
{
uint16_t reg;
uint32_t count;
/* Reset PHY */
_phy_write(BASIC_MODE_CONTROL_REG, 0x8000);
count = 0;
do
{
vTaskDelay( 2 / portTICK_PERIOD_MS );
reg = _phy_read(BASIC_MODE_CONTROL_REG);
count++;
} while (reg & 0x8000 && count < PHY_RESET_WAIT);
if( count < PHY_RESET_WAIT )
{
return R_PHY_OK;
}
return R_PHY_ERROR;
}
/******************************************************************************
* Function Name: phy_set_100full
* Description : Set Ethernet PHY device to 100 Mbps full duplex
* Arguments : none
* Return Value : none
******************************************************************************/
void phy_set_100full( void )
{
_phy_write(BASIC_MODE_CONTROL_REG, 0x2100);
}
/******************************************************************************
* Function Name: phy_set_10half
* Description : Sets Ethernet PHY device to 10 Mbps half duplexR
* Arguments : none
* Return Value : none
******************************************************************************/
void phy_set_10half( void )
{
_phy_write(BASIC_MODE_CONTROL_REG, 0x0000);
}
/******************************************************************************
* Function Name: phy_set_autonegotiate
* Description : Starts autonegotiate and reports the other side's
* : physical capability
* Arguments : none
* Return Value : bit 8 - Full duplex 100 mbps
* : bit 7 - Half duplex 100 mbps
* : bit 6 - Full duplex 10 mbps
* : bit 5 - Half duplex 10 mbps
* : bit 4:0 - Always set to 00001 (IEEE 802.3)
* : -1 if error
******************************************************************************/
int16_t phy_set_autonegotiate( void )
{
uint16_t reg;
uint32_t count;
_phy_write(AN_ADVERTISEMENT_REG, 0x01E1);
_phy_write(BASIC_MODE_CONTROL_REG, 0x1200);
count = 0;
do
{
reg = _phy_read(BASIC_MODE_STATUS_REG);
count++;
vTaskDelay( 100 / portTICK_PERIOD_MS );
/* Make sure we don't break out if reg just contains 0xffff. */
if( reg == 0xffff )
{
reg = 0;
}
} while (!(reg & 0x0020) && (count < PHY_AUTO_NEGOTIATON_WAIT));
if (count >= PHY_AUTO_NEGOTIATON_WAIT)
{
return R_PHY_ERROR;
}
else
{
/* Get the link partner response */
reg = (int16_t)_phy_read(AN_LINK_PARTNER_ABILITY_REG);
if (reg & ( 1 << 8 ) )
{
return PHY_LINK_100F;
}
if (reg & ( 1 << 7 ) )
{
return PHY_LINK_100H;
}
if (reg & ( 1 << 6 ) )
{
return PHY_LINK_10F;
}
if (reg & 1 << 5 )
{
return PHY_LINK_10H;
}
return (-1);
}
}
/**
* Internal functions
*/
/******************************************************************************
* Function Name: _phy_read
* Description : Reads a PHY register
* Arguments : reg_addr - address of the PHY register
* Return Value : read value
******************************************************************************/
uint16_t _phy_read( uint16_t reg_addr )
{
uint16_t data;
_phy_preamble();
_phy_reg_set( reg_addr, PHY_READ );
_phy_ta_z0();
_phy_reg_read( &data );
_phy_ta_z0();
return( data );
}
/******************************************************************************
* Function Name: _phy_write
* Description : Writes to a PHY register
* Arguments : reg_addr - address of the PHY register
* : data - value
* Return Value : none
******************************************************************************/
void _phy_write( uint16_t reg_addr, uint16_t data )
{
_phy_preamble();
_phy_reg_set( reg_addr, PHY_WRITE );
_phy_ta_10();
_phy_reg_write( data );
_phy_ta_z0();
}
/******************************************************************************
* Function Name: _phy_preamble
* Description : As preliminary preparation for access to the PHY module register,
* "1" is output via the MII management interface.
* Arguments : none
* Return Value : none
******************************************************************************/
void _phy_preamble( void )
{
int16_t i;
i = 32;
while( i > 0 )
{
_phy_mii_write_1();
i--;
}
}
/******************************************************************************
* Function Name: _phy_reg_set
* Description : Sets a PHY device to read or write mode
* Arguments : reg_addr - address of the PHY register
* : option - mode
* Return Value : none
******************************************************************************/
void _phy_reg_set( uint16_t reg_addr, int32_t option )
{
int32_t i;
uint16_t data;
data = 0;
data = (PHY_ST << 14); /* ST code */
if( option == PHY_READ )
{
data |= (PHY_READ << 12); /* OP code(RD) */
}
else
{
data |= (PHY_WRITE << 12); /* OP code(WT) */
}
data |= (PHY_ADDR << 7); /* PHY Address */
data |= (reg_addr << 2); /* Reg Address */
i = 14;
while( i > 0 )
{
if( (data & 0x8000) == 0 )
{
_phy_mii_write_0();
}
else
{
_phy_mii_write_1();
}
data <<= 1;
i--;
}
}
/******************************************************************************
* Function Name: _phy_reg_read
* Description : Reads PHY register through MII interface
* Arguments : data - pointer to store the data read
* Return Value : none
******************************************************************************/
void _phy_reg_read( uint16_t *data )
{
int32_t i, j;
uint16_t reg_data;
reg_data = 0;
i = 16;
while( i > 0 )
{
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000000;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000001;
}
reg_data <<= 1;
reg_data |= (uint16_t)((ETHERC.PIR.LONG & 0x00000008) >> 3); /* MDI read */
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000001;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000000;
}
i--;
}
*data = reg_data;
}
/******************************************************************************
* Function Name: _phy_reg_write
* Description : Writes to PHY register through MII interface
* Arguments : data - value to write
* Return Value : none
******************************************************************************/
void _phy_reg_write( uint16_t data )
{
int32_t i;
i = 16;
while( i > 0 )
{
if( (data & 0x8000) == 0 )
{
_phy_mii_write_0();
}
else
{
_phy_mii_write_1();
}
i--;
data <<= 1;
}
}
/******************************************************************************
* Function Name: _phy_ta_z0
* Description : Performs bus release so that PHY can drive data
* : for read operation
* Arguments : none
* Return Value : none
******************************************************************************/
void _phy_ta_z0( void )
{
int32_t j;
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000000;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000001;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000001;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000000;
}
}
/******************************************************************************
* Function Name: _phy_ta_10
* Description : Switches data bus so MII interface can drive data
* : for write operation
* Arguments : none
* Return Value : none
******************************************************************************/
void _phy_ta_10(void)
{
_phy_mii_write_1();
_phy_mii_write_0();
}
/******************************************************************************
* Function Name: _phy_mii_write_1
* Description : Outputs 1 to the MII interface
* Arguments : none
* Return Value : none
******************************************************************************/
void _phy_mii_write_1( void )
{
int32_t j;
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000006;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000007;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000007;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000006;
}
}
/******************************************************************************
* Function Name: _phy_mii_write_0
* Description : Outputs 0 to the MII interface
* Arguments : none
* Return Value : none
******************************************************************************/
void _phy_mii_write_0( void )
{
int32_t j;
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000002;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000003;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000003;
}
for(j = MDC_WAIT; j > 0; j--)
{
ETHERC.PIR.LONG = 0x00000002;
}
}
| apache-2.0 |
Omegaphora/external_deqp | framework/randomshaders/rsgToken.cpp | 18 | 2503 | /*-------------------------------------------------------------------------
* drawElements Quality Program Random Shader Generator
* ----------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Token class.
*//*--------------------------------------------------------------------*/
#include "rsgToken.hpp"
#include "deMemory.h"
#include "deString.h"
namespace rsg
{
Token::Token (const char* identifier)
: m_type(IDENTIFIER)
{
m_arg.identifier = deStrdup(identifier);
if (!m_arg.identifier)
throw std::bad_alloc();
}
Token::~Token (void)
{
if (m_type == IDENTIFIER)
deFree(m_arg.identifier);
}
Token& Token::operator= (const Token& other)
{
if (m_type == IDENTIFIER)
{
deFree(m_arg.identifier);
m_arg.identifier = DE_NULL;
}
m_type = other.m_type;
if (m_type == IDENTIFIER)
{
m_arg.identifier = deStrdup(other.m_arg.identifier);
if (!m_arg.identifier)
throw std::bad_alloc();
}
else if (m_type == FLOAT_LITERAL)
m_arg.floatValue = other.m_arg.floatValue;
else if (m_type == INT_LITERAL)
m_arg.intValue = other.m_arg.intValue;
else if (m_type == BOOL_LITERAL)
m_arg.boolValue = other.m_arg.boolValue;
return *this;
}
Token::Token (const Token& other)
: m_type(TYPE_LAST)
{
*this = other;
}
bool Token::operator!= (const Token& other) const
{
if (m_type != other.m_type)
return false;
if (m_type == IDENTIFIER && !deStringEqual(m_arg.identifier, other.m_arg.identifier))
return false;
else if (m_type == FLOAT_LITERAL && m_arg.floatValue != other.m_arg.floatValue)
return false;
else if (m_type == INT_LITERAL && m_arg.intValue != other.m_arg.intValue)
return false;
else if (m_type == BOOL_LITERAL && m_arg.boolValue != other.m_arg.boolValue)
return false;
return true;
}
TokenStream::TokenStream (void)
: m_tokens (ALLOC_SIZE)
, m_numTokens (0)
{
}
TokenStream::~TokenStream (void)
{
}
} // rsg
| apache-2.0 |
stuckless/sagetv | third_party/ffmpeg/libavformat/flvenc.c | 18 | 14319 | /*
* FLV muxer
* Copyright (c) 2003 The FFmpeg Project
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "avformat.h"
#include "flv.h"
#include "internal.h"
#include "avc.h"
#undef NDEBUG
#include <assert.h>
static const AVCodecTag flv_video_codec_ids[] = {
{CODEC_ID_FLV1, FLV_CODECID_H263 },
{CODEC_ID_FLASHSV, FLV_CODECID_SCREEN},
{CODEC_ID_FLASHSV2, FLV_CODECID_SCREEN2},
{CODEC_ID_VP6F, FLV_CODECID_VP6 },
{CODEC_ID_VP6, FLV_CODECID_VP6 },
{CODEC_ID_H264, FLV_CODECID_H264 },
{CODEC_ID_NONE, 0}
};
static const AVCodecTag flv_audio_codec_ids[] = {
{CODEC_ID_MP3, FLV_CODECID_MP3 >> FLV_AUDIO_CODECID_OFFSET},
{CODEC_ID_PCM_U8, FLV_CODECID_PCM >> FLV_AUDIO_CODECID_OFFSET},
{CODEC_ID_PCM_S16BE, FLV_CODECID_PCM >> FLV_AUDIO_CODECID_OFFSET},
{CODEC_ID_PCM_S16LE, FLV_CODECID_PCM_LE >> FLV_AUDIO_CODECID_OFFSET},
{CODEC_ID_ADPCM_SWF, FLV_CODECID_ADPCM >> FLV_AUDIO_CODECID_OFFSET},
{CODEC_ID_AAC, FLV_CODECID_AAC >> FLV_AUDIO_CODECID_OFFSET},
{CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET},
{CODEC_ID_SPEEX, FLV_CODECID_SPEEX >> FLV_AUDIO_CODECID_OFFSET},
{CODEC_ID_NONE, 0}
};
typedef struct FLVContext {
int reserved;
int64_t duration_offset;
int64_t filesize_offset;
int64_t duration;
int delay; ///< first dts delay for AVC
} FLVContext;
static int get_audio_flags(AVCodecContext *enc){
int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT;
if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters
return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
else if (enc->codec_id == CODEC_ID_SPEEX) {
if (enc->sample_rate != 16000) {
av_log(enc, AV_LOG_ERROR, "flv only supports wideband (16kHz) Speex audio\n");
return -1;
}
if (enc->channels != 1) {
av_log(enc, AV_LOG_ERROR, "flv only supports mono Speex audio\n");
return -1;
}
if (enc->frame_size / 320 > 8) {
av_log(enc, AV_LOG_WARNING, "Warning: Speex stream has more than "
"8 frames per packet. Adobe Flash "
"Player cannot handle this!\n");
}
return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;
} else {
switch (enc->sample_rate) {
case 44100:
flags |= FLV_SAMPLERATE_44100HZ;
break;
case 22050:
flags |= FLV_SAMPLERATE_22050HZ;
break;
case 11025:
flags |= FLV_SAMPLERATE_11025HZ;
break;
case 8000: //nellymoser only
case 5512: //not mp3
if(enc->codec_id != CODEC_ID_MP3){
flags |= FLV_SAMPLERATE_SPECIAL;
break;
}
default:
av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n");
return -1;
}
}
if (enc->channels > 1) {
flags |= FLV_STEREO;
}
switch(enc->codec_id){
case CODEC_ID_MP3:
flags |= FLV_CODECID_MP3 | FLV_SAMPLESSIZE_16BIT;
break;
case CODEC_ID_PCM_U8:
flags |= FLV_CODECID_PCM | FLV_SAMPLESSIZE_8BIT;
break;
case CODEC_ID_PCM_S16BE:
flags |= FLV_CODECID_PCM | FLV_SAMPLESSIZE_16BIT;
break;
case CODEC_ID_PCM_S16LE:
flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
break;
case CODEC_ID_ADPCM_SWF:
flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT;
break;
case CODEC_ID_NELLYMOSER:
if (enc->sample_rate == 8000) {
flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
} else {
flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT;
}
break;
case 0:
flags |= enc->codec_tag<<4;
break;
default:
av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n");
return -1;
}
return flags;
}
static void put_amf_string(ByteIOContext *pb, const char *str)
{
size_t len = strlen(str);
put_be16(pb, len);
put_buffer(pb, str, len);
}
static void put_amf_double(ByteIOContext *pb, double d)
{
put_byte(pb, AMF_DATA_TYPE_NUMBER);
put_be64(pb, av_dbl2int(d));
}
static void put_amf_bool(ByteIOContext *pb, int b) {
put_byte(pb, AMF_DATA_TYPE_BOOL);
put_byte(pb, !!b);
}
static int flv_write_header(AVFormatContext *s)
{
ByteIOContext *pb = s->pb;
FLVContext *flv = s->priv_data;
AVCodecContext *audio_enc = NULL, *video_enc = NULL;
int i;
double framerate = 0.0;
int metadata_size_pos, data_size;
for(i=0; i<s->nb_streams; i++){
AVCodecContext *enc = s->streams[i]->codec;
if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
if (s->streams[i]->r_frame_rate.den && s->streams[i]->r_frame_rate.num) {
framerate = av_q2d(s->streams[i]->r_frame_rate);
} else {
framerate = 1/av_q2d(s->streams[i]->codec->time_base);
}
video_enc = enc;
if(enc->codec_tag == 0) {
av_log(enc, AV_LOG_ERROR, "video codec not compatible with flv\n");
return -1;
}
} else {
audio_enc = enc;
if(get_audio_flags(enc)<0)
return -1;
}
av_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
}
put_tag(pb,"FLV");
put_byte(pb,1);
put_byte(pb, FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
+ FLV_HEADER_FLAG_HASVIDEO * !!video_enc);
put_be32(pb,9);
put_be32(pb,0);
for(i=0; i<s->nb_streams; i++){
if(s->streams[i]->codec->codec_tag == 5){
put_byte(pb,8); // message type
put_be24(pb,0); // include flags
put_be24(pb,0); // time stamp
put_be32(pb,0); // reserved
put_be32(pb,11); // size
flv->reserved=5;
}
}
/* write meta_tag */
put_byte(pb, 18); // tag type META
metadata_size_pos= url_ftell(pb);
put_be24(pb, 0); // size of data part (sum of all parts below)
put_be24(pb, 0); // time stamp
put_be32(pb, 0); // reserved
/* now data of data_size size */
/* first event name as a string */
put_byte(pb, AMF_DATA_TYPE_STRING);
put_amf_string(pb, "onMetaData"); // 12 bytes
/* mixed array (hash) with size and string/type/data tuples */
put_byte(pb, AMF_DATA_TYPE_MIXEDARRAY);
put_be32(pb, 5*!!video_enc + 5*!!audio_enc + 2); // +2 for duration and file size
put_amf_string(pb, "duration");
flv->duration_offset= url_ftell(pb);
put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect
if(video_enc){
put_amf_string(pb, "width");
put_amf_double(pb, video_enc->width);
put_amf_string(pb, "height");
put_amf_double(pb, video_enc->height);
put_amf_string(pb, "videodatarate");
put_amf_double(pb, video_enc->bit_rate / 1024.0);
put_amf_string(pb, "framerate");
put_amf_double(pb, framerate);
put_amf_string(pb, "videocodecid");
put_amf_double(pb, video_enc->codec_tag);
}
if(audio_enc){
put_amf_string(pb, "audiodatarate");
put_amf_double(pb, audio_enc->bit_rate / 1024.0);
put_amf_string(pb, "audiosamplerate");
put_amf_double(pb, audio_enc->sample_rate);
put_amf_string(pb, "audiosamplesize");
put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);
put_amf_string(pb, "stereo");
put_amf_bool(pb, audio_enc->channels == 2);
put_amf_string(pb, "audiocodecid");
put_amf_double(pb, audio_enc->codec_tag);
}
put_amf_string(pb, "filesize");
flv->filesize_offset= url_ftell(pb);
put_amf_double(pb, 0); // delayed write
put_amf_string(pb, "");
put_byte(pb, AMF_END_OF_OBJECT);
/* write total size of tag */
data_size= url_ftell(pb) - metadata_size_pos - 10;
url_fseek(pb, metadata_size_pos, SEEK_SET);
put_be24(pb, data_size);
url_fseek(pb, data_size + 10 - 3, SEEK_CUR);
put_be32(pb, data_size + 11);
for (i = 0; i < s->nb_streams; i++) {
AVCodecContext *enc = s->streams[i]->codec;
if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {
int64_t pos;
put_byte(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
put_be24(pb, 0); // size patched later
put_be24(pb, 0); // ts
put_byte(pb, 0); // ts ext
put_be24(pb, 0); // streamid
pos = url_ftell(pb);
if (enc->codec_id == CODEC_ID_AAC) {
put_byte(pb, get_audio_flags(enc));
put_byte(pb, 0); // AAC sequence header
put_buffer(pb, enc->extradata, enc->extradata_size);
} else {
put_byte(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
put_byte(pb, 0); // AVC sequence header
put_be24(pb, 0); // composition time
ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
}
data_size = url_ftell(pb) - pos;
url_fseek(pb, -data_size - 10, SEEK_CUR);
put_be24(pb, data_size);
url_fseek(pb, data_size + 10 - 3, SEEK_CUR);
put_be32(pb, data_size + 11); // previous tag size
}
}
return 0;
}
static int flv_write_trailer(AVFormatContext *s)
{
int64_t file_size;
ByteIOContext *pb = s->pb;
FLVContext *flv = s->priv_data;
file_size = url_ftell(pb);
/* update informations */
url_fseek(pb, flv->duration_offset, SEEK_SET);
put_amf_double(pb, flv->duration / (double)1000);
url_fseek(pb, flv->filesize_offset, SEEK_SET);
put_amf_double(pb, file_size);
url_fseek(pb, file_size, SEEK_SET);
return 0;
}
static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
{
ByteIOContext *pb = s->pb;
AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
FLVContext *flv = s->priv_data;
unsigned ts;
int size= pkt->size;
uint8_t *data= NULL;
int flags, flags_size;
// av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);
if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||
enc->codec_id == CODEC_ID_AAC)
flags_size= 2;
else if(enc->codec_id == CODEC_ID_H264)
flags_size= 5;
else
flags_size= 1;
if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
put_byte(pb, FLV_TAG_TYPE_VIDEO);
flags = enc->codec_tag;
if(flags == 0) {
av_log(enc, AV_LOG_ERROR, "video codec %X not compatible with flv\n",enc->codec_id);
return -1;
}
flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
} else {
assert(enc->codec_type == AVMEDIA_TYPE_AUDIO);
flags = get_audio_flags(enc);
assert(size);
put_byte(pb, FLV_TAG_TYPE_AUDIO);
}
if (enc->codec_id == CODEC_ID_H264) {
/* check if extradata looks like mp4 formated */
if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) {
if (ff_avc_parse_nal_units_buf(pkt->data, &data, &size) < 0)
return -1;
}
if (!flv->delay && pkt->dts < 0)
flv->delay = -pkt->dts;
}
ts = pkt->dts + flv->delay; // add delay to force positive dts
put_be24(pb,size + flags_size);
put_be24(pb,ts);
put_byte(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_
put_be24(pb,flv->reserved);
put_byte(pb,flags);
if (enc->codec_id == CODEC_ID_VP6)
put_byte(pb,0);
if (enc->codec_id == CODEC_ID_VP6F)
put_byte(pb, enc->extradata_size ? enc->extradata[0] : 0);
else if (enc->codec_id == CODEC_ID_AAC)
put_byte(pb,1); // AAC raw
else if (enc->codec_id == CODEC_ID_H264) {
put_byte(pb,1); // AVC NALU
put_be24(pb,pkt->pts - pkt->dts);
}
put_buffer(pb, data ? data : pkt->data, size);
put_be32(pb,size+flags_size+11); // previous tag size
flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
put_flush_packet(pb);
av_free(data);
return 0;
}
AVOutputFormat flv_muxer = {
"flv",
NULL_IF_CONFIG_SMALL("FLV format"),
"video/x-flv",
"flv",
sizeof(FLVContext),
#if CONFIG_LIBMP3LAME
CODEC_ID_MP3,
#else // CONFIG_LIBMP3LAME
CODEC_ID_ADPCM_SWF,
#endif // CONFIG_LIBMP3LAME
CODEC_ID_FLV1,
flv_write_header,
flv_write_packet,
flv_write_trailer,
.codec_tag= (const AVCodecTag* const []){flv_video_codec_ids, flv_audio_codec_ids, 0},
.flags= AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
};
| apache-2.0 |
geekboxzone/mmallow_external_deqp | modules/gles3/functional/es3fFboDepthbufferTests.cpp | 18 | 11937 | /*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.0 Module
* -------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief FBO depthbuffer tests.
*//*--------------------------------------------------------------------*/
#include "es3fFboDepthbufferTests.hpp"
#include "es3fFboTestCase.hpp"
#include "es3fFboTestUtil.hpp"
#include "gluTextureUtil.hpp"
#include "tcuTextureUtil.hpp"
#include "sglrContextUtil.hpp"
#include "glwEnums.hpp"
namespace deqp
{
namespace gles3
{
namespace Functional
{
using std::string;
using tcu::Vec2;
using tcu::Vec3;
using tcu::Vec4;
using tcu::IVec2;
using tcu::IVec3;
using tcu::IVec4;
using tcu::UVec4;
using namespace FboTestUtil;
class BasicFboDepthCase : public FboTestCase
{
public:
BasicFboDepthCase (Context& context, const char* name, const char* desc, deUint32 format, int width, int height)
: FboTestCase (context, name, desc)
, m_format (format)
, m_width (width)
, m_height (height)
{
}
protected:
void preCheck (void)
{
checkFormatSupport(m_format);
}
void render (tcu::Surface& dst)
{
const deUint32 colorFormat = GL_RGBA8;
deUint32 fbo = 0;
deUint32 colorRbo = 0;
deUint32 depthRbo = 0;
GradientShader gradShader (glu::TYPE_FLOAT_VEC4);
Texture2DShader texShader (DataTypes() << glu::TYPE_SAMPLER_2D, glu::TYPE_FLOAT_VEC4);
deUint32 gradShaderID = getCurrentContext()->createProgram(&gradShader);
deUint32 texShaderID = getCurrentContext()->createProgram(&texShader);
float clearDepth = 1.0f;
// Setup shaders
gradShader.setGradient(*getCurrentContext(), gradShaderID, tcu::Vec4(0.0f), tcu::Vec4(1.0f));
texShader.setUniforms (*getCurrentContext(), texShaderID);
// Setup FBO
glGenFramebuffers(1, &fbo);
glGenRenderbuffers(1, &colorRbo);
glGenRenderbuffers(1, &depthRbo);
glBindRenderbuffer(GL_RENDERBUFFER, colorRbo);
glRenderbufferStorage(GL_RENDERBUFFER, colorFormat, m_width, m_height);
glBindRenderbuffer(GL_RENDERBUFFER, depthRbo);
glRenderbufferStorage(GL_RENDERBUFFER, m_format, m_width, m_height);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRbo);
checkError();
checkFramebufferStatus(GL_FRAMEBUFFER);
glViewport(0, 0, m_width, m_height);
// Clear depth to 1
glClearBufferfv(GL_DEPTH, 0, &clearDepth);
// Render gradient with depth = [-1..1]
glEnable(GL_DEPTH_TEST);
sglr::drawQuad(*getCurrentContext(), gradShaderID, Vec3(-1.0f, -1.0f, -1.0f), Vec3(1.0f, 1.0f, 1.0f));
// Render grid pattern with depth = 0
{
const deUint32 format = GL_RGBA;
const deUint32 dataType = GL_UNSIGNED_BYTE;
const int texW = 128;
const int texH = 128;
deUint32 gridTex = 0;
tcu::TextureLevel data (glu::mapGLTransferFormat(format, dataType), texW, texH, 1);
tcu::fillWithGrid(data.getAccess(), 8, Vec4(0.2f, 0.7f, 0.1f, 1.0f), Vec4(0.7f, 0.1f, 0.5f, 0.8f));
glGenTextures(1, &gridTex);
glBindTexture(GL_TEXTURE_2D, gridTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, format, texW, texH, 0, format, dataType, data.getAccess().getDataPtr());
sglr::drawQuad(*getCurrentContext(), texShaderID, Vec3(-1.0f, -1.0f, 0.0f), Vec3(1.0f, 1.0f, 0.0f));
}
// Read results.
readPixels(dst, 0, 0, m_width, m_height, glu::mapGLInternalFormat(colorFormat), Vec4(1.0f), Vec4(0.0f));
}
private:
deUint32 m_format;
int m_width;
int m_height;
};
class DepthWriteClampCase : public FboTestCase
{
public:
DepthWriteClampCase (Context& context, const char* name, const char* desc, deUint32 format, int width, int height)
: FboTestCase (context, name, desc)
, m_format (format)
, m_width (width)
, m_height (height)
{
}
protected:
void preCheck (void)
{
checkFormatSupport(m_format);
}
void render (tcu::Surface& dst)
{
const deUint32 colorFormat = GL_RGBA8;
deUint32 fbo = 0;
deUint32 colorRbo = 0;
deUint32 depthTexture = 0;
glu::TransferFormat transferFmt = glu::getTransferFormat(glu::mapGLInternalFormat(m_format));
DepthGradientShader depthGradShader (glu::TYPE_FLOAT_VEC4);
const deUint32 depthGradShaderID = getCurrentContext()->createProgram(&depthGradShader);
const float clearDepth = 1.0f;
const tcu::Vec4 red (1.0, 0.0, 0.0, 1.0);
const tcu::Vec4 green (0.0, 1.0, 0.0, 1.0);
// Setup FBO
glGenFramebuffers(1, &fbo);
glGenRenderbuffers(1, &colorRbo);
glGenTextures(1, &depthTexture);
glBindRenderbuffer(GL_RENDERBUFFER, colorRbo);
glRenderbufferStorage(GL_RENDERBUFFER, colorFormat, m_width, m_height);
glBindTexture(GL_TEXTURE_2D, depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, m_format, m_width, m_height, 0, transferFmt.format, transferFmt.dataType, DE_NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);
checkError();
checkFramebufferStatus(GL_FRAMEBUFFER);
glViewport(0, 0, m_width, m_height);
// Clear depth to 1
glClearBufferfv(GL_DEPTH, 0, &clearDepth);
// Test that invalid values are not written to the depth buffer
// Render green quad, depth gradient = [-1..2]
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_ALWAYS);
depthGradShader.setUniforms(*getCurrentContext(), depthGradShaderID, -1.0f, 2.0f, green);
sglr::drawQuad(*getCurrentContext(), depthGradShaderID, Vec3(-1.0f, -1.0f, -1.0f), Vec3(1.0f, 1.0f, 1.0f));
glDepthMask(GL_FALSE);
// Test if any fragment has greater depth than 1; there should be none
glDepthFunc(GL_LESS); // (1 < depth) ?
depthGradShader.setUniforms(*getCurrentContext(), depthGradShaderID, 1.0f, 1.0f, red);
sglr::drawQuad(*getCurrentContext(), depthGradShaderID, Vec3(-1.0f, -1.0f, -1.0f), Vec3(1.0f, 1.0f, 1.0f));
// Test if any fragment has smaller depth than 0; there should be none
glDepthFunc(GL_GREATER); // (0 > depth) ?
depthGradShader.setUniforms(*getCurrentContext(), depthGradShaderID, 0.0f, 0.0f, red);
sglr::drawQuad(*getCurrentContext(), depthGradShaderID, Vec3(-1.0f, -1.0f, -1.0f), Vec3(1.0f, 1.0f, 1.0f));
// Read results.
readPixels(dst, 0, 0, m_width, m_height, glu::mapGLInternalFormat(colorFormat), Vec4(1.0f), Vec4(0.0f));
}
private:
const deUint32 m_format;
const int m_width;
const int m_height;
};
class DepthTestClampCase : public FboTestCase
{
public:
DepthTestClampCase (Context& context, const char* name, const char* desc, deUint32 format, int width, int height)
: FboTestCase (context, name, desc)
, m_format (format)
, m_width (width)
, m_height (height)
{
}
protected:
void preCheck (void)
{
checkFormatSupport(m_format);
}
void render (tcu::Surface& dst)
{
const deUint32 colorFormat = GL_RGBA8;
deUint32 fbo = 0;
deUint32 colorRbo = 0;
deUint32 depthTexture = 0;
glu::TransferFormat transferFmt = glu::getTransferFormat(glu::mapGLInternalFormat(m_format));
DepthGradientShader depthGradShader (glu::TYPE_FLOAT_VEC4);
const deUint32 depthGradShaderID = getCurrentContext()->createProgram(&depthGradShader);
const float clearDepth = 1.0f;
const tcu::Vec4 yellow (1.0, 1.0, 0.0, 1.0);
const tcu::Vec4 green (0.0, 1.0, 0.0, 1.0);
// Setup FBO
glGenFramebuffers(1, &fbo);
glGenRenderbuffers(1, &colorRbo);
glGenTextures(1, &depthTexture);
glBindRenderbuffer(GL_RENDERBUFFER, colorRbo);
glRenderbufferStorage(GL_RENDERBUFFER, colorFormat, m_width, m_height);
glBindTexture(GL_TEXTURE_2D, depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, m_format, m_width, m_height, 0, transferFmt.format, transferFmt.dataType, DE_NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);
checkError();
checkFramebufferStatus(GL_FRAMEBUFFER);
glViewport(0, 0, m_width, m_height);
// Clear depth to 1
glClearBufferfv(GL_DEPTH, 0, &clearDepth);
// Test values used in depth test are clamped
// Render green quad, depth gradient = [-1..2]
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_ALWAYS);
depthGradShader.setUniforms(*getCurrentContext(), depthGradShaderID, -1.0f, 2.0f, green);
sglr::drawQuad(*getCurrentContext(), depthGradShaderID, Vec3(-1.0f, -1.0f, -1.0f), Vec3(1.0f, 1.0f, 1.0f));
// Render yellow quad, depth gradient = [-0.5..3]. Gradients have equal values only outside [0, 1] range due to clamping
glDepthFunc(GL_EQUAL);
depthGradShader.setUniforms(*getCurrentContext(), depthGradShaderID, -0.5f, 3.0f, yellow);
sglr::drawQuad(*getCurrentContext(), depthGradShaderID, Vec3(-1.0f, -1.0f, -1.0f), Vec3(1.0f, 1.0f, 1.0f));
// Read results.
readPixels(dst, 0, 0, m_width, m_height, glu::mapGLInternalFormat(colorFormat), Vec4(1.0f), Vec4(0.0f));
}
private:
const deUint32 m_format;
const int m_width;
const int m_height;
};
FboDepthTests::FboDepthTests (Context& context)
: TestCaseGroup(context, "depth", "Depth tests")
{
}
FboDepthTests::~FboDepthTests (void)
{
}
void FboDepthTests::init (void)
{
static const deUint32 depthFormats[] =
{
GL_DEPTH_COMPONENT32F,
GL_DEPTH_COMPONENT24,
GL_DEPTH_COMPONENT16,
GL_DEPTH32F_STENCIL8,
GL_DEPTH24_STENCIL8
};
// .basic
{
tcu::TestCaseGroup* basicGroup = new tcu::TestCaseGroup(m_testCtx, "basic", "Basic depth tests");
addChild(basicGroup);
for (int fmtNdx = 0; fmtNdx < DE_LENGTH_OF_ARRAY(depthFormats); fmtNdx++)
basicGroup->addChild(new BasicFboDepthCase(m_context, getFormatName(depthFormats[fmtNdx]), "", depthFormats[fmtNdx], 119, 127));
}
// .depth_write_clamp
{
tcu::TestCaseGroup* depthClampGroup = new tcu::TestCaseGroup(m_testCtx, "depth_write_clamp", "Depth write clamping tests");
addChild(depthClampGroup);
for (int fmtNdx = 0; fmtNdx < DE_LENGTH_OF_ARRAY(depthFormats); fmtNdx++)
depthClampGroup->addChild(new DepthWriteClampCase(m_context, getFormatName(depthFormats[fmtNdx]), "", depthFormats[fmtNdx], 119, 127));
}
// .depth_test_clamp
{
tcu::TestCaseGroup* depthClampGroup = new tcu::TestCaseGroup(m_testCtx, "depth_test_clamp", "Depth test value clamping tests");
addChild(depthClampGroup);
for (int fmtNdx = 0; fmtNdx < DE_LENGTH_OF_ARRAY(depthFormats); fmtNdx++)
depthClampGroup->addChild(new DepthTestClampCase(m_context, getFormatName(depthFormats[fmtNdx]), "", depthFormats[fmtNdx], 119, 127));
}
}
} // Functional
} // gles3
} // deqp
| apache-2.0 |
gdos/libgdx | extensions/gdx-box2d/gdx-box2d/jni/Box2D/Dynamics/Joints/b2FrictionJoint.cpp | 532 | 6893 | /*
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2FrictionJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
{
bodyA = bA;
bodyB = bB;
localAnchorA = bodyA->GetLocalPoint(anchor);
localAnchorB = bodyB->GetLocalPoint(anchor);
}
b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def)
: b2Joint(def)
{
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
}
void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0f)
{
m_angularMass = 1.0f / m_angularMass;
}
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
float32 h = data.step.dt;
// Solve angular friction
{
float32 Cdot = wB - wA;
float32 impulse = -m_angularMass * Cdot;
float32 oldImpulse = m_angularImpulse;
float32 maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float32 maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2FrictionJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2FrictionJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2FrictionJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float32 b2FrictionJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2FrictionJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float32 b2FrictionJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2FrictionJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2FrictionJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Log(" jd.maxForce = %.15lef;\n", m_maxForce);
b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| apache-2.0 |
ksuarz/libbson | src/bson/bson-utf8.c | 22 | 12073 | /*
* Copyright 2013 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include "bson-memory.h"
#include "bson-string.h"
#include "bson-utf8.h"
/*
*--------------------------------------------------------------------------
*
* _bson_utf8_get_sequence --
*
* Determine the sequence length of the first UTF-8 character in
* @utf8. The sequence length is stored in @seq_length and the mask
* for the first character is stored in @first_mask.
*
* Returns:
* None.
*
* Side effects:
* @seq_length is set.
* @first_mask is set.
*
*--------------------------------------------------------------------------
*/
static BSON_INLINE void
_bson_utf8_get_sequence (const char *utf8, /* IN */
uint8_t *seq_length, /* OUT */
uint8_t *first_mask) /* OUT */
{
unsigned char c = *(const unsigned char *)utf8;
uint8_t m;
uint8_t n;
/*
* See the following[1] for a description of what the given multi-byte
* sequences will be based on the bits set of the first byte. We also need
* to mask the first byte based on that. All subsequent bytes are masked
* against 0x3F.
*
* [1] http://www.joelonsoftware.com/articles/Unicode.html
*/
if ((c & 0x80) == 0) {
n = 1;
m = 0x7F;
} else if ((c & 0xE0) == 0xC0) {
n = 2;
m = 0x1F;
} else if ((c & 0xF0) == 0xE0) {
n = 3;
m = 0x0F;
} else if ((c & 0xF8) == 0xF0) {
n = 4;
m = 0x07;
} else if ((c & 0xFC) == 0xF8) {
n = 5;
m = 0x03;
} else if ((c & 0xFE) == 0xFC) {
n = 6;
m = 0x01;
} else {
n = 0;
m = 0;
}
*seq_length = n;
*first_mask = m;
}
/*
*--------------------------------------------------------------------------
*
* bson_utf8_validate --
*
* Validates that @utf8 is a valid UTF-8 string.
*
* If @allow_null is true, then \0 is allowed within @utf8_len bytes
* of @utf8. Generally, this is bad practice since the main point of
* UTF-8 strings is that they can be used with strlen() and friends.
* However, some languages such as Python can send UTF-8 encoded
* strings with NUL's in them.
*
* Parameters:
* @utf8: A UTF-8 encoded string.
* @utf8_len: The length of @utf8 in bytes.
* @allow_null: If \0 is allowed within @utf8, exclusing trailing \0.
*
* Returns:
* true if @utf8 is valid UTF-8. otherwise false.
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
bool
bson_utf8_validate (const char *utf8, /* IN */
size_t utf8_len, /* IN */
bool allow_null) /* IN */
{
bson_unichar_t c;
uint8_t first_mask;
uint8_t seq_length;
unsigned i;
unsigned j;
BSON_ASSERT (utf8);
for (i = 0; i < utf8_len; i += seq_length) {
_bson_utf8_get_sequence (&utf8[i], &seq_length, &first_mask);
/*
* Ensure we have a valid multi-byte sequence length.
*/
if (!seq_length) {
return false;
}
/*
* Ensure we have enough bytes left.
*/
if ((utf8_len - i) < seq_length) {
return false;
}
/*
* Also calculate the next char as a unichar so we can
* check code ranges for non-shortest form.
*/
c = utf8 [i] & first_mask;
/*
* Check the high-bits for each additional sequence byte.
*/
for (j = i + 1; j < (i + seq_length); j++) {
c = (c << 6) | (utf8 [j] & 0x3F);
if ((utf8[j] & 0xC0) != 0x80) {
return false;
}
}
/*
* Check for NULL bytes afterwards.
*
* Hint: if you want to optimize this function, starting here to do
* this in the same pass as the data above would probably be a good
* idea. You would add a branch into the inner loop, but save possibly
* on cache-line bouncing on larger strings. Just a thought.
*/
if (!allow_null) {
for (j = 0; j < seq_length; j++) {
if (((i + j) > utf8_len) || !utf8[i + j]) {
return false;
}
}
}
/*
* Code point wont fit in utf-16, not allowed.
*/
if (c > 0x0010FFFF) {
return false;
}
/*
* Byte is in reserved range for UTF-16 high-marks
* for surrogate pairs.
*/
if ((c & 0xFFFFF800) == 0xD800) {
return false;
}
/*
* Check non-shortest form unicode.
*/
switch (seq_length) {
case 1:
if (c <= 0x007F) {
continue;
}
return false;
case 2:
if ((c >= 0x0080) && (c <= 0x07FF)) {
continue;
} else if (c == 0) {
/* Two-byte representation for NULL. */
continue;
}
return false;
case 3:
if (((c >= 0x0800) && (c <= 0x0FFF)) ||
((c >= 0x1000) && (c <= 0xFFFF))) {
continue;
}
return false;
case 4:
if (((c >= 0x10000) && (c <= 0x3FFFF)) ||
((c >= 0x40000) && (c <= 0xFFFFF)) ||
((c >= 0x100000) && (c <= 0x10FFFF))) {
continue;
}
return false;
default:
return false;
}
}
return true;
}
/*
*--------------------------------------------------------------------------
*
* bson_utf8_escape_for_json --
*
* Allocates a new string matching @utf8 except that special
* characters in JSON will be escaped. The resulting string is also
* UTF-8 encoded.
*
* Both " and \ characters will be escaped. Additionally, if a NUL
* byte is found before @utf8_len bytes, it will be converted to the
* two byte UTF-8 sequence.
*
* Parameters:
* @utf8: A UTF-8 encoded string.
* @utf8_len: The length of @utf8 in bytes or -1 if NUL terminated.
*
* Returns:
* A newly allocated string that should be freed with bson_free().
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
char *
bson_utf8_escape_for_json (const char *utf8, /* IN */
ssize_t utf8_len) /* IN */
{
bson_unichar_t c;
bson_string_t *str;
bool length_provided = true;
const char *end;
BSON_ASSERT (utf8);
str = bson_string_new (NULL);
if (utf8_len < 0) {
length_provided = false;
utf8_len = strlen (utf8);
}
end = utf8 + utf8_len;
while (utf8 < end) {
c = bson_utf8_get_char (utf8);
switch (c) {
case '\\':
case '"':
case '/':
bson_string_append_c (str, '\\');
bson_string_append_unichar (str, c);
break;
case '\b':
bson_string_append (str, "\\b");
break;
case '\f':
bson_string_append (str, "\\f");
break;
case '\n':
bson_string_append (str, "\\n");
break;
case '\r':
bson_string_append (str, "\\r");
break;
case '\t':
bson_string_append (str, "\\t");
break;
default:
if (c < ' ') {
bson_string_append_printf (str, "\\u%04u", (unsigned)c);
} else {
bson_string_append_unichar (str, c);
}
break;
}
if (c) {
utf8 = bson_utf8_next_char (utf8);
} else {
if (length_provided && !*utf8) {
/* we escaped nil as '\u0000', now advance past it */
utf8++;
} else {
/* invalid UTF-8 */
bson_string_free (str, true);
return NULL;
}
}
}
return bson_string_free (str, false);
}
/*
*--------------------------------------------------------------------------
*
* bson_utf8_get_char --
*
* Fetches the next UTF-8 character from the UTF-8 sequence.
*
* Parameters:
* @utf8: A string containing validated UTF-8.
*
* Returns:
* A 32-bit bson_unichar_t reprsenting the multi-byte sequence.
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
bson_unichar_t
bson_utf8_get_char (const char *utf8) /* IN */
{
bson_unichar_t c;
uint8_t mask;
uint8_t num;
int i;
BSON_ASSERT (utf8);
_bson_utf8_get_sequence (utf8, &num, &mask);
c = (*utf8) & mask;
for (i = 1; i < num; i++) {
c = (c << 6) | (utf8[i] & 0x3F);
}
return c;
}
/*
*--------------------------------------------------------------------------
*
* bson_utf8_next_char --
*
* Returns an incremented pointer to the beginning of the next
* multi-byte sequence in @utf8.
*
* Parameters:
* @utf8: A string containing validated UTF-8.
*
* Returns:
* An incremented pointer in @utf8.
*
* Side effects:
* None.
*
*--------------------------------------------------------------------------
*/
const char *
bson_utf8_next_char (const char *utf8) /* IN */
{
uint8_t mask;
uint8_t num;
BSON_ASSERT (utf8);
_bson_utf8_get_sequence (utf8, &num, &mask);
return utf8 + num;
}
/*
*--------------------------------------------------------------------------
*
* bson_utf8_from_unichar --
*
* Converts the unichar to a sequence of utf8 bytes and stores those
* in @utf8. The number of bytes in the sequence are stored in @len.
*
* Parameters:
* @unichar: A bson_unichar_t.
* @utf8: A location for the multi-byte sequence.
* @len: A location for number of bytes stored in @utf8.
*
* Returns:
* None.
*
* Side effects:
* @utf8 is set.
* @len is set.
*
*--------------------------------------------------------------------------
*/
void
bson_utf8_from_unichar (
bson_unichar_t unichar, /* IN */
char utf8[BSON_ENSURE_ARRAY_PARAM_SIZE(6)], /* OUT */
uint32_t *len) /* OUT */
{
BSON_ASSERT (utf8);
BSON_ASSERT (len);
if (unichar <= 0x7F) {
utf8[0] = unichar;
*len = 1;
} else if (unichar <= 0x7FF) {
*len = 2;
utf8[0] = 0xC0 | ((unichar >> 6) & 0x3F);
utf8[1] = 0x80 | ((unichar) & 0x3F);
} else if (unichar <= 0xFFFF) {
*len = 3;
utf8[0] = 0xE0 | ((unichar >> 12) & 0xF);
utf8[1] = 0x80 | ((unichar >> 6) & 0x3F);
utf8[2] = 0x80 | ((unichar) & 0x3F);
} else if (unichar <= 0x1FFFFF) {
*len = 4;
utf8[0] = 0xF0 | ((unichar >> 18) & 0x7);
utf8[1] = 0x80 | ((unichar >> 12) & 0x3F);
utf8[2] = 0x80 | ((unichar >> 6) & 0x3F);
utf8[3] = 0x80 | ((unichar) & 0x3F);
} else if (unichar <= 0x3FFFFFF) {
*len = 5;
utf8[0] = 0xF8 | ((unichar >> 24) & 0x3);
utf8[1] = 0x80 | ((unichar >> 18) & 0x3F);
utf8[2] = 0x80 | ((unichar >> 12) & 0x3F);
utf8[3] = 0x80 | ((unichar >> 6) & 0x3F);
utf8[4] = 0x80 | ((unichar) & 0x3F);
} else if (unichar <= 0x7FFFFFFF) {
*len = 6;
utf8[0] = 0xFC | ((unichar >> 31) & 0x1);
utf8[1] = 0x80 | ((unichar >> 25) & 0x3F);
utf8[2] = 0x80 | ((unichar >> 19) & 0x3F);
utf8[3] = 0x80 | ((unichar >> 13) & 0x3F);
utf8[4] = 0x80 | ((unichar >> 7) & 0x3F);
utf8[5] = 0x80 | ((unichar) & 0x1);
} else {
*len = 0;
}
}
| apache-2.0 |
wsyzxcn/tornado | dev/client/libs/minicap/jni/vendor/libjpeg-turbo/jni/vendor/libjpeg-turbo/libjpeg-turbo-1.4.1/jdmaster.c | 23 | 27782 | /*
* jdmaster.c
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 2002-2009 by Guido Vollbeding.
* libjpeg-turbo Modifications:
* Copyright (C) 2009-2011, D. R. Commander.
* Copyright (C) 2013, Linaro Limited.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains master control logic for the JPEG decompressor.
* These routines are concerned with selecting the modules to be executed
* and with determining the number of passes and the work to be done in each
* pass.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jpegcomp.h"
/* Private state */
typedef struct {
struct jpeg_decomp_master pub; /* public fields */
int pass_number; /* # of passes completed */
boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
/* Saved references to initialized quantizer modules,
* in case we need to switch modes.
*/
struct jpeg_color_quantizer * quantizer_1pass;
struct jpeg_color_quantizer * quantizer_2pass;
} my_decomp_master;
typedef my_decomp_master * my_master_ptr;
/*
* Determine whether merged upsample/color conversion should be used.
* CRUCIAL: this must match the actual capabilities of jdmerge.c!
*/
LOCAL(boolean)
use_merged_upsample (j_decompress_ptr cinfo)
{
#ifdef UPSAMPLE_MERGING_SUPPORTED
/* Merging is the equivalent of plain box-filter upsampling */
if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
return FALSE;
/* jdmerge.c only supports YCC=>RGB and YCC=>RGB565 color conversion */
if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
(cinfo->out_color_space != JCS_RGB &&
cinfo->out_color_space != JCS_RGB565 &&
cinfo->out_color_space != JCS_EXT_RGB &&
cinfo->out_color_space != JCS_EXT_RGBX &&
cinfo->out_color_space != JCS_EXT_BGR &&
cinfo->out_color_space != JCS_EXT_BGRX &&
cinfo->out_color_space != JCS_EXT_XBGR &&
cinfo->out_color_space != JCS_EXT_XRGB &&
cinfo->out_color_space != JCS_EXT_RGBA &&
cinfo->out_color_space != JCS_EXT_BGRA &&
cinfo->out_color_space != JCS_EXT_ABGR &&
cinfo->out_color_space != JCS_EXT_ARGB))
return FALSE;
if ((cinfo->out_color_space == JCS_RGB565 &&
cinfo->out_color_components != 3) ||
(cinfo->out_color_space != JCS_RGB565 &&
cinfo->out_color_components != rgb_pixelsize[cinfo->out_color_space]))
return FALSE;
/* and it only handles 2h1v or 2h2v sampling ratios */
if (cinfo->comp_info[0].h_samp_factor != 2 ||
cinfo->comp_info[1].h_samp_factor != 1 ||
cinfo->comp_info[2].h_samp_factor != 1 ||
cinfo->comp_info[0].v_samp_factor > 2 ||
cinfo->comp_info[1].v_samp_factor != 1 ||
cinfo->comp_info[2].v_samp_factor != 1)
return FALSE;
/* furthermore, it doesn't work if we've scaled the IDCTs differently */
if (cinfo->comp_info[0]._DCT_scaled_size != cinfo->_min_DCT_scaled_size ||
cinfo->comp_info[1]._DCT_scaled_size != cinfo->_min_DCT_scaled_size ||
cinfo->comp_info[2]._DCT_scaled_size != cinfo->_min_DCT_scaled_size)
return FALSE;
/* ??? also need to test for upsample-time rescaling, when & if supported */
return TRUE; /* by golly, it'll work... */
#else
return FALSE;
#endif
}
/*
* Compute output image dimensions and related values.
* NOTE: this is exported for possible use by application.
* Hence it mustn't do anything that can't be done twice.
*/
#if JPEG_LIB_VERSION >= 80
GLOBAL(void)
#else
LOCAL(void)
#endif
jpeg_core_output_dimensions (j_decompress_ptr cinfo)
/* Do computations that are needed before master selection phase.
* This function is used for transcoding and full decompression.
*/
{
#ifdef IDCT_SCALING_SUPPORTED
int ci;
jpeg_component_info *compptr;
/* Compute actual output image dimensions and DCT scaling choices. */
if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom) {
/* Provide 1/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 1;
cinfo->_min_DCT_v_scaled_size = 1;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 2) {
/* Provide 2/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 2L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 2L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 2;
cinfo->_min_DCT_v_scaled_size = 2;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 3) {
/* Provide 3/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 3L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 3L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 3;
cinfo->_min_DCT_v_scaled_size = 3;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 4) {
/* Provide 4/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 4L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 4L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 4;
cinfo->_min_DCT_v_scaled_size = 4;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 5) {
/* Provide 5/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 5L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 5L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 5;
cinfo->_min_DCT_v_scaled_size = 5;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 6) {
/* Provide 6/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 6L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 6L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 6;
cinfo->_min_DCT_v_scaled_size = 6;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 7) {
/* Provide 7/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 7L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 7L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 7;
cinfo->_min_DCT_v_scaled_size = 7;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 8) {
/* Provide 8/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 8L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 8L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 8;
cinfo->_min_DCT_v_scaled_size = 8;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 9) {
/* Provide 9/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 9L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 9L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 9;
cinfo->_min_DCT_v_scaled_size = 9;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 10) {
/* Provide 10/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 10L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 10L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 10;
cinfo->_min_DCT_v_scaled_size = 10;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 11) {
/* Provide 11/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 11L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 11L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 11;
cinfo->_min_DCT_v_scaled_size = 11;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 12) {
/* Provide 12/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 12L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 12L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 12;
cinfo->_min_DCT_v_scaled_size = 12;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 13) {
/* Provide 13/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 13L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 13L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 13;
cinfo->_min_DCT_v_scaled_size = 13;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 14) {
/* Provide 14/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 14L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 14L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 14;
cinfo->_min_DCT_v_scaled_size = 14;
} else if (cinfo->scale_num * DCTSIZE <= cinfo->scale_denom * 15) {
/* Provide 15/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 15L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 15L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 15;
cinfo->_min_DCT_v_scaled_size = 15;
} else {
/* Provide 16/block_size scaling */
cinfo->output_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width * 16L, (long) DCTSIZE);
cinfo->output_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height * 16L, (long) DCTSIZE);
cinfo->_min_DCT_h_scaled_size = 16;
cinfo->_min_DCT_v_scaled_size = 16;
}
/* Recompute dimensions of components */
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
compptr->_DCT_h_scaled_size = cinfo->_min_DCT_h_scaled_size;
compptr->_DCT_v_scaled_size = cinfo->_min_DCT_v_scaled_size;
}
#else /* !IDCT_SCALING_SUPPORTED */
/* Hardwire it to "no scaling" */
cinfo->output_width = cinfo->image_width;
cinfo->output_height = cinfo->image_height;
/* jdinput.c has already initialized DCT_scaled_size,
* and has computed unscaled downsampled_width and downsampled_height.
*/
#endif /* IDCT_SCALING_SUPPORTED */
}
/*
* Compute output image dimensions and related values.
* NOTE: this is exported for possible use by application.
* Hence it mustn't do anything that can't be done twice.
* Also note that it may be called before the master module is initialized!
*/
GLOBAL(void)
jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
/* Do computations that are needed before master selection phase */
{
#ifdef IDCT_SCALING_SUPPORTED
int ci;
jpeg_component_info *compptr;
#endif
/* Prevent application from calling me at wrong times */
if (cinfo->global_state != DSTATE_READY)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
/* Compute core output image dimensions and DCT scaling choices. */
jpeg_core_output_dimensions(cinfo);
#ifdef IDCT_SCALING_SUPPORTED
/* In selecting the actual DCT scaling for each component, we try to
* scale up the chroma components via IDCT scaling rather than upsampling.
* This saves time if the upsampler gets to use 1:1 scaling.
* Note this code adapts subsampling ratios which are powers of 2.
*/
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
int ssize = cinfo->_min_DCT_scaled_size;
while (ssize < DCTSIZE &&
((cinfo->max_h_samp_factor * cinfo->_min_DCT_scaled_size) %
(compptr->h_samp_factor * ssize * 2) == 0) &&
((cinfo->max_v_samp_factor * cinfo->_min_DCT_scaled_size) %
(compptr->v_samp_factor * ssize * 2) == 0)) {
ssize = ssize * 2;
}
#if JPEG_LIB_VERSION >= 70
compptr->DCT_h_scaled_size = compptr->DCT_v_scaled_size = ssize;
#else
compptr->DCT_scaled_size = ssize;
#endif
}
/* Recompute downsampled dimensions of components;
* application needs to know these if using raw downsampled data.
*/
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
/* Size in samples, after IDCT scaling */
compptr->downsampled_width = (JDIMENSION)
jdiv_round_up((long) cinfo->image_width *
(long) (compptr->h_samp_factor * compptr->_DCT_scaled_size),
(long) (cinfo->max_h_samp_factor * DCTSIZE));
compptr->downsampled_height = (JDIMENSION)
jdiv_round_up((long) cinfo->image_height *
(long) (compptr->v_samp_factor * compptr->_DCT_scaled_size),
(long) (cinfo->max_v_samp_factor * DCTSIZE));
}
#else /* !IDCT_SCALING_SUPPORTED */
/* Hardwire it to "no scaling" */
cinfo->output_width = cinfo->image_width;
cinfo->output_height = cinfo->image_height;
/* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
* and has computed unscaled downsampled_width and downsampled_height.
*/
#endif /* IDCT_SCALING_SUPPORTED */
/* Report number of components in selected colorspace. */
/* Probably this should be in the color conversion module... */
switch (cinfo->out_color_space) {
case JCS_GRAYSCALE:
cinfo->out_color_components = 1;
break;
case JCS_RGB:
case JCS_EXT_RGB:
case JCS_EXT_RGBX:
case JCS_EXT_BGR:
case JCS_EXT_BGRX:
case JCS_EXT_XBGR:
case JCS_EXT_XRGB:
case JCS_EXT_RGBA:
case JCS_EXT_BGRA:
case JCS_EXT_ABGR:
case JCS_EXT_ARGB:
cinfo->out_color_components = rgb_pixelsize[cinfo->out_color_space];
break;
case JCS_YCbCr:
case JCS_RGB565:
cinfo->out_color_components = 3;
break;
case JCS_CMYK:
case JCS_YCCK:
cinfo->out_color_components = 4;
break;
default: /* else must be same colorspace as in file */
cinfo->out_color_components = cinfo->num_components;
break;
}
cinfo->output_components = (cinfo->quantize_colors ? 1 :
cinfo->out_color_components);
/* See if upsampler will want to emit more than one row at a time */
if (use_merged_upsample(cinfo))
cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
else
cinfo->rec_outbuf_height = 1;
}
/*
* Several decompression processes need to range-limit values to the range
* 0..MAXJSAMPLE; the input value may fall somewhat outside this range
* due to noise introduced by quantization, roundoff error, etc. These
* processes are inner loops and need to be as fast as possible. On most
* machines, particularly CPUs with pipelines or instruction prefetch,
* a (subscript-check-less) C table lookup
* x = sample_range_limit[x];
* is faster than explicit tests
* if (x < 0) x = 0;
* else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
* These processes all use a common table prepared by the routine below.
*
* For most steps we can mathematically guarantee that the initial value
* of x is within MAXJSAMPLE+1 of the legal range, so a table running from
* -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
* limiting step (just after the IDCT), a wildly out-of-range value is
* possible if the input data is corrupt. To avoid any chance of indexing
* off the end of memory and getting a bad-pointer trap, we perform the
* post-IDCT limiting thus:
* x = range_limit[x & MASK];
* where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
* samples. Under normal circumstances this is more than enough range and
* a correct output will be generated; with bogus input data the mask will
* cause wraparound, and we will safely generate a bogus-but-in-range output.
* For the post-IDCT step, we want to convert the data from signed to unsigned
* representation by adding CENTERJSAMPLE at the same time that we limit it.
* So the post-IDCT limiting table ends up looking like this:
* CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
* MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
* 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
* 0,1,...,CENTERJSAMPLE-1
* Negative inputs select values from the upper half of the table after
* masking.
*
* We can save some space by overlapping the start of the post-IDCT table
* with the simpler range limiting table. The post-IDCT table begins at
* sample_range_limit + CENTERJSAMPLE.
*/
LOCAL(void)
prepare_range_limit_table (j_decompress_ptr cinfo)
/* Allocate and fill in the sample_range_limit table */
{
JSAMPLE * table;
int i;
table = (JSAMPLE *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
(5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * sizeof(JSAMPLE));
table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
cinfo->sample_range_limit = table;
/* First segment of "simple" table: limit[x] = 0 for x < 0 */
MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * sizeof(JSAMPLE));
/* Main part of "simple" table: limit[x] = x */
for (i = 0; i <= MAXJSAMPLE; i++)
table[i] = (JSAMPLE) i;
table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
/* End of simple table, rest of first half of post-IDCT table */
for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
table[i] = MAXJSAMPLE;
/* Second half of post-IDCT table */
MEMZERO(table + (2 * (MAXJSAMPLE+1)),
(2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * sizeof(JSAMPLE));
MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
cinfo->sample_range_limit, CENTERJSAMPLE * sizeof(JSAMPLE));
}
/*
* Master selection of decompression modules.
* This is done once at jpeg_start_decompress time. We determine
* which modules will be used and give them appropriate initialization calls.
* We also initialize the decompressor input side to begin consuming data.
*
* Since jpeg_read_header has finished, we know what is in the SOF
* and (first) SOS markers. We also have all the application parameter
* settings.
*/
LOCAL(void)
master_selection (j_decompress_ptr cinfo)
{
my_master_ptr master = (my_master_ptr) cinfo->master;
boolean use_c_buffer;
long samplesperrow;
JDIMENSION jd_samplesperrow;
/* Initialize dimensions and other stuff */
jpeg_calc_output_dimensions(cinfo);
prepare_range_limit_table(cinfo);
/* Width of an output scanline must be representable as JDIMENSION. */
samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
jd_samplesperrow = (JDIMENSION) samplesperrow;
if ((long) jd_samplesperrow != samplesperrow)
ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
/* Initialize my private state */
master->pass_number = 0;
master->using_merged_upsample = use_merged_upsample(cinfo);
/* Color quantizer selection */
master->quantizer_1pass = NULL;
master->quantizer_2pass = NULL;
/* No mode changes if not using buffered-image mode. */
if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
cinfo->enable_1pass_quant = FALSE;
cinfo->enable_external_quant = FALSE;
cinfo->enable_2pass_quant = FALSE;
}
if (cinfo->quantize_colors) {
if (cinfo->raw_data_out)
ERREXIT(cinfo, JERR_NOTIMPL);
/* 2-pass quantizer only works in 3-component color space. */
if (cinfo->out_color_components != 3) {
cinfo->enable_1pass_quant = TRUE;
cinfo->enable_external_quant = FALSE;
cinfo->enable_2pass_quant = FALSE;
cinfo->colormap = NULL;
} else if (cinfo->colormap != NULL) {
cinfo->enable_external_quant = TRUE;
} else if (cinfo->two_pass_quantize) {
cinfo->enable_2pass_quant = TRUE;
} else {
cinfo->enable_1pass_quant = TRUE;
}
if (cinfo->enable_1pass_quant) {
#ifdef QUANT_1PASS_SUPPORTED
jinit_1pass_quantizer(cinfo);
master->quantizer_1pass = cinfo->cquantize;
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
}
/* We use the 2-pass code to map to external colormaps. */
if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
#ifdef QUANT_2PASS_SUPPORTED
jinit_2pass_quantizer(cinfo);
master->quantizer_2pass = cinfo->cquantize;
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
}
/* If both quantizers are initialized, the 2-pass one is left active;
* this is necessary for starting with quantization to an external map.
*/
}
/* Post-processing: in particular, color conversion first */
if (! cinfo->raw_data_out) {
if (master->using_merged_upsample) {
#ifdef UPSAMPLE_MERGING_SUPPORTED
jinit_merged_upsampler(cinfo); /* does color conversion too */
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
} else {
jinit_color_deconverter(cinfo);
jinit_upsampler(cinfo);
}
jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
}
/* Inverse DCT */
jinit_inverse_dct(cinfo);
/* Entropy decoding: either Huffman or arithmetic coding. */
if (cinfo->arith_code) {
#ifdef D_ARITH_CODING_SUPPORTED
jinit_arith_decoder(cinfo);
#else
ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
#endif
} else {
if (cinfo->progressive_mode) {
#ifdef D_PROGRESSIVE_SUPPORTED
jinit_phuff_decoder(cinfo);
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
} else
jinit_huff_decoder(cinfo);
}
/* Initialize principal buffer controllers. */
use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
jinit_d_coef_controller(cinfo, use_c_buffer);
if (! cinfo->raw_data_out)
jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
/* We can now tell the memory manager to allocate virtual arrays. */
(*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
/* Initialize input side of decompressor to consume first scan. */
(*cinfo->inputctl->start_input_pass) (cinfo);
#ifdef D_MULTISCAN_FILES_SUPPORTED
/* If jpeg_start_decompress will read the whole file, initialize
* progress monitoring appropriately. The input step is counted
* as one pass.
*/
if (cinfo->progress != NULL && ! cinfo->buffered_image &&
cinfo->inputctl->has_multiple_scans) {
int nscans;
/* Estimate number of scans to set pass_limit. */
if (cinfo->progressive_mode) {
/* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
nscans = 2 + 3 * cinfo->num_components;
} else {
/* For a nonprogressive multiscan file, estimate 1 scan per component. */
nscans = cinfo->num_components;
}
cinfo->progress->pass_counter = 0L;
cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
cinfo->progress->completed_passes = 0;
cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
/* Count the input pass as done */
master->pass_number++;
}
#endif /* D_MULTISCAN_FILES_SUPPORTED */
}
/*
* Per-pass setup.
* This is called at the beginning of each output pass. We determine which
* modules will be active during this pass and give them appropriate
* start_pass calls. We also set is_dummy_pass to indicate whether this
* is a "real" output pass or a dummy pass for color quantization.
* (In the latter case, jdapistd.c will crank the pass to completion.)
*/
METHODDEF(void)
prepare_for_output_pass (j_decompress_ptr cinfo)
{
my_master_ptr master = (my_master_ptr) cinfo->master;
if (master->pub.is_dummy_pass) {
#ifdef QUANT_2PASS_SUPPORTED
/* Final pass of 2-pass quantization */
master->pub.is_dummy_pass = FALSE;
(*cinfo->cquantize->start_pass) (cinfo, FALSE);
(*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
(*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif /* QUANT_2PASS_SUPPORTED */
} else {
if (cinfo->quantize_colors && cinfo->colormap == NULL) {
/* Select new quantization method */
if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
cinfo->cquantize = master->quantizer_2pass;
master->pub.is_dummy_pass = TRUE;
} else if (cinfo->enable_1pass_quant) {
cinfo->cquantize = master->quantizer_1pass;
} else {
ERREXIT(cinfo, JERR_MODE_CHANGE);
}
}
(*cinfo->idct->start_pass) (cinfo);
(*cinfo->coef->start_output_pass) (cinfo);
if (! cinfo->raw_data_out) {
if (! master->using_merged_upsample)
(*cinfo->cconvert->start_pass) (cinfo);
(*cinfo->upsample->start_pass) (cinfo);
if (cinfo->quantize_colors)
(*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
(*cinfo->post->start_pass) (cinfo,
(master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
(*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
}
}
/* Set up progress monitor's pass info if present */
if (cinfo->progress != NULL) {
cinfo->progress->completed_passes = master->pass_number;
cinfo->progress->total_passes = master->pass_number +
(master->pub.is_dummy_pass ? 2 : 1);
/* In buffered-image mode, we assume one more output pass if EOI not
* yet reached, but no more passes if EOI has been reached.
*/
if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
}
}
}
/*
* Finish up at end of an output pass.
*/
METHODDEF(void)
finish_output_pass (j_decompress_ptr cinfo)
{
my_master_ptr master = (my_master_ptr) cinfo->master;
if (cinfo->quantize_colors)
(*cinfo->cquantize->finish_pass) (cinfo);
master->pass_number++;
}
#ifdef D_MULTISCAN_FILES_SUPPORTED
/*
* Switch to a new external colormap between output passes.
*/
GLOBAL(void)
jpeg_new_colormap (j_decompress_ptr cinfo)
{
my_master_ptr master = (my_master_ptr) cinfo->master;
/* Prevent application from calling me at wrong times */
if (cinfo->global_state != DSTATE_BUFIMAGE)
ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
if (cinfo->quantize_colors && cinfo->enable_external_quant &&
cinfo->colormap != NULL) {
/* Select 2-pass quantizer for external colormap use */
cinfo->cquantize = master->quantizer_2pass;
/* Notify quantizer of colormap change */
(*cinfo->cquantize->new_color_map) (cinfo);
master->pub.is_dummy_pass = FALSE; /* just in case */
} else
ERREXIT(cinfo, JERR_MODE_CHANGE);
}
#endif /* D_MULTISCAN_FILES_SUPPORTED */
/*
* Initialize master decompression control and select active modules.
* This is performed at the start of jpeg_start_decompress.
*/
GLOBAL(void)
jinit_master_decompress (j_decompress_ptr cinfo)
{
my_master_ptr master;
master = (my_master_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
sizeof(my_decomp_master));
cinfo->master = (struct jpeg_decomp_master *) master;
master->pub.prepare_for_output_pass = prepare_for_output_pass;
master->pub.finish_output_pass = finish_output_pass;
master->pub.is_dummy_pass = FALSE;
master_selection(cinfo);
}
| apache-2.0 |
vic/otp | erts/emulator/beam/erl_term.c | 23 | 6964 | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2000-2013. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include "sys.h"
#include "erl_vm.h"
#include "global.h"
#include "erl_map.h"
#include <stdlib.h>
#include <stdio.h>
__decl_noreturn static void __noreturn
et_abort(const char *expr, const char *file, unsigned line)
{
#ifdef EXIT_ON_ET_ABORT
static int have_been_called = 0;
if (have_been_called) {
abort();
} else {
/*
* Prevent infinite loop.
*/
have_been_called = 1;
erl_exit(1, "TYPE ASSERTION FAILED, file %s, line %u: %s\n", file, line, expr);
}
#else
erts_fprintf(stderr, "TYPE ASSERTION FAILED, file %s, line %u: %s\n", file, line, expr);
abort();
#endif
}
#if ET_DEBUG
#define ET_ASSERT(expr,file,line) \
do { \
if (!(expr)) \
et_abort(#expr, file, line); \
} while(0)
#else
#define ET_ASSERT(expr,file,line) do { } while(0)
#endif
#if ET_DEBUG
unsigned tag_val_def_debug(Wterm x, const char *file, unsigned line)
#else
unsigned tag_val_def(Wterm x)
#define file __FILE__
#define line __LINE__
#endif
{
static char msg[32];
switch (x & _TAG_PRIMARY_MASK) {
case TAG_PRIMARY_LIST:
ET_ASSERT(_list_precond(x),file,line);
return LIST_DEF;
case TAG_PRIMARY_BOXED: {
Eterm hdr = *boxed_val(x);
ET_ASSERT(is_header(hdr),file,line);
switch ((hdr & _TAG_HEADER_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_HEADER_ARITYVAL >> _TAG_PRIMARY_SIZE): return TUPLE_DEF;
case (_TAG_HEADER_POS_BIG >> _TAG_PRIMARY_SIZE): return BIG_DEF;
case (_TAG_HEADER_NEG_BIG >> _TAG_PRIMARY_SIZE): return BIG_DEF;
case (_TAG_HEADER_REF >> _TAG_PRIMARY_SIZE): return REF_DEF;
case (_TAG_HEADER_FLOAT >> _TAG_PRIMARY_SIZE): return FLOAT_DEF;
case (_TAG_HEADER_EXPORT >> _TAG_PRIMARY_SIZE): return EXPORT_DEF;
case (_TAG_HEADER_FUN >> _TAG_PRIMARY_SIZE): return FUN_DEF;
case (_TAG_HEADER_EXTERNAL_PID >> _TAG_PRIMARY_SIZE): return EXTERNAL_PID_DEF;
case (_TAG_HEADER_EXTERNAL_PORT >> _TAG_PRIMARY_SIZE): return EXTERNAL_PORT_DEF;
case (_TAG_HEADER_EXTERNAL_REF >> _TAG_PRIMARY_SIZE): return EXTERNAL_REF_DEF;
case (_TAG_HEADER_MAP >> _TAG_PRIMARY_SIZE): return MAP_DEF;
case (_TAG_HEADER_REFC_BIN >> _TAG_PRIMARY_SIZE): return BINARY_DEF;
case (_TAG_HEADER_HEAP_BIN >> _TAG_PRIMARY_SIZE): return BINARY_DEF;
case (_TAG_HEADER_SUB_BIN >> _TAG_PRIMARY_SIZE): return BINARY_DEF;
}
break;
}
case TAG_PRIMARY_IMMED1: {
switch ((x & _TAG_IMMED1_MASK) >> _TAG_PRIMARY_SIZE) {
case (_TAG_IMMED1_PID >> _TAG_PRIMARY_SIZE): return PID_DEF;
case (_TAG_IMMED1_PORT >> _TAG_PRIMARY_SIZE): return PORT_DEF;
case (_TAG_IMMED1_IMMED2 >> _TAG_PRIMARY_SIZE): {
switch ((x & _TAG_IMMED2_MASK) >> _TAG_IMMED1_SIZE) {
case (_TAG_IMMED2_ATOM >> _TAG_IMMED1_SIZE): return ATOM_DEF;
case (_TAG_IMMED2_NIL >> _TAG_IMMED1_SIZE): return NIL_DEF;
}
break;
}
case (_TAG_IMMED1_SMALL >> _TAG_PRIMARY_SIZE): return SMALL_DEF;
}
break;
}
}
erts_snprintf(msg, sizeof(msg), "tag_val_def: %#lx", (unsigned long) x);
et_abort(msg, file, line);
#undef file
#undef line
}
/*
* XXX: define NUMBER_CODE() here when new representation is used
*/
#if ET_DEBUG
#define ET_DEFINE_CHECKED(FUNTY,FUN,ARGTY,PRECOND) \
FUNTY checked_##FUN(ARGTY x, const char *file, unsigned line) \
{ \
ET_ASSERT(PRECOND(x),file,line); \
return _unchecked_##FUN(x); \
}
ET_DEFINE_CHECKED(Eterm,make_boxed,const Eterm*,_is_taggable_pointer);
ET_DEFINE_CHECKED(int,is_boxed,Eterm,!is_header);
ET_DEFINE_CHECKED(Eterm*,boxed_val,Wterm,_boxed_precond);
ET_DEFINE_CHECKED(Eterm,make_list,const Eterm*,_is_taggable_pointer);
ET_DEFINE_CHECKED(int,is_not_list,Eterm,!is_header);
ET_DEFINE_CHECKED(Eterm*,list_val,Wterm,_list_precond);
ET_DEFINE_CHECKED(Uint,unsigned_val,Eterm,is_small);
ET_DEFINE_CHECKED(Sint,signed_val,Eterm,is_small);
ET_DEFINE_CHECKED(Uint,atom_val,Eterm,is_atom);
ET_DEFINE_CHECKED(Uint,header_arity,Eterm,is_header);
ET_DEFINE_CHECKED(Uint,arityval,Eterm,is_sane_arity_value);
ET_DEFINE_CHECKED(Uint,thing_arityval,Eterm,is_thing);
ET_DEFINE_CHECKED(Uint,thing_subtag,Eterm,is_thing);
ET_DEFINE_CHECKED(Eterm*,binary_val,Wterm,is_binary);
ET_DEFINE_CHECKED(Eterm*,fun_val,Wterm,is_fun);
ET_DEFINE_CHECKED(int,bignum_header_is_neg,Eterm,_is_bignum_header);
ET_DEFINE_CHECKED(Eterm,bignum_header_neg,Eterm,_is_bignum_header);
ET_DEFINE_CHECKED(Uint,bignum_header_arity,Eterm,_is_bignum_header);
ET_DEFINE_CHECKED(Eterm*,big_val,Wterm,is_big);
ET_DEFINE_CHECKED(Eterm*,float_val,Wterm,is_float);
ET_DEFINE_CHECKED(Eterm*,tuple_val,Wterm,is_tuple);
ET_DEFINE_CHECKED(struct erl_node_*,internal_pid_node,Eterm,is_internal_pid);
ET_DEFINE_CHECKED(struct erl_node_*,internal_port_node,Eterm,is_internal_port);
ET_DEFINE_CHECKED(Eterm*,internal_ref_val,Wterm,is_internal_ref);
ET_DEFINE_CHECKED(Uint,internal_ref_data_words,Wterm,is_internal_ref);
ET_DEFINE_CHECKED(Uint32*,internal_ref_data,Wterm,is_internal_ref);
ET_DEFINE_CHECKED(struct erl_node_*,internal_ref_node,Eterm,is_internal_ref);
ET_DEFINE_CHECKED(Eterm*,external_val,Wterm,is_external);
ET_DEFINE_CHECKED(Uint,external_data_words,Wterm,is_external);
ET_DEFINE_CHECKED(Uint,external_pid_data_words,Wterm,is_external_pid);
ET_DEFINE_CHECKED(Uint,external_pid_data,Wterm,is_external_pid);
ET_DEFINE_CHECKED(struct erl_node_*,external_pid_node,Wterm,is_external_pid);
ET_DEFINE_CHECKED(Uint,external_port_data_words,Wterm,is_external_port);
ET_DEFINE_CHECKED(Uint,external_port_data,Wterm,is_external_port);
ET_DEFINE_CHECKED(struct erl_node_*,external_port_node,Wterm,is_external_port);
ET_DEFINE_CHECKED(Uint,external_ref_data_words,Wterm,is_external_ref);
ET_DEFINE_CHECKED(Uint32*,external_ref_data,Wterm,is_external_ref);
ET_DEFINE_CHECKED(struct erl_node_*,external_ref_node,Eterm,is_external_ref);
ET_DEFINE_CHECKED(Eterm*,export_val,Wterm,is_export);
ET_DEFINE_CHECKED(Uint,external_thing_data_words,ExternalThing*,is_thing_ptr);
ET_DEFINE_CHECKED(Eterm,make_cp,UWord *,_is_taggable_pointer);
ET_DEFINE_CHECKED(UWord *,cp_val,Eterm,is_CP);
ET_DEFINE_CHECKED(Uint,catch_val,Eterm,is_catch);
ET_DEFINE_CHECKED(Uint,x_reg_offset,Uint,_is_xreg);
ET_DEFINE_CHECKED(Uint,y_reg_offset,Uint,_is_yreg);
ET_DEFINE_CHECKED(Uint,x_reg_index,Uint,_is_xreg);
ET_DEFINE_CHECKED(Uint,y_reg_index,Uint,_is_yreg);
#endif /* ET_DEBUG */
| apache-2.0 |
inonomori/opencore-amr-iOS | opencore/codecs_v2/audio/gsm_amr/amr_nb/enc/src/c4_17pf.cpp | 28 | 28881 | /* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
* -------------------------------------------------------------------
*/
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:
3GPP TS 26.073
ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
Available from http://www.3gpp.org
(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*
------------------------------------------------------------------------------
Filename: c4_17pf.cpp
------------------------------------------------------------------------------
MODULE DESCRIPTION
Purpose : Searches a 17 bit algebraic codebook containing 4 pulses
in a frame of 40 samples
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "c4_17pf.h"
#include "typedef.h"
#include "inv_sqrt.h"
#include "cnst.h"
#include "cor_h.h"
#include "set_sign.h"
#include "basic_op.h"
/*--------------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C"
{
#endif
/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here. Include conditional
; compile variables also.
----------------------------------------------------------------------------*/
#define NB_PULSE 4
/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/
static void search_4i40(
Word16 dn[], /* i : correlation between target and h[] */
Word16 dn2[], /* i : maximum of corr. in each track. */
Word16 rr[][L_CODE],/* i : matrix of autocorrelation */
Word16 codvec[], /* o : algebraic codebook vector */
Flag * pOverflow /* o : Flag set when overflow occurs */
);
static Word16 build_code(
Word16 codvec[], /* i : algebraic codebook vector */
Word16 dn_sign[], /* i : sign of dn[] */
Word16 cod[], /* o : algebraic (fixed) codebook excitation */
Word16 h[], /* i : impulse response of weighted synthesis filter */
Word16 y[], /* o : filtered fixed codebook excitation */
Word16 sign[], /* o : index of 4 pulses (position+sign+ampl)*4 */
const Word16* gray_ptr, /* i : ptr to read-only table */
Flag * pOverflow /* o : Flag set when overflow occurs */
);
/*----------------------------------------------------------------------------
; LOCAL VARIABLE DEFINITIONS
; Variable declaration - defined here and used outside this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/
/*
------------------------------------------------------------------------------
FUNCTION NAME: code_4i40_17bits()
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
Inputs:
x[] Array of type Word16 -- target vector
h[] Array of type Word16 -- impulse response of weighted synthesis filter
h[-L_subfr..-1] must be set to zero.
T0 Array of type Word16 -- Pitch lag
pitch_sharp, Array of type Word16 -- Last quantized pitch gain
Outputs:
code[] Array of type Word16 -- Innovative codebook
y[] Array of type Word16 -- filtered fixed codebook excitation
* sign Pointer of type Word16 -- Pointer to the signs of 4 pulses
pOverflow Pointer to Flag -- set when overflow occurs
Returns:
index
Global Variables Used:
None
Local Variables Needed:
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
PURPOSE: Searches a 17 bit algebraic codebook containing 4 pulses
in a frame of 40 samples.
DESCRIPTION:
The code length is 40, containing 4 nonzero pulses: i0...i3.
All pulses can have two possible amplitudes: +1 or -1.
Pulse i0 to i2 can have 8 possible positions, pulse i3 can have
2x8=16 positions.
i0 : 0, 5, 10, 15, 20, 25, 30, 35.
i1 : 1, 6, 11, 16, 21, 26, 31, 36.
i2 : 2, 7, 12, 17, 22, 27, 32, 37.
i3 : 3, 8, 13, 18, 23, 28, 33, 38.
4, 9, 14, 19, 24, 29, 34, 39.
------------------------------------------------------------------------------
REQUIREMENTS
None
------------------------------------------------------------------------------
REFERENCES
[1] c3_14pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
------------------------------------------------------------------------------
PSEUDO-CODE
------------------------------------------------------------------------------
CAUTION [optional]
[State any special notes, constraints or cautions for users of this function]
------------------------------------------------------------------------------
*/
Word16 code_4i40_17bits(
Word16 x[], /* i : target vector */
Word16 h[], /* i : impulse response of weighted synthesis filter */
/* h[-L_subfr..-1] must be set to zero. */
Word16 T0, /* i : Pitch lag */
Word16 pitch_sharp, /* i : Last quantized pitch gain */
Word16 code[], /* o : Innovative codebook */
Word16 y[], /* o : filtered fixed codebook excitation */
Word16 * sign, /* o : Signs of 4 pulses */
const Word16* gray_ptr, /* i : ptr to read-only table */
Flag * pOverflow /* o : Flag set when overflow occurs */
)
{
Word16 codvec[NB_PULSE];
Word16 dn[L_CODE];
Word16 dn2[L_CODE];
Word16 dn_sign[L_CODE];
Word16 rr[L_CODE][L_CODE];
Word16 i;
Word16 index;
Word16 sharp;
Word16 tempWord;
sharp = pitch_sharp << 1;
if (T0 < L_CODE)
{
for (i = T0; i < L_CODE; i++)
{
tempWord =
mult(
h[i - T0],
sharp,
pOverflow);
h[i] =
add_16(
h[i],
tempWord,
pOverflow);
}
}
cor_h_x(
h,
x,
dn,
1,
pOverflow);
set_sign(
dn,
dn_sign,
dn2,
4);
cor_h(
h,
dn_sign,
rr,
pOverflow);
search_4i40(
dn,
dn2,
rr,
codvec,
pOverflow);
/* function result */
index =
build_code(
codvec,
dn_sign,
code,
h,
y,
sign,
gray_ptr,
pOverflow);
/*-----------------------------------------------------------------*
* Compute innovation vector gain. *
* Include fixed-gain pitch contribution into code[]. *
*-----------------------------------------------------------------*/
tempWord = T0 - L_CODE;
if (tempWord < 0)
{
for (i = T0; i < L_CODE; i++)
{
tempWord =
mult(
code[i - T0],
sharp,
pOverflow);
code[i] =
add_16(
code[i],
tempWord,
pOverflow);
}
}
return index;
}
/****************************************************************************/
/*
------------------------------------------------------------------------------
FUNCTION NAME: search_4i40()
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
Inputs:
dn[] Array of type Word16 -- correlation between target and h[]
dn2[] Array of type Word16 -- maximum of corr. in each track.
rr[][L_CODE] Double Array of type Word16 -- autocorrelation matrix
Outputs:
codvec[] Array of type Word16 -- algebraic codebook vector
pOverflow Pointer to Flag -- set when overflow occurs
Returns:
Global Variables Used:
None
Local Variables Needed:
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
PURPOSE: Search the best codevector; determine positions of the 4 pulses
in the 40-sample frame.
------------------------------------------------------------------------------
REQUIREMENTS
None
------------------------------------------------------------------------------
REFERENCES
[1] c4_17pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
------------------------------------------------------------------------------
PSEUDO-CODE
------------------------------------------------------------------------------
CAUTION [optional]
[State any special notes, constraints or cautions for users of this function]
------------------------------------------------------------------------------
*/
static void search_4i40(
Word16 dn[], /* i : correlation between target and h[] */
Word16 dn2[], /* i : maximum of corr. in each track. */
Word16 rr[][L_CODE], /* i : matrix of autocorrelation */
Word16 codvec[], /* o : algebraic codebook vector */
Flag * pOverflow /* o : Flag set when overflow occurs */
)
{
Word16 i0;
Word16 i1;
Word16 i2;
Word16 i3;
Word16 ix = 0; /* initialization only needed to keep gcc silent */
Word16 ps = 0; /* initialization only needed to keep gcc silent */
Word16 i;
Word16 pos;
Word16 track;
Word16 ipos[NB_PULSE];
Word16 psk;
Word16 ps0;
Word16 ps1;
Word16 sq;
Word16 sq1;
Word16 alpk;
Word16 alp;
Word16 alp_16;
Word16 *p_codvec = &codvec[0];
Word32 s;
Word32 alp0;
Word32 alp1;
OSCL_UNUSED_ARG(pOverflow);
/* Default value */
psk = -1;
alpk = 1;
for (i = 0; i < NB_PULSE; i++)
{
*(p_codvec++) = i;
}
for (track = 3; track < 5; track++)
{
/* fix starting position */
ipos[0] = 0;
ipos[1] = 1;
ipos[2] = 2;
ipos[3] = track;
/*------------------------------------------------------------------*
* main loop: try 4 tracks. *
*------------------------------------------------------------------*/
for (i = 0; i < NB_PULSE; i++)
{
/*----------------------------------------------------------------*
* i0 loop: try 4 positions (use position with max of corr.). *
*----------------------------------------------------------------*/
for (i0 = ipos[0]; i0 < L_CODE; i0 += STEP)
{
if (dn2[i0] >= 0)
{
ps0 = dn[i0];
alp0 = (Word32) rr[i0][i0] << 14;
/*----------------------------------------------------------------*
* i1 loop: 8 positions. *
*----------------------------------------------------------------*/
sq = -1;
alp = 1;
ps = 0;
ix = ipos[1];
/* initialize 4 index for next loop. */
/*-------------------------------------------------------------------*
* These index have low complexity address computation because *
* they are, in fact, pointers with fixed increment. For example, *
* "rr[i0][i3]" is a pointer initialized to "&rr[i0][ipos[3]]" *
* and incremented by "STEP". *
*-------------------------------------------------------------------*/
for (i1 = ipos[1]; i1 < L_CODE; i1 += STEP)
{
/* idx increment = STEP */
/* ps1 = add(ps0, dn[i1], pOverflow); */
ps1 = ps0 + dn[i1];
/* alp1 = alp0 + rr[i0][i1] + 1/2*rr[i1][i1]; */
/* alp1 = L_mac(alp0, rr[i1][i1], _1_4, pOverflow); */
alp1 = alp0 + ((Word32) rr[i1][i1] << 14);
/* alp1 = L_mac(alp1, rr[i0][i1], _1_2, pOverflow); */
alp1 += (Word32) rr[i0][i1] << 15;
/* sq1 = mult(ps1, ps1, pOverflow); */
sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
/* alp_16 = pv_round(alp1, pOverflow); */
alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
/* s = L_mult(alp, sq1, pOverflow); */
s = ((Word32) alp * sq1) << 1;
/* s = L_msu(s, sq, alp_16, pOverflow); */
s -= (((Word32) sq * alp_16) << 1);
if (s > 0)
{
sq = sq1;
ps = ps1;
alp = alp_16;
ix = i1;
}
}
i1 = ix;
/*----------------------------------------------------------------*
* i2 loop: 8 positions. *
*----------------------------------------------------------------*/
ps0 = ps;
/* alp0 = L_mult(alp, _1_4, pOverflow); */
alp0 = (Word32) alp << 14;
sq = -1;
alp = 1;
ps = 0;
ix = ipos[2];
/* initialize 4 index for next loop (see i1 loop) */
for (i2 = ipos[2]; i2 < L_CODE; i2 += STEP)
{
/* index increment = STEP */
/* ps1 = add(ps0, dn[i2], pOverflow); */
ps1 = ps0 + dn[i2];
/* alp1 = alp0 + rr[i0][i2] + rr[i1][i2] + 1/2*rr[i2][i2]; */
/* idx incr = STEP */
/* alp1 = L_mac(alp0, rr[i2][i2], _1_16, pOverflow); */
alp1 = alp0 + ((Word32) rr[i2][i2] << 12);
/* idx incr = STEP */
/* alp1 = L_mac(alp1, rr[i1][i2], _1_8, pOverflow); */
alp1 += (Word32) rr[i1][i2] << 13;
/* idx incr = STEP */
/* alp1 = L_mac(alp1,rr[i0][i2], _1_8, pOverflow); */
alp1 += (Word32) rr[i0][i2] << 13;
/* sq1 = mult(ps1, ps1, pOverflow); */
sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
/* alp_16 = pv_round(alp1, pOverflow); */
alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
/* s = L_mult(alp, sq1, pOverflow); */
s = ((Word32) alp * sq1) << 1;
/* s = L_msu(s, sq, alp_16, pOverflow); */
s -= (((Word32) sq * alp_16) << 1);
if (s > 0)
{
sq = sq1;
ps = ps1;
alp = alp_16;
ix = i2;
}
}
i2 = ix;
/*----------------------------------------------------------------*
* i3 loop: 8 positions. *
*----------------------------------------------------------------*/
ps0 = ps;
alp0 = ((Word32)alp << 16);
sq = -1;
alp = 1;
ps = 0;
ix = ipos[3];
/* initialize 5 index for next loop (see i1 loop) */
for (i3 = ipos[3]; i3 < L_CODE; i3 += STEP)
{
/* ps1 = add(ps0, dn[i3], pOverflow); */
ps1 = ps0 + dn[i3]; /* index increment = STEP */
/* alp1 = alp0 + rr[i0][i3] + rr[i1][i3] + rr[i2][i3] + 1/2*rr[i3][i3]; */
/* alp1 = L_mac(alp0, rr[i3][i3], _1_16, pOverflow); */
alp1 = alp0 + ((Word32) rr[i3][i3] << 12); /* idx incr = STEP */
/* alp1 = L_mac(alp1, rr[i2][i3], _1_8, pOverflow); */
alp1 += (Word32) rr[i2][i3] << 13; /* idx incr = STEP */
/* alp1 = L_mac(alp1, rr[i1][i3], _1_8, pOverflow); */
alp1 += (Word32) rr[i1][i3] << 13; /* idx incr = STEP */
/* alp1 = L_mac(alp1, rr[i0][i3], _1_8, pOverflow); */
alp1 += (Word32) rr[i0][i3] << 13; /* idx incr = STEP */
/* sq1 = mult(ps1, ps1, pOverflow); */
sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
/* alp_16 = pv_round(alp1, pOverflow); */
alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
/* s = L_mult(alp, sq1, pOverflow); */
s = ((Word32) alp * sq1) << 1;
/* s = L_msu(s, sq, alp_16, pOverflow); */
s -= (((Word32) sq * alp_16) << 1);
if (s > 0)
{
sq = sq1;
ps = ps1;
alp = alp_16;
ix = i3;
}
}
/*----------------------------------------------------------------*
* memorise codevector if this one is better than the last one. *
*----------------------------------------------------------------*/
/* s = L_mult(alpk, sq, pOverflow); */
s = ((Word32) alpk * sq) << 1;
/* s = L_msu(s, psk, alp, pOverflow); */
s -= (((Word32) psk * alp) << 1);
if (s > 0)
{
psk = sq;
alpk = alp;
p_codvec = &codvec[0];
*(p_codvec++) = i0;
*(p_codvec++) = i1;
*(p_codvec++) = i2;
*(p_codvec) = ix;
}
}
}
/*----------------------------------------------------------------*
* Cyclic permutation of i0,i1,i2 and i3. *
*----------------------------------------------------------------*/
pos = ipos[3];
ipos[3] = ipos[2];
ipos[2] = ipos[1];
ipos[1] = ipos[0];
ipos[0] = pos;
}
}
return;
}
/****************************************************************************/
/*
------------------------------------------------------------------------------
FUNCTION NAME: build_code()
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
Inputs:
codvec[] Array of type Word16 -- position of pulses
dn_sign[] Array of type Word16 -- sign of pulses
h[] Array of type Word16 -- impulse response of
weighted synthesis filter
Outputs:
cod[] Array of type Word16 -- innovative code vector
y[] Array of type Word16 -- filtered innovative code
sign[] Array of type Word16 -- index of 4 pulses (sign + position)
pOverflow Pointer to Flag -- set when overflow occurs
Returns:
indx
Global Variables Used:
None
Local Variables Needed:
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
PURPOSE: Builds the codeword, the filtered codeword and index of the
codevector, based on the signs and positions of 4 pulses.
------------------------------------------------------------------------------
REQUIREMENTS
None
------------------------------------------------------------------------------
REFERENCES
[1] c4_17pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
------------------------------------------------------------------------------
PSEUDO-CODE
------------------------------------------------------------------------------
CAUTION [optional]
[State any special notes, constraints or cautions for users of this function]
------------------------------------------------------------------------------
*/
static Word16
build_code(
Word16 codvec[], /* i : position of pulses */
Word16 dn_sign[], /* i : sign of pulses */
Word16 cod[], /* o : innovative code vector */
Word16 h[], /* i : impulse response of weighted synthesis filter */
Word16 y[], /* o : filtered innovative code */
Word16 sign[], /* o : index of 4 pulses (sign+position) */
const Word16* gray_ptr, /* i : ptr to read-only table */
Flag * pOverflow /* o : Flag set when overflow occurs */
)
{
Word16 i;
Word16 j;
Word16 k;
Word16 track;
Word16 index;
Word16 _sign[NB_PULSE];
Word16 indx;
Word16 rsign;
Word16 *p0;
Word16 *p1;
Word16 *p2;
Word16 *p3;
Word16 *p_cod = &cod[0];
Word32 s;
for (i = 0; i < L_CODE; i++)
{
*(p_cod++) = 0;
}
indx = 0;
rsign = 0;
for (k = 0; k < NB_PULSE; k++)
{
i = codvec[k]; /* read pulse position */
j = dn_sign[i]; /* read sign */
/* index = pos/5 */
/* index = mult(i, 6554, pOverflow); */
index = (Word16)(((Word32) i * 6554) >> 15);
/* track = pos%5 */
/* s = L_mult(index, 5, pOverflow); */
s = ((Word32) index * 5) << 1;
/* s = L_shr(s, 1, pOverflow); */
s >>= 1;
/* track = sub(i, (Word16) s, pOverflow); */
track = i - (Word16) s;
index = gray_ptr[index];
if (track == 1)
{
/* index = shl(index, 3, pOverflow); */
index <<= 3;
}
else if (track == 2)
{
/* index = shl(index, 6, pOverflow); */
index <<= 6;
}
else if (track == 3)
{
/* index = shl(index, 10, pOverflow); */
index <<= 10;
}
else if (track == 4)
{
track = 3;
/* index = shl(index, 10, pOverflow); */
index <<= 10;
/* index = add(index, 512, pOverflow); */
index += 512;
}
if (j > 0)
{
cod[i] = 8191;
_sign[k] = 32767;
/* track = shl(1, track, pOverflow); */
track = 1 << track;
/* rsign = add(rsign, track, pOverflow); */
rsign += track;
}
else
{
cod[i] = -8192;
_sign[k] = (Word16) - 32768L;
}
/* indx = add(indx, index, pOverflow); */
indx += index;
}
*sign = rsign;
p0 = h - codvec[0];
p1 = h - codvec[1];
p2 = h - codvec[2];
p3 = h - codvec[3];
for (i = 0; i < L_CODE; i++)
{
s = 0;
s =
L_mac(
s,
*p0++,
_sign[0],
pOverflow);
s =
L_mac(
s,
*p1++,
_sign[1],
pOverflow);
s =
L_mac(
s,
*p2++,
_sign[2],
pOverflow);
s =
L_mac(
s,
*p3++,
_sign[3],
pOverflow);
y[i] =
pv_round(
s,
pOverflow);
} /* for (i = 0; i < L_CODE; i++) */
return indx;
} /* build_code */
#ifdef __cplusplus
}
#endif
| apache-2.0 |
darlyhellen/oto | NDKFFmpeg/jni/ffmpeg/libavcodec/dct32_template.c | 30 | 7270 | /*
* Template for the Discrete Cosine Transform for 32 samples
* Copyright (c) 2001, 2002 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "dct32.h"
#include "mathops.h"
#if DCT32_FLOAT
# define dct32 ff_dct32_float
# define FIXHR(x) ((float)(x))
# define MULH3(x, y, s) ((s)*(y)*(x))
# define INTFLOAT float
#else
# define dct32 ff_dct32_fixed
# define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
# define MULH3(x, y, s) MULH((s)*(x), y)
# define INTFLOAT int
#endif
/* tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j))) */
/* cos(i*pi/64) */
#define COS0_0 FIXHR(0.50060299823519630134/2)
#define COS0_1 FIXHR(0.50547095989754365998/2)
#define COS0_2 FIXHR(0.51544730992262454697/2)
#define COS0_3 FIXHR(0.53104259108978417447/2)
#define COS0_4 FIXHR(0.55310389603444452782/2)
#define COS0_5 FIXHR(0.58293496820613387367/2)
#define COS0_6 FIXHR(0.62250412303566481615/2)
#define COS0_7 FIXHR(0.67480834145500574602/2)
#define COS0_8 FIXHR(0.74453627100229844977/2)
#define COS0_9 FIXHR(0.83934964541552703873/2)
#define COS0_10 FIXHR(0.97256823786196069369/2)
#define COS0_11 FIXHR(1.16943993343288495515/4)
#define COS0_12 FIXHR(1.48416461631416627724/4)
#define COS0_13 FIXHR(2.05778100995341155085/8)
#define COS0_14 FIXHR(3.40760841846871878570/8)
#define COS0_15 FIXHR(10.19000812354805681150/32)
#define COS1_0 FIXHR(0.50241928618815570551/2)
#define COS1_1 FIXHR(0.52249861493968888062/2)
#define COS1_2 FIXHR(0.56694403481635770368/2)
#define COS1_3 FIXHR(0.64682178335999012954/2)
#define COS1_4 FIXHR(0.78815462345125022473/2)
#define COS1_5 FIXHR(1.06067768599034747134/4)
#define COS1_6 FIXHR(1.72244709823833392782/4)
#define COS1_7 FIXHR(5.10114861868916385802/16)
#define COS2_0 FIXHR(0.50979557910415916894/2)
#define COS2_1 FIXHR(0.60134488693504528054/2)
#define COS2_2 FIXHR(0.89997622313641570463/2)
#define COS2_3 FIXHR(2.56291544774150617881/8)
#define COS3_0 FIXHR(0.54119610014619698439/2)
#define COS3_1 FIXHR(1.30656296487637652785/4)
#define COS4_0 FIXHR(M_SQRT1_2/2)
/* butterfly operator */
#define BF(a, b, c, s)\
{\
tmp0 = val##a + val##b;\
tmp1 = val##a - val##b;\
val##a = tmp0;\
val##b = MULH3(tmp1, c, 1<<(s));\
}
#define BF0(a, b, c, s)\
{\
tmp0 = tab[a] + tab[b];\
tmp1 = tab[a] - tab[b];\
val##a = tmp0;\
val##b = MULH3(tmp1, c, 1<<(s));\
}
#define BF1(a, b, c, d)\
{\
BF(a, b, COS4_0, 1);\
BF(c, d,-COS4_0, 1);\
val##c += val##d;\
}
#define BF2(a, b, c, d)\
{\
BF(a, b, COS4_0, 1);\
BF(c, d,-COS4_0, 1);\
val##c += val##d;\
val##a += val##c;\
val##c += val##b;\
val##b += val##d;\
}
#define ADD(a, b) val##a += val##b
/* DCT32 without 1/sqrt(2) coef zero scaling. */
void dct32(INTFLOAT *out, const INTFLOAT *tab)
{
INTFLOAT tmp0, tmp1;
INTFLOAT val0 , val1 , val2 , val3 , val4 , val5 , val6 , val7 ,
val8 , val9 , val10, val11, val12, val13, val14, val15,
val16, val17, val18, val19, val20, val21, val22, val23,
val24, val25, val26, val27, val28, val29, val30, val31;
/* pass 1 */
BF0( 0, 31, COS0_0 , 1);
BF0(15, 16, COS0_15, 5);
/* pass 2 */
BF( 0, 15, COS1_0 , 1);
BF(16, 31,-COS1_0 , 1);
/* pass 1 */
BF0( 7, 24, COS0_7 , 1);
BF0( 8, 23, COS0_8 , 1);
/* pass 2 */
BF( 7, 8, COS1_7 , 4);
BF(23, 24,-COS1_7 , 4);
/* pass 3 */
BF( 0, 7, COS2_0 , 1);
BF( 8, 15,-COS2_0 , 1);
BF(16, 23, COS2_0 , 1);
BF(24, 31,-COS2_0 , 1);
/* pass 1 */
BF0( 3, 28, COS0_3 , 1);
BF0(12, 19, COS0_12, 2);
/* pass 2 */
BF( 3, 12, COS1_3 , 1);
BF(19, 28,-COS1_3 , 1);
/* pass 1 */
BF0( 4, 27, COS0_4 , 1);
BF0(11, 20, COS0_11, 2);
/* pass 2 */
BF( 4, 11, COS1_4 , 1);
BF(20, 27,-COS1_4 , 1);
/* pass 3 */
BF( 3, 4, COS2_3 , 3);
BF(11, 12,-COS2_3 , 3);
BF(19, 20, COS2_3 , 3);
BF(27, 28,-COS2_3 , 3);
/* pass 4 */
BF( 0, 3, COS3_0 , 1);
BF( 4, 7,-COS3_0 , 1);
BF( 8, 11, COS3_0 , 1);
BF(12, 15,-COS3_0 , 1);
BF(16, 19, COS3_0 , 1);
BF(20, 23,-COS3_0 , 1);
BF(24, 27, COS3_0 , 1);
BF(28, 31,-COS3_0 , 1);
/* pass 1 */
BF0( 1, 30, COS0_1 , 1);
BF0(14, 17, COS0_14, 3);
/* pass 2 */
BF( 1, 14, COS1_1 , 1);
BF(17, 30,-COS1_1 , 1);
/* pass 1 */
BF0( 6, 25, COS0_6 , 1);
BF0( 9, 22, COS0_9 , 1);
/* pass 2 */
BF( 6, 9, COS1_6 , 2);
BF(22, 25,-COS1_6 , 2);
/* pass 3 */
BF( 1, 6, COS2_1 , 1);
BF( 9, 14,-COS2_1 , 1);
BF(17, 22, COS2_1 , 1);
BF(25, 30,-COS2_1 , 1);
/* pass 1 */
BF0( 2, 29, COS0_2 , 1);
BF0(13, 18, COS0_13, 3);
/* pass 2 */
BF( 2, 13, COS1_2 , 1);
BF(18, 29,-COS1_2 , 1);
/* pass 1 */
BF0( 5, 26, COS0_5 , 1);
BF0(10, 21, COS0_10, 1);
/* pass 2 */
BF( 5, 10, COS1_5 , 2);
BF(21, 26,-COS1_5 , 2);
/* pass 3 */
BF( 2, 5, COS2_2 , 1);
BF(10, 13,-COS2_2 , 1);
BF(18, 21, COS2_2 , 1);
BF(26, 29,-COS2_2 , 1);
/* pass 4 */
BF( 1, 2, COS3_1 , 2);
BF( 5, 6,-COS3_1 , 2);
BF( 9, 10, COS3_1 , 2);
BF(13, 14,-COS3_1 , 2);
BF(17, 18, COS3_1 , 2);
BF(21, 22,-COS3_1 , 2);
BF(25, 26, COS3_1 , 2);
BF(29, 30,-COS3_1 , 2);
/* pass 5 */
BF1( 0, 1, 2, 3);
BF2( 4, 5, 6, 7);
BF1( 8, 9, 10, 11);
BF2(12, 13, 14, 15);
BF1(16, 17, 18, 19);
BF2(20, 21, 22, 23);
BF1(24, 25, 26, 27);
BF2(28, 29, 30, 31);
/* pass 6 */
ADD( 8, 12);
ADD(12, 10);
ADD(10, 14);
ADD(14, 9);
ADD( 9, 13);
ADD(13, 11);
ADD(11, 15);
out[ 0] = val0;
out[16] = val1;
out[ 8] = val2;
out[24] = val3;
out[ 4] = val4;
out[20] = val5;
out[12] = val6;
out[28] = val7;
out[ 2] = val8;
out[18] = val9;
out[10] = val10;
out[26] = val11;
out[ 6] = val12;
out[22] = val13;
out[14] = val14;
out[30] = val15;
ADD(24, 28);
ADD(28, 26);
ADD(26, 30);
ADD(30, 25);
ADD(25, 29);
ADD(29, 27);
ADD(27, 31);
out[ 1] = val16 + val24;
out[17] = val17 + val25;
out[ 9] = val18 + val26;
out[25] = val19 + val27;
out[ 5] = val20 + val28;
out[21] = val21 + val29;
out[13] = val22 + val30;
out[29] = val23 + val31;
out[ 3] = val24 + val20;
out[19] = val25 + val21;
out[11] = val26 + val22;
out[27] = val27 + val23;
out[ 7] = val28 + val18;
out[23] = val29 + val19;
out[15] = val30 + val17;
out[31] = val31;
}
| apache-2.0 |
vvtam/wrk | src/http_parser.c | 30 | 69712 | /* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev
*
* Additional changes are licensed under the same terms as NGINX and
* copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "http_parser.h"
#include <assert.h>
#include <stddef.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#ifndef ULLONG_MAX
# define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */
#endif
#ifndef MIN
# define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
#ifndef ARRAY_SIZE
# define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#endif
#ifndef BIT_AT
# define BIT_AT(a, i) \
(!!((unsigned int) (a)[(unsigned int) (i) >> 3] & \
(1 << ((unsigned int) (i) & 7))))
#endif
#ifndef ELEM_AT
# define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v))
#endif
#define SET_ERRNO(e) \
do { \
parser->http_errno = (e); \
} while(0)
#define CURRENT_STATE() p_state
#define UPDATE_STATE(V) p_state = (enum state) (V);
#define RETURN(V) \
do { \
parser->state = CURRENT_STATE(); \
return (V); \
} while (0);
#define REEXECUTE() \
--p; \
break;
#ifdef __GNUC__
# define LIKELY(X) __builtin_expect(!!(X), 1)
# define UNLIKELY(X) __builtin_expect(!!(X), 0)
#else
# define LIKELY(X) (X)
# define UNLIKELY(X) (X)
#endif
/* Run the notify callback FOR, returning ER if it fails */
#define CALLBACK_NOTIFY_(FOR, ER) \
do { \
assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \
\
if (LIKELY(settings->on_##FOR)) { \
parser->state = CURRENT_STATE(); \
if (UNLIKELY(0 != settings->on_##FOR(parser))) { \
SET_ERRNO(HPE_CB_##FOR); \
} \
UPDATE_STATE(parser->state); \
\
/* We either errored above or got paused; get out */ \
if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \
return (ER); \
} \
} \
} while (0)
/* Run the notify callback FOR and consume the current byte */
#define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1)
/* Run the notify callback FOR and don't consume the current byte */
#define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data)
/* Run data callback FOR with LEN bytes, returning ER if it fails */
#define CALLBACK_DATA_(FOR, LEN, ER) \
do { \
assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \
\
if (FOR##_mark) { \
if (LIKELY(settings->on_##FOR)) { \
parser->state = CURRENT_STATE(); \
if (UNLIKELY(0 != \
settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \
SET_ERRNO(HPE_CB_##FOR); \
} \
UPDATE_STATE(parser->state); \
\
/* We either errored above or got paused; get out */ \
if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \
return (ER); \
} \
} \
FOR##_mark = NULL; \
} \
} while (0)
/* Run the data callback FOR and consume the current byte */
#define CALLBACK_DATA(FOR) \
CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1)
/* Run the data callback FOR and don't consume the current byte */
#define CALLBACK_DATA_NOADVANCE(FOR) \
CALLBACK_DATA_(FOR, p - FOR##_mark, p - data)
/* Set the mark FOR; non-destructive if mark is already set */
#define MARK(FOR) \
do { \
if (!FOR##_mark) { \
FOR##_mark = p; \
} \
} while (0)
/* Don't allow the total size of the HTTP headers (including the status
* line) to exceed HTTP_MAX_HEADER_SIZE. This check is here to protect
* embedders against denial-of-service attacks where the attacker feeds
* us a never-ending header that the embedder keeps buffering.
*
* This check is arguably the responsibility of embedders but we're doing
* it on the embedder's behalf because most won't bother and this way we
* make the web a little safer. HTTP_MAX_HEADER_SIZE is still far bigger
* than any reasonable request or response so this should never affect
* day-to-day operation.
*/
#define COUNT_HEADER_SIZE(V) \
do { \
parser->nread += (V); \
if (UNLIKELY(parser->nread > (HTTP_MAX_HEADER_SIZE))) { \
SET_ERRNO(HPE_HEADER_OVERFLOW); \
goto error; \
} \
} while (0)
#define PROXY_CONNECTION "proxy-connection"
#define CONNECTION "connection"
#define CONTENT_LENGTH "content-length"
#define TRANSFER_ENCODING "transfer-encoding"
#define UPGRADE "upgrade"
#define CHUNKED "chunked"
#define KEEP_ALIVE "keep-alive"
#define CLOSE "close"
static const char *method_strings[] =
{
#define XX(num, name, string) #string,
HTTP_METHOD_MAP(XX)
#undef XX
};
/* Tokens as defined by rfc 2616. Also lowercases them.
* token = 1*<any CHAR except CTLs or separators>
* separators = "(" | ")" | "<" | ">" | "@"
* | "," | ";" | ":" | "\" | <">
* | "/" | "[" | "]" | "?" | "="
* | "{" | "}" | SP | HT
*/
static const char tokens[256] = {
/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */
0, 0, 0, 0, 0, 0, 0, 0,
/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */
0, 0, 0, 0, 0, 0, 0, 0,
/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */
0, 0, 0, 0, 0, 0, 0, 0,
/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */
0, 0, 0, 0, 0, 0, 0, 0,
/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */
0, '!', 0, '#', '$', '%', '&', '\'',
/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */
0, 0, '*', '+', 0, '-', '.', 0,
/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */
'0', '1', '2', '3', '4', '5', '6', '7',
/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */
'8', '9', 0, 0, 0, 0, 0, 0,
/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */
0, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */
'x', 'y', 'z', 0, 0, 0, '^', '_',
/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */
'x', 'y', 'z', 0, '|', 0, '~', 0 };
static const int8_t unhex[256] =
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
#if HTTP_PARSER_STRICT
# define T(v) 0
#else
# define T(v) v
#endif
static const uint8_t normal_url_char[32] = {
/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */
0 | T(2) | 0 | 0 | T(16) | 0 | 0 | 0,
/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */
0 | 2 | 4 | 0 | 16 | 32 | 64 | 128,
/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 0,
/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */
1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, };
#undef T
enum state
{ s_dead = 1 /* important that this is > 0 */
, s_start_req_or_res
, s_res_or_resp_H
, s_start_res
, s_res_H
, s_res_HT
, s_res_HTT
, s_res_HTTP
, s_res_first_http_major
, s_res_http_major
, s_res_first_http_minor
, s_res_http_minor
, s_res_first_status_code
, s_res_status_code
, s_res_status_start
, s_res_status
, s_res_line_almost_done
, s_start_req
, s_req_method
, s_req_spaces_before_url
, s_req_schema
, s_req_schema_slash
, s_req_schema_slash_slash
, s_req_server_start
, s_req_server
, s_req_server_with_at
, s_req_path
, s_req_query_string_start
, s_req_query_string
, s_req_fragment_start
, s_req_fragment
, s_req_http_start
, s_req_http_H
, s_req_http_HT
, s_req_http_HTT
, s_req_http_HTTP
, s_req_first_http_major
, s_req_http_major
, s_req_first_http_minor
, s_req_http_minor
, s_req_line_almost_done
, s_header_field_start
, s_header_field
, s_header_value_discard_ws
, s_header_value_discard_ws_almost_done
, s_header_value_discard_lws
, s_header_value_start
, s_header_value
, s_header_value_lws
, s_header_almost_done
, s_chunk_size_start
, s_chunk_size
, s_chunk_parameters
, s_chunk_size_almost_done
, s_headers_almost_done
, s_headers_done
/* Important: 's_headers_done' must be the last 'header' state. All
* states beyond this must be 'body' states. It is used for overflow
* checking. See the PARSING_HEADER() macro.
*/
, s_chunk_data
, s_chunk_data_almost_done
, s_chunk_data_done
, s_body_identity
, s_body_identity_eof
, s_message_done
};
#define PARSING_HEADER(state) (state <= s_headers_done)
enum header_states
{ h_general = 0
, h_C
, h_CO
, h_CON
, h_matching_connection
, h_matching_proxy_connection
, h_matching_content_length
, h_matching_transfer_encoding
, h_matching_upgrade
, h_connection
, h_content_length
, h_transfer_encoding
, h_upgrade
, h_matching_transfer_encoding_chunked
, h_matching_connection_token_start
, h_matching_connection_keep_alive
, h_matching_connection_close
, h_matching_connection_upgrade
, h_matching_connection_token
, h_transfer_encoding_chunked
, h_connection_keep_alive
, h_connection_close
, h_connection_upgrade
};
enum http_host_state
{
s_http_host_dead = 1
, s_http_userinfo_start
, s_http_userinfo
, s_http_host_start
, s_http_host_v6_start
, s_http_host
, s_http_host_v6
, s_http_host_v6_end
, s_http_host_port_start
, s_http_host_port
};
/* Macros for character classes; depends on strict-mode */
#define CR '\r'
#define LF '\n'
#define LOWER(c) (unsigned char)(c | 0x20)
#define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z')
#define IS_NUM(c) ((c) >= '0' && (c) <= '9')
#define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c))
#define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f'))
#define IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \
(c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \
(c) == ')')
#define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \
(c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \
(c) == '$' || (c) == ',')
#define STRICT_TOKEN(c) (tokens[(unsigned char)c])
#if HTTP_PARSER_STRICT
#define TOKEN(c) (tokens[(unsigned char)c])
#define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c))
#define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
#else
#define TOKEN(c) ((c == ' ') ? ' ' : tokens[(unsigned char)c])
#define IS_URL_CHAR(c) \
(BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80))
#define IS_HOST_CHAR(c) \
(IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
#endif
#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res)
#if HTTP_PARSER_STRICT
# define STRICT_CHECK(cond) \
do { \
if (cond) { \
SET_ERRNO(HPE_STRICT); \
goto error; \
} \
} while (0)
# define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead)
#else
# define STRICT_CHECK(cond)
# define NEW_MESSAGE() start_state
#endif
/* Map errno values to strings for human-readable output */
#define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s },
static struct {
const char *name;
const char *description;
} http_strerror_tab[] = {
HTTP_ERRNO_MAP(HTTP_STRERROR_GEN)
};
#undef HTTP_STRERROR_GEN
int http_message_needs_eof(const http_parser *parser);
/* Our URL parser.
*
* This is designed to be shared by http_parser_execute() for URL validation,
* hence it has a state transition + byte-for-byte interface. In addition, it
* is meant to be embedded in http_parser_parse_url(), which does the dirty
* work of turning state transitions URL components for its API.
*
* This function should only be invoked with non-space characters. It is
* assumed that the caller cares about (and can detect) the transition between
* URL and non-URL states by looking for these.
*/
static enum state
parse_url_char(enum state s, const char ch)
{
if (ch == ' ' || ch == '\r' || ch == '\n') {
return s_dead;
}
#if HTTP_PARSER_STRICT
if (ch == '\t' || ch == '\f') {
return s_dead;
}
#endif
switch (s) {
case s_req_spaces_before_url:
/* Proxied requests are followed by scheme of an absolute URI (alpha).
* All methods except CONNECT are followed by '/' or '*'.
*/
if (ch == '/' || ch == '*') {
return s_req_path;
}
if (IS_ALPHA(ch)) {
return s_req_schema;
}
break;
case s_req_schema:
if (IS_ALPHA(ch)) {
return s;
}
if (ch == ':') {
return s_req_schema_slash;
}
break;
case s_req_schema_slash:
if (ch == '/') {
return s_req_schema_slash_slash;
}
break;
case s_req_schema_slash_slash:
if (ch == '/') {
return s_req_server_start;
}
break;
case s_req_server_with_at:
if (ch == '@') {
return s_dead;
}
/* FALLTHROUGH */
case s_req_server_start:
case s_req_server:
if (ch == '/') {
return s_req_path;
}
if (ch == '?') {
return s_req_query_string_start;
}
if (ch == '@') {
return s_req_server_with_at;
}
if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') {
return s_req_server;
}
break;
case s_req_path:
if (IS_URL_CHAR(ch)) {
return s;
}
switch (ch) {
case '?':
return s_req_query_string_start;
case '#':
return s_req_fragment_start;
}
break;
case s_req_query_string_start:
case s_req_query_string:
if (IS_URL_CHAR(ch)) {
return s_req_query_string;
}
switch (ch) {
case '?':
/* allow extra '?' in query string */
return s_req_query_string;
case '#':
return s_req_fragment_start;
}
break;
case s_req_fragment_start:
if (IS_URL_CHAR(ch)) {
return s_req_fragment;
}
switch (ch) {
case '?':
return s_req_fragment;
case '#':
return s;
}
break;
case s_req_fragment:
if (IS_URL_CHAR(ch)) {
return s;
}
switch (ch) {
case '?':
case '#':
return s;
}
break;
default:
break;
}
/* We should never fall out of the switch above unless there's an error */
return s_dead;
}
size_t http_parser_execute (http_parser *parser,
const http_parser_settings *settings,
const char *data,
size_t len)
{
char c, ch;
int8_t unhex_val;
const char *p = data;
const char *header_field_mark = 0;
const char *header_value_mark = 0;
const char *url_mark = 0;
const char *body_mark = 0;
const char *status_mark = 0;
enum state p_state = (enum state) parser->state;
/* We're in an error state. Don't bother doing anything. */
if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
return 0;
}
if (len == 0) {
switch (CURRENT_STATE()) {
case s_body_identity_eof:
/* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if
* we got paused.
*/
CALLBACK_NOTIFY_NOADVANCE(message_complete);
return 0;
case s_dead:
case s_start_req_or_res:
case s_start_res:
case s_start_req:
return 0;
default:
SET_ERRNO(HPE_INVALID_EOF_STATE);
return 1;
}
}
if (CURRENT_STATE() == s_header_field)
header_field_mark = data;
if (CURRENT_STATE() == s_header_value)
header_value_mark = data;
switch (CURRENT_STATE()) {
case s_req_path:
case s_req_schema:
case s_req_schema_slash:
case s_req_schema_slash_slash:
case s_req_server_start:
case s_req_server:
case s_req_server_with_at:
case s_req_query_string_start:
case s_req_query_string:
case s_req_fragment_start:
case s_req_fragment:
url_mark = data;
break;
case s_res_status:
status_mark = data;
break;
default:
break;
}
for (p=data; p != data + len; p++) {
ch = *p;
if (PARSING_HEADER(CURRENT_STATE()))
COUNT_HEADER_SIZE(1);
switch (CURRENT_STATE()) {
case s_dead:
/* this state is used after a 'Connection: close' message
* the parser will error out if it reads another message
*/
if (LIKELY(ch == CR || ch == LF))
break;
SET_ERRNO(HPE_CLOSED_CONNECTION);
goto error;
case s_start_req_or_res:
{
if (ch == CR || ch == LF)
break;
parser->flags = 0;
parser->content_length = ULLONG_MAX;
if (ch == 'H') {
UPDATE_STATE(s_res_or_resp_H);
CALLBACK_NOTIFY(message_begin);
} else {
parser->type = HTTP_REQUEST;
UPDATE_STATE(s_start_req);
REEXECUTE();
}
break;
}
case s_res_or_resp_H:
if (ch == 'T') {
parser->type = HTTP_RESPONSE;
UPDATE_STATE(s_res_HT);
} else {
if (UNLIKELY(ch != 'E')) {
SET_ERRNO(HPE_INVALID_CONSTANT);
goto error;
}
parser->type = HTTP_REQUEST;
parser->method = HTTP_HEAD;
parser->index = 2;
UPDATE_STATE(s_req_method);
}
break;
case s_start_res:
{
parser->flags = 0;
parser->content_length = ULLONG_MAX;
switch (ch) {
case 'H':
UPDATE_STATE(s_res_H);
break;
case CR:
case LF:
break;
default:
SET_ERRNO(HPE_INVALID_CONSTANT);
goto error;
}
CALLBACK_NOTIFY(message_begin);
break;
}
case s_res_H:
STRICT_CHECK(ch != 'T');
UPDATE_STATE(s_res_HT);
break;
case s_res_HT:
STRICT_CHECK(ch != 'T');
UPDATE_STATE(s_res_HTT);
break;
case s_res_HTT:
STRICT_CHECK(ch != 'P');
UPDATE_STATE(s_res_HTTP);
break;
case s_res_HTTP:
STRICT_CHECK(ch != '/');
UPDATE_STATE(s_res_first_http_major);
break;
case s_res_first_http_major:
if (UNLIKELY(ch < '0' || ch > '9')) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
parser->http_major = ch - '0';
UPDATE_STATE(s_res_http_major);
break;
/* major HTTP version or dot */
case s_res_http_major:
{
if (ch == '.') {
UPDATE_STATE(s_res_first_http_minor);
break;
}
if (!IS_NUM(ch)) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
parser->http_major *= 10;
parser->http_major += ch - '0';
if (UNLIKELY(parser->http_major > 999)) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
break;
}
/* first digit of minor HTTP version */
case s_res_first_http_minor:
if (UNLIKELY(!IS_NUM(ch))) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
parser->http_minor = ch - '0';
UPDATE_STATE(s_res_http_minor);
break;
/* minor HTTP version or end of request line */
case s_res_http_minor:
{
if (ch == ' ') {
UPDATE_STATE(s_res_first_status_code);
break;
}
if (UNLIKELY(!IS_NUM(ch))) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
parser->http_minor *= 10;
parser->http_minor += ch - '0';
if (UNLIKELY(parser->http_minor > 999)) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
break;
}
case s_res_first_status_code:
{
if (!IS_NUM(ch)) {
if (ch == ' ') {
break;
}
SET_ERRNO(HPE_INVALID_STATUS);
goto error;
}
parser->status_code = ch - '0';
UPDATE_STATE(s_res_status_code);
break;
}
case s_res_status_code:
{
if (!IS_NUM(ch)) {
switch (ch) {
case ' ':
UPDATE_STATE(s_res_status_start);
break;
case CR:
UPDATE_STATE(s_res_line_almost_done);
break;
case LF:
UPDATE_STATE(s_header_field_start);
break;
default:
SET_ERRNO(HPE_INVALID_STATUS);
goto error;
}
break;
}
parser->status_code *= 10;
parser->status_code += ch - '0';
if (UNLIKELY(parser->status_code > 999)) {
SET_ERRNO(HPE_INVALID_STATUS);
goto error;
}
break;
}
case s_res_status_start:
{
if (ch == CR) {
UPDATE_STATE(s_res_line_almost_done);
break;
}
if (ch == LF) {
UPDATE_STATE(s_header_field_start);
break;
}
MARK(status);
UPDATE_STATE(s_res_status);
parser->index = 0;
break;
}
case s_res_status:
if (ch == CR) {
UPDATE_STATE(s_res_line_almost_done);
CALLBACK_DATA(status);
break;
}
if (ch == LF) {
UPDATE_STATE(s_header_field_start);
CALLBACK_DATA(status);
break;
}
break;
case s_res_line_almost_done:
STRICT_CHECK(ch != LF);
UPDATE_STATE(s_header_field_start);
break;
case s_start_req:
{
if (ch == CR || ch == LF)
break;
parser->flags = 0;
parser->content_length = ULLONG_MAX;
if (UNLIKELY(!IS_ALPHA(ch))) {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
parser->method = (enum http_method) 0;
parser->index = 1;
switch (ch) {
case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break;
case 'D': parser->method = HTTP_DELETE; break;
case 'G': parser->method = HTTP_GET; break;
case 'H': parser->method = HTTP_HEAD; break;
case 'L': parser->method = HTTP_LOCK; break;
case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break;
case 'N': parser->method = HTTP_NOTIFY; break;
case 'O': parser->method = HTTP_OPTIONS; break;
case 'P': parser->method = HTTP_POST;
/* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */
break;
case 'R': parser->method = HTTP_REPORT; break;
case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break;
case 'T': parser->method = HTTP_TRACE; break;
case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE */ break;
default:
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
UPDATE_STATE(s_req_method);
CALLBACK_NOTIFY(message_begin);
break;
}
case s_req_method:
{
const char *matcher;
if (UNLIKELY(ch == '\0')) {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
matcher = method_strings[parser->method];
if (ch == ' ' && matcher[parser->index] == '\0') {
UPDATE_STATE(s_req_spaces_before_url);
} else if (ch == matcher[parser->index]) {
; /* nada */
} else if (parser->method == HTTP_CONNECT) {
if (parser->index == 1 && ch == 'H') {
parser->method = HTTP_CHECKOUT;
} else if (parser->index == 2 && ch == 'P') {
parser->method = HTTP_COPY;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
} else if (parser->method == HTTP_MKCOL) {
if (parser->index == 1 && ch == 'O') {
parser->method = HTTP_MOVE;
} else if (parser->index == 1 && ch == 'E') {
parser->method = HTTP_MERGE;
} else if (parser->index == 1 && ch == '-') {
parser->method = HTTP_MSEARCH;
} else if (parser->index == 2 && ch == 'A') {
parser->method = HTTP_MKACTIVITY;
} else if (parser->index == 3 && ch == 'A') {
parser->method = HTTP_MKCALENDAR;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
} else if (parser->method == HTTP_SUBSCRIBE) {
if (parser->index == 1 && ch == 'E') {
parser->method = HTTP_SEARCH;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
} else if (parser->index == 1 && parser->method == HTTP_POST) {
if (ch == 'R') {
parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */
} else if (ch == 'U') {
parser->method = HTTP_PUT; /* or HTTP_PURGE */
} else if (ch == 'A') {
parser->method = HTTP_PATCH;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
} else if (parser->index == 2) {
if (parser->method == HTTP_PUT) {
if (ch == 'R') {
parser->method = HTTP_PURGE;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
} else if (parser->method == HTTP_UNLOCK) {
if (ch == 'S') {
parser->method = HTTP_UNSUBSCRIBE;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
} else if (parser->index == 4 && parser->method == HTTP_PROPFIND && ch == 'P') {
parser->method = HTTP_PROPPATCH;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
++parser->index;
break;
}
case s_req_spaces_before_url:
{
if (ch == ' ') break;
MARK(url);
if (parser->method == HTTP_CONNECT) {
UPDATE_STATE(s_req_server_start);
}
UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
if (UNLIKELY(CURRENT_STATE() == s_dead)) {
SET_ERRNO(HPE_INVALID_URL);
goto error;
}
break;
}
case s_req_schema:
case s_req_schema_slash:
case s_req_schema_slash_slash:
case s_req_server_start:
{
switch (ch) {
/* No whitespace allowed here */
case ' ':
case CR:
case LF:
SET_ERRNO(HPE_INVALID_URL);
goto error;
default:
UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
if (UNLIKELY(CURRENT_STATE() == s_dead)) {
SET_ERRNO(HPE_INVALID_URL);
goto error;
}
}
break;
}
case s_req_server:
case s_req_server_with_at:
case s_req_path:
case s_req_query_string_start:
case s_req_query_string:
case s_req_fragment_start:
case s_req_fragment:
{
switch (ch) {
case ' ':
UPDATE_STATE(s_req_http_start);
CALLBACK_DATA(url);
break;
case CR:
case LF:
parser->http_major = 0;
parser->http_minor = 9;
UPDATE_STATE((ch == CR) ?
s_req_line_almost_done :
s_header_field_start);
CALLBACK_DATA(url);
break;
default:
UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch));
if (UNLIKELY(CURRENT_STATE() == s_dead)) {
SET_ERRNO(HPE_INVALID_URL);
goto error;
}
}
break;
}
case s_req_http_start:
switch (ch) {
case 'H':
UPDATE_STATE(s_req_http_H);
break;
case ' ':
break;
default:
SET_ERRNO(HPE_INVALID_CONSTANT);
goto error;
}
break;
case s_req_http_H:
STRICT_CHECK(ch != 'T');
UPDATE_STATE(s_req_http_HT);
break;
case s_req_http_HT:
STRICT_CHECK(ch != 'T');
UPDATE_STATE(s_req_http_HTT);
break;
case s_req_http_HTT:
STRICT_CHECK(ch != 'P');
UPDATE_STATE(s_req_http_HTTP);
break;
case s_req_http_HTTP:
STRICT_CHECK(ch != '/');
UPDATE_STATE(s_req_first_http_major);
break;
/* first digit of major HTTP version */
case s_req_first_http_major:
if (UNLIKELY(ch < '1' || ch > '9')) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
parser->http_major = ch - '0';
UPDATE_STATE(s_req_http_major);
break;
/* major HTTP version or dot */
case s_req_http_major:
{
if (ch == '.') {
UPDATE_STATE(s_req_first_http_minor);
break;
}
if (UNLIKELY(!IS_NUM(ch))) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
parser->http_major *= 10;
parser->http_major += ch - '0';
if (UNLIKELY(parser->http_major > 999)) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
break;
}
/* first digit of minor HTTP version */
case s_req_first_http_minor:
if (UNLIKELY(!IS_NUM(ch))) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
parser->http_minor = ch - '0';
UPDATE_STATE(s_req_http_minor);
break;
/* minor HTTP version or end of request line */
case s_req_http_minor:
{
if (ch == CR) {
UPDATE_STATE(s_req_line_almost_done);
break;
}
if (ch == LF) {
UPDATE_STATE(s_header_field_start);
break;
}
/* XXX allow spaces after digit? */
if (UNLIKELY(!IS_NUM(ch))) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
parser->http_minor *= 10;
parser->http_minor += ch - '0';
if (UNLIKELY(parser->http_minor > 999)) {
SET_ERRNO(HPE_INVALID_VERSION);
goto error;
}
break;
}
/* end of request line */
case s_req_line_almost_done:
{
if (UNLIKELY(ch != LF)) {
SET_ERRNO(HPE_LF_EXPECTED);
goto error;
}
UPDATE_STATE(s_header_field_start);
break;
}
case s_header_field_start:
{
if (ch == CR) {
UPDATE_STATE(s_headers_almost_done);
break;
}
if (ch == LF) {
/* they might be just sending \n instead of \r\n so this would be
* the second \n to denote the end of headers*/
UPDATE_STATE(s_headers_almost_done);
REEXECUTE();
}
c = TOKEN(ch);
if (UNLIKELY(!c)) {
SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
goto error;
}
MARK(header_field);
parser->index = 0;
UPDATE_STATE(s_header_field);
switch (c) {
case 'c':
parser->header_state = h_C;
break;
case 'p':
parser->header_state = h_matching_proxy_connection;
break;
case 't':
parser->header_state = h_matching_transfer_encoding;
break;
case 'u':
parser->header_state = h_matching_upgrade;
break;
default:
parser->header_state = h_general;
break;
}
break;
}
case s_header_field:
{
const char* start = p;
for (; p != data + len; p++) {
ch = *p;
c = TOKEN(ch);
if (!c)
break;
switch (parser->header_state) {
case h_general:
break;
case h_C:
parser->index++;
parser->header_state = (c == 'o' ? h_CO : h_general);
break;
case h_CO:
parser->index++;
parser->header_state = (c == 'n' ? h_CON : h_general);
break;
case h_CON:
parser->index++;
switch (c) {
case 'n':
parser->header_state = h_matching_connection;
break;
case 't':
parser->header_state = h_matching_content_length;
break;
default:
parser->header_state = h_general;
break;
}
break;
/* connection */
case h_matching_connection:
parser->index++;
if (parser->index > sizeof(CONNECTION)-1
|| c != CONNECTION[parser->index]) {
parser->header_state = h_general;
} else if (parser->index == sizeof(CONNECTION)-2) {
parser->header_state = h_connection;
}
break;
/* proxy-connection */
case h_matching_proxy_connection:
parser->index++;
if (parser->index > sizeof(PROXY_CONNECTION)-1
|| c != PROXY_CONNECTION[parser->index]) {
parser->header_state = h_general;
} else if (parser->index == sizeof(PROXY_CONNECTION)-2) {
parser->header_state = h_connection;
}
break;
/* content-length */
case h_matching_content_length:
parser->index++;
if (parser->index > sizeof(CONTENT_LENGTH)-1
|| c != CONTENT_LENGTH[parser->index]) {
parser->header_state = h_general;
} else if (parser->index == sizeof(CONTENT_LENGTH)-2) {
parser->header_state = h_content_length;
}
break;
/* transfer-encoding */
case h_matching_transfer_encoding:
parser->index++;
if (parser->index > sizeof(TRANSFER_ENCODING)-1
|| c != TRANSFER_ENCODING[parser->index]) {
parser->header_state = h_general;
} else if (parser->index == sizeof(TRANSFER_ENCODING)-2) {
parser->header_state = h_transfer_encoding;
}
break;
/* upgrade */
case h_matching_upgrade:
parser->index++;
if (parser->index > sizeof(UPGRADE)-1
|| c != UPGRADE[parser->index]) {
parser->header_state = h_general;
} else if (parser->index == sizeof(UPGRADE)-2) {
parser->header_state = h_upgrade;
}
break;
case h_connection:
case h_content_length:
case h_transfer_encoding:
case h_upgrade:
if (ch != ' ') parser->header_state = h_general;
break;
default:
assert(0 && "Unknown header_state");
break;
}
}
COUNT_HEADER_SIZE(p - start);
if (p == data + len) {
--p;
break;
}
if (ch == ':') {
UPDATE_STATE(s_header_value_discard_ws);
CALLBACK_DATA(header_field);
break;
}
SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
goto error;
}
case s_header_value_discard_ws:
if (ch == ' ' || ch == '\t') break;
if (ch == CR) {
UPDATE_STATE(s_header_value_discard_ws_almost_done);
break;
}
if (ch == LF) {
UPDATE_STATE(s_header_value_discard_lws);
break;
}
/* FALLTHROUGH */
case s_header_value_start:
{
MARK(header_value);
UPDATE_STATE(s_header_value);
parser->index = 0;
c = LOWER(ch);
switch (parser->header_state) {
case h_upgrade:
parser->flags |= F_UPGRADE;
parser->header_state = h_general;
break;
case h_transfer_encoding:
/* looking for 'Transfer-Encoding: chunked' */
if ('c' == c) {
parser->header_state = h_matching_transfer_encoding_chunked;
} else {
parser->header_state = h_general;
}
break;
case h_content_length:
if (UNLIKELY(!IS_NUM(ch))) {
SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
goto error;
}
parser->content_length = ch - '0';
break;
case h_connection:
/* looking for 'Connection: keep-alive' */
if (c == 'k') {
parser->header_state = h_matching_connection_keep_alive;
/* looking for 'Connection: close' */
} else if (c == 'c') {
parser->header_state = h_matching_connection_close;
} else if (c == 'u') {
parser->header_state = h_matching_connection_upgrade;
} else {
parser->header_state = h_matching_connection_token;
}
break;
/* Multi-value `Connection` header */
case h_matching_connection_token_start:
break;
default:
parser->header_state = h_general;
break;
}
break;
}
case s_header_value:
{
const char* start = p;
enum header_states h_state = (enum header_states) parser->header_state;
for (; p != data + len; p++) {
ch = *p;
if (ch == CR) {
UPDATE_STATE(s_header_almost_done);
parser->header_state = h_state;
CALLBACK_DATA(header_value);
break;
}
if (ch == LF) {
UPDATE_STATE(s_header_almost_done);
COUNT_HEADER_SIZE(p - start);
parser->header_state = h_state;
CALLBACK_DATA_NOADVANCE(header_value);
REEXECUTE();
}
c = LOWER(ch);
switch (h_state) {
case h_general:
{
const char* p_cr;
const char* p_lf;
size_t limit = data + len - p;
limit = MIN(limit, HTTP_MAX_HEADER_SIZE);
p_cr = (const char*) memchr(p, CR, limit);
p_lf = (const char*) memchr(p, LF, limit);
if (p_cr != NULL) {
if (p_lf != NULL && p_cr >= p_lf)
p = p_lf;
else
p = p_cr;
} else if (UNLIKELY(p_lf != NULL)) {
p = p_lf;
} else {
p = data + len;
}
--p;
break;
}
case h_connection:
case h_transfer_encoding:
assert(0 && "Shouldn't get here.");
break;
case h_content_length:
{
uint64_t t;
if (ch == ' ') break;
if (UNLIKELY(!IS_NUM(ch))) {
SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
parser->header_state = h_state;
goto error;
}
t = parser->content_length;
t *= 10;
t += ch - '0';
/* Overflow? Test against a conservative limit for simplicity. */
if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) {
SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
parser->header_state = h_state;
goto error;
}
parser->content_length = t;
break;
}
/* Transfer-Encoding: chunked */
case h_matching_transfer_encoding_chunked:
parser->index++;
if (parser->index > sizeof(CHUNKED)-1
|| c != CHUNKED[parser->index]) {
h_state = h_general;
} else if (parser->index == sizeof(CHUNKED)-2) {
h_state = h_transfer_encoding_chunked;
}
break;
case h_matching_connection_token_start:
/* looking for 'Connection: keep-alive' */
if (c == 'k') {
h_state = h_matching_connection_keep_alive;
/* looking for 'Connection: close' */
} else if (c == 'c') {
h_state = h_matching_connection_close;
} else if (c == 'u') {
h_state = h_matching_connection_upgrade;
} else if (STRICT_TOKEN(c)) {
h_state = h_matching_connection_token;
} else if (c == ' ' || c == '\t') {
/* Skip lws */
} else {
h_state = h_general;
}
break;
/* looking for 'Connection: keep-alive' */
case h_matching_connection_keep_alive:
parser->index++;
if (parser->index > sizeof(KEEP_ALIVE)-1
|| c != KEEP_ALIVE[parser->index]) {
h_state = h_matching_connection_token;
} else if (parser->index == sizeof(KEEP_ALIVE)-2) {
h_state = h_connection_keep_alive;
}
break;
/* looking for 'Connection: close' */
case h_matching_connection_close:
parser->index++;
if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) {
h_state = h_matching_connection_token;
} else if (parser->index == sizeof(CLOSE)-2) {
h_state = h_connection_close;
}
break;
/* looking for 'Connection: upgrade' */
case h_matching_connection_upgrade:
parser->index++;
if (parser->index > sizeof(UPGRADE) - 1 ||
c != UPGRADE[parser->index]) {
h_state = h_matching_connection_token;
} else if (parser->index == sizeof(UPGRADE)-2) {
h_state = h_connection_upgrade;
}
break;
case h_matching_connection_token:
if (ch == ',') {
h_state = h_matching_connection_token_start;
parser->index = 0;
}
break;
case h_transfer_encoding_chunked:
if (ch != ' ') h_state = h_general;
break;
case h_connection_keep_alive:
case h_connection_close:
case h_connection_upgrade:
if (ch == ',') {
if (h_state == h_connection_keep_alive) {
parser->flags |= F_CONNECTION_KEEP_ALIVE;
} else if (h_state == h_connection_close) {
parser->flags |= F_CONNECTION_CLOSE;
} else if (h_state == h_connection_upgrade) {
parser->flags |= F_CONNECTION_UPGRADE;
}
h_state = h_matching_connection_token_start;
parser->index = 0;
} else if (ch != ' ') {
h_state = h_matching_connection_token;
}
break;
default:
UPDATE_STATE(s_header_value);
h_state = h_general;
break;
}
}
parser->header_state = h_state;
COUNT_HEADER_SIZE(p - start);
if (p == data + len)
--p;
break;
}
case s_header_almost_done:
{
STRICT_CHECK(ch != LF);
UPDATE_STATE(s_header_value_lws);
break;
}
case s_header_value_lws:
{
if (ch == ' ' || ch == '\t') {
UPDATE_STATE(s_header_value_start);
REEXECUTE();
}
/* finished the header */
switch (parser->header_state) {
case h_connection_keep_alive:
parser->flags |= F_CONNECTION_KEEP_ALIVE;
break;
case h_connection_close:
parser->flags |= F_CONNECTION_CLOSE;
break;
case h_transfer_encoding_chunked:
parser->flags |= F_CHUNKED;
break;
case h_connection_upgrade:
parser->flags |= F_CONNECTION_UPGRADE;
break;
default:
break;
}
UPDATE_STATE(s_header_field_start);
REEXECUTE();
}
case s_header_value_discard_ws_almost_done:
{
STRICT_CHECK(ch != LF);
UPDATE_STATE(s_header_value_discard_lws);
break;
}
case s_header_value_discard_lws:
{
if (ch == ' ' || ch == '\t') {
UPDATE_STATE(s_header_value_discard_ws);
break;
} else {
switch (parser->header_state) {
case h_connection_keep_alive:
parser->flags |= F_CONNECTION_KEEP_ALIVE;
break;
case h_connection_close:
parser->flags |= F_CONNECTION_CLOSE;
break;
case h_connection_upgrade:
parser->flags |= F_CONNECTION_UPGRADE;
break;
case h_transfer_encoding_chunked:
parser->flags |= F_CHUNKED;
break;
default:
break;
}
/* header value was empty */
MARK(header_value);
UPDATE_STATE(s_header_field_start);
CALLBACK_DATA_NOADVANCE(header_value);
REEXECUTE();
}
}
case s_headers_almost_done:
{
STRICT_CHECK(ch != LF);
if (parser->flags & F_TRAILING) {
/* End of a chunked request */
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
break;
}
UPDATE_STATE(s_headers_done);
/* Set this here so that on_headers_complete() callbacks can see it */
parser->upgrade =
((parser->flags & (F_UPGRADE | F_CONNECTION_UPGRADE)) ==
(F_UPGRADE | F_CONNECTION_UPGRADE) ||
parser->method == HTTP_CONNECT);
/* Here we call the headers_complete callback. This is somewhat
* different than other callbacks because if the user returns 1, we
* will interpret that as saying that this message has no body. This
* is needed for the annoying case of recieving a response to a HEAD
* request.
*
* We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so
* we have to simulate it by handling a change in errno below.
*/
if (settings->on_headers_complete) {
switch (settings->on_headers_complete(parser)) {
case 0:
break;
case 1:
parser->flags |= F_SKIPBODY;
break;
default:
SET_ERRNO(HPE_CB_headers_complete);
RETURN(p - data); /* Error */
}
}
if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
RETURN(p - data);
}
REEXECUTE();
}
case s_headers_done:
{
STRICT_CHECK(ch != LF);
parser->nread = 0;
/* Exit, the rest of the connect is in a different protocol. */
if (parser->upgrade) {
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
RETURN((p - data) + 1);
}
if (parser->flags & F_SKIPBODY) {
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
} else if (parser->flags & F_CHUNKED) {
/* chunked encoding - ignore Content-Length header */
UPDATE_STATE(s_chunk_size_start);
} else {
if (parser->content_length == 0) {
/* Content-Length header given but zero: Content-Length: 0\r\n */
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
} else if (parser->content_length != ULLONG_MAX) {
/* Content-Length header given and non-zero */
UPDATE_STATE(s_body_identity);
} else {
if (parser->type == HTTP_REQUEST ||
!http_message_needs_eof(parser)) {
/* Assume content-length 0 - read the next */
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
} else {
/* Read body until EOF */
UPDATE_STATE(s_body_identity_eof);
}
}
}
break;
}
case s_body_identity:
{
uint64_t to_read = MIN(parser->content_length,
(uint64_t) ((data + len) - p));
assert(parser->content_length != 0
&& parser->content_length != ULLONG_MAX);
/* The difference between advancing content_length and p is because
* the latter will automaticaly advance on the next loop iteration.
* Further, if content_length ends up at 0, we want to see the last
* byte again for our message complete callback.
*/
MARK(body);
parser->content_length -= to_read;
p += to_read - 1;
if (parser->content_length == 0) {
UPDATE_STATE(s_message_done);
/* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte.
*
* The alternative to doing this is to wait for the next byte to
* trigger the data callback, just as in every other case. The
* problem with this is that this makes it difficult for the test
* harness to distinguish between complete-on-EOF and
* complete-on-length. It's not clear that this distinction is
* important for applications, but let's keep it for now.
*/
CALLBACK_DATA_(body, p - body_mark + 1, p - data);
REEXECUTE();
}
break;
}
/* read until EOF */
case s_body_identity_eof:
MARK(body);
p = data + len - 1;
break;
case s_message_done:
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
break;
case s_chunk_size_start:
{
assert(parser->nread == 1);
assert(parser->flags & F_CHUNKED);
unhex_val = unhex[(unsigned char)ch];
if (UNLIKELY(unhex_val == -1)) {
SET_ERRNO(HPE_INVALID_CHUNK_SIZE);
goto error;
}
parser->content_length = unhex_val;
UPDATE_STATE(s_chunk_size);
break;
}
case s_chunk_size:
{
uint64_t t;
assert(parser->flags & F_CHUNKED);
if (ch == CR) {
UPDATE_STATE(s_chunk_size_almost_done);
break;
}
unhex_val = unhex[(unsigned char)ch];
if (unhex_val == -1) {
if (ch == ';' || ch == ' ') {
UPDATE_STATE(s_chunk_parameters);
break;
}
SET_ERRNO(HPE_INVALID_CHUNK_SIZE);
goto error;
}
t = parser->content_length;
t *= 16;
t += unhex_val;
/* Overflow? Test against a conservative limit for simplicity. */
if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) {
SET_ERRNO(HPE_INVALID_CONTENT_LENGTH);
goto error;
}
parser->content_length = t;
break;
}
case s_chunk_parameters:
{
assert(parser->flags & F_CHUNKED);
/* just ignore this shit. TODO check for overflow */
if (ch == CR) {
UPDATE_STATE(s_chunk_size_almost_done);
break;
}
break;
}
case s_chunk_size_almost_done:
{
assert(parser->flags & F_CHUNKED);
STRICT_CHECK(ch != LF);
parser->nread = 0;
if (parser->content_length == 0) {
parser->flags |= F_TRAILING;
UPDATE_STATE(s_header_field_start);
} else {
UPDATE_STATE(s_chunk_data);
}
break;
}
case s_chunk_data:
{
uint64_t to_read = MIN(parser->content_length,
(uint64_t) ((data + len) - p));
assert(parser->flags & F_CHUNKED);
assert(parser->content_length != 0
&& parser->content_length != ULLONG_MAX);
/* See the explanation in s_body_identity for why the content
* length and data pointers are managed this way.
*/
MARK(body);
parser->content_length -= to_read;
p += to_read - 1;
if (parser->content_length == 0) {
UPDATE_STATE(s_chunk_data_almost_done);
}
break;
}
case s_chunk_data_almost_done:
assert(parser->flags & F_CHUNKED);
assert(parser->content_length == 0);
STRICT_CHECK(ch != CR);
UPDATE_STATE(s_chunk_data_done);
CALLBACK_DATA(body);
break;
case s_chunk_data_done:
assert(parser->flags & F_CHUNKED);
STRICT_CHECK(ch != LF);
parser->nread = 0;
UPDATE_STATE(s_chunk_size_start);
break;
default:
assert(0 && "unhandled state");
SET_ERRNO(HPE_INVALID_INTERNAL_STATE);
goto error;
}
}
/* Run callbacks for any marks that we have leftover after we ran our of
* bytes. There should be at most one of these set, so it's OK to invoke
* them in series (unset marks will not result in callbacks).
*
* We use the NOADVANCE() variety of callbacks here because 'p' has already
* overflowed 'data' and this allows us to correct for the off-by-one that
* we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p'
* value that's in-bounds).
*/
assert(((header_field_mark ? 1 : 0) +
(header_value_mark ? 1 : 0) +
(url_mark ? 1 : 0) +
(body_mark ? 1 : 0) +
(status_mark ? 1 : 0)) <= 1);
CALLBACK_DATA_NOADVANCE(header_field);
CALLBACK_DATA_NOADVANCE(header_value);
CALLBACK_DATA_NOADVANCE(url);
CALLBACK_DATA_NOADVANCE(body);
CALLBACK_DATA_NOADVANCE(status);
RETURN(len);
error:
if (HTTP_PARSER_ERRNO(parser) == HPE_OK) {
SET_ERRNO(HPE_UNKNOWN);
}
RETURN(p - data);
}
/* Does the parser need to see an EOF to find the end of the message? */
int
http_message_needs_eof (const http_parser *parser)
{
if (parser->type == HTTP_REQUEST) {
return 0;
}
/* See RFC 2616 section 4.4 */
if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */
parser->status_code == 204 || /* No Content */
parser->status_code == 304 || /* Not Modified */
parser->flags & F_SKIPBODY) { /* response to a HEAD request */
return 0;
}
if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) {
return 0;
}
return 1;
}
int
http_should_keep_alive (const http_parser *parser)
{
if (parser->http_major > 0 && parser->http_minor > 0) {
/* HTTP/1.1 */
if (parser->flags & F_CONNECTION_CLOSE) {
return 0;
}
} else {
/* HTTP/1.0 or earlier */
if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) {
return 0;
}
}
return !http_message_needs_eof(parser);
}
const char *
http_method_str (enum http_method m)
{
return ELEM_AT(method_strings, m, "<unknown>");
}
void
http_parser_init (http_parser *parser, enum http_parser_type t)
{
void *data = parser->data; /* preserve application data */
memset(parser, 0, sizeof(*parser));
parser->data = data;
parser->type = t;
parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res));
parser->http_errno = HPE_OK;
}
const char *
http_errno_name(enum http_errno err) {
assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0])));
return http_strerror_tab[err].name;
}
const char *
http_errno_description(enum http_errno err) {
assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0])));
return http_strerror_tab[err].description;
}
static enum http_host_state
http_parse_host_char(enum http_host_state s, const char ch) {
switch(s) {
case s_http_userinfo:
case s_http_userinfo_start:
if (ch == '@') {
return s_http_host_start;
}
if (IS_USERINFO_CHAR(ch)) {
return s_http_userinfo;
}
break;
case s_http_host_start:
if (ch == '[') {
return s_http_host_v6_start;
}
if (IS_HOST_CHAR(ch)) {
return s_http_host;
}
break;
case s_http_host:
if (IS_HOST_CHAR(ch)) {
return s_http_host;
}
/* FALLTHROUGH */
case s_http_host_v6_end:
if (ch == ':') {
return s_http_host_port_start;
}
break;
case s_http_host_v6:
if (ch == ']') {
return s_http_host_v6_end;
}
/* FALLTHROUGH */
case s_http_host_v6_start:
if (IS_HEX(ch) || ch == ':' || ch == '.') {
return s_http_host_v6;
}
break;
case s_http_host_port:
case s_http_host_port_start:
if (IS_NUM(ch)) {
return s_http_host_port;
}
break;
default:
break;
}
return s_http_host_dead;
}
static int
http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
enum http_host_state s;
const char *p;
size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len;
u->field_data[UF_HOST].len = 0;
s = found_at ? s_http_userinfo_start : s_http_host_start;
for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) {
enum http_host_state new_s = http_parse_host_char(s, *p);
if (new_s == s_http_host_dead) {
return 1;
}
switch(new_s) {
case s_http_host:
if (s != s_http_host) {
u->field_data[UF_HOST].off = p - buf;
}
u->field_data[UF_HOST].len++;
break;
case s_http_host_v6:
if (s != s_http_host_v6) {
u->field_data[UF_HOST].off = p - buf;
}
u->field_data[UF_HOST].len++;
break;
case s_http_host_port:
if (s != s_http_host_port) {
u->field_data[UF_PORT].off = p - buf;
u->field_data[UF_PORT].len = 0;
u->field_set |= (1 << UF_PORT);
}
u->field_data[UF_PORT].len++;
break;
case s_http_userinfo:
if (s != s_http_userinfo) {
u->field_data[UF_USERINFO].off = p - buf ;
u->field_data[UF_USERINFO].len = 0;
u->field_set |= (1 << UF_USERINFO);
}
u->field_data[UF_USERINFO].len++;
break;
default:
break;
}
s = new_s;
}
/* Make sure we don't end somewhere unexpected */
switch (s) {
case s_http_host_start:
case s_http_host_v6_start:
case s_http_host_v6:
case s_http_host_port_start:
case s_http_userinfo:
case s_http_userinfo_start:
return 1;
default:
break;
}
return 0;
}
int
http_parser_parse_url(const char *buf, size_t buflen, int is_connect,
struct http_parser_url *u)
{
enum state s;
const char *p;
enum http_parser_url_fields uf, old_uf;
int found_at = 0;
u->port = u->field_set = 0;
s = is_connect ? s_req_server_start : s_req_spaces_before_url;
old_uf = UF_MAX;
for (p = buf; p < buf + buflen; p++) {
s = parse_url_char(s, *p);
/* Figure out the next field that we're operating on */
switch (s) {
case s_dead:
return 1;
/* Skip delimeters */
case s_req_schema_slash:
case s_req_schema_slash_slash:
case s_req_server_start:
case s_req_query_string_start:
case s_req_fragment_start:
continue;
case s_req_schema:
uf = UF_SCHEMA;
break;
case s_req_server_with_at:
found_at = 1;
/* FALLTROUGH */
case s_req_server:
uf = UF_HOST;
break;
case s_req_path:
uf = UF_PATH;
break;
case s_req_query_string:
uf = UF_QUERY;
break;
case s_req_fragment:
uf = UF_FRAGMENT;
break;
default:
assert(!"Unexpected state");
return 1;
}
/* Nothing's changed; soldier on */
if (uf == old_uf) {
u->field_data[uf].len++;
continue;
}
u->field_data[uf].off = p - buf;
u->field_data[uf].len = 1;
u->field_set |= (1 << uf);
old_uf = uf;
}
/* host must be present if there is a schema */
/* parsing http:///toto will fail */
if ((u->field_set & ((1 << UF_SCHEMA) | (1 << UF_HOST))) != 0) {
if (http_parse_host(buf, u, found_at) != 0) {
return 1;
}
}
/* CONNECT requests can only contain "hostname:port" */
if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) {
return 1;
}
if (u->field_set & (1 << UF_PORT)) {
/* Don't bother with endp; we've already validated the string */
unsigned long v = strtoul(buf + u->field_data[UF_PORT].off, NULL, 10);
/* Ports have a max value of 2^16 */
if (v > 0xffff) {
return 1;
}
u->port = (uint16_t) v;
}
return 0;
}
void
http_parser_pause(http_parser *parser, int paused) {
/* Users should only be pausing/unpausing a parser that is not in an error
* state. In non-debug builds, there's not much that we can do about this
* other than ignore it.
*/
if (HTTP_PARSER_ERRNO(parser) == HPE_OK ||
HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) {
SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK);
} else {
assert(0 && "Attempting to pause parser in error state");
}
}
int
http_body_is_final(const struct http_parser *parser) {
return parser->state == s_message_done;
}
unsigned long
http_parser_version(void) {
return HTTP_PARSER_VERSION_MAJOR * 0x10000 |
HTTP_PARSER_VERSION_MINOR * 0x00100 |
HTTP_PARSER_VERSION_PATCH * 0x00001;
}
| apache-2.0 |
jrmull/sagetv | native/dll/Win32ShellHook/Win32ShellHook.cpp | 31 | 7124 | /*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
#include "Win32ShellHook.h"
#include "sage_UserEvent.h"
static HINSTANCE g_hInstance = NULL;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_hInstance = (HINSTANCE)hModule;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#pragma data_seg(".shared")
HWND hShellNotifyWnd = NULL;
HHOOK hShellHook = NULL; // Handle to the Shell hook
#pragma data_seg( )
LRESULT CALLBACK ShellProc (int nCode, WPARAM wParam, LPARAM lParam);
DllExport BOOL InstallShellHook(HWND hWnd)
{
if (hWnd == NULL) return FALSE;
if (hShellNotifyWnd != NULL) return FALSE;
// Add the ShellProc hook
hShellHook = SetWindowsHookEx(
WH_SHELL, // Hook in before msg reaches app
(HOOKPROC) ShellProc, // Hook procedure
g_hInstance, // This DLL instance
0L // Hook in to all apps
);
if (hShellHook != NULL)
{
hShellNotifyWnd = hWnd;
return TRUE;
}
return FALSE;
}
DllExport BOOL RemoveShellHook(HWND hWnd)
{
if (hWnd != hShellNotifyWnd || !hWnd) return FALSE;
UnhookWindowsHookEx(hShellHook);
hShellHook = NULL;
hShellNotifyWnd = NULL;
return TRUE;
}
// Hook procedure for Shell hook
#define HSHELL_APPCOMMAND 12
#define FAPPCOMMAND_MASK 0xF000
#define GET_APPCOMMAND_LPARAM(lParam) ((short)(HIWORD(lParam) & ~FAPPCOMMAND_MASK))
#define WM_APPCOMMAND 0x0319
#define APPCOMMAND_BROWSER_BACKWARD 1
#define APPCOMMAND_BROWSER_FORWARD 2
#define APPCOMMAND_BROWSER_REFRESH 3
#define APPCOMMAND_BROWSER_STOP 4
#define APPCOMMAND_BROWSER_SEARCH 5
#define APPCOMMAND_BROWSER_FAVORITES 6
#define APPCOMMAND_BROWSER_HOME 7
#define APPCOMMAND_VOLUME_MUTE 8
#define APPCOMMAND_VOLUME_DOWN 9
#define APPCOMMAND_VOLUME_UP 10
#define APPCOMMAND_MEDIA_NEXTTRACK 11
#define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
#define APPCOMMAND_MEDIA_STOP 13
#define APPCOMMAND_MEDIA_PLAY_PAUSE 14
#define APPCOMMAND_LAUNCH_MAIL 15
#define APPCOMMAND_LAUNCH_MEDIA_SELECT 16
#define APPCOMMAND_LAUNCH_APP1 17
#define APPCOMMAND_LAUNCH_APP2 18
#define APPCOMMAND_BASS_DOWN 19
#define APPCOMMAND_BASS_BOOST 20
#define APPCOMMAND_BASS_UP 21
#define APPCOMMAND_TREBLE_DOWN 22
#define APPCOMMAND_TREBLE_UP 23
#define APPCOMMAND_MICROPHONE_VOLUME_MUTE 24
#define APPCOMMAND_MICROPHONE_VOLUME_DOWN 25
#define APPCOMMAND_MICROPHONE_VOLUME_UP 26
#define APPCOMMAND_HELP 27
#define APPCOMMAND_FIND 28
#define APPCOMMAND_NEW 29
#define APPCOMMAND_OPEN 30
#define APPCOMMAND_CLOSE 31
#define APPCOMMAND_SAVE 32
#define APPCOMMAND_PRINT 33
#define APPCOMMAND_UNDO 34
#define APPCOMMAND_REDO 35
#define APPCOMMAND_COPY 36
#define APPCOMMAND_CUT 37
#define APPCOMMAND_PASTE 38
#define APPCOMMAND_REPLY_TO_MAIL 39
#define APPCOMMAND_FORWARD_MAIL 40
#define APPCOMMAND_SEND_MAIL 41
#define APPCOMMAND_SPELL_CHECK 42
#define APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE 43
#define APPCOMMAND_MIC_ON_OFF_TOGGLE 44
#define APPCOMMAND_CORRECTION_LIST 45
#define APPCOMMAND_MEDIA_PLAY 46
#define APPCOMMAND_MEDIA_PAUSE 47
#define APPCOMMAND_MEDIA_RECORD 48
#define APPCOMMAND_MEDIA_FAST_FORWARD 49
#define APPCOMMAND_MEDIA_REWIND 50
#define APPCOMMAND_MEDIA_CHANNEL_UP 51
#define APPCOMMAND_MEDIA_CHANNEL_DOWN 52
LRESULT CALLBACK ShellProc(int nCode, WPARAM wParam, LPARAM lParam)
{
// Do we have to handle this message?
if (nCode == HSHELL_APPCOMMAND)
{
// Process the hook if the hNotifyWnd window handle is valid
if (hShellNotifyWnd != NULL)
{
short AppCommand = GET_APPCOMMAND_LPARAM(lParam);
LPARAM testParam = 0;
switch (AppCommand)
{
case APPCOMMAND_BROWSER_BACKWARD:
testParam = sage_UserEvent_BACK;
break;
case APPCOMMAND_BROWSER_FORWARD:
testParam = sage_UserEvent_FORWARD;
break;
case APPCOMMAND_VOLUME_MUTE:
testParam = sage_UserEvent_MUTE;
break;
case APPCOMMAND_VOLUME_DOWN:
testParam = sage_UserEvent_VOLUME_DOWN;
break;
case APPCOMMAND_VOLUME_UP:
testParam = sage_UserEvent_VOLUME_UP;
break;
case APPCOMMAND_MEDIA_STOP:
testParam = sage_UserEvent_STOP;
break;
case APPCOMMAND_MEDIA_PLAY_PAUSE:
testParam = sage_UserEvent_PLAY_PAUSE;
break;
case APPCOMMAND_MEDIA_NEXTTRACK:
testParam = sage_UserEvent_FF_2;
break;
case APPCOMMAND_MEDIA_PREVIOUSTRACK:
testParam = sage_UserEvent_REW_2;
break;
// case APPCOMMAND_BROWSER_FAVORITES:
// testParam = sage_UserEvent_RATE_UP;
// break;
// case APPCOMMAND_BROWSER_HOME:
// testParam = sage_UserEvent_HOME;
// break;
// case APPCOMMAND_BROWSER_SEARCH:
// testParam = sage_UserEvent_SEARCH;
// break;
case APPCOMMAND_MEDIA_PLAY:
testParam = sage_UserEvent_PLAY;
break;
case APPCOMMAND_MEDIA_PAUSE:
testParam = sage_UserEvent_PAUSE;
break;
case APPCOMMAND_MEDIA_RECORD:
testParam = sage_UserEvent_RECORD;
break;
case APPCOMMAND_MEDIA_FAST_FORWARD:
testParam = sage_UserEvent_FF;
break;
case APPCOMMAND_MEDIA_REWIND:
testParam = sage_UserEvent_REW;
break;
case APPCOMMAND_MEDIA_CHANNEL_UP:
testParam = sage_UserEvent_CHANNEL_UP;
break;
case APPCOMMAND_MEDIA_CHANNEL_DOWN:
testParam = sage_UserEvent_CHANNEL_DOWN;
break;
}
if (testParam)
{
PostMessage(hShellNotifyWnd,WM_USER + 234,wParam,testParam);
return 1; // dont call CallNextHookEx, instead return non-zero, because we have handled the message (see MSDN doc)
}
}
}
// Call the next handler in the chain
return CallNextHookEx (hShellHook, nCode, wParam, lParam);
}
| apache-2.0 |
m0ppers/arangodb | 3rdParty/boost/1.61.0/libs/multiprecision/test/test_arithmetic_cpp_bin_float_2.cpp | 32 | 1533 | ///////////////////////////////////////////////////////////////
// Copyright 2012 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_
#ifdef _MSC_VER
# define _SCL_SECURE_NO_WARNINGS
#endif
#include <boost/multiprecision/cpp_bin_float.hpp>
#include "libs/multiprecision/test/test_arithmetic.hpp"
template <unsigned Digits, boost::multiprecision::backends::digit_base_type DigitBase, class Allocator, class Exponent, Exponent MinExponent, Exponent MaxExponent, boost::multiprecision::expression_template_option ET>
struct related_type<boost::multiprecision::number< boost::multiprecision::cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinExponent, MaxExponent>, ET> >
{
typedef boost::multiprecision::number< boost::multiprecision::cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinExponent, MaxExponent>, ET> number_type;
typedef boost::multiprecision::number< boost::multiprecision::cpp_bin_float<((std::numeric_limits<number_type>::digits / 2) > std::numeric_limits<long double>::digits ? Digits / 2 : Digits), DigitBase, Allocator, Exponent, MinExponent, MaxExponent>, ET> type;
};
int main()
{
//test<boost::multiprecision::cpp_bin_float_50>();
test<boost::multiprecision::number<boost::multiprecision::cpp_bin_float<1000, boost::multiprecision::digit_base_10, std::allocator<void> > > >();
//test<boost::multiprecision::cpp_bin_float_quad>();
return boost::report_errors();
}
| apache-2.0 |
gonboy/sl4a | python/src/Modules/_lsprof.c | 32 | 24033 | #include "Python.h"
#include "compile.h"
#include "frameobject.h"
#include "structseq.h"
#include "rotatingtree.h"
#if !defined(HAVE_LONG_LONG)
#error "This module requires long longs!"
#endif
/*** Selection of a high-precision timer ***/
#ifdef MS_WINDOWS
#include <windows.h>
static PY_LONG_LONG
hpTimer(void)
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return li.QuadPart;
}
static double
hpTimerUnit(void)
{
LARGE_INTEGER li;
if (QueryPerformanceFrequency(&li))
return 1.0 / li.QuadPart;
else
return 0.000001; /* unlikely */
}
#else /* !MS_WINDOWS */
#ifndef HAVE_GETTIMEOFDAY
#error "This module requires gettimeofday() on non-Windows platforms!"
#endif
#if (defined(PYOS_OS2) && defined(PYCC_GCC))
#include <sys/time.h>
#else
#include <sys/resource.h>
#include <sys/times.h>
#endif
static PY_LONG_LONG
hpTimer(void)
{
struct timeval tv;
PY_LONG_LONG ret;
#ifdef GETTIMEOFDAY_NO_TZ
gettimeofday(&tv);
#else
gettimeofday(&tv, (struct timezone *)NULL);
#endif
ret = tv.tv_sec;
ret = ret * 1000000 + tv.tv_usec;
return ret;
}
static double
hpTimerUnit(void)
{
return 0.000001;
}
#endif /* MS_WINDOWS */
/************************************************************/
/* Written by Brett Rosen and Ted Czotter */
struct _ProfilerEntry;
/* represents a function called from another function */
typedef struct _ProfilerSubEntry {
rotating_node_t header;
PY_LONG_LONG tt;
PY_LONG_LONG it;
long callcount;
long recursivecallcount;
long recursionLevel;
} ProfilerSubEntry;
/* represents a function or user defined block */
typedef struct _ProfilerEntry {
rotating_node_t header;
PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */
PY_LONG_LONG tt; /* total time in this entry */
PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */
long callcount; /* how many times this was called */
long recursivecallcount; /* how many times called recursively */
long recursionLevel;
rotating_node_t *calls;
} ProfilerEntry;
typedef struct _ProfilerContext {
PY_LONG_LONG t0;
PY_LONG_LONG subt;
struct _ProfilerContext *previous;
ProfilerEntry *ctxEntry;
} ProfilerContext;
typedef struct {
PyObject_HEAD
rotating_node_t *profilerEntries;
ProfilerContext *currentProfilerContext;
ProfilerContext *freelistProfilerContext;
int flags;
PyObject *externalTimer;
double externalTimerUnit;
} ProfilerObject;
#define POF_ENABLED 0x001
#define POF_SUBCALLS 0x002
#define POF_BUILTINS 0x004
#define POF_NOMEMORY 0x100
staticforward PyTypeObject PyProfiler_Type;
#define PyProfiler_Check(op) PyObject_TypeCheck(op, &PyProfiler_Type)
#define PyProfiler_CheckExact(op) (Py_TYPE(op) == &PyProfiler_Type)
/*** External Timers ***/
#define DOUBLE_TIMER_PRECISION 4294967296.0
static PyObject *empty_tuple;
static PY_LONG_LONG CallExternalTimer(ProfilerObject *pObj)
{
PY_LONG_LONG result;
PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL);
if (o == NULL) {
PyErr_WriteUnraisable(pObj->externalTimer);
return 0;
}
if (pObj->externalTimerUnit > 0.0) {
/* interpret the result as an integer that will be scaled
in profiler_getstats() */
result = PyLong_AsLongLong(o);
}
else {
/* interpret the result as a double measured in seconds.
As the profiler works with PY_LONG_LONG internally
we convert it to a large integer */
double val = PyFloat_AsDouble(o);
/* error handling delayed to the code below */
result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION);
}
Py_DECREF(o);
if (PyErr_Occurred()) {
PyErr_WriteUnraisable(pObj->externalTimer);
return 0;
}
return result;
}
#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \
CallExternalTimer(pObj) : \
hpTimer())
/*** ProfilerObject ***/
static PyObject *
normalizeUserObj(PyObject *obj)
{
PyCFunctionObject *fn;
if (!PyCFunction_Check(obj)) {
Py_INCREF(obj);
return obj;
}
/* Replace built-in function objects with a descriptive string
because of built-in methods -- keeping a reference to
__self__ is probably not a good idea. */
fn = (PyCFunctionObject *)obj;
if (fn->m_self == NULL) {
/* built-in function: look up the module name */
PyObject *mod = fn->m_module;
char *modname;
if (mod && PyString_Check(mod)) {
modname = PyString_AS_STRING(mod);
}
else if (mod && PyModule_Check(mod)) {
modname = PyModule_GetName(mod);
if (modname == NULL) {
PyErr_Clear();
modname = "__builtin__";
}
}
else {
modname = "__builtin__";
}
if (strcmp(modname, "__builtin__") != 0)
return PyString_FromFormat("<%s.%s>",
modname,
fn->m_ml->ml_name);
else
return PyString_FromFormat("<%s>",
fn->m_ml->ml_name);
}
else {
/* built-in method: try to return
repr(getattr(type(__self__), __name__))
*/
PyObject *self = fn->m_self;
PyObject *name = PyString_FromString(fn->m_ml->ml_name);
if (name != NULL) {
PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
Py_XINCREF(mo);
Py_DECREF(name);
if (mo != NULL) {
PyObject *res = PyObject_Repr(mo);
Py_DECREF(mo);
if (res != NULL)
return res;
}
}
PyErr_Clear();
return PyString_FromFormat("<built-in method %s>",
fn->m_ml->ml_name);
}
}
static ProfilerEntry*
newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj)
{
ProfilerEntry *self;
self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry));
if (self == NULL) {
pObj->flags |= POF_NOMEMORY;
return NULL;
}
userObj = normalizeUserObj(userObj);
if (userObj == NULL) {
PyErr_Clear();
free(self);
pObj->flags |= POF_NOMEMORY;
return NULL;
}
self->header.key = key;
self->userObj = userObj;
self->tt = 0;
self->it = 0;
self->callcount = 0;
self->recursivecallcount = 0;
self->recursionLevel = 0;
self->calls = EMPTY_ROTATING_TREE;
RotatingTree_Add(&pObj->profilerEntries, &self->header);
return self;
}
static ProfilerEntry*
getEntry(ProfilerObject *pObj, void *key)
{
return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key);
}
static ProfilerSubEntry *
getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
{
return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls,
(void *)entry);
}
static ProfilerSubEntry *
newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
{
ProfilerSubEntry *self;
self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry));
if (self == NULL) {
pObj->flags |= POF_NOMEMORY;
return NULL;
}
self->header.key = (void *)entry;
self->tt = 0;
self->it = 0;
self->callcount = 0;
self->recursivecallcount = 0;
self->recursionLevel = 0;
RotatingTree_Add(&caller->calls, &self->header);
return self;
}
static int freeSubEntry(rotating_node_t *header, void *arg)
{
ProfilerSubEntry *subentry = (ProfilerSubEntry*) header;
free(subentry);
return 0;
}
static int freeEntry(rotating_node_t *header, void *arg)
{
ProfilerEntry *entry = (ProfilerEntry*) header;
RotatingTree_Enum(entry->calls, freeSubEntry, NULL);
Py_DECREF(entry->userObj);
free(entry);
return 0;
}
static void clearEntries(ProfilerObject *pObj)
{
RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL);
pObj->profilerEntries = EMPTY_ROTATING_TREE;
/* release the memory hold by the free list of ProfilerContexts */
while (pObj->freelistProfilerContext) {
ProfilerContext *c = pObj->freelistProfilerContext;
pObj->freelistProfilerContext = c->previous;
free(c);
}
}
static void
initContext(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
{
self->ctxEntry = entry;
self->subt = 0;
self->previous = pObj->currentProfilerContext;
pObj->currentProfilerContext = self;
++entry->recursionLevel;
if ((pObj->flags & POF_SUBCALLS) && self->previous) {
/* find or create an entry for me in my caller's entry */
ProfilerEntry *caller = self->previous->ctxEntry;
ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
if (subentry == NULL)
subentry = newSubEntry(pObj, caller, entry);
if (subentry)
++subentry->recursionLevel;
}
self->t0 = CALL_TIMER(pObj);
}
static void
Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
{
PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0;
PY_LONG_LONG it = tt - self->subt;
if (self->previous)
self->previous->subt += tt;
pObj->currentProfilerContext = self->previous;
if (--entry->recursionLevel == 0)
entry->tt += tt;
else
++entry->recursivecallcount;
entry->it += it;
entry->callcount++;
if ((pObj->flags & POF_SUBCALLS) && self->previous) {
/* find or create an entry for me in my caller's entry */
ProfilerEntry *caller = self->previous->ctxEntry;
ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
if (subentry) {
if (--subentry->recursionLevel == 0)
subentry->tt += tt;
else
++subentry->recursivecallcount;
subentry->it += it;
++subentry->callcount;
}
}
}
static void
ptrace_enter_call(PyObject *self, void *key, PyObject *userObj)
{
/* entering a call to the function identified by 'key'
(which can be a PyCodeObject or a PyMethodDef pointer) */
ProfilerObject *pObj = (ProfilerObject*)self;
ProfilerEntry *profEntry;
ProfilerContext *pContext;
/* In the case of entering a generator expression frame via a
* throw (gen_send_ex(.., 1)), we may already have an
* Exception set here. We must not mess around with this
* exception, and some of the code under here assumes that
* PyErr_* is its own to mess around with, so we have to
* save and restore any current exception. */
PyObject *last_type, *last_value, *last_tb;
PyErr_Fetch(&last_type, &last_value, &last_tb);
profEntry = getEntry(pObj, key);
if (profEntry == NULL) {
profEntry = newProfilerEntry(pObj, key, userObj);
if (profEntry == NULL)
goto restorePyerr;
}
/* grab a ProfilerContext out of the free list */
pContext = pObj->freelistProfilerContext;
if (pContext) {
pObj->freelistProfilerContext = pContext->previous;
}
else {
/* free list exhausted, allocate a new one */
pContext = (ProfilerContext*)
malloc(sizeof(ProfilerContext));
if (pContext == NULL) {
pObj->flags |= POF_NOMEMORY;
goto restorePyerr;
}
}
initContext(pObj, pContext, profEntry);
restorePyerr:
PyErr_Restore(last_type, last_value, last_tb);
}
static void
ptrace_leave_call(PyObject *self, void *key)
{
/* leaving a call to the function identified by 'key' */
ProfilerObject *pObj = (ProfilerObject*)self;
ProfilerEntry *profEntry;
ProfilerContext *pContext;
pContext = pObj->currentProfilerContext;
if (pContext == NULL)
return;
profEntry = getEntry(pObj, key);
if (profEntry) {
Stop(pObj, pContext, profEntry);
}
else {
pObj->currentProfilerContext = pContext->previous;
}
/* put pContext into the free list */
pContext->previous = pObj->freelistProfilerContext;
pObj->freelistProfilerContext = pContext;
}
static int
profiler_callback(PyObject *self, PyFrameObject *frame, int what,
PyObject *arg)
{
switch (what) {
/* the 'frame' of a called function is about to start its execution */
case PyTrace_CALL:
ptrace_enter_call(self, (void *)frame->f_code,
(PyObject *)frame->f_code);
break;
/* the 'frame' of a called function is about to finish
(either normally or with an exception) */
case PyTrace_RETURN:
ptrace_leave_call(self, (void *)frame->f_code);
break;
/* case PyTrace_EXCEPTION:
If the exception results in the function exiting, a
PyTrace_RETURN event will be generated, so we don't need to
handle it. */
#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */
/* the Python function 'frame' is issuing a call to the built-in
function 'arg' */
case PyTrace_C_CALL:
if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
&& PyCFunction_Check(arg)) {
ptrace_enter_call(self,
((PyCFunctionObject *)arg)->m_ml,
arg);
}
break;
/* the call to the built-in function 'arg' is returning into its
caller 'frame' */
case PyTrace_C_RETURN: /* ...normally */
case PyTrace_C_EXCEPTION: /* ...with an exception set */
if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
&& PyCFunction_Check(arg)) {
ptrace_leave_call(self,
((PyCFunctionObject *)arg)->m_ml);
}
break;
#endif
default:
break;
}
return 0;
}
static int
pending_exception(ProfilerObject *pObj)
{
if (pObj->flags & POF_NOMEMORY) {
pObj->flags -= POF_NOMEMORY;
PyErr_SetString(PyExc_MemoryError,
"memory was exhausted while profiling");
return -1;
}
return 0;
}
/************************************************************/
static PyStructSequence_Field profiler_entry_fields[] = {
{"code", "code object or built-in function name"},
{"callcount", "how many times this was called"},
{"reccallcount", "how many times called recursively"},
{"totaltime", "total time in this entry"},
{"inlinetime", "inline time in this entry (not in subcalls)"},
{"calls", "details of the calls"},
{0}
};
static PyStructSequence_Field profiler_subentry_fields[] = {
{"code", "called code object or built-in function name"},
{"callcount", "how many times this is called"},
{"reccallcount", "how many times this is called recursively"},
{"totaltime", "total time spent in this call"},
{"inlinetime", "inline time (not in further subcalls)"},
{0}
};
static PyStructSequence_Desc profiler_entry_desc = {
"_lsprof.profiler_entry", /* name */
NULL, /* doc */
profiler_entry_fields,
6
};
static PyStructSequence_Desc profiler_subentry_desc = {
"_lsprof.profiler_subentry", /* name */
NULL, /* doc */
profiler_subentry_fields,
5
};
static int initialized;
static PyTypeObject StatsEntryType;
static PyTypeObject StatsSubEntryType;
typedef struct {
PyObject *list;
PyObject *sublist;
double factor;
} statscollector_t;
static int statsForSubEntry(rotating_node_t *node, void *arg)
{
ProfilerSubEntry *sentry = (ProfilerSubEntry*) node;
statscollector_t *collect = (statscollector_t*) arg;
ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key;
int err;
PyObject *sinfo;
sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType,
"((Olldd))",
entry->userObj,
sentry->callcount,
sentry->recursivecallcount,
collect->factor * sentry->tt,
collect->factor * sentry->it);
if (sinfo == NULL)
return -1;
err = PyList_Append(collect->sublist, sinfo);
Py_DECREF(sinfo);
return err;
}
static int statsForEntry(rotating_node_t *node, void *arg)
{
ProfilerEntry *entry = (ProfilerEntry*) node;
statscollector_t *collect = (statscollector_t*) arg;
PyObject *info;
int err;
if (entry->callcount == 0)
return 0; /* skip */
if (entry->calls != EMPTY_ROTATING_TREE) {
collect->sublist = PyList_New(0);
if (collect->sublist == NULL)
return -1;
if (RotatingTree_Enum(entry->calls,
statsForSubEntry, collect) != 0) {
Py_DECREF(collect->sublist);
return -1;
}
}
else {
Py_INCREF(Py_None);
collect->sublist = Py_None;
}
info = PyObject_CallFunction((PyObject*) &StatsEntryType,
"((OllddO))",
entry->userObj,
entry->callcount,
entry->recursivecallcount,
collect->factor * entry->tt,
collect->factor * entry->it,
collect->sublist);
Py_DECREF(collect->sublist);
if (info == NULL)
return -1;
err = PyList_Append(collect->list, info);
Py_DECREF(info);
return err;
}
PyDoc_STRVAR(getstats_doc, "\
getstats() -> list of profiler_entry objects\n\
\n\
Return all information collected by the profiler.\n\
Each profiler_entry is a tuple-like object with the\n\
following attributes:\n\
\n\
code code object\n\
callcount how many times this was called\n\
reccallcount how many times called recursively\n\
totaltime total time in this entry\n\
inlinetime inline time in this entry (not in subcalls)\n\
calls details of the calls\n\
\n\
The calls attribute is either None or a list of\n\
profiler_subentry objects:\n\
\n\
code called code object\n\
callcount how many times this is called\n\
reccallcount how many times this is called recursively\n\
totaltime total time spent in this call\n\
inlinetime inline time (not in further subcalls)\n\
");
static PyObject*
profiler_getstats(ProfilerObject *pObj, PyObject* noarg)
{
statscollector_t collect;
if (pending_exception(pObj))
return NULL;
if (!pObj->externalTimer)
collect.factor = hpTimerUnit();
else if (pObj->externalTimerUnit > 0.0)
collect.factor = pObj->externalTimerUnit;
else
collect.factor = 1.0 / DOUBLE_TIMER_PRECISION;
collect.list = PyList_New(0);
if (collect.list == NULL)
return NULL;
if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect)
!= 0) {
Py_DECREF(collect.list);
return NULL;
}
return collect.list;
}
static int
setSubcalls(ProfilerObject *pObj, int nvalue)
{
if (nvalue == 0)
pObj->flags &= ~POF_SUBCALLS;
else if (nvalue > 0)
pObj->flags |= POF_SUBCALLS;
return 0;
}
static int
setBuiltins(ProfilerObject *pObj, int nvalue)
{
if (nvalue == 0)
pObj->flags &= ~POF_BUILTINS;
else if (nvalue > 0) {
#ifndef PyTrace_C_CALL
PyErr_SetString(PyExc_ValueError,
"builtins=True requires Python >= 2.4");
return -1;
#else
pObj->flags |= POF_BUILTINS;
#endif
}
return 0;
}
PyDoc_STRVAR(enable_doc, "\
enable(subcalls=True, builtins=True)\n\
\n\
Start collecting profiling information.\n\
If 'subcalls' is True, also records for each function\n\
statistics separated according to its current caller.\n\
If 'builtins' is True, records the time spent in\n\
built-in functions separately from their caller.\n\
");
static PyObject*
profiler_enable(ProfilerObject *self, PyObject *args, PyObject *kwds)
{
int subcalls = -1;
int builtins = -1;
static char *kwlist[] = {"subcalls", "builtins", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable",
kwlist, &subcalls, &builtins))
return NULL;
if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0)
return NULL;
PyEval_SetProfile(profiler_callback, (PyObject*)self);
self->flags |= POF_ENABLED;
Py_INCREF(Py_None);
return Py_None;
}
static void
flush_unmatched(ProfilerObject *pObj)
{
while (pObj->currentProfilerContext) {
ProfilerContext *pContext = pObj->currentProfilerContext;
ProfilerEntry *profEntry= pContext->ctxEntry;
if (profEntry)
Stop(pObj, pContext, profEntry);
else
pObj->currentProfilerContext = pContext->previous;
if (pContext)
free(pContext);
}
}
PyDoc_STRVAR(disable_doc, "\
disable()\n\
\n\
Stop collecting profiling information.\n\
");
static PyObject*
profiler_disable(ProfilerObject *self, PyObject* noarg)
{
self->flags &= ~POF_ENABLED;
PyEval_SetProfile(NULL, NULL);
flush_unmatched(self);
if (pending_exception(self))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(clear_doc, "\
clear()\n\
\n\
Clear all profiling information collected so far.\n\
");
static PyObject*
profiler_clear(ProfilerObject *pObj, PyObject* noarg)
{
clearEntries(pObj);
Py_INCREF(Py_None);
return Py_None;
}
static void
profiler_dealloc(ProfilerObject *op)
{
if (op->flags & POF_ENABLED)
PyEval_SetProfile(NULL, NULL);
flush_unmatched(op);
clearEntries(op);
Py_XDECREF(op->externalTimer);
Py_TYPE(op)->tp_free(op);
}
static int
profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw)
{
PyObject *o;
PyObject *timer = NULL;
double timeunit = 0.0;
int subcalls = 1;
#ifdef PyTrace_C_CALL
int builtins = 1;
#else
int builtins = 0;
#endif
static char *kwlist[] = {"timer", "timeunit",
"subcalls", "builtins", 0};
if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist,
&timer, &timeunit,
&subcalls, &builtins))
return -1;
if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0)
return -1;
o = pObj->externalTimer;
pObj->externalTimer = timer;
Py_XINCREF(timer);
Py_XDECREF(o);
pObj->externalTimerUnit = timeunit;
return 0;
}
static PyMethodDef profiler_methods[] = {
{"getstats", (PyCFunction)profiler_getstats,
METH_NOARGS, getstats_doc},
{"enable", (PyCFunction)profiler_enable,
METH_VARARGS | METH_KEYWORDS, enable_doc},
{"disable", (PyCFunction)profiler_disable,
METH_NOARGS, disable_doc},
{"clear", (PyCFunction)profiler_clear,
METH_NOARGS, clear_doc},
{NULL, NULL}
};
PyDoc_STRVAR(profiler_doc, "\
Profiler(custom_timer=None, time_unit=None, subcalls=True, builtins=True)\n\
\n\
Builds a profiler object using the specified timer function.\n\
The default timer is a fast built-in one based on real time.\n\
For custom timer functions returning integers, time_unit can\n\
be a float specifying a scale (i.e. how long each integer unit\n\
is, in seconds).\n\
");
statichere PyTypeObject PyProfiler_Type = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"_lsprof.Profiler", /* tp_name */
sizeof(ProfilerObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)profiler_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
profiler_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
profiler_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)profiler_init, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
PyType_GenericNew, /* tp_new */
PyObject_Del, /* tp_free */
};
static PyMethodDef moduleMethods[] = {
{NULL, NULL}
};
PyMODINIT_FUNC
init_lsprof(void)
{
PyObject *module, *d;
module = Py_InitModule3("_lsprof", moduleMethods, "Fast profiler");
if (module == NULL)
return;
d = PyModule_GetDict(module);
if (PyType_Ready(&PyProfiler_Type) < 0)
return;
PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type);
if (!initialized) {
PyStructSequence_InitType(&StatsEntryType,
&profiler_entry_desc);
PyStructSequence_InitType(&StatsSubEntryType,
&profiler_subentry_desc);
}
Py_INCREF((PyObject*) &StatsEntryType);
Py_INCREF((PyObject*) &StatsSubEntryType);
PyModule_AddObject(module, "profiler_entry",
(PyObject*) &StatsEntryType);
PyModule_AddObject(module, "profiler_subentry",
(PyObject*) &StatsSubEntryType);
empty_tuple = PyTuple_New(0);
initialized = 1;
}
| apache-2.0 |
jusjoken/sagetv | third_party/mplayer/libavformat/au.c | 32 | 5030 | /*
* AU muxer and demuxer
* Copyright (c) 2001 Fabrice Bellard.
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* First version by Francois Revol revol@free.fr
*
* Reference documents:
* http://www.opengroup.org/public/pubs/external/auformat.html
* http://www.goice.co.jp/member/mo/formats/au.html
*/
#include "avformat.h"
#include "allformats.h"
#include "riff.h"
/* if we don't know the size in advance */
#define AU_UNKNOWN_SIZE ((uint32_t)(~0))
/* The ffmpeg codecs we support, and the IDs they have in the file */
static const AVCodecTag codec_au_tags[] = {
{ CODEC_ID_PCM_MULAW, 1 },
{ CODEC_ID_PCM_S16BE, 3 },
{ CODEC_ID_PCM_ALAW, 27 },
{ 0, 0 },
};
#ifdef CONFIG_MUXERS
/* AUDIO_FILE header */
static int put_au_header(ByteIOContext *pb, AVCodecContext *enc)
{
if(!enc->codec_tag)
return -1;
put_tag(pb, ".snd"); /* magic number */
put_be32(pb, 24); /* header size */
put_be32(pb, AU_UNKNOWN_SIZE); /* data size */
put_be32(pb, (uint32_t)enc->codec_tag); /* codec ID */
put_be32(pb, enc->sample_rate);
put_be32(pb, (uint32_t)enc->channels);
return 0;
}
static int au_write_header(AVFormatContext *s)
{
ByteIOContext *pb = &s->pb;
s->priv_data = NULL;
/* format header */
if (put_au_header(pb, s->streams[0]->codec) < 0) {
return -1;
}
put_flush_packet(pb);
return 0;
}
static int au_write_packet(AVFormatContext *s, AVPacket *pkt)
{
ByteIOContext *pb = &s->pb;
put_buffer(pb, pkt->data, pkt->size);
return 0;
}
static int au_write_trailer(AVFormatContext *s)
{
ByteIOContext *pb = &s->pb;
offset_t file_size;
if (!url_is_streamed(&s->pb)) {
/* update file size */
file_size = url_ftell(pb);
url_fseek(pb, 8, SEEK_SET);
put_be32(pb, (uint32_t)(file_size - 24));
url_fseek(pb, file_size, SEEK_SET);
put_flush_packet(pb);
}
return 0;
}
#endif //CONFIG_MUXERS
static int au_probe(AVProbeData *p)
{
/* check file header */
if (p->buf_size <= 24)
return 0;
if (p->buf[0] == '.' && p->buf[1] == 's' &&
p->buf[2] == 'n' && p->buf[3] == 'd')
return AVPROBE_SCORE_MAX;
else
return 0;
}
/* au input */
static int au_read_header(AVFormatContext *s,
AVFormatParameters *ap)
{
int size;
unsigned int tag;
ByteIOContext *pb = &s->pb;
unsigned int id, codec, channels, rate;
AVStream *st;
/* check ".snd" header */
tag = get_le32(pb);
if (tag != MKTAG('.', 's', 'n', 'd'))
return -1;
size = get_be32(pb); /* header size */
get_be32(pb); /* data size */
id = get_be32(pb);
rate = get_be32(pb);
channels = get_be32(pb);
codec = codec_get_id(codec_au_tags, id);
if (size >= 24) {
/* skip unused data */
url_fseek(pb, size - 24, SEEK_CUR);
}
/* now we are ready: build format streams */
st = av_new_stream(s, 0);
if (!st)
return -1;
st->codec->codec_type = CODEC_TYPE_AUDIO;
st->codec->codec_tag = id;
st->codec->codec_id = codec;
st->codec->channels = channels;
st->codec->sample_rate = rate;
av_set_pts_info(st, 64, 1, rate);
return 0;
}
#define MAX_SIZE 4096
static int au_read_packet(AVFormatContext *s,
AVPacket *pkt)
{
int ret;
if (url_feof(&s->pb))
return AVERROR_IO;
ret= av_get_packet(&s->pb, pkt, MAX_SIZE);
if (ret < 0)
return AVERROR_IO;
pkt->stream_index = 0;
/* note: we need to modify the packet size here to handle the last
packet */
pkt->size = ret;
return 0;
}
static int au_read_close(AVFormatContext *s)
{
return 0;
}
#ifdef CONFIG_AU_DEMUXER
AVInputFormat au_demuxer = {
"au",
"SUN AU Format",
0,
au_probe,
au_read_header,
au_read_packet,
au_read_close,
pcm_read_seek,
.codec_tag= (const AVCodecTag*[]){codec_au_tags, 0},
};
#endif
#ifdef CONFIG_AU_MUXER
AVOutputFormat au_muxer = {
"au",
"SUN AU Format",
"audio/basic",
"au",
0,
CODEC_ID_PCM_S16BE,
CODEC_ID_NONE,
au_write_header,
au_write_packet,
au_write_trailer,
.codec_tag= (const AVCodecTag*[]){codec_au_tags, 0},
};
#endif //CONFIG_AU_MUXER
| apache-2.0 |
c1728p9/mbed-os | targets/TARGET_ARM_SSG/TARGET_CM3DS_MPS2/device/drivers/TZ-TRNG/host/src/tztrng_lib/llf_rnd_common.c | 36 | 3237 | /******************************************************************************
* Copyright (c) 2017-2017, ARM, All Rights Reserved *
* SPDX-License-Identifier: Apache-2.0 *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* *
* You may obtain a copy of the License at *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT *
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/
#include "tztrng_defs.h"
#include "tztrng_pal.h"
CCError_t LLF_RND_GetRoscSampleCnt(uint32_t rosc, CCRndParams_t *pTrngParams)
{
switch (rosc) {
case 0x1:
pTrngParams->SubSamplingRatio = pTrngParams->SubSamplingRatio1;
break;
case 0x2:
pTrngParams->SubSamplingRatio = pTrngParams->SubSamplingRatio2;
break;
case 0x4:
pTrngParams->SubSamplingRatio = pTrngParams->SubSamplingRatio3;
break;
case 0x8:
pTrngParams->SubSamplingRatio = pTrngParams->SubSamplingRatio4;
break;
default:
return LLF_RND_TRNG_REQUIRED_ROSCS_NOT_ALLOWED_ERROR;
}
return CC_OK;
}
uint32_t LLF_RND_TRNG_RoscMaskToNum(uint32_t mask)
{
return (mask == LLF_RND_HW_TRNG_ROSC3_BIT) ? LLF_RND_HW_TRNG_ROSC3_NUM :
(mask == LLF_RND_HW_TRNG_ROSC2_BIT) ? LLF_RND_HW_TRNG_ROSC2_NUM :
(mask == LLF_RND_HW_TRNG_ROSC1_BIT) ? LLF_RND_HW_TRNG_ROSC1_NUM :
LLF_RND_HW_TRNG_ROSC0_NUM;
}
/**
* The function gets next allowed rosc
*
* @author reuvenl (9/12/2012)
*
* @param trngParams_ptr - a pointer to params structure.
* @param rosc_ptr - a pointer to previous rosc /in/, and
* to next rosc /out/.
* @param isNext - defines is increment of rosc ID needed or not.
* if isNext = TRUE - the function shifts rosc by one bit; Then
* the function checks is this rosc allowed, if yes - updates
* the rosc, else repeats previous steps. If no roscs allowed -
* returns an error.
*
* @return CCError_t
*/
CCError_t LLF_RND_GetFastestRosc(
CCRndParams_t *trngParams_ptr,
uint32_t *rosc_ptr /*in/out*/)
{
/* setting rosc */
do {
if (*rosc_ptr & trngParams_ptr->RoscsAllowed) {
return CC_OK;
} else {
*rosc_ptr <<= 1;
}
} while (*rosc_ptr <= 0x08);
return LLF_RND_TRNG_REQUIRED_ROSCS_NOT_ALLOWED_ERROR;
}
| apache-2.0 |
blowekamp/ITK | Modules/ThirdParty/VNL/src/vxl/v3p/netlib/lapack/complex16/zlatdf.f | 40 | 8797 | SUBROUTINE ZLATDF( IJOB, N, Z, LDZ, RHS, RDSUM, RDSCAL, IPIV,
$ JPIV )
*
* -- LAPACK auxiliary routine (version 3.2) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2006
*
* .. Scalar Arguments ..
INTEGER IJOB, LDZ, N
DOUBLE PRECISION RDSCAL, RDSUM
* ..
* .. Array Arguments ..
INTEGER IPIV( * ), JPIV( * )
COMPLEX*16 RHS( * ), Z( LDZ, * )
* ..
*
* Purpose
* =======
*
* ZLATDF computes the contribution to the reciprocal Dif-estimate
* by solving for x in Z * x = b, where b is chosen such that the norm
* of x is as large as possible. It is assumed that LU decomposition
* of Z has been computed by ZGETC2. On entry RHS = f holds the
* contribution from earlier solved sub-systems, and on return RHS = x.
*
* The factorization of Z returned by ZGETC2 has the form
* Z = P * L * U * Q, where P and Q are permutation matrices. L is lower
* triangular with unit diagonal elements and U is upper triangular.
*
* Arguments
* =========
*
* IJOB (input) INTEGER
* IJOB = 2: First compute an approximative null-vector e
* of Z using ZGECON, e is normalized and solve for
* Zx = +-e - f with the sign giving the greater value of
* 2-norm(x). About 5 times as expensive as Default.
* IJOB .ne. 2: Local look ahead strategy where
* all entries of the r.h.s. b is choosen as either +1 or
* -1. Default.
*
* N (input) INTEGER
* The number of columns of the matrix Z.
*
* Z (input) DOUBLE PRECISION array, dimension (LDZ, N)
* On entry, the LU part of the factorization of the n-by-n
* matrix Z computed by ZGETC2: Z = P * L * U * Q
*
* LDZ (input) INTEGER
* The leading dimension of the array Z. LDA >= max(1, N).
*
* RHS (input/output) DOUBLE PRECISION array, dimension (N).
* On entry, RHS contains contributions from other subsystems.
* On exit, RHS contains the solution of the subsystem with
* entries according to the value of IJOB (see above).
*
* RDSUM (input/output) DOUBLE PRECISION
* On entry, the sum of squares of computed contributions to
* the Dif-estimate under computation by ZTGSYL, where the
* scaling factor RDSCAL (see below) has been factored out.
* On exit, the corresponding sum of squares updated with the
* contributions from the current sub-system.
* If TRANS = 'T' RDSUM is not touched.
* NOTE: RDSUM only makes sense when ZTGSY2 is called by CTGSYL.
*
* RDSCAL (input/output) DOUBLE PRECISION
* On entry, scaling factor used to prevent overflow in RDSUM.
* On exit, RDSCAL is updated w.r.t. the current contributions
* in RDSUM.
* If TRANS = 'T', RDSCAL is not touched.
* NOTE: RDSCAL only makes sense when ZTGSY2 is called by
* ZTGSYL.
*
* IPIV (input) INTEGER array, dimension (N).
* The pivot indices; for 1 <= i <= N, row i of the
* matrix has been interchanged with row IPIV(i).
*
* JPIV (input) INTEGER array, dimension (N).
* The pivot indices; for 1 <= j <= N, column j of the
* matrix has been interchanged with column JPIV(j).
*
* Further Details
* ===============
*
* Based on contributions by
* Bo Kagstrom and Peter Poromaa, Department of Computing Science,
* Umea University, S-901 87 Umea, Sweden.
*
* This routine is a further developed implementation of algorithm
* BSOLVE in [1] using complete pivoting in the LU factorization.
*
* [1] Bo Kagstrom and Lars Westin,
* Generalized Schur Methods with Condition Estimators for
* Solving the Generalized Sylvester Equation, IEEE Transactions
* on Automatic Control, Vol. 34, No. 7, July 1989, pp 745-751.
*
* [2] Peter Poromaa,
* On Efficient and Robust Estimators for the Separation
* between two Regular Matrix Pairs with Applications in
* Condition Estimation. Report UMINF-95.05, Department of
* Computing Science, Umea University, S-901 87 Umea, Sweden,
* 1995.
*
* =====================================================================
*
* .. Parameters ..
INTEGER MAXDIM
PARAMETER ( MAXDIM = 2 )
DOUBLE PRECISION ZERO, ONE
PARAMETER ( ZERO = 0.0D+0, ONE = 1.0D+0 )
COMPLEX*16 CONE
PARAMETER ( CONE = ( 1.0D+0, 0.0D+0 ) )
* ..
* .. Local Scalars ..
INTEGER I, INFO, J, K
DOUBLE PRECISION RTEMP, SCALE, SMINU, SPLUS
COMPLEX*16 BM, BP, PMONE, TEMP
* ..
* .. Local Arrays ..
DOUBLE PRECISION RWORK( MAXDIM )
COMPLEX*16 WORK( 4*MAXDIM ), XM( MAXDIM ), XP( MAXDIM )
* ..
* .. External Subroutines ..
EXTERNAL ZAXPY, ZCOPY, ZGECON, ZGESC2, ZLASSQ, ZLASWP,
$ ZSCAL
* ..
* .. External Functions ..
DOUBLE PRECISION DZASUM
COMPLEX*16 ZDOTC
EXTERNAL DZASUM, ZDOTC
* ..
* .. Intrinsic Functions ..
INTRINSIC ABS, DBLE, SQRT
* ..
* .. Executable Statements ..
*
IF( IJOB.NE.2 ) THEN
*
* Apply permutations IPIV to RHS
*
CALL ZLASWP( 1, RHS, LDZ, 1, N-1, IPIV, 1 )
*
* Solve for L-part choosing RHS either to +1 or -1.
*
PMONE = -CONE
DO 10 J = 1, N - 1
BP = RHS( J ) + CONE
BM = RHS( J ) - CONE
SPLUS = ONE
*
* Lockahead for L- part RHS(1:N-1) = +-1
* SPLUS and SMIN computed more efficiently than in BSOLVE[1].
*
SPLUS = SPLUS + DBLE( ZDOTC( N-J, Z( J+1, J ), 1, Z( J+1,
$ J ), 1 ) )
SMINU = DBLE( ZDOTC( N-J, Z( J+1, J ), 1, RHS( J+1 ), 1 ) )
SPLUS = SPLUS*DBLE( RHS( J ) )
IF( SPLUS.GT.SMINU ) THEN
RHS( J ) = BP
ELSE IF( SMINU.GT.SPLUS ) THEN
RHS( J ) = BM
ELSE
*
* In this case the updating sums are equal and we can
* choose RHS(J) +1 or -1. The first time this happens we
* choose -1, thereafter +1. This is a simple way to get
* good estimates of matrices like Byers well-known example
* (see [1]). (Not done in BSOLVE.)
*
RHS( J ) = RHS( J ) + PMONE
PMONE = CONE
END IF
*
* Compute the remaining r.h.s.
*
TEMP = -RHS( J )
CALL ZAXPY( N-J, TEMP, Z( J+1, J ), 1, RHS( J+1 ), 1 )
10 CONTINUE
*
* Solve for U- part, lockahead for RHS(N) = +-1. This is not done
* In BSOLVE and will hopefully give us a better estimate because
* any ill-conditioning of the original matrix is transfered to U
* and not to L. U(N, N) is an approximation to sigma_min(LU).
*
CALL ZCOPY( N-1, RHS, 1, WORK, 1 )
WORK( N ) = RHS( N ) + CONE
RHS( N ) = RHS( N ) - CONE
SPLUS = ZERO
SMINU = ZERO
DO 30 I = N, 1, -1
TEMP = CONE / Z( I, I )
WORK( I ) = WORK( I )*TEMP
RHS( I ) = RHS( I )*TEMP
DO 20 K = I + 1, N
WORK( I ) = WORK( I ) - WORK( K )*( Z( I, K )*TEMP )
RHS( I ) = RHS( I ) - RHS( K )*( Z( I, K )*TEMP )
20 CONTINUE
SPLUS = SPLUS + ABS( WORK( I ) )
SMINU = SMINU + ABS( RHS( I ) )
30 CONTINUE
IF( SPLUS.GT.SMINU )
$ CALL ZCOPY( N, WORK, 1, RHS, 1 )
*
* Apply the permutations JPIV to the computed solution (RHS)
*
CALL ZLASWP( 1, RHS, LDZ, 1, N-1, JPIV, -1 )
*
* Compute the sum of squares
*
CALL ZLASSQ( N, RHS, 1, RDSCAL, RDSUM )
RETURN
END IF
*
* ENTRY IJOB = 2
*
* Compute approximate nullvector XM of Z
*
CALL ZGECON( 'I', N, Z, LDZ, ONE, RTEMP, WORK, RWORK, INFO )
CALL ZCOPY( N, WORK( N+1 ), 1, XM, 1 )
*
* Compute RHS
*
CALL ZLASWP( 1, XM, LDZ, 1, N-1, IPIV, -1 )
TEMP = CONE / SQRT( ZDOTC( N, XM, 1, XM, 1 ) )
CALL ZSCAL( N, TEMP, XM, 1 )
CALL ZCOPY( N, XM, 1, XP, 1 )
CALL ZAXPY( N, CONE, RHS, 1, XP, 1 )
CALL ZAXPY( N, -CONE, XM, 1, RHS, 1 )
CALL ZGESC2( N, Z, LDZ, RHS, IPIV, JPIV, SCALE )
CALL ZGESC2( N, Z, LDZ, XP, IPIV, JPIV, SCALE )
IF( DZASUM( N, XP, 1 ).GT.DZASUM( N, RHS, 1 ) )
$ CALL ZCOPY( N, XP, 1, RHS, 1 )
*
* Compute the sum of squares
*
CALL ZLASSQ( N, RHS, 1, RDSCAL, RDSUM )
RETURN
*
* End of ZLATDF
*
END
| apache-2.0 |
adirab/wg-wrk | src/tinymt64.c | 52 | 3533 | /**
* @file tinymt64.c
*
* @brief 64-bit Tiny Mersenne Twister only 127 bit internal state
*
* @author Mutsuo Saito (Hiroshima University)
* @author Makoto Matsumoto (The University of Tokyo)
*
* Copyright (C) 2011 Mutsuo Saito, Makoto Matsumoto,
* Hiroshima University and The University of Tokyo.
* All rights reserved.
*
* The 3-clause BSD License is applied to this software, see
* LICENSE.txt
*/
#include "tinymt64.h"
#define MIN_LOOP 8
/**
* This function represents a function used in the initialization
* by init_by_array
* @param[in] x 64-bit integer
* @return 64-bit integer
*/
static uint64_t ini_func1(uint64_t x) {
return (x ^ (x >> 59)) * UINT64_C(2173292883993);
}
/**
* This function represents a function used in the initialization
* by init_by_array
* @param[in] x 64-bit integer
* @return 64-bit integer
*/
static uint64_t ini_func2(uint64_t x) {
return (x ^ (x >> 59)) * UINT64_C(58885565329898161);
}
/**
* This function certificate the period of 2^127-1.
* @param random tinymt state vector.
*/
static void period_certification(tinymt64_t * random) {
if ((random->status[0] & TINYMT64_MASK) == 0 &&
random->status[1] == 0) {
random->status[0] = 'T';
random->status[1] = 'M';
}
}
/**
* This function initializes the internal state array with a 64-bit
* unsigned integer seed.
* @param random tinymt state vector.
* @param seed a 64-bit unsigned integer used as a seed.
*/
void tinymt64_init(tinymt64_t * random, uint64_t seed) {
random->status[0] = seed ^ ((uint64_t)random->mat1 << 32);
random->status[1] = random->mat2 ^ random->tmat;
for (int i = 1; i < MIN_LOOP; i++) {
random->status[i & 1] ^= i + UINT64_C(6364136223846793005)
* (random->status[(i - 1) & 1]
^ (random->status[(i - 1) & 1] >> 62));
}
period_certification(random);
}
/**
* This function initializes the internal state array,
* with an array of 64-bit unsigned integers used as seeds
* @param random tinymt state vector.
* @param init_key the array of 64-bit integers, used as a seed.
* @param key_length the length of init_key.
*/
void tinymt64_init_by_array(tinymt64_t * random, const uint64_t init_key[],
int key_length) {
const int lag = 1;
const int mid = 1;
const int size = 4;
int i, j;
int count;
uint64_t r;
uint64_t st[4];
st[0] = 0;
st[1] = random->mat1;
st[2] = random->mat2;
st[3] = random->tmat;
if (key_length + 1 > MIN_LOOP) {
count = key_length + 1;
} else {
count = MIN_LOOP;
}
r = ini_func1(st[0] ^ st[mid % size]
^ st[(size - 1) % size]);
st[mid % size] += r;
r += key_length;
st[(mid + lag) % size] += r;
st[0] = r;
count--;
for (i = 1, j = 0; (j < count) && (j < key_length); j++) {
r = ini_func1(st[i] ^ st[(i + mid) % size] ^ st[(i + size - 1) % size]);
st[(i + mid) % size] += r;
r += init_key[j] + i;
st[(i + mid + lag) % size] += r;
st[i] = r;
i = (i + 1) % size;
}
for (; j < count; j++) {
r = ini_func1(st[i] ^ st[(i + mid) % size] ^ st[(i + size - 1) % size]);
st[(i + mid) % size] += r;
r += i;
st[(i + mid + lag) % size] += r;
st[i] = r;
i = (i + 1) % size;
}
for (j = 0; j < size; j++) {
r = ini_func2(st[i] + st[(i + mid) % size] + st[(i + size - 1) % size]);
st[(i + mid) % size] ^= r;
r -= i;
st[(i + mid + lag) % size] ^= r;
st[i] = r;
i = (i + 1) % size;
}
random->status[0] = st[0] ^ st[1];
random->status[1] = st[2] ^ st[3];
period_certification(random);
}
| apache-2.0 |
wilebeast/FireFox-OS | B2G/external/bluetooth/bluez/attrib/gattrib.c | 54 | 12296 | /*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2010 Nokia Corporation
* Copyright (C) 2010 Marcel Holtmann <marcel@holtmann.org>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <stdint.h>
#include <string.h>
#include <glib.h>
#include <stdio.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/uuid.h>
#include "att.h"
#include "btio.h"
#include "gattrib.h"
#define GATT_TIMEOUT 30
struct _GAttrib {
GIOChannel *io;
gint refs;
uint8_t *buf;
int buflen;
guint read_watch;
guint write_watch;
guint timeout_watch;
GQueue *queue;
GSList *events;
guint next_cmd_id;
guint next_evt_id;
GDestroyNotify destroy;
GAttribDisconnectFunc disconnect;
gpointer destroy_user_data;
gpointer disc_user_data;
};
struct command {
guint id;
guint8 opcode;
guint8 *pdu;
guint16 len;
guint8 expected;
gboolean sent;
GAttribResultFunc func;
gpointer user_data;
GDestroyNotify notify;
};
struct event {
guint id;
guint8 expected;
GAttribNotifyFunc func;
gpointer user_data;
GDestroyNotify notify;
};
static guint8 opcode2expected(guint8 opcode)
{
switch (opcode) {
case ATT_OP_MTU_REQ:
return ATT_OP_MTU_RESP;
case ATT_OP_FIND_INFO_REQ:
return ATT_OP_FIND_INFO_RESP;
case ATT_OP_FIND_BY_TYPE_REQ:
return ATT_OP_FIND_BY_TYPE_RESP;
case ATT_OP_READ_BY_TYPE_REQ:
return ATT_OP_READ_BY_TYPE_RESP;
case ATT_OP_READ_REQ:
return ATT_OP_READ_RESP;
case ATT_OP_READ_BLOB_REQ:
return ATT_OP_READ_BLOB_RESP;
case ATT_OP_READ_MULTI_REQ:
return ATT_OP_READ_MULTI_RESP;
case ATT_OP_READ_BY_GROUP_REQ:
return ATT_OP_READ_BY_GROUP_RESP;
case ATT_OP_WRITE_REQ:
return ATT_OP_WRITE_RESP;
case ATT_OP_PREP_WRITE_REQ:
return ATT_OP_PREP_WRITE_RESP;
case ATT_OP_EXEC_WRITE_REQ:
return ATT_OP_EXEC_WRITE_RESP;
case ATT_OP_HANDLE_IND:
return ATT_OP_HANDLE_CNF;
}
return 0;
}
static gboolean is_response(guint8 opcode)
{
switch (opcode) {
case ATT_OP_ERROR:
case ATT_OP_MTU_RESP:
case ATT_OP_FIND_INFO_RESP:
case ATT_OP_FIND_BY_TYPE_RESP:
case ATT_OP_READ_BY_TYPE_RESP:
case ATT_OP_READ_RESP:
case ATT_OP_READ_BLOB_RESP:
case ATT_OP_READ_MULTI_RESP:
case ATT_OP_READ_BY_GROUP_RESP:
case ATT_OP_WRITE_RESP:
case ATT_OP_PREP_WRITE_RESP:
case ATT_OP_EXEC_WRITE_RESP:
case ATT_OP_HANDLE_CNF:
return TRUE;
}
return FALSE;
}
GAttrib *g_attrib_ref(GAttrib *attrib)
{
if (!attrib)
return NULL;
g_atomic_int_inc(&attrib->refs);
return attrib;
}
static void command_destroy(struct command *cmd)
{
if (cmd->notify)
cmd->notify(cmd->user_data);
g_free(cmd->pdu);
g_free(cmd);
}
static void event_destroy(struct event *evt)
{
if (evt->notify)
evt->notify(evt->user_data);
g_free(evt);
}
static void attrib_destroy(GAttrib *attrib)
{
GSList *l;
struct command *c;
while ((c = g_queue_pop_head(attrib->queue)))
command_destroy(c);
g_queue_free(attrib->queue);
attrib->queue = NULL;
for (l = attrib->events; l; l = l->next)
event_destroy(l->data);
g_slist_free(attrib->events);
attrib->events = NULL;
if (attrib->timeout_watch > 0)
g_source_remove(attrib->timeout_watch);
if (attrib->write_watch > 0)
g_source_remove(attrib->write_watch);
if (attrib->read_watch > 0) {
g_source_remove(attrib->read_watch);
g_io_channel_unref(attrib->io);
}
g_free(attrib->buf);
if (attrib->destroy)
attrib->destroy(attrib->destroy_user_data);
g_free(attrib);
}
void g_attrib_unref(GAttrib *attrib)
{
if (!attrib)
return;
if (g_atomic_int_dec_and_test(&attrib->refs) == FALSE)
return;
attrib_destroy(attrib);
}
GIOChannel *g_attrib_get_channel(GAttrib *attrib)
{
if (!attrib)
return NULL;
return attrib->io;
}
gboolean g_attrib_set_disconnect_function(GAttrib *attrib,
GAttribDisconnectFunc disconnect, gpointer user_data)
{
if (attrib == NULL)
return FALSE;
attrib->disconnect = disconnect;
attrib->disc_user_data = user_data;
return TRUE;
}
gboolean g_attrib_set_destroy_function(GAttrib *attrib,
GDestroyNotify destroy, gpointer user_data)
{
if (attrib == NULL)
return FALSE;
attrib->destroy = destroy;
attrib->destroy_user_data = user_data;
return TRUE;
}
static gboolean disconnect_timeout(gpointer data)
{
struct _GAttrib *attrib = data;
attrib_destroy(attrib);
return FALSE;
}
static gboolean can_write_data(GIOChannel *io, GIOCondition cond,
gpointer data)
{
struct _GAttrib *attrib = data;
struct command *cmd;
GError *gerr = NULL;
gsize len;
GIOStatus iostat;
if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
if (attrib->disconnect)
attrib->disconnect(attrib->disc_user_data);
return FALSE;
}
cmd = g_queue_peek_head(attrib->queue);
if (cmd == NULL)
return FALSE;
iostat = g_io_channel_write_chars(io, (gchar *) cmd->pdu, cmd->len,
&len, &gerr);
if (iostat != G_IO_STATUS_NORMAL)
return FALSE;
if (cmd->expected == 0) {
g_queue_pop_head(attrib->queue);
command_destroy(cmd);
return TRUE;
}
cmd->sent = TRUE;
if (attrib->timeout_watch == 0)
attrib->timeout_watch = g_timeout_add_seconds(GATT_TIMEOUT,
disconnect_timeout, attrib);
return FALSE;
}
static void destroy_sender(gpointer data)
{
struct _GAttrib *attrib = data;
attrib->write_watch = 0;
}
static void wake_up_sender(struct _GAttrib *attrib)
{
if (attrib->write_watch == 0)
attrib->write_watch = g_io_add_watch_full(attrib->io,
G_PRIORITY_DEFAULT, G_IO_OUT, can_write_data,
attrib, destroy_sender);
}
static gboolean received_data(GIOChannel *io, GIOCondition cond, gpointer data)
{
struct _GAttrib *attrib = data;
struct command *cmd = NULL;
GSList *l;
uint8_t buf[512], status;
gsize len;
GIOStatus iostat;
gboolean qempty;
if (attrib->timeout_watch > 0) {
g_source_remove(attrib->timeout_watch);
attrib->timeout_watch = 0;
}
if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
attrib->read_watch = 0;
if (attrib->disconnect)
attrib->disconnect(attrib->disc_user_data);
return FALSE;
}
memset(buf, 0, sizeof(buf));
iostat = g_io_channel_read_chars(io, (gchar *) buf, sizeof(buf),
&len, NULL);
if (iostat != G_IO_STATUS_NORMAL) {
status = ATT_ECODE_IO;
goto done;
}
for (l = attrib->events; l; l = l->next) {
struct event *evt = l->data;
if (evt->expected == buf[0] ||
evt->expected == GATTRIB_ALL_EVENTS)
evt->func(buf, len, evt->user_data);
}
if (is_response(buf[0]) == FALSE)
return TRUE;
cmd = g_queue_pop_head(attrib->queue);
if (cmd == NULL) {
/* Keep the watch if we have events to report */
return attrib->events != NULL;
}
if (buf[0] == ATT_OP_ERROR) {
status = buf[4];
goto done;
}
if (cmd->expected != buf[0]) {
status = ATT_ECODE_IO;
goto done;
}
status = 0;
done:
qempty = attrib->queue == NULL || g_queue_is_empty(attrib->queue);
if (cmd) {
if (cmd->func)
cmd->func(status, buf, len, cmd->user_data);
command_destroy(cmd);
}
if (!qempty)
wake_up_sender(attrib);
return TRUE;
}
GAttrib *g_attrib_new(GIOChannel *io)
{
struct _GAttrib *attrib;
uint16_t omtu;
g_io_channel_set_encoding(io, NULL, NULL);
g_io_channel_set_buffered(io, FALSE);
attrib = g_try_new0(struct _GAttrib, 1);
if (attrib == NULL)
return NULL;
attrib->io = g_io_channel_ref(io);
attrib->queue = g_queue_new();
attrib->read_watch = g_io_add_watch(attrib->io,
G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
received_data, attrib);
if (bt_io_get(attrib->io, BT_IO_L2CAP, NULL,
BT_IO_OPT_OMTU, &omtu,
BT_IO_OPT_INVALID)) {
if (omtu == 0 || omtu > ATT_MAX_MTU)
omtu = ATT_MAX_MTU;
} else
omtu = ATT_DEFAULT_LE_MTU;
attrib->buf = g_malloc0(omtu);
attrib->buflen = omtu;
return g_attrib_ref(attrib);
}
guint g_attrib_send(GAttrib *attrib, guint id, guint8 opcode,
const guint8 *pdu, guint16 len, GAttribResultFunc func,
gpointer user_data, GDestroyNotify notify)
{
struct command *c;
c = g_try_new0(struct command, 1);
if (c == NULL)
return 0;
c->opcode = opcode;
c->expected = opcode2expected(opcode);
c->pdu = g_malloc(len);
memcpy(c->pdu, pdu, len);
c->len = len;
c->func = func;
c->user_data = user_data;
c->notify = notify;
if (id) {
c->id = id;
g_queue_push_head(attrib->queue, c);
} else {
c->id = ++attrib->next_cmd_id;
g_queue_push_tail(attrib->queue, c);
}
if (g_queue_get_length(attrib->queue) == 1)
wake_up_sender(attrib);
return c->id;
}
static gint command_cmp_by_id(gconstpointer a, gconstpointer b)
{
const struct command *cmd = a;
guint id = GPOINTER_TO_UINT(b);
return cmd->id - id;
}
gboolean g_attrib_cancel(GAttrib *attrib, guint id)
{
GList *l;
struct command *cmd;
if (attrib == NULL || attrib->queue == NULL)
return FALSE;
l = g_queue_find_custom(attrib->queue, GUINT_TO_POINTER(id),
command_cmp_by_id);
if (l == NULL)
return FALSE;
cmd = l->data;
if (cmd == g_queue_peek_head(attrib->queue) && cmd->sent)
cmd->func = NULL;
else {
g_queue_remove(attrib->queue, cmd);
command_destroy(cmd);
}
return TRUE;
}
gboolean g_attrib_cancel_all(GAttrib *attrib)
{
struct command *c, *head = NULL;
gboolean first = TRUE;
if (attrib == NULL || attrib->queue == NULL)
return FALSE;
while ((c = g_queue_pop_head(attrib->queue))) {
if (first && c->sent) {
/* If the command was sent ignore its callback ... */
c->func = NULL;
head = c;
continue;
}
first = FALSE;
command_destroy(c);
}
if (head) {
/* ... and put it back in the queue */
g_queue_push_head(attrib->queue, head);
}
return TRUE;
}
gboolean g_attrib_set_debug(GAttrib *attrib,
GAttribDebugFunc func, gpointer user_data)
{
return TRUE;
}
uint8_t *g_attrib_get_buffer(GAttrib *attrib, int *len)
{
if (len == NULL)
return NULL;
*len = attrib->buflen;
return attrib->buf;
}
gboolean g_attrib_set_mtu(GAttrib *attrib, int mtu)
{
if (mtu < ATT_DEFAULT_LE_MTU)
mtu = ATT_DEFAULT_LE_MTU;
if (mtu > ATT_MAX_MTU)
mtu = ATT_MAX_MTU;
if (!bt_io_set(attrib->io, BT_IO_L2CAP, NULL,
BT_IO_OPT_OMTU, mtu,
BT_IO_OPT_INVALID))
return FALSE;
attrib->buf = g_realloc(attrib->buf, mtu);
attrib->buflen = mtu;
return TRUE;
}
guint g_attrib_register(GAttrib *attrib, guint8 opcode,
GAttribNotifyFunc func, gpointer user_data,
GDestroyNotify notify)
{
struct event *event;
event = g_try_new0(struct event, 1);
if (event == NULL)
return 0;
event->expected = opcode;
event->func = func;
event->user_data = user_data;
event->notify = notify;
event->id = ++attrib->next_evt_id;
attrib->events = g_slist_append(attrib->events, event);
return event->id;
}
static gint event_cmp_by_id(gconstpointer a, gconstpointer b)
{
const struct event *evt = a;
guint id = GPOINTER_TO_UINT(b);
return evt->id - id;
}
gboolean g_attrib_is_encrypted(GAttrib *attrib)
{
BtIOSecLevel sec_level;
if (!bt_io_get(attrib->io, BT_IO_L2CAP, NULL,
BT_IO_OPT_SEC_LEVEL, &sec_level,
BT_IO_OPT_INVALID))
return FALSE;
return sec_level > BT_IO_SEC_LOW;
}
gboolean g_attrib_unregister(GAttrib *attrib, guint id)
{
struct event *evt;
GSList *l;
l = g_slist_find_custom(attrib->events, GUINT_TO_POINTER(id),
event_cmp_by_id);
if (l == NULL)
return FALSE;
evt = l->data;
attrib->events = g_slist_remove(attrib->events, evt);
if (evt->notify)
evt->notify(evt->user_data);
g_free(evt);
return TRUE;
}
gboolean g_attrib_unregister_all(GAttrib *attrib)
{
GSList *l;
if (attrib->events == NULL)
return FALSE;
for (l = attrib->events; l; l = l->next) {
struct event *evt = l->data;
if (evt->notify)
evt->notify(evt->user_data);
g_free(evt);
}
g_slist_free(attrib->events);
attrib->events = NULL;
return TRUE;
}
| apache-2.0 |
nachshon/xerces-c | src/xercesc/util/XML256TableTranscoder.cpp | 59 | 7256 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/BitOps.hpp>
#include <xercesc/util/TranscodingException.hpp>
#include <xercesc/util/XML256TableTranscoder.hpp>
#include <xercesc/util/XMLString.hpp>
#include <string.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XML256TableTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XML256TableTranscoder::~XML256TableTranscoder()
{
// We don't own the tables, we just reference them
}
// ---------------------------------------------------------------------------
// XML256TableTranscoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
XMLSize_t
XML256TableTranscoder::transcodeFrom(const XMLByte* const srcData
, const XMLSize_t srcCount
, XMLCh* const toFill
, const XMLSize_t maxChars
, XMLSize_t& bytesEaten
, unsigned char* const charSizes)
{
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the number of chars in the source.
//
const XMLSize_t countToDo = srcCount < maxChars ? srcCount : maxChars;
//
// Loop through the count we have to do and map each char via the
// lookup table.
//
const XMLByte* srcPtr = srcData;
const XMLByte* endPtr = (srcPtr + countToDo);
XMLCh* outPtr = toFill;
while (srcPtr < endPtr)
{
const XMLCh uniCh = fFromTable[*srcPtr++];
if (uniCh != 0xFFFF)
{
*outPtr++ = uniCh;
continue;
}
}
// Set the bytes eaten
bytesEaten = countToDo;
// Set the character sizes to the fixed size
memset(charSizes, 1, countToDo);
// Return the chars we transcoded
return countToDo;
}
XMLSize_t
XML256TableTranscoder::transcodeTo( const XMLCh* const srcData
, const XMLSize_t srcCount
, XMLByte* const toFill
, const XMLSize_t maxBytes
, XMLSize_t& charsEaten
, const UnRepOpts options)
{
//
// Calculate the max chars we can do here. Its the lesser of the
// max output chars and the number of chars in the source.
//
const XMLSize_t countToDo = srcCount < maxBytes ? srcCount : maxBytes;
//
// Loop through the count we have to do and map each char via the
// lookup table.
//
const XMLCh* srcPtr = srcData;
const XMLCh* endPtr = (srcPtr + countToDo);
XMLByte* outPtr = toFill;
XMLByte nextOut;
while (srcPtr < endPtr)
{
//
// Get the next src char out to a temp, then do a binary search
// of the 'to' table for this entry.
//
if ((nextOut = xlatOneTo(*srcPtr))!=0)
{
*outPtr++ = nextOut;
srcPtr++;
continue;
}
//
// Its not representable so, according to the options, either
// throw or use the replacement.
//
if (options == UnRep_Throw)
{
XMLCh tmpBuf[17];
XMLString::binToText((unsigned int)*srcPtr, tmpBuf, 16, 16, getMemoryManager());
ThrowXMLwithMemMgr2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
, getMemoryManager()
);
}
// Eat the source char and use the replacement char
srcPtr++;
*outPtr++ = 0x3F;
}
// Set the chars eaten
charsEaten = countToDo;
// Return the bytes we transcoded
return countToDo;
}
bool XML256TableTranscoder::canTranscodeTo(const unsigned int toCheck)
{
return (xlatOneTo(toCheck) != 0);
}
// ---------------------------------------------------------------------------
// XML256TableTranscoder: Hidden constructor
// ---------------------------------------------------------------------------
XML256TableTranscoder::
XML256TableTranscoder( const XMLCh* const encodingName
, const XMLSize_t blockSize
, const XMLCh* const fromTable
, const XMLTransService::TransRec* const toTable
, const XMLSize_t toTableSize
, MemoryManager* const manager) :
XMLTranscoder(encodingName, blockSize, manager)
, fFromTable(fromTable)
, fToSize(toTableSize)
, fToTable(toTable)
{
}
// ---------------------------------------------------------------------------
// XML256TableTranscoder: Private helper methods
// ---------------------------------------------------------------------------
XMLByte XML256TableTranscoder::xlatOneTo(const XMLCh toXlat) const
{
XMLSize_t lowOfs = 0;
XMLSize_t hiOfs = fToSize - 1;
do
{
// Calc the mid point of the low and high offset.
const XMLSize_t midOfs = ((hiOfs - lowOfs) / 2) + lowOfs;
//
// If our test char is greater than the mid point char, then
// we move up to the upper half. Else we move to the lower
// half. If its equal, then its our guy.
//
if (toXlat > fToTable[midOfs].intCh)
{
lowOfs = midOfs;
}
else if (toXlat < fToTable[midOfs].intCh)
{
hiOfs = midOfs;
}
else
{
return fToTable[midOfs].extCh;
}
} while (lowOfs + 1 < hiOfs);
// Check the high end of the range otherwise the
// last item in the table may never be found.
if (toXlat == fToTable[hiOfs].intCh)
{
return fToTable[hiOfs].extCh;
}
return 0;
}
XERCES_CPP_NAMESPACE_END
| apache-2.0 |
jango2015/twemproxy | src/hashkit/nc_fnv.c | 62 | 1936 | /*
* twemproxy - A fast and lightweight proxy for memcached protocol.
* Copyright (C) 2011 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <nc_core.h>
static uint64_t FNV_64_INIT = UINT64_C(0xcbf29ce484222325);
static uint64_t FNV_64_PRIME = UINT64_C(0x100000001b3);
static uint32_t FNV_32_INIT = 2166136261UL;
static uint32_t FNV_32_PRIME = 16777619;
uint32_t
hash_fnv1_64(const char *key, size_t key_length)
{
uint64_t hash = FNV_64_INIT;
size_t x;
for (x = 0; x < key_length; x++) {
hash *= FNV_64_PRIME;
hash ^= (uint64_t)key[x];
}
return (uint32_t)hash;
}
uint32_t
hash_fnv1a_64(const char *key, size_t key_length)
{
uint32_t hash = (uint32_t) FNV_64_INIT;
size_t x;
for (x = 0; x < key_length; x++) {
uint32_t val = (uint32_t)key[x];
hash ^= val;
hash *= (uint32_t) FNV_64_PRIME;
}
return hash;
}
uint32_t
hash_fnv1_32(const char *key, size_t key_length)
{
uint32_t hash = FNV_32_INIT;
size_t x;
for (x = 0; x < key_length; x++) {
uint32_t val = (uint32_t)key[x];
hash *= FNV_32_PRIME;
hash ^= val;
}
return hash;
}
uint32_t
hash_fnv1a_32(const char *key, size_t key_length)
{
uint32_t hash = FNV_32_INIT;
size_t x;
for (x= 0; x < key_length; x++) {
uint32_t val = (uint32_t)key[x];
hash ^= val;
hash *= FNV_32_PRIME;
}
return hash;
}
| apache-2.0 |
MattsFleaMarket/python-for-android | python-build/openssl/crypto/engine/eng_ctrl.c | 830 | 12340 | /* crypto/engine/eng_ctrl.c */
/* ====================================================================
* Copyright (c) 1999-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "eng_int.h"
/* When querying a ENGINE-specific control command's 'description', this string
* is used if the ENGINE_CMD_DEFN has cmd_desc set to NULL. */
static const char *int_no_description = "";
/* These internal functions handle 'CMD'-related control commands when the
* ENGINE in question has asked us to take care of it (ie. the ENGINE did not
* set the ENGINE_FLAGS_MANUAL_CMD_CTRL flag. */
static int int_ctrl_cmd_is_null(const ENGINE_CMD_DEFN *defn)
{
if((defn->cmd_num == 0) || (defn->cmd_name == NULL))
return 1;
return 0;
}
static int int_ctrl_cmd_by_name(const ENGINE_CMD_DEFN *defn, const char *s)
{
int idx = 0;
while(!int_ctrl_cmd_is_null(defn) && (strcmp(defn->cmd_name, s) != 0))
{
idx++;
defn++;
}
if(int_ctrl_cmd_is_null(defn))
/* The given name wasn't found */
return -1;
return idx;
}
static int int_ctrl_cmd_by_num(const ENGINE_CMD_DEFN *defn, unsigned int num)
{
int idx = 0;
/* NB: It is stipulated that 'cmd_defn' lists are ordered by cmd_num. So
* our searches don't need to take any longer than necessary. */
while(!int_ctrl_cmd_is_null(defn) && (defn->cmd_num < num))
{
idx++;
defn++;
}
if(defn->cmd_num == num)
return idx;
/* The given cmd_num wasn't found */
return -1;
}
static int int_ctrl_helper(ENGINE *e, int cmd, long i, void *p,
void (*f)(void))
{
int idx;
char *s = (char *)p;
/* Take care of the easy one first (eg. it requires no searches) */
if(cmd == ENGINE_CTRL_GET_FIRST_CMD_TYPE)
{
if((e->cmd_defns == NULL) || int_ctrl_cmd_is_null(e->cmd_defns))
return 0;
return e->cmd_defns->cmd_num;
}
/* One or two commands require that "p" be a valid string buffer */
if((cmd == ENGINE_CTRL_GET_CMD_FROM_NAME) ||
(cmd == ENGINE_CTRL_GET_NAME_FROM_CMD) ||
(cmd == ENGINE_CTRL_GET_DESC_FROM_CMD))
{
if(s == NULL)
{
ENGINEerr(ENGINE_F_INT_CTRL_HELPER,
ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
}
/* Now handle cmd_name -> cmd_num conversion */
if(cmd == ENGINE_CTRL_GET_CMD_FROM_NAME)
{
if((e->cmd_defns == NULL) || ((idx = int_ctrl_cmd_by_name(
e->cmd_defns, s)) < 0))
{
ENGINEerr(ENGINE_F_INT_CTRL_HELPER,
ENGINE_R_INVALID_CMD_NAME);
return -1;
}
return e->cmd_defns[idx].cmd_num;
}
/* For the rest of the commands, the 'long' argument must specify a
* valie command number - so we need to conduct a search. */
if((e->cmd_defns == NULL) || ((idx = int_ctrl_cmd_by_num(e->cmd_defns,
(unsigned int)i)) < 0))
{
ENGINEerr(ENGINE_F_INT_CTRL_HELPER,
ENGINE_R_INVALID_CMD_NUMBER);
return -1;
}
/* Now the logic splits depending on command type */
switch(cmd)
{
case ENGINE_CTRL_GET_NEXT_CMD_TYPE:
idx++;
if(int_ctrl_cmd_is_null(e->cmd_defns + idx))
/* end-of-list */
return 0;
else
return e->cmd_defns[idx].cmd_num;
case ENGINE_CTRL_GET_NAME_LEN_FROM_CMD:
return strlen(e->cmd_defns[idx].cmd_name);
case ENGINE_CTRL_GET_NAME_FROM_CMD:
return BIO_snprintf(s,strlen(e->cmd_defns[idx].cmd_name) + 1,
"%s", e->cmd_defns[idx].cmd_name);
case ENGINE_CTRL_GET_DESC_LEN_FROM_CMD:
if(e->cmd_defns[idx].cmd_desc)
return strlen(e->cmd_defns[idx].cmd_desc);
return strlen(int_no_description);
case ENGINE_CTRL_GET_DESC_FROM_CMD:
if(e->cmd_defns[idx].cmd_desc)
return BIO_snprintf(s,
strlen(e->cmd_defns[idx].cmd_desc) + 1,
"%s", e->cmd_defns[idx].cmd_desc);
return BIO_snprintf(s, strlen(int_no_description) + 1,"%s",
int_no_description);
case ENGINE_CTRL_GET_CMD_FLAGS:
return e->cmd_defns[idx].cmd_flags;
}
/* Shouldn't really be here ... */
ENGINEerr(ENGINE_F_INT_CTRL_HELPER,ENGINE_R_INTERNAL_LIST_ERROR);
return -1;
}
int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void))
{
int ctrl_exists, ref_exists;
if(e == NULL)
{
ENGINEerr(ENGINE_F_ENGINE_CTRL,ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
ref_exists = ((e->struct_ref > 0) ? 1 : 0);
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
ctrl_exists = ((e->ctrl == NULL) ? 0 : 1);
if(!ref_exists)
{
ENGINEerr(ENGINE_F_ENGINE_CTRL,ENGINE_R_NO_REFERENCE);
return 0;
}
/* Intercept any "root-level" commands before trying to hand them on to
* ctrl() handlers. */
switch(cmd)
{
case ENGINE_CTRL_HAS_CTRL_FUNCTION:
return ctrl_exists;
case ENGINE_CTRL_GET_FIRST_CMD_TYPE:
case ENGINE_CTRL_GET_NEXT_CMD_TYPE:
case ENGINE_CTRL_GET_CMD_FROM_NAME:
case ENGINE_CTRL_GET_NAME_LEN_FROM_CMD:
case ENGINE_CTRL_GET_NAME_FROM_CMD:
case ENGINE_CTRL_GET_DESC_LEN_FROM_CMD:
case ENGINE_CTRL_GET_DESC_FROM_CMD:
case ENGINE_CTRL_GET_CMD_FLAGS:
if(ctrl_exists && !(e->flags & ENGINE_FLAGS_MANUAL_CMD_CTRL))
return int_ctrl_helper(e,cmd,i,p,f);
if(!ctrl_exists)
{
ENGINEerr(ENGINE_F_ENGINE_CTRL,ENGINE_R_NO_CONTROL_FUNCTION);
/* For these cmd-related functions, failure is indicated
* by a -1 return value (because 0 is used as a valid
* return in some places). */
return -1;
}
default:
break;
}
/* Anything else requires a ctrl() handler to exist. */
if(!ctrl_exists)
{
ENGINEerr(ENGINE_F_ENGINE_CTRL,ENGINE_R_NO_CONTROL_FUNCTION);
return 0;
}
return e->ctrl(e, cmd, i, p, f);
}
int ENGINE_cmd_is_executable(ENGINE *e, int cmd)
{
int flags;
if((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, cmd, NULL, NULL)) < 0)
{
ENGINEerr(ENGINE_F_ENGINE_CMD_IS_EXECUTABLE,
ENGINE_R_INVALID_CMD_NUMBER);
return 0;
}
if(!(flags & ENGINE_CMD_FLAG_NO_INPUT) &&
!(flags & ENGINE_CMD_FLAG_NUMERIC) &&
!(flags & ENGINE_CMD_FLAG_STRING))
return 0;
return 1;
}
int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name,
long i, void *p, void (*f)(void), int cmd_optional)
{
int num;
if((e == NULL) || (cmd_name == NULL))
{
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD,
ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if((e->ctrl == NULL) || ((num = ENGINE_ctrl(e,
ENGINE_CTRL_GET_CMD_FROM_NAME,
0, (void *)cmd_name, NULL)) <= 0))
{
/* If the command didn't *have* to be supported, we fake
* success. This allows certain settings to be specified for
* multiple ENGINEs and only require a change of ENGINE id
* (without having to selectively apply settings). Eg. changing
* from a hardware device back to the regular software ENGINE
* without editing the config file, etc. */
if(cmd_optional)
{
ERR_clear_error();
return 1;
}
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD,
ENGINE_R_INVALID_CMD_NAME);
return 0;
}
/* Force the result of the control command to 0 or 1, for the reasons
* mentioned before. */
if (ENGINE_ctrl(e, num, i, p, f) > 0)
return 1;
return 0;
}
int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg,
int cmd_optional)
{
int num, flags;
long l;
char *ptr;
if((e == NULL) || (cmd_name == NULL))
{
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING,
ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if((e->ctrl == NULL) || ((num = ENGINE_ctrl(e,
ENGINE_CTRL_GET_CMD_FROM_NAME,
0, (void *)cmd_name, NULL)) <= 0))
{
/* If the command didn't *have* to be supported, we fake
* success. This allows certain settings to be specified for
* multiple ENGINEs and only require a change of ENGINE id
* (without having to selectively apply settings). Eg. changing
* from a hardware device back to the regular software ENGINE
* without editing the config file, etc. */
if(cmd_optional)
{
ERR_clear_error();
return 1;
}
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING,
ENGINE_R_INVALID_CMD_NAME);
return 0;
}
if(!ENGINE_cmd_is_executable(e, num))
{
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING,
ENGINE_R_CMD_NOT_EXECUTABLE);
return 0;
}
if((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num, NULL, NULL)) < 0)
{
/* Shouldn't happen, given that ENGINE_cmd_is_executable()
* returned success. */
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING,
ENGINE_R_INTERNAL_LIST_ERROR);
return 0;
}
/* If the command takes no input, there must be no input. And vice
* versa. */
if(flags & ENGINE_CMD_FLAG_NO_INPUT)
{
if(arg != NULL)
{
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING,
ENGINE_R_COMMAND_TAKES_NO_INPUT);
return 0;
}
/* We deliberately force the result of ENGINE_ctrl() to 0 or 1
* rather than returning it as "return data". This is to ensure
* usage of these commands is consistent across applications and
* that certain applications don't understand it one way, and
* others another. */
if(ENGINE_ctrl(e, num, 0, (void *)arg, NULL) > 0)
return 1;
return 0;
}
/* So, we require input */
if(arg == NULL)
{
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING,
ENGINE_R_COMMAND_TAKES_INPUT);
return 0;
}
/* If it takes string input, that's easy */
if(flags & ENGINE_CMD_FLAG_STRING)
{
/* Same explanation as above */
if(ENGINE_ctrl(e, num, 0, (void *)arg, NULL) > 0)
return 1;
return 0;
}
/* If it doesn't take numeric either, then it is unsupported for use in
* a config-setting situation, which is what this function is for. This
* should never happen though, because ENGINE_cmd_is_executable() was
* used. */
if(!(flags & ENGINE_CMD_FLAG_NUMERIC))
{
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING,
ENGINE_R_INTERNAL_LIST_ERROR);
return 0;
}
l = strtol(arg, &ptr, 10);
if((arg == ptr) || (*ptr != '\0'))
{
ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING,
ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER);
return 0;
}
/* Force the result of the control command to 0 or 1, for the reasons
* mentioned before. */
if(ENGINE_ctrl(e, num, l, NULL, NULL) > 0)
return 1;
return 0;
}
| apache-2.0 |
Pankaj-Sakariya/android-source-browsing.platform--external--apache-log4cxx | src/test/cpp/l7dtestcase.cpp | 66 | 3806 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/propertyresourcebundle.h>
#include <log4cxx/helpers/locale.h>
#include "util/compare.h"
#include <vector>
#include <sstream>
#include "testchar.h"
#include "logunit.h"
#include <log4cxx/spi/loggerrepository.h>
typedef std::basic_ostringstream<testchar> StringBuffer;
using namespace log4cxx;
using namespace log4cxx::helpers;
LOGUNIT_CLASS(L7dTestCase)
{
LOGUNIT_TEST_SUITE(L7dTestCase);
LOGUNIT_TEST(test1);
LOGUNIT_TEST_SUITE_END();
LoggerPtr root;
ResourceBundlePtr bundles[3];
public:
void setUp()
{
Locale localeUS(LOG4CXX_STR("en"), LOG4CXX_STR("US"));
bundles[0] =
ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeUS);
LOGUNIT_ASSERT(bundles[0] != 0);
Locale localeFR(LOG4CXX_STR("fr"), LOG4CXX_STR("FR"));
bundles[1] =
ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeFR);
LOGUNIT_ASSERT(bundles[1] != 0);
Locale localeCH(LOG4CXX_STR("fr"), LOG4CXX_STR("CH"));
bundles[2] =
ResourceBundle::getBundle(LOG4CXX_STR("L7D"), localeCH);
LOGUNIT_ASSERT(bundles[2] != 0);
root = Logger::getRootLogger();
}
void tearDown()
{
root->getLoggerRepository()->resetConfiguration();
}
void test1()
{
PropertyConfigurator::configure(LOG4CXX_FILE("input/l7d1.properties"));
log4cxx::helpers::Pool pool;
for (int i = 0; i < 3; i++)
{
root->setResourceBundle(bundles[i]);
LOG4CXX_L7DLOG(root, Level::getDebug(), LOG4CXX_TEST_STR("bogus1"));
LOG4CXX_L7DLOG(root, Level::getInfo(), LOG4CXX_TEST_STR("test"));
LOG4CXX_L7DLOG(root, Level::getWarn(), LOG4CXX_TEST_STR("hello_world"));
StringBuffer os;
os << (i + 1);
LOG4CXX_L7DLOG2(root, Level::getDebug(), LOG4CXX_TEST_STR("msg1"), os.str().c_str(),
LOG4CXX_TEST_STR("log4j"));
LOG4CXX_L7DLOG2(root, Level::getError(), LOG4CXX_TEST_STR("bogusMsg"), os.str().c_str(),
LOG4CXX_TEST_STR("log4j"));
LOG4CXX_L7DLOG2(root, Level::getError(), LOG4CXX_TEST_STR("msg1"), os.str().c_str(),
LOG4CXX_TEST_STR("log4j"));
LOG4CXX_L7DLOG(root, Level::getInfo(), LOG4CXX_TEST_STR("bogus2"));
}
LOGUNIT_ASSERT(Compare::compare(LOG4CXX_FILE("output/temp"),
LOG4CXX_FILE("witness/l7d.1")));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(L7dTestCase);
| apache-2.0 |
jsdosa/TizenRT | external/libopus/celt/x86/celt_lpc_sse.c | 75 | 2783 | /* Copyright (c) 2014, Cisco Systems, INC
Written by XiangMingZhu WeiZhou MinPeng YanWang
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <xmmintrin.h>
#include <emmintrin.h>
#include <smmintrin.h>
#include "celt_lpc.h"
#include "stack_alloc.h"
#include "mathops.h"
#include "pitch.h"
#include "x86cpu.h"
#if defined(FIXED_POINT)
void celt_fir_sse4_1(const opus_val16 *x,
const opus_val16 *num,
opus_val16 *y,
int N,
int ord,
int arch)
{
int i,j;
VARDECL(opus_val16, rnum);
__m128i vecNoA;
opus_int32 noA ;
SAVE_STACK;
ALLOC(rnum, ord, opus_val16);
for(i=0;i<ord;i++)
rnum[i] = num[ord-i-1];
noA = EXTEND32(1) << SIG_SHIFT >> 1;
vecNoA = _mm_set_epi32(noA, noA, noA, noA);
for (i=0;i<N-3;i+=4)
{
opus_val32 sums[4] = {0};
__m128i vecSum, vecX;
xcorr_kernel(rnum, x+i-ord, sums, ord, arch);
vecSum = _mm_loadu_si128((__m128i *)sums);
vecSum = _mm_add_epi32(vecSum, vecNoA);
vecSum = _mm_srai_epi32(vecSum, SIG_SHIFT);
vecX = OP_CVTEPI16_EPI32_M64(x + i);
vecSum = _mm_add_epi32(vecSum, vecX);
vecSum = _mm_packs_epi32(vecSum, vecSum);
_mm_storel_epi64((__m128i *)(y + i), vecSum);
}
for (;i<N;i++)
{
opus_val32 sum = 0;
for (j=0;j<ord;j++)
sum = MAC16_16(sum, rnum[j], x[i+j-ord]);
y[i] = SATURATE16(ADD32(EXTEND32(x[i]), PSHR32(sum, SIG_SHIFT)));
}
RESTORE_STACK;
}
#endif
| apache-2.0 |
michelborgess/RealOne-Victara-Kernel | arch/mips/lantiq/xway/prom-xway.c | 4693 | 1148 | /*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Copyright (C) 2010 John Crispin <blogic@openwrt.org>
*/
#include <linux/export.h>
#include <linux/clk.h>
#include <asm/bootinfo.h>
#include <asm/time.h>
#include <lantiq_soc.h>
#include "../prom.h"
#define SOC_DANUBE "Danube"
#define SOC_TWINPASS "Twinpass"
#define SOC_AR9 "AR9"
#define PART_SHIFT 12
#define PART_MASK 0x0FFFFFFF
#define REV_SHIFT 28
#define REV_MASK 0xF0000000
void __init ltq_soc_detect(struct ltq_soc_info *i)
{
i->partnum = (ltq_r32(LTQ_MPS_CHIPID) & PART_MASK) >> PART_SHIFT;
i->rev = (ltq_r32(LTQ_MPS_CHIPID) & REV_MASK) >> REV_SHIFT;
switch (i->partnum) {
case SOC_ID_DANUBE1:
case SOC_ID_DANUBE2:
i->name = SOC_DANUBE;
i->type = SOC_TYPE_DANUBE;
break;
case SOC_ID_TWINPASS:
i->name = SOC_TWINPASS;
i->type = SOC_TYPE_DANUBE;
break;
case SOC_ID_ARX188:
case SOC_ID_ARX168:
case SOC_ID_ARX182:
i->name = SOC_AR9;
i->type = SOC_TYPE_AR9;
break;
default:
unreachable();
break;
}
}
| apache-2.0 |
GreenLightning/libgdx | extensions/gdx-freetype/jni/freetype-2.5.5/src/otvalid/otvgdef.c | 147 | 7694 | /***************************************************************************/
/* */
/* otvgdef.c */
/* */
/* OpenType GDEF table validation (body). */
/* */
/* Copyright 2004, 2005, 2007 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include "otvalid.h"
#include "otvcommn.h"
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_otvgdef
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** UTILITY FUNCTIONS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define AttachListFunc otv_O_x_Ox
#define LigCaretListFunc otv_O_x_Ox
/* sets valid->extra1 (0) */
static void
otv_O_x_Ox( FT_Bytes table,
OTV_Validator otvalid )
{
FT_Bytes p = table;
FT_Bytes Coverage;
FT_UInt GlyphCount;
OTV_Validate_Func func;
OTV_ENTER;
OTV_LIMIT_CHECK( 4 );
Coverage = table + FT_NEXT_USHORT( p );
GlyphCount = FT_NEXT_USHORT( p );
OTV_TRACE(( " (GlyphCount = %d)\n", GlyphCount ));
otv_Coverage_validate( Coverage, otvalid, GlyphCount );
if ( GlyphCount != otv_Coverage_get_count( Coverage ) )
FT_INVALID_DATA;
OTV_LIMIT_CHECK( GlyphCount * 2 );
otvalid->nesting_level++;
func = otvalid->func[otvalid->nesting_level];
otvalid->extra1 = 0;
for ( ; GlyphCount > 0; GlyphCount-- )
func( table + FT_NEXT_USHORT( p ), otvalid );
otvalid->nesting_level--;
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** LIGATURE CARETS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define CaretValueFunc otv_CaretValue_validate
static void
otv_CaretValue_validate( FT_Bytes table,
OTV_Validator otvalid )
{
FT_Bytes p = table;
FT_UInt CaretValueFormat;
OTV_ENTER;
OTV_LIMIT_CHECK( 4 );
CaretValueFormat = FT_NEXT_USHORT( p );
OTV_TRACE(( " (format = %d)\n", CaretValueFormat ));
switch ( CaretValueFormat )
{
case 1: /* CaretValueFormat1 */
/* skip Coordinate, no test */
break;
case 2: /* CaretValueFormat2 */
/* skip CaretValuePoint, no test */
break;
case 3: /* CaretValueFormat3 */
p += 2; /* skip Coordinate */
OTV_LIMIT_CHECK( 2 );
/* DeviceTable */
otv_Device_validate( table + FT_NEXT_USHORT( p ), otvalid );
break;
default:
FT_INVALID_FORMAT;
}
OTV_EXIT;
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** GDEF TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* sets otvalid->glyph_count */
FT_LOCAL_DEF( void )
otv_GDEF_validate( FT_Bytes table,
FT_Bytes gsub,
FT_Bytes gpos,
FT_UInt glyph_count,
FT_Validator ftvalid )
{
OTV_ValidatorRec otvalidrec;
OTV_Validator otvalid = &otvalidrec;
FT_Bytes p = table;
FT_UInt table_size;
FT_Bool need_MarkAttachClassDef;
OTV_OPTIONAL_TABLE( GlyphClassDef );
OTV_OPTIONAL_TABLE( AttachListOffset );
OTV_OPTIONAL_TABLE( LigCaretListOffset );
OTV_OPTIONAL_TABLE( MarkAttachClassDef );
otvalid->root = ftvalid;
FT_TRACE3(( "validating GDEF table\n" ));
OTV_INIT;
OTV_LIMIT_CHECK( 12 );
if ( FT_NEXT_ULONG( p ) != 0x10000UL ) /* Version */
FT_INVALID_FORMAT;
/* MarkAttachClassDef has been added to the OpenType */
/* specification without increasing GDEF's version, */
/* so we use this ugly hack to find out whether the */
/* table is needed actually. */
need_MarkAttachClassDef = FT_BOOL(
otv_GSUBGPOS_have_MarkAttachmentType_flag( gsub ) ||
otv_GSUBGPOS_have_MarkAttachmentType_flag( gpos ) );
if ( need_MarkAttachClassDef )
table_size = 12; /* OpenType >= 1.2 */
else
table_size = 10; /* OpenType < 1.2 */
otvalid->glyph_count = glyph_count;
OTV_OPTIONAL_OFFSET( GlyphClassDef );
OTV_SIZE_CHECK( GlyphClassDef );
if ( GlyphClassDef )
otv_ClassDef_validate( table + GlyphClassDef, otvalid );
OTV_OPTIONAL_OFFSET( AttachListOffset );
OTV_SIZE_CHECK( AttachListOffset );
if ( AttachListOffset )
{
OTV_NEST2( AttachList, AttachPoint );
OTV_RUN( table + AttachListOffset, otvalid );
}
OTV_OPTIONAL_OFFSET( LigCaretListOffset );
OTV_SIZE_CHECK( LigCaretListOffset );
if ( LigCaretListOffset )
{
OTV_NEST3( LigCaretList, LigGlyph, CaretValue );
OTV_RUN( table + LigCaretListOffset, otvalid );
}
if ( need_MarkAttachClassDef )
{
OTV_OPTIONAL_OFFSET( MarkAttachClassDef );
OTV_SIZE_CHECK( MarkAttachClassDef );
if ( MarkAttachClassDef )
otv_ClassDef_validate( table + MarkAttachClassDef, otvalid );
}
FT_TRACE4(( "\n" ));
}
/* END */
| apache-2.0 |
ckewinjones/sagetv | third_party/mingw/pthreads/attr.c | 420 | 2077 | /*
* attr.c
*
* Description:
* This translation unit agregates operations on thread attribute objects.
* It is used for inline optimisation.
*
* The included modules are used separately when static executable sizes
* must be minimised.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "pthread.h"
#include "implement.h"
#include "pthread_attr_init.c"
#include "pthread_attr_destroy.c"
#include "pthread_attr_getdetachstate.c"
#include "pthread_attr_setdetachstate.c"
#include "pthread_attr_getstackaddr.c"
#include "pthread_attr_setstackaddr.c"
#include "pthread_attr_getstacksize.c"
#include "pthread_attr_setstacksize.c"
#include "pthread_attr_getscope.c"
#include "pthread_attr_setscope.c"
| apache-2.0 |
nrallakis/libgdx | extensions/gdx-freetype/jni/freetype-2.6.2/src/base/ftwinfnt.c | 172 | 1968 | /***************************************************************************/
/* */
/* ftwinfnt.c */
/* */
/* FreeType API for accessing Windows FNT specific info (body). */
/* */
/* Copyright 2003-2015 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_DEBUG_H
#include FT_WINFONTS_H
#include FT_INTERNAL_OBJECTS_H
#include FT_SERVICE_WINFNT_H
/* documentation is in ftwinfnt.h */
FT_EXPORT_DEF( FT_Error )
FT_Get_WinFNT_Header( FT_Face face,
FT_WinFNT_HeaderRec *header )
{
FT_Service_WinFnt service;
FT_Error error;
if ( !face )
return FT_THROW( Invalid_Face_Handle );
if ( !header )
return FT_THROW( Invalid_Argument );
FT_FACE_LOOKUP_SERVICE( face, service, WINFNT );
if ( service )
error = service->get_header( face, header );
else
error = FT_THROW( Invalid_Argument );
return error;
}
/* END */
| apache-2.0 |
execunix/vinos | external/gpl3/gdb/dist/libiberty/floatformat.c | 182 | 22032 | /* IEEE floating point support routines, for GDB, the GNU Debugger.
Copyright 1991, 1994, 1999, 2000, 2003, 2005, 2006, 2010, 2012
Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */
/* This is needed to pick up the NAN macro on some systems. */
#define _GNU_SOURCE
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <math.h>
#ifdef HAVE_STRING_H
#include <string.h>
#endif
/* On some platforms, <float.h> provides DBL_QNAN. */
#ifdef STDC_HEADERS
#include <float.h>
#endif
#include "ansidecl.h"
#include "libiberty.h"
#include "floatformat.h"
#ifndef INFINITY
#ifdef HUGE_VAL
#define INFINITY HUGE_VAL
#else
#define INFINITY (1.0 / 0.0)
#endif
#endif
#ifndef NAN
#ifdef DBL_QNAN
#define NAN DBL_QNAN
#else
#define NAN (0.0 / 0.0)
#endif
#endif
static int mant_bits_set (const struct floatformat *, const unsigned char *);
static unsigned long get_field (const unsigned char *,
enum floatformat_byteorders,
unsigned int,
unsigned int,
unsigned int);
static int floatformat_always_valid (const struct floatformat *fmt,
const void *from);
static int
floatformat_always_valid (const struct floatformat *fmt ATTRIBUTE_UNUSED,
const void *from ATTRIBUTE_UNUSED)
{
return 1;
}
/* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
going to bother with trying to muck around with whether it is defined in
a system header, what we do if not, etc. */
#define FLOATFORMAT_CHAR_BIT 8
/* floatformats for IEEE half, single and double, big and little endian. */
const struct floatformat floatformat_ieee_half_big =
{
floatformat_big, 16, 0, 1, 5, 15, 31, 6, 10,
floatformat_intbit_no,
"floatformat_ieee_half_big",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ieee_half_little =
{
floatformat_little, 16, 0, 1, 5, 15, 31, 6, 10,
floatformat_intbit_no,
"floatformat_ieee_half_little",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ieee_single_big =
{
floatformat_big, 32, 0, 1, 8, 127, 255, 9, 23,
floatformat_intbit_no,
"floatformat_ieee_single_big",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ieee_single_little =
{
floatformat_little, 32, 0, 1, 8, 127, 255, 9, 23,
floatformat_intbit_no,
"floatformat_ieee_single_little",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ieee_double_big =
{
floatformat_big, 64, 0, 1, 11, 1023, 2047, 12, 52,
floatformat_intbit_no,
"floatformat_ieee_double_big",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ieee_double_little =
{
floatformat_little, 64, 0, 1, 11, 1023, 2047, 12, 52,
floatformat_intbit_no,
"floatformat_ieee_double_little",
floatformat_always_valid,
NULL
};
/* floatformat for IEEE double, little endian byte order, with big endian word
ordering, as on the ARM. */
const struct floatformat floatformat_ieee_double_littlebyte_bigword =
{
floatformat_littlebyte_bigword, 64, 0, 1, 11, 1023, 2047, 12, 52,
floatformat_intbit_no,
"floatformat_ieee_double_littlebyte_bigword",
floatformat_always_valid,
NULL
};
/* floatformat for VAX. Not quite IEEE, but close enough. */
const struct floatformat floatformat_vax_f =
{
floatformat_vax, 32, 0, 1, 8, 129, 0, 9, 23,
floatformat_intbit_no,
"floatformat_vax_f",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_vax_d =
{
floatformat_vax, 64, 0, 1, 8, 129, 0, 9, 55,
floatformat_intbit_no,
"floatformat_vax_d",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_vax_g =
{
floatformat_vax, 64, 0, 1, 11, 1025, 0, 12, 52,
floatformat_intbit_no,
"floatformat_vax_g",
floatformat_always_valid,
NULL
};
static int floatformat_i387_ext_is_valid (const struct floatformat *fmt,
const void *from);
static int
floatformat_i387_ext_is_valid (const struct floatformat *fmt, const void *from)
{
/* In the i387 double-extended format, if the exponent is all ones,
then the integer bit must be set. If the exponent is neither 0
nor ~0, the intbit must also be set. Only if the exponent is
zero can it be zero, and then it must be zero. */
unsigned long exponent, int_bit;
const unsigned char *ufrom = (const unsigned char *) from;
exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
fmt->exp_start, fmt->exp_len);
int_bit = get_field (ufrom, fmt->byteorder, fmt->totalsize,
fmt->man_start, 1);
if ((exponent == 0) != (int_bit == 0))
return 0;
else
return 1;
}
const struct floatformat floatformat_i387_ext =
{
floatformat_little, 80, 0, 1, 15, 0x3fff, 0x7fff, 16, 64,
floatformat_intbit_yes,
"floatformat_i387_ext",
floatformat_i387_ext_is_valid,
NULL
};
const struct floatformat floatformat_m68881_ext =
{
/* Note that the bits from 16 to 31 are unused. */
floatformat_big, 96, 0, 1, 15, 0x3fff, 0x7fff, 32, 64,
floatformat_intbit_yes,
"floatformat_m68881_ext",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_i960_ext =
{
/* Note that the bits from 0 to 15 are unused. */
floatformat_little, 96, 16, 17, 15, 0x3fff, 0x7fff, 32, 64,
floatformat_intbit_yes,
"floatformat_i960_ext",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_m88110_ext =
{
floatformat_big, 80, 0, 1, 15, 0x3fff, 0x7fff, 16, 64,
floatformat_intbit_yes,
"floatformat_m88110_ext",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_m88110_harris_ext =
{
/* Harris uses raw format 128 bytes long, but the number is just an ieee
double, and the last 64 bits are wasted. */
floatformat_big,128, 0, 1, 11, 0x3ff, 0x7ff, 12, 52,
floatformat_intbit_no,
"floatformat_m88110_ext_harris",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_arm_ext_big =
{
/* Bits 1 to 16 are unused. */
floatformat_big, 96, 0, 17, 15, 0x3fff, 0x7fff, 32, 64,
floatformat_intbit_yes,
"floatformat_arm_ext_big",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_arm_ext_littlebyte_bigword =
{
/* Bits 1 to 16 are unused. */
floatformat_littlebyte_bigword, 96, 0, 17, 15, 0x3fff, 0x7fff, 32, 64,
floatformat_intbit_yes,
"floatformat_arm_ext_littlebyte_bigword",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ia64_spill_big =
{
floatformat_big, 128, 0, 1, 17, 65535, 0x1ffff, 18, 64,
floatformat_intbit_yes,
"floatformat_ia64_spill_big",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ia64_spill_little =
{
floatformat_little, 128, 0, 1, 17, 65535, 0x1ffff, 18, 64,
floatformat_intbit_yes,
"floatformat_ia64_spill_little",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ia64_quad_big =
{
floatformat_big, 128, 0, 1, 15, 16383, 0x7fff, 16, 112,
floatformat_intbit_no,
"floatformat_ia64_quad_big",
floatformat_always_valid,
NULL
};
const struct floatformat floatformat_ia64_quad_little =
{
floatformat_little, 128, 0, 1, 15, 16383, 0x7fff, 16, 112,
floatformat_intbit_no,
"floatformat_ia64_quad_little",
floatformat_always_valid,
NULL
};
static int
floatformat_ibm_long_double_is_valid (const struct floatformat *fmt,
const void *from)
{
const unsigned char *ufrom = (const unsigned char *) from;
const struct floatformat *hfmt = fmt->split_half;
long top_exp, bot_exp;
int top_nan = 0;
top_exp = get_field (ufrom, hfmt->byteorder, hfmt->totalsize,
hfmt->exp_start, hfmt->exp_len);
bot_exp = get_field (ufrom + 8, hfmt->byteorder, hfmt->totalsize,
hfmt->exp_start, hfmt->exp_len);
if ((unsigned long) top_exp == hfmt->exp_nan)
top_nan = mant_bits_set (hfmt, ufrom);
/* A NaN is valid with any low part. */
if (top_nan)
return 1;
/* An infinity, zero or denormal requires low part 0 (positive or
negative). */
if ((unsigned long) top_exp == hfmt->exp_nan || top_exp == 0)
{
if (bot_exp != 0)
return 0;
return !mant_bits_set (hfmt, ufrom + 8);
}
/* The top part is now a finite normal value. The long double value
is the sum of the two parts, and the top part must equal the
result of rounding the long double value to nearest double. Thus
the bottom part must be <= 0.5ulp of the top part in absolute
value, and if it is < 0.5ulp then the long double is definitely
valid. */
if (bot_exp < top_exp - 53)
return 1;
if (bot_exp > top_exp - 53 && bot_exp != 0)
return 0;
if (bot_exp == 0)
{
/* The bottom part is 0 or denormal. Determine which, and if
denormal the first two set bits. */
int first_bit = -1, second_bit = -1, cur_bit;
for (cur_bit = 0; (unsigned int) cur_bit < hfmt->man_len; cur_bit++)
if (get_field (ufrom + 8, hfmt->byteorder, hfmt->totalsize,
hfmt->man_start + cur_bit, 1))
{
if (first_bit == -1)
first_bit = cur_bit;
else
{
second_bit = cur_bit;
break;
}
}
/* Bottom part 0 is OK. */
if (first_bit == -1)
return 1;
/* The real exponent of the bottom part is -first_bit. */
if (-first_bit < top_exp - 53)
return 1;
if (-first_bit > top_exp - 53)
return 0;
/* The bottom part is at least 0.5ulp of the top part. For this
to be OK, the bottom part must be exactly 0.5ulp (i.e. no
more bits set) and the top part must have last bit 0. */
if (second_bit != -1)
return 0;
return !get_field (ufrom, hfmt->byteorder, hfmt->totalsize,
hfmt->man_start + hfmt->man_len - 1, 1);
}
else
{
/* The bottom part is at least 0.5ulp of the top part. For this
to be OK, it must be exactly 0.5ulp (i.e. no explicit bits
set) and the top part must have last bit 0. */
if (get_field (ufrom, hfmt->byteorder, hfmt->totalsize,
hfmt->man_start + hfmt->man_len - 1, 1))
return 0;
return !mant_bits_set (hfmt, ufrom + 8);
}
}
const struct floatformat floatformat_ibm_long_double_big =
{
floatformat_big, 128, 0, 1, 11, 1023, 2047, 12, 52,
floatformat_intbit_no,
"floatformat_ibm_long_double_big",
floatformat_ibm_long_double_is_valid,
&floatformat_ieee_double_big
};
const struct floatformat floatformat_ibm_long_double_little =
{
floatformat_little, 128, 0, 1, 11, 1023, 2047, 12, 52,
floatformat_intbit_no,
"floatformat_ibm_long_double_little",
floatformat_ibm_long_double_is_valid,
&floatformat_ieee_double_little
};
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
/* Return 1 if any bits are explicitly set in the mantissa of UFROM,
format FMT, 0 otherwise. */
static int
mant_bits_set (const struct floatformat *fmt, const unsigned char *ufrom)
{
unsigned int mant_bits, mant_off;
int mant_bits_left;
mant_off = fmt->man_start;
mant_bits_left = fmt->man_len;
while (mant_bits_left > 0)
{
mant_bits = min (mant_bits_left, 32);
if (get_field (ufrom, fmt->byteorder, fmt->totalsize,
mant_off, mant_bits) != 0)
return 1;
mant_off += mant_bits;
mant_bits_left -= mant_bits;
}
return 0;
}
/* Extract a field which starts at START and is LEN bits long. DATA and
TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
static unsigned long
get_field (const unsigned char *data, enum floatformat_byteorders order,
unsigned int total_len, unsigned int start, unsigned int len)
{
unsigned long result = 0;
unsigned int cur_byte;
int lo_bit, hi_bit, cur_bitshift = 0;
int nextbyte = (order == floatformat_little) ? 1 : -1;
/* Start is in big-endian bit order! Fix that first. */
start = total_len - (start + len);
/* Start at the least significant part of the field. */
if (order == floatformat_little)
cur_byte = start / FLOATFORMAT_CHAR_BIT;
else
cur_byte = (total_len - start - 1) / FLOATFORMAT_CHAR_BIT;
lo_bit = start % FLOATFORMAT_CHAR_BIT;
hi_bit = min (lo_bit + len, FLOATFORMAT_CHAR_BIT);
do
{
unsigned int shifted = *(data + cur_byte) >> lo_bit;
unsigned int bits = hi_bit - lo_bit;
unsigned int mask = (1 << bits) - 1;
result |= (shifted & mask) << cur_bitshift;
len -= bits;
cur_bitshift += bits;
cur_byte += nextbyte;
lo_bit = 0;
hi_bit = min (len, FLOATFORMAT_CHAR_BIT);
}
while (len != 0);
return result;
}
/* Convert from FMT to a double.
FROM is the address of the extended float.
Store the double in *TO. */
void
floatformat_to_double (const struct floatformat *fmt,
const void *from, double *to)
{
const unsigned char *ufrom = (const unsigned char *) from;
double dto;
long exponent;
unsigned long mant;
unsigned int mant_bits, mant_off;
int mant_bits_left;
/* Split values are not handled specially, since the top half has
the correctly rounded double value (in the only supported case of
split values). */
exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
fmt->exp_start, fmt->exp_len);
/* If the exponent indicates a NaN, we don't have information to
decide what to do. So we handle it like IEEE, except that we
don't try to preserve the type of NaN. FIXME. */
if ((unsigned long) exponent == fmt->exp_nan)
{
int nan = mant_bits_set (fmt, ufrom);
/* On certain systems (such as GNU/Linux), the use of the
INFINITY macro below may generate a warning that can not be
silenced due to a bug in GCC (PR preprocessor/11931). The
preprocessor fails to recognise the __extension__ keyword in
conjunction with the GNU/C99 extension for hexadecimal
floating point constants and will issue a warning when
compiling with -pedantic. */
if (nan)
dto = NAN;
else
dto = INFINITY;
if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
dto = -dto;
*to = dto;
return;
}
mant_bits_left = fmt->man_len;
mant_off = fmt->man_start;
dto = 0.0;
/* Build the result algebraically. Might go infinite, underflow, etc;
who cares. */
/* For denorms use minimum exponent. */
if (exponent == 0)
exponent = 1 - fmt->exp_bias;
else
{
exponent -= fmt->exp_bias;
/* If this format uses a hidden bit, explicitly add it in now.
Otherwise, increment the exponent by one to account for the
integer bit. */
if (fmt->intbit == floatformat_intbit_no)
dto = ldexp (1.0, exponent);
else
exponent++;
}
while (mant_bits_left > 0)
{
mant_bits = min (mant_bits_left, 32);
mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
mant_off, mant_bits);
dto += ldexp ((double) mant, exponent - mant_bits);
exponent -= mant_bits;
mant_off += mant_bits;
mant_bits_left -= mant_bits;
}
/* Negate it if negative. */
if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
dto = -dto;
*to = dto;
}
static void put_field (unsigned char *, enum floatformat_byteorders,
unsigned int,
unsigned int,
unsigned int,
unsigned long);
/* Set a field which starts at START and is LEN bits long. DATA and
TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
static void
put_field (unsigned char *data, enum floatformat_byteorders order,
unsigned int total_len, unsigned int start, unsigned int len,
unsigned long stuff_to_put)
{
unsigned int cur_byte;
int lo_bit, hi_bit;
int nextbyte = (order == floatformat_little) ? 1 : -1;
/* Start is in big-endian bit order! Fix that first. */
start = total_len - (start + len);
/* Start at the least significant part of the field. */
if (order == floatformat_little)
cur_byte = start / FLOATFORMAT_CHAR_BIT;
else
cur_byte = (total_len - start - 1) / FLOATFORMAT_CHAR_BIT;
lo_bit = start % FLOATFORMAT_CHAR_BIT;
hi_bit = min (lo_bit + len, FLOATFORMAT_CHAR_BIT);
do
{
unsigned char *byte_ptr = data + cur_byte;
unsigned int bits = hi_bit - lo_bit;
unsigned int mask = ((1 << bits) - 1) << lo_bit;
*byte_ptr = (*byte_ptr & ~mask) | ((stuff_to_put << lo_bit) & mask);
stuff_to_put >>= bits;
len -= bits;
cur_byte += nextbyte;
lo_bit = 0;
hi_bit = min (len, FLOATFORMAT_CHAR_BIT);
}
while (len != 0);
}
/* The converse: convert the double *FROM to an extended float
and store where TO points. Neither FROM nor TO have any alignment
restrictions. */
void
floatformat_from_double (const struct floatformat *fmt,
const double *from, void *to)
{
double dfrom;
int exponent;
double mant;
unsigned int mant_bits, mant_off;
int mant_bits_left;
unsigned char *uto = (unsigned char *) to;
dfrom = *from;
memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
/* Split values are not handled specially, since a bottom half of
zero is correct for any value representable as double (in the
only supported case of split values). */
/* If negative, set the sign bit. */
if (dfrom < 0)
{
put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
dfrom = -dfrom;
}
if (dfrom == 0)
{
/* 0.0. */
return;
}
if (dfrom != dfrom)
{
/* NaN. */
put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
fmt->exp_len, fmt->exp_nan);
/* Be sure it's not infinity, but NaN value is irrelevant. */
put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
32, 1);
return;
}
if (dfrom + dfrom == dfrom)
{
/* This can only happen for an infinite value (or zero, which we
already handled above). */
put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
fmt->exp_len, fmt->exp_nan);
return;
}
mant = frexp (dfrom, &exponent);
if (exponent + fmt->exp_bias - 1 > 0)
put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
fmt->exp_len, exponent + fmt->exp_bias - 1);
else
{
/* Handle a denormalized number. FIXME: What should we do for
non-IEEE formats? */
put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
fmt->exp_len, 0);
mant = ldexp (mant, exponent + fmt->exp_bias - 1);
}
mant_bits_left = fmt->man_len;
mant_off = fmt->man_start;
while (mant_bits_left > 0)
{
unsigned long mant_long;
mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
mant *= 4294967296.0;
mant_long = (unsigned long)mant;
mant -= mant_long;
/* If the integer bit is implicit, and we are not creating a
denormalized number, then we need to discard it. */
if ((unsigned int) mant_bits_left == fmt->man_len
&& fmt->intbit == floatformat_intbit_no
&& exponent + fmt->exp_bias - 1 > 0)
{
mant_long &= 0x7fffffff;
mant_bits -= 1;
}
else if (mant_bits < 32)
{
/* The bits we want are in the most significant MANT_BITS bits of
mant_long. Move them to the least significant. */
mant_long >>= 32 - mant_bits;
}
put_field (uto, fmt->byteorder, fmt->totalsize,
mant_off, mant_bits, mant_long);
mant_off += mant_bits;
mant_bits_left -= mant_bits;
}
}
/* Return non-zero iff the data at FROM is a valid number in format FMT. */
int
floatformat_is_valid (const struct floatformat *fmt, const void *from)
{
return fmt->is_valid (fmt, from);
}
#ifdef IEEE_DEBUG
#include <stdio.h>
/* This is to be run on a host which uses IEEE floating point. */
void
ieee_test (double n)
{
double result;
floatformat_to_double (&floatformat_ieee_double_little, &n, &result);
if ((n != result && (! isnan (n) || ! isnan (result)))
|| (n < 0 && result >= 0)
|| (n >= 0 && result < 0))
printf ("Differ(to): %.20g -> %.20g\n", n, result);
floatformat_from_double (&floatformat_ieee_double_little, &n, &result);
if ((n != result && (! isnan (n) || ! isnan (result)))
|| (n < 0 && result >= 0)
|| (n >= 0 && result < 0))
printf ("Differ(from): %.20g -> %.20g\n", n, result);
#if 0
{
char exten[16];
floatformat_from_double (&floatformat_m68881_ext, &n, exten);
floatformat_to_double (&floatformat_m68881_ext, exten, &result);
if (n != result)
printf ("Differ(to+from): %.20g -> %.20g\n", n, result);
}
#endif
#if IEEE_DEBUG > 1
/* This is to be run on a host which uses 68881 format. */
{
long double ex = *(long double *)exten;
if (ex != n)
printf ("Differ(from vs. extended): %.20g\n", n);
}
#endif
}
int
main (void)
{
ieee_test (0.0);
ieee_test (0.5);
ieee_test (1.1);
ieee_test (256.0);
ieee_test (0.12345);
ieee_test (234235.78907234);
ieee_test (-512.0);
ieee_test (-0.004321);
ieee_test (1.2E-70);
ieee_test (1.2E-316);
ieee_test (4.9406564584124654E-324);
ieee_test (- 4.9406564584124654E-324);
ieee_test (- 0.0);
ieee_test (- INFINITY);
ieee_test (- NAN);
ieee_test (INFINITY);
ieee_test (NAN);
return 0;
}
#endif
| apache-2.0 |
unrealinux/FinancialDataCrawlingPlatform | src/github.com/henrylee2cn/pholcus/vendor/gopkg.in/mgo.v2/sasl/sspi_windows.c | 451 | 3457 | // Code adapted from the NodeJS kerberos library:
//
// https://github.com/christkv/kerberos/tree/master/lib/win32/kerberos_sspi.c
//
// Under the terms of the Apache License, Version 2.0:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
#include <stdlib.h>
#include "sspi_windows.h"
static HINSTANCE sspi_secur32_dll = NULL;
int load_secur32_dll()
{
sspi_secur32_dll = LoadLibrary("secur32.dll");
if (sspi_secur32_dll == NULL) {
return GetLastError();
}
return 0;
}
SECURITY_STATUS SEC_ENTRY call_sspi_encrypt_message(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo)
{
if (sspi_secur32_dll == NULL) {
return -1;
}
encryptMessage_fn pfn_encryptMessage = (encryptMessage_fn) GetProcAddress(sspi_secur32_dll, "EncryptMessage");
if (!pfn_encryptMessage) {
return -2;
}
return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo);
}
SECURITY_STATUS SEC_ENTRY call_sspi_acquire_credentials_handle(
LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse,
void *pvLogonId, void *pAuthData, SEC_GET_KEY_FN pGetKeyFn, void *pvGetKeyArgument,
PCredHandle phCredential, PTimeStamp ptsExpiry)
{
if (sspi_secur32_dll == NULL) {
return -1;
}
acquireCredentialsHandle_fn pfn_acquireCredentialsHandle;
#ifdef _UNICODE
pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn) GetProcAddress(sspi_secur32_dll, "AcquireCredentialsHandleW");
#else
pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn) GetProcAddress(sspi_secur32_dll, "AcquireCredentialsHandleA");
#endif
if (!pfn_acquireCredentialsHandle) {
return -2;
}
return (*pfn_acquireCredentialsHandle)(
pszPrincipal, pszPackage, fCredentialUse, pvLogonId, pAuthData,
pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry);
}
SECURITY_STATUS SEC_ENTRY call_sspi_initialize_security_context(
PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName,
unsigned long fContextReq, unsigned long Reserved1, unsigned long TargetDataRep,
PSecBufferDesc pInput, unsigned long Reserved2, PCtxtHandle phNewContext,
PSecBufferDesc pOutput, unsigned long *pfContextAttr, PTimeStamp ptsExpiry)
{
if (sspi_secur32_dll == NULL) {
return -1;
}
initializeSecurityContext_fn pfn_initializeSecurityContext;
#ifdef _UNICODE
pfn_initializeSecurityContext = (initializeSecurityContext_fn) GetProcAddress(sspi_secur32_dll, "InitializeSecurityContextW");
#else
pfn_initializeSecurityContext = (initializeSecurityContext_fn) GetProcAddress(sspi_secur32_dll, "InitializeSecurityContextA");
#endif
if (!pfn_initializeSecurityContext) {
return -2;
}
return (*pfn_initializeSecurityContext)(
phCredential, phContext, pszTargetName, fContextReq, Reserved1, TargetDataRep,
pInput, Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry);
}
SECURITY_STATUS SEC_ENTRY call_sspi_query_context_attributes(PCtxtHandle phContext, unsigned long ulAttribute, void *pBuffer)
{
if (sspi_secur32_dll == NULL) {
return -1;
}
queryContextAttributes_fn pfn_queryContextAttributes;
#ifdef _UNICODE
pfn_queryContextAttributes = (queryContextAttributes_fn) GetProcAddress(sspi_secur32_dll, "QueryContextAttributesW");
#else
pfn_queryContextAttributes = (queryContextAttributes_fn) GetProcAddress(sspi_secur32_dll, "QueryContextAttributesA");
#endif
if (!pfn_queryContextAttributes) {
return -2;
}
return (*pfn_queryContextAttributes)(phContext, ulAttribute, pBuffer);
}
| apache-2.0 |
michelborgess/RealOne-Victara-Kernel | drivers/isdn/divert/isdn_divert.c | 5085 | 23568 | /* $Id: isdn_divert.c,v 1.6.6.3 2001/09/23 22:24:36 kai Exp $
*
* DSS1 main diversion supplementary handling for i4l.
*
* Copyright 1999 by Werner Cornelius (werner@isdn4linux.de)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/proc_fs.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include "isdn_divert.h"
/**********************************/
/* structure keeping calling info */
/**********************************/
struct call_struc
{ isdn_ctrl ics; /* delivered setup + driver parameters */
ulong divert_id; /* Id delivered to user */
unsigned char akt_state; /* actual state */
char deflect_dest[35]; /* deflection destination */
struct timer_list timer; /* timer control structure */
char info[90]; /* device info output */
struct call_struc *next; /* pointer to next entry */
struct call_struc *prev;
};
/********************************************/
/* structure keeping deflection table entry */
/********************************************/
struct deflect_struc
{ struct deflect_struc *next, *prev;
divert_rule rule; /* used rule */
};
/*****************************************/
/* variables for main diversion services */
/*****************************************/
/* diversion/deflection processes */
static struct call_struc *divert_head = NULL; /* head of remembered entrys */
static ulong next_id = 1; /* next info id */
static struct deflect_struc *table_head = NULL;
static struct deflect_struc *table_tail = NULL;
static unsigned char extern_wait_max = 4; /* maximum wait in s for external process */
DEFINE_SPINLOCK(divert_lock);
/***************************/
/* timer callback function */
/***************************/
static void deflect_timer_expire(ulong arg)
{
unsigned long flags;
struct call_struc *cs = (struct call_struc *) arg;
spin_lock_irqsave(&divert_lock, flags);
del_timer(&cs->timer); /* delete active timer */
spin_unlock_irqrestore(&divert_lock, flags);
switch (cs->akt_state)
{ case DEFLECT_PROCEED:
cs->ics.command = ISDN_CMD_HANGUP; /* cancel action */
divert_if.ll_cmd(&cs->ics);
spin_lock_irqsave(&divert_lock, flags);
cs->akt_state = DEFLECT_AUTODEL; /* delete after timeout */
cs->timer.expires = jiffies + (HZ * AUTODEL_TIME);
add_timer(&cs->timer);
spin_unlock_irqrestore(&divert_lock, flags);
break;
case DEFLECT_ALERT:
cs->ics.command = ISDN_CMD_REDIR; /* protocol */
strlcpy(cs->ics.parm.setup.phone, cs->deflect_dest, sizeof(cs->ics.parm.setup.phone));
strcpy(cs->ics.parm.setup.eazmsn, "Testtext delayed");
divert_if.ll_cmd(&cs->ics);
spin_lock_irqsave(&divert_lock, flags);
cs->akt_state = DEFLECT_AUTODEL; /* delete after timeout */
cs->timer.expires = jiffies + (HZ * AUTODEL_TIME);
add_timer(&cs->timer);
spin_unlock_irqrestore(&divert_lock, flags);
break;
case DEFLECT_AUTODEL:
default:
spin_lock_irqsave(&divert_lock, flags);
if (cs->prev)
cs->prev->next = cs->next; /* forward link */
else
divert_head = cs->next;
if (cs->next)
cs->next->prev = cs->prev; /* back link */
spin_unlock_irqrestore(&divert_lock, flags);
kfree(cs);
return;
} /* switch */
} /* deflect_timer_func */
/*****************************************/
/* handle call forwarding de/activations */
/* 0 = deact, 1 = act, 2 = interrogate */
/*****************************************/
int cf_command(int drvid, int mode,
u_char proc, char *msn,
u_char service, char *fwd_nr, ulong *procid)
{ unsigned long flags;
int retval, msnlen;
int fwd_len;
char *p, *ielenp, tmp[60];
struct call_struc *cs;
if (strchr(msn, '.')) return (-EINVAL); /* subaddress not allowed in msn */
if ((proc & 0x7F) > 2) return (-EINVAL);
proc &= 3;
p = tmp;
*p++ = 0x30; /* enumeration */
ielenp = p++; /* remember total length position */
*p++ = 0xa; /* proc tag */
*p++ = 1; /* length */
*p++ = proc & 0x7F; /* procedure to de/activate/interrogate */
*p++ = 0xa; /* service tag */
*p++ = 1; /* length */
*p++ = service; /* service to handle */
if (mode == 1)
{ if (!*fwd_nr) return (-EINVAL); /* destination missing */
if (strchr(fwd_nr, '.')) return (-EINVAL); /* subaddress not allowed */
fwd_len = strlen(fwd_nr);
*p++ = 0x30; /* number enumeration */
*p++ = fwd_len + 2; /* complete forward to len */
*p++ = 0x80; /* fwd to nr */
*p++ = fwd_len; /* length of number */
strcpy(p, fwd_nr); /* copy number */
p += fwd_len; /* pointer beyond fwd */
} /* activate */
msnlen = strlen(msn);
*p++ = 0x80; /* msn number */
if (msnlen > 1)
{ *p++ = msnlen; /* length */
strcpy(p, msn);
p += msnlen;
}
else *p++ = 0;
*ielenp = p - ielenp - 1; /* set total IE length */
/* allocate mem for information struct */
if (!(cs = kmalloc(sizeof(struct call_struc), GFP_ATOMIC)))
return (-ENOMEM); /* no memory */
init_timer(&cs->timer);
cs->info[0] = '\0';
cs->timer.function = deflect_timer_expire;
cs->timer.data = (ulong) cs; /* pointer to own structure */
cs->ics.driver = drvid;
cs->ics.command = ISDN_CMD_PROT_IO; /* protocol specific io */
cs->ics.arg = DSS1_CMD_INVOKE; /* invoke supplementary service */
cs->ics.parm.dss1_io.proc = (mode == 1) ? 7 : (mode == 2) ? 11 : 8; /* operation */
cs->ics.parm.dss1_io.timeout = 4000; /* from ETS 300 207-1 */
cs->ics.parm.dss1_io.datalen = p - tmp; /* total len */
cs->ics.parm.dss1_io.data = tmp; /* start of buffer */
spin_lock_irqsave(&divert_lock, flags);
cs->ics.parm.dss1_io.ll_id = next_id++; /* id for callback */
spin_unlock_irqrestore(&divert_lock, flags);
*procid = cs->ics.parm.dss1_io.ll_id;
sprintf(cs->info, "%d 0x%lx %s%s 0 %s %02x %d%s%s\n",
(!mode) ? DIVERT_DEACTIVATE : (mode == 1) ? DIVERT_ACTIVATE : DIVERT_REPORT,
cs->ics.parm.dss1_io.ll_id,
(mode != 2) ? "" : "0 ",
divert_if.drv_to_name(cs->ics.driver),
msn,
service & 0xFF,
proc,
(mode != 1) ? "" : " 0 ",
(mode != 1) ? "" : fwd_nr);
retval = divert_if.ll_cmd(&cs->ics); /* execute command */
if (!retval)
{ cs->prev = NULL;
spin_lock_irqsave(&divert_lock, flags);
cs->next = divert_head;
divert_head = cs;
spin_unlock_irqrestore(&divert_lock, flags);
}
else
kfree(cs);
return (retval);
} /* cf_command */
/****************************************/
/* handle a external deflection command */
/****************************************/
int deflect_extern_action(u_char cmd, ulong callid, char *to_nr)
{ struct call_struc *cs;
isdn_ctrl ic;
unsigned long flags;
int i;
if ((cmd & 0x7F) > 2) return (-EINVAL); /* invalid command */
cs = divert_head; /* start of parameter list */
while (cs)
{ if (cs->divert_id == callid) break; /* found */
cs = cs->next;
} /* search entry */
if (!cs) return (-EINVAL); /* invalid callid */
ic.driver = cs->ics.driver;
ic.arg = cs->ics.arg;
i = -EINVAL;
if (cs->akt_state == DEFLECT_AUTODEL) return (i); /* no valid call */
switch (cmd & 0x7F)
{ case 0: /* hangup */
del_timer(&cs->timer);
ic.command = ISDN_CMD_HANGUP;
i = divert_if.ll_cmd(&ic);
spin_lock_irqsave(&divert_lock, flags);
cs->akt_state = DEFLECT_AUTODEL; /* delete after timeout */
cs->timer.expires = jiffies + (HZ * AUTODEL_TIME);
add_timer(&cs->timer);
spin_unlock_irqrestore(&divert_lock, flags);
break;
case 1: /* alert */
if (cs->akt_state == DEFLECT_ALERT) return (0);
cmd &= 0x7F; /* never wait */
del_timer(&cs->timer);
ic.command = ISDN_CMD_ALERT;
if ((i = divert_if.ll_cmd(&ic)))
{
spin_lock_irqsave(&divert_lock, flags);
cs->akt_state = DEFLECT_AUTODEL; /* delete after timeout */
cs->timer.expires = jiffies + (HZ * AUTODEL_TIME);
add_timer(&cs->timer);
spin_unlock_irqrestore(&divert_lock, flags);
}
else
cs->akt_state = DEFLECT_ALERT;
break;
case 2: /* redir */
del_timer(&cs->timer);
strlcpy(cs->ics.parm.setup.phone, to_nr, sizeof(cs->ics.parm.setup.phone));
strcpy(cs->ics.parm.setup.eazmsn, "Testtext manual");
ic.command = ISDN_CMD_REDIR;
if ((i = divert_if.ll_cmd(&ic)))
{
spin_lock_irqsave(&divert_lock, flags);
cs->akt_state = DEFLECT_AUTODEL; /* delete after timeout */
cs->timer.expires = jiffies + (HZ * AUTODEL_TIME);
add_timer(&cs->timer);
spin_unlock_irqrestore(&divert_lock, flags);
}
else
cs->akt_state = DEFLECT_ALERT;
break;
} /* switch */
return (i);
} /* deflect_extern_action */
/********************************/
/* insert a new rule before idx */
/********************************/
int insertrule(int idx, divert_rule *newrule)
{ struct deflect_struc *ds, *ds1 = NULL;
unsigned long flags;
if (!(ds = kmalloc(sizeof(struct deflect_struc),
GFP_KERNEL)))
return (-ENOMEM); /* no memory */
ds->rule = *newrule; /* set rule */
spin_lock_irqsave(&divert_lock, flags);
if (idx >= 0)
{ ds1 = table_head;
while ((ds1) && (idx > 0))
{ idx--;
ds1 = ds1->next;
}
if (!ds1) idx = -1;
}
if (idx < 0)
{ ds->prev = table_tail; /* previous entry */
ds->next = NULL; /* end of chain */
if (ds->prev)
ds->prev->next = ds; /* last forward */
else
table_head = ds; /* is first entry */
table_tail = ds; /* end of queue */
}
else
{ ds->next = ds1; /* next entry */
ds->prev = ds1->prev; /* prev entry */
ds1->prev = ds; /* backward chain old element */
if (!ds->prev)
table_head = ds; /* first element */
}
spin_unlock_irqrestore(&divert_lock, flags);
return (0);
} /* insertrule */
/***********************************/
/* delete the rule at position idx */
/***********************************/
int deleterule(int idx)
{ struct deflect_struc *ds, *ds1;
unsigned long flags;
if (idx < 0)
{ spin_lock_irqsave(&divert_lock, flags);
ds = table_head;
table_head = NULL;
table_tail = NULL;
spin_unlock_irqrestore(&divert_lock, flags);
while (ds)
{ ds1 = ds;
ds = ds->next;
kfree(ds1);
}
return (0);
}
spin_lock_irqsave(&divert_lock, flags);
ds = table_head;
while ((ds) && (idx > 0))
{ idx--;
ds = ds->next;
}
if (!ds)
{
spin_unlock_irqrestore(&divert_lock, flags);
return (-EINVAL);
}
if (ds->next)
ds->next->prev = ds->prev; /* backward chain */
else
table_tail = ds->prev; /* end of chain */
if (ds->prev)
ds->prev->next = ds->next; /* forward chain */
else
table_head = ds->next; /* start of chain */
spin_unlock_irqrestore(&divert_lock, flags);
kfree(ds);
return (0);
} /* deleterule */
/*******************************************/
/* get a pointer to a specific rule number */
/*******************************************/
divert_rule *getruleptr(int idx)
{ struct deflect_struc *ds = table_head;
if (idx < 0) return (NULL);
while ((ds) && (idx >= 0))
{ if (!(idx--))
{ return (&ds->rule);
break;
}
ds = ds->next;
}
return (NULL);
} /* getruleptr */
/*************************************************/
/* called from common module on an incoming call */
/*************************************************/
static int isdn_divert_icall(isdn_ctrl *ic)
{ int retval = 0;
unsigned long flags;
struct call_struc *cs = NULL;
struct deflect_struc *dv;
char *p, *p1;
u_char accept;
/* first check the internal deflection table */
for (dv = table_head; dv; dv = dv->next)
{ /* scan table */
if (((dv->rule.callopt == 1) && (ic->command == ISDN_STAT_ICALLW)) ||
((dv->rule.callopt == 2) && (ic->command == ISDN_STAT_ICALL)))
continue; /* call option check */
if (!(dv->rule.drvid & (1L << ic->driver)))
continue; /* driver not matching */
if ((dv->rule.si1) && (dv->rule.si1 != ic->parm.setup.si1))
continue; /* si1 not matching */
if ((dv->rule.si2) && (dv->rule.si2 != ic->parm.setup.si2))
continue; /* si2 not matching */
p = dv->rule.my_msn;
p1 = ic->parm.setup.eazmsn;
accept = 0;
while (*p)
{ /* complete compare */
if (*p == '-')
{ accept = 1; /* call accepted */
break;
}
if (*p++ != *p1++)
break; /* not accepted */
if ((!*p) && (!*p1))
accept = 1;
} /* complete compare */
if (!accept) continue; /* not accepted */
if ((strcmp(dv->rule.caller, "0")) || (ic->parm.setup.phone[0]))
{ p = dv->rule.caller;
p1 = ic->parm.setup.phone;
accept = 0;
while (*p)
{ /* complete compare */
if (*p == '-')
{ accept = 1; /* call accepted */
break;
}
if (*p++ != *p1++)
break; /* not accepted */
if ((!*p) && (!*p1))
accept = 1;
} /* complete compare */
if (!accept) continue; /* not accepted */
}
switch (dv->rule.action)
{ case DEFLECT_IGNORE:
return (0);
break;
case DEFLECT_ALERT:
case DEFLECT_PROCEED:
case DEFLECT_REPORT:
case DEFLECT_REJECT:
if (dv->rule.action == DEFLECT_PROCEED)
if ((!if_used) || ((!extern_wait_max) && (!dv->rule.waittime)))
return (0); /* no external deflection needed */
if (!(cs = kmalloc(sizeof(struct call_struc), GFP_ATOMIC)))
return (0); /* no memory */
init_timer(&cs->timer);
cs->info[0] = '\0';
cs->timer.function = deflect_timer_expire;
cs->timer.data = (ulong) cs; /* pointer to own structure */
cs->ics = *ic; /* copy incoming data */
if (!cs->ics.parm.setup.phone[0]) strcpy(cs->ics.parm.setup.phone, "0");
if (!cs->ics.parm.setup.eazmsn[0]) strcpy(cs->ics.parm.setup.eazmsn, "0");
cs->ics.parm.setup.screen = dv->rule.screen;
if (dv->rule.waittime)
cs->timer.expires = jiffies + (HZ * dv->rule.waittime);
else
if (dv->rule.action == DEFLECT_PROCEED)
cs->timer.expires = jiffies + (HZ * extern_wait_max);
else
cs->timer.expires = 0;
cs->akt_state = dv->rule.action;
spin_lock_irqsave(&divert_lock, flags);
cs->divert_id = next_id++; /* new sequence number */
spin_unlock_irqrestore(&divert_lock, flags);
cs->prev = NULL;
if (cs->akt_state == DEFLECT_ALERT)
{ strcpy(cs->deflect_dest, dv->rule.to_nr);
if (!cs->timer.expires)
{ strcpy(ic->parm.setup.eazmsn, "Testtext direct");
ic->parm.setup.screen = dv->rule.screen;
strlcpy(ic->parm.setup.phone, dv->rule.to_nr, sizeof(ic->parm.setup.phone));
cs->akt_state = DEFLECT_AUTODEL; /* delete after timeout */
cs->timer.expires = jiffies + (HZ * AUTODEL_TIME);
retval = 5;
}
else
retval = 1; /* alerting */
}
else
{ cs->deflect_dest[0] = '\0';
retval = 4; /* only proceed */
}
sprintf(cs->info, "%d 0x%lx %s %s %s %s 0x%x 0x%x %d %d %s\n",
cs->akt_state,
cs->divert_id,
divert_if.drv_to_name(cs->ics.driver),
(ic->command == ISDN_STAT_ICALLW) ? "1" : "0",
cs->ics.parm.setup.phone,
cs->ics.parm.setup.eazmsn,
cs->ics.parm.setup.si1,
cs->ics.parm.setup.si2,
cs->ics.parm.setup.screen,
dv->rule.waittime,
cs->deflect_dest);
if ((dv->rule.action == DEFLECT_REPORT) ||
(dv->rule.action == DEFLECT_REJECT))
{ put_info_buffer(cs->info);
kfree(cs); /* remove */
return ((dv->rule.action == DEFLECT_REPORT) ? 0 : 2); /* nothing to do */
}
break;
default:
return (0); /* ignore call */
break;
} /* switch action */
break;
} /* scan_table */
if (cs)
{ cs->prev = NULL;
spin_lock_irqsave(&divert_lock, flags);
cs->next = divert_head;
divert_head = cs;
if (cs->timer.expires) add_timer(&cs->timer);
spin_unlock_irqrestore(&divert_lock, flags);
put_info_buffer(cs->info);
return (retval);
}
else
return (0);
} /* isdn_divert_icall */
void deleteprocs(void)
{ struct call_struc *cs, *cs1;
unsigned long flags;
spin_lock_irqsave(&divert_lock, flags);
cs = divert_head;
divert_head = NULL;
while (cs)
{ del_timer(&cs->timer);
cs1 = cs;
cs = cs->next;
kfree(cs1);
}
spin_unlock_irqrestore(&divert_lock, flags);
} /* deleteprocs */
/****************************************************/
/* put a address including address type into buffer */
/****************************************************/
static int put_address(char *st, u_char *p, int len)
{ u_char retval = 0;
u_char adr_typ = 0; /* network standard */
if (len < 2) return (retval);
if (*p == 0xA1)
{ retval = *(++p) + 2; /* total length */
if (retval > len) return (0); /* too short */
len = retval - 2; /* remaining length */
if (len < 3) return (0);
if ((*(++p) != 0x0A) || (*(++p) != 1)) return (0);
adr_typ = *(++p);
len -= 3;
p++;
if (len < 2) return (0);
if (*p++ != 0x12) return (0);
if (*p > len) return (0); /* check number length */
len = *p++;
}
else
if (*p == 0x80)
{ retval = *(++p) + 2; /* total length */
if (retval > len) return (0);
len = retval - 2;
p++;
}
else
return (0); /* invalid address information */
sprintf(st, "%d ", adr_typ);
st += strlen(st);
if (!len)
*st++ = '-';
else
while (len--)
*st++ = *p++;
*st = '\0';
return (retval);
} /* put_address */
/*************************************/
/* report a successful interrogation */
/*************************************/
static int interrogate_success(isdn_ctrl *ic, struct call_struc *cs)
{ char *src = ic->parm.dss1_io.data;
int restlen = ic->parm.dss1_io.datalen;
int cnt = 1;
u_char n, n1;
char st[90], *p, *stp;
if (restlen < 2) return (-100); /* frame too short */
if (*src++ != 0x30) return (-101);
if ((n = *src++) > 0x81) return (-102); /* invalid length field */
restlen -= 2; /* remaining bytes */
if (n == 0x80)
{ if (restlen < 2) return (-103);
if ((*(src + restlen - 1)) || (*(src + restlen - 2))) return (-104);
restlen -= 2;
}
else
if (n == 0x81)
{ n = *src++;
restlen--;
if (n > restlen) return (-105);
restlen = n;
}
else
if (n > restlen) return (-106);
else
restlen = n; /* standard format */
if (restlen < 3) return (-107); /* no procedure */
if ((*src++ != 2) || (*src++ != 1) || (*src++ != 0x0B)) return (-108);
restlen -= 3;
if (restlen < 2) return (-109); /* list missing */
if (*src == 0x31)
{ src++;
if ((n = *src++) > 0x81) return (-110); /* invalid length field */
restlen -= 2; /* remaining bytes */
if (n == 0x80)
{ if (restlen < 2) return (-111);
if ((*(src + restlen - 1)) || (*(src + restlen - 2))) return (-112);
restlen -= 2;
}
else
if (n == 0x81)
{ n = *src++;
restlen--;
if (n > restlen) return (-113);
restlen = n;
}
else
if (n > restlen) return (-114);
else
restlen = n; /* standard format */
} /* result list header */
while (restlen >= 2)
{ stp = st;
sprintf(stp, "%d 0x%lx %d %s ", DIVERT_REPORT, ic->parm.dss1_io.ll_id,
cnt++, divert_if.drv_to_name(ic->driver));
stp += strlen(stp);
if (*src++ != 0x30) return (-115); /* invalid enum */
n = *src++;
restlen -= 2;
if (n > restlen) return (-116); /* enum length wrong */
restlen -= n;
p = src; /* one entry */
src += n;
if (!(n1 = put_address(stp, p, n & 0xFF))) continue;
stp += strlen(stp);
p += n1;
n -= n1;
if (n < 6) continue; /* no service and proc */
if ((*p++ != 0x0A) || (*p++ != 1)) continue;
sprintf(stp, " 0x%02x ", (*p++) & 0xFF);
stp += strlen(stp);
if ((*p++ != 0x0A) || (*p++ != 1)) continue;
sprintf(stp, "%d ", (*p++) & 0xFF);
stp += strlen(stp);
n -= 6;
if (n > 2)
{ if (*p++ != 0x30) continue;
if (*p > (n - 2)) continue;
n = *p++;
if (!(n1 = put_address(stp, p, n & 0xFF))) continue;
stp += strlen(stp);
}
sprintf(stp, "\n");
put_info_buffer(st);
} /* while restlen */
if (restlen) return (-117);
return (0);
} /* interrogate_success */
/*********************************************/
/* callback for protocol specific extensions */
/*********************************************/
static int prot_stat_callback(isdn_ctrl *ic)
{ struct call_struc *cs, *cs1;
int i;
unsigned long flags;
cs = divert_head; /* start of list */
cs1 = NULL;
while (cs)
{ if (ic->driver == cs->ics.driver)
{ switch (cs->ics.arg)
{ case DSS1_CMD_INVOKE:
if ((cs->ics.parm.dss1_io.ll_id == ic->parm.dss1_io.ll_id) &&
(cs->ics.parm.dss1_io.hl_id == ic->parm.dss1_io.hl_id))
{ switch (ic->arg)
{ case DSS1_STAT_INVOKE_ERR:
sprintf(cs->info, "128 0x%lx 0x%x\n",
ic->parm.dss1_io.ll_id,
ic->parm.dss1_io.timeout);
put_info_buffer(cs->info);
break;
case DSS1_STAT_INVOKE_RES:
switch (cs->ics.parm.dss1_io.proc)
{ case 7:
case 8:
put_info_buffer(cs->info);
break;
case 11:
i = interrogate_success(ic, cs);
if (i)
sprintf(cs->info, "%d 0x%lx %d\n", DIVERT_REPORT,
ic->parm.dss1_io.ll_id, i);
put_info_buffer(cs->info);
break;
default:
printk(KERN_WARNING "dss1_divert: unknown proc %d\n", cs->ics.parm.dss1_io.proc);
break;
}
break;
default:
printk(KERN_WARNING "dss1_divert unknown invoke answer %lx\n", ic->arg);
break;
}
cs1 = cs; /* remember structure */
cs = NULL;
continue; /* abort search */
} /* id found */
break;
case DSS1_CMD_INVOKE_ABORT:
printk(KERN_WARNING "dss1_divert unhandled invoke abort\n");
break;
default:
printk(KERN_WARNING "dss1_divert unknown cmd 0x%lx\n", cs->ics.arg);
break;
} /* switch ics.arg */
cs = cs->next;
} /* driver ok */
}
if (!cs1)
{ printk(KERN_WARNING "dss1_divert unhandled process\n");
return (0);
}
if (cs1->ics.driver == -1)
{
spin_lock_irqsave(&divert_lock, flags);
del_timer(&cs1->timer);
if (cs1->prev)
cs1->prev->next = cs1->next; /* forward link */
else
divert_head = cs1->next;
if (cs1->next)
cs1->next->prev = cs1->prev; /* back link */
spin_unlock_irqrestore(&divert_lock, flags);
kfree(cs1);
}
return (0);
} /* prot_stat_callback */
/***************************/
/* status callback from HL */
/***************************/
static int isdn_divert_stat_callback(isdn_ctrl *ic)
{ struct call_struc *cs, *cs1;
unsigned long flags;
int retval;
retval = -1;
cs = divert_head; /* start of list */
while (cs)
{ if ((ic->driver == cs->ics.driver) && (ic->arg == cs->ics.arg))
{ switch (ic->command)
{ case ISDN_STAT_DHUP:
sprintf(cs->info, "129 0x%lx\n", cs->divert_id);
del_timer(&cs->timer);
cs->ics.driver = -1;
break;
case ISDN_STAT_CAUSE:
sprintf(cs->info, "130 0x%lx %s\n", cs->divert_id, ic->parm.num);
break;
case ISDN_STAT_REDIR:
sprintf(cs->info, "131 0x%lx\n", cs->divert_id);
del_timer(&cs->timer);
cs->ics.driver = -1;
break;
default:
sprintf(cs->info, "999 0x%lx 0x%x\n", cs->divert_id, (int)(ic->command));
break;
}
put_info_buffer(cs->info);
retval = 0;
}
cs1 = cs;
cs = cs->next;
if (cs1->ics.driver == -1)
{
spin_lock_irqsave(&divert_lock, flags);
if (cs1->prev)
cs1->prev->next = cs1->next; /* forward link */
else
divert_head = cs1->next;
if (cs1->next)
cs1->next->prev = cs1->prev; /* back link */
spin_unlock_irqrestore(&divert_lock, flags);
kfree(cs1);
}
}
return (retval); /* not found */
} /* isdn_divert_stat_callback */
/********************/
/* callback from ll */
/********************/
int ll_callback(isdn_ctrl *ic)
{
switch (ic->command)
{ case ISDN_STAT_ICALL:
case ISDN_STAT_ICALLW:
return (isdn_divert_icall(ic));
break;
case ISDN_STAT_PROT:
if ((ic->arg & 0xFF) == ISDN_PTYPE_EURO)
{ if (ic->arg != DSS1_STAT_INVOKE_BRD)
return (prot_stat_callback(ic));
else
return (0); /* DSS1 invoke broadcast */
}
else
return (-1); /* protocol not euro */
default:
return (isdn_divert_stat_callback(ic));
}
} /* ll_callback */
| apache-2.0 |
manuelmagix/kernel_bq_piccolo | arch/sh/boards/mach-microdev/irq.c | 9196 | 5212 | /*
* arch/sh/boards/superh/microdev/irq.c
*
* Copyright (C) 2003 Sean McGoogan (Sean.McGoogan@superh.com)
*
* SuperH SH4-202 MicroDev board support.
*
* May be copied or modified under the terms of the GNU General Public
* License. See linux/COPYING for more information.
*/
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include <mach/microdev.h>
#define NUM_EXTERNAL_IRQS 16 /* IRL0 .. IRL15 */
static const struct {
unsigned char fpgaIrq;
unsigned char mapped;
const char *name;
} fpgaIrqTable[NUM_EXTERNAL_IRQS] = {
{ 0, 0, "unused" }, /* IRQ #0 IRL=15 0x200 */
{ MICRODEV_FPGA_IRQ_KEYBOARD, 1, "keyboard" }, /* IRQ #1 IRL=14 0x220 */
{ MICRODEV_FPGA_IRQ_SERIAL1, 1, "Serial #1"}, /* IRQ #2 IRL=13 0x240 */
{ MICRODEV_FPGA_IRQ_ETHERNET, 1, "Ethernet" }, /* IRQ #3 IRL=12 0x260 */
{ MICRODEV_FPGA_IRQ_SERIAL2, 0, "Serial #2"}, /* IRQ #4 IRL=11 0x280 */
{ 0, 0, "unused" }, /* IRQ #5 IRL=10 0x2a0 */
{ 0, 0, "unused" }, /* IRQ #6 IRL=9 0x2c0 */
{ MICRODEV_FPGA_IRQ_USB_HC, 1, "USB" }, /* IRQ #7 IRL=8 0x2e0 */
{ MICRODEV_IRQ_PCI_INTA, 1, "PCI INTA" }, /* IRQ #8 IRL=7 0x300 */
{ MICRODEV_IRQ_PCI_INTB, 1, "PCI INTB" }, /* IRQ #9 IRL=6 0x320 */
{ MICRODEV_IRQ_PCI_INTC, 1, "PCI INTC" }, /* IRQ #10 IRL=5 0x340 */
{ MICRODEV_IRQ_PCI_INTD, 1, "PCI INTD" }, /* IRQ #11 IRL=4 0x360 */
{ MICRODEV_FPGA_IRQ_MOUSE, 1, "mouse" }, /* IRQ #12 IRL=3 0x380 */
{ MICRODEV_FPGA_IRQ_IDE2, 1, "IDE #2" }, /* IRQ #13 IRL=2 0x3a0 */
{ MICRODEV_FPGA_IRQ_IDE1, 1, "IDE #1" }, /* IRQ #14 IRL=1 0x3c0 */
{ 0, 0, "unused" }, /* IRQ #15 IRL=0 0x3e0 */
};
#if (MICRODEV_LINUX_IRQ_KEYBOARD != 1)
# error Inconsistancy in defining the IRQ# for Keyboard!
#endif
#if (MICRODEV_LINUX_IRQ_ETHERNET != 3)
# error Inconsistancy in defining the IRQ# for Ethernet!
#endif
#if (MICRODEV_LINUX_IRQ_USB_HC != 7)
# error Inconsistancy in defining the IRQ# for USB!
#endif
#if (MICRODEV_LINUX_IRQ_MOUSE != 12)
# error Inconsistancy in defining the IRQ# for PS/2 Mouse!
#endif
#if (MICRODEV_LINUX_IRQ_IDE2 != 13)
# error Inconsistancy in defining the IRQ# for secondary IDE!
#endif
#if (MICRODEV_LINUX_IRQ_IDE1 != 14)
# error Inconsistancy in defining the IRQ# for primary IDE!
#endif
static void disable_microdev_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
unsigned int fpgaIrq;
if (irq >= NUM_EXTERNAL_IRQS)
return;
if (!fpgaIrqTable[irq].mapped)
return;
fpgaIrq = fpgaIrqTable[irq].fpgaIrq;
/* disable interrupts on the FPGA INTC register */
__raw_writel(MICRODEV_FPGA_INTC_MASK(fpgaIrq), MICRODEV_FPGA_INTDSB_REG);
}
static void enable_microdev_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
unsigned long priorityReg, priorities, pri;
unsigned int fpgaIrq;
if (unlikely(irq >= NUM_EXTERNAL_IRQS))
return;
if (unlikely(!fpgaIrqTable[irq].mapped))
return;
pri = 15 - irq;
fpgaIrq = fpgaIrqTable[irq].fpgaIrq;
priorityReg = MICRODEV_FPGA_INTPRI_REG(fpgaIrq);
/* set priority for the interrupt */
priorities = __raw_readl(priorityReg);
priorities &= ~MICRODEV_FPGA_INTPRI_MASK(fpgaIrq);
priorities |= MICRODEV_FPGA_INTPRI_LEVEL(fpgaIrq, pri);
__raw_writel(priorities, priorityReg);
/* enable interrupts on the FPGA INTC register */
__raw_writel(MICRODEV_FPGA_INTC_MASK(fpgaIrq), MICRODEV_FPGA_INTENB_REG);
}
static struct irq_chip microdev_irq_type = {
.name = "MicroDev-IRQ",
.irq_unmask = enable_microdev_irq,
.irq_mask = disable_microdev_irq,
};
/* This function sets the desired irq handler to be a MicroDev type */
static void __init make_microdev_irq(unsigned int irq)
{
disable_irq_nosync(irq);
irq_set_chip_and_handler(irq, µdev_irq_type, handle_level_irq);
disable_microdev_irq(irq_get_irq_data(irq));
}
extern void __init init_microdev_irq(void)
{
int i;
/* disable interrupts on the FPGA INTC register */
__raw_writel(~0ul, MICRODEV_FPGA_INTDSB_REG);
for (i = 0; i < NUM_EXTERNAL_IRQS; i++)
make_microdev_irq(i);
}
extern void microdev_print_fpga_intc_status(void)
{
volatile unsigned int * const intenb = (unsigned int*)MICRODEV_FPGA_INTENB_REG;
volatile unsigned int * const intdsb = (unsigned int*)MICRODEV_FPGA_INTDSB_REG;
volatile unsigned int * const intpria = (unsigned int*)MICRODEV_FPGA_INTPRI_REG(0);
volatile unsigned int * const intprib = (unsigned int*)MICRODEV_FPGA_INTPRI_REG(8);
volatile unsigned int * const intpric = (unsigned int*)MICRODEV_FPGA_INTPRI_REG(16);
volatile unsigned int * const intprid = (unsigned int*)MICRODEV_FPGA_INTPRI_REG(24);
volatile unsigned int * const intsrc = (unsigned int*)MICRODEV_FPGA_INTSRC_REG;
volatile unsigned int * const intreq = (unsigned int*)MICRODEV_FPGA_INTREQ_REG;
printk("-------------------------- microdev_print_fpga_intc_status() ------------------\n");
printk("FPGA_INTENB = 0x%08x\n", *intenb);
printk("FPGA_INTDSB = 0x%08x\n", *intdsb);
printk("FPGA_INTSRC = 0x%08x\n", *intsrc);
printk("FPGA_INTREQ = 0x%08x\n", *intreq);
printk("FPGA_INTPRI[3..0] = %08x:%08x:%08x:%08x\n", *intprid, *intpric, *intprib, *intpria);
printk("-------------------------------------------------------------------------------\n");
}
| apache-2.0 |
srajag/contrail-vrouter | linux/vr_host_interface.c | 1 | 63036 | /*
* vr_host_interface.c -- linux specific handling of vrouter interfaces
*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <linux/init.h>
#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include <linux/if_arp.h>
#include <linux/ip.h>
#include <linux/jhash.h>
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,39))
#include <linux/if_bridge.h>
#include <linux/openvswitch.h>
#endif
#include <net/rtnetlink.h>
#include "vrouter.h"
#include "vr_packet.h"
#include "vr_compat.h"
#include "vr_interface.h"
#include "vr_linux.h"
#include "vr_bridge.h"
#include "vr_os.h"
#include "vhost.h"
extern int vhost_init(void);
extern void vhost_exit(void);
extern void vhost_if_add(struct vr_interface *);
extern void vhost_if_del(struct net_device *);
extern void vhost_if_del_phys(struct net_device *);
extern void lh_pfree_skb(struct sk_buff *, unsigned short);
extern int vr_gro_vif_add(struct vrouter *, unsigned int, char *);
extern struct vr_interface_stats *vif_get_stats(struct vr_interface *,
unsigned short);
extern void vif_attach(struct vr_interface *);
extern void vif_detach(struct vr_interface *);
static int vr_napi_poll(struct napi_struct *, int);
static rx_handler_result_t pkt_gro_dev_rx_handler(struct sk_buff **);
static int linux_xmit_segments(struct vr_interface *, struct sk_buff *,
unsigned short);
static rx_handler_result_t pkt_rps_dev_rx_handler(struct sk_buff **pskb);
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39))
extern rx_handler_result_t vhost_rx_handler(struct sk_buff **);
#else
struct vr_interface vr_reset_interface;
#endif
extern volatile bool agent_alive;
/*
* Structure to store information required to be sent across CPU cores
* when RPS is performed on the physical interface (vr_perfr3 is 1).
*/
typedef struct vr_rps_ {
unsigned int vif_idx;
unsigned short vif_rid;
} vr_rps_t;
/*
* pkt_gro_dev - this is a device used to do receive offload on packets
* destined over a TAP interface to a VM.
*/
static struct net_device *pkt_gro_dev = NULL;
/*
* pkt_gro_dev_ops - netdevice operations on GRO packet device. Currently,
* no operations are needed, but an empty structure is required to
* register the device.
*
*/
static struct net_device_ops pkt_gro_dev_ops;
/*
* pkt_rps_dev - this is a device used to perform RPS on packets coming in
* on a physical interface.
*/
static struct net_device *pkt_rps_dev = NULL;
/*
* pkt_rps_dev_ops - netdevice operations on RPS packet device. Currently,
* no operations are needed, but an empty structure is required to
* register the device.
*
*/
static struct net_device_ops pkt_rps_dev_ops;
/*
* vr_skb_set_rxhash - set the rxhash on a skb if the kernel version
* allows it.
*/
void
vr_skb_set_rxhash(struct sk_buff *skb, __u32 val)
{
#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32))
#if defined(RHEL_MAJOR) && defined(RHEL_MINOR) && \
(RHEL_MAJOR == 6) && (RHEL_MINOR == 4)
skb->rxhash = val;
#endif
#elif (LINUX_VERSION_CODE < KERNEL_VERSION(3,15,0))
skb->rxhash = val;
#else
skb->hash = val;
#endif
}
/*
* vr_skb_get_rxhash - get the rxhash on a skb if the kernel version
* allows it.
*/
__u32
vr_skb_get_rxhash(struct sk_buff *skb)
{
#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32))
#if defined(RHEL_MAJOR) && defined(RHEL_MINOR) && \
(RHEL_MAJOR == 6) && (RHEL_MINOR == 4)
return skb->rxhash;
#else
return 0;
#endif
#elif (LINUX_VERSION_CODE < KERNEL_VERSION(3,15,0))
return skb->rxhash;
#else
return skb->hash;
#endif
}
static inline struct sk_buff*
linux_skb_vlan_insert(struct sk_buff *skb, unsigned short vlan_id)
{
struct vlan_ethhdr *veth;
if (skb_cow_head(skb, VLAN_HLEN) < 0) {
lh_pfree_skb(skb, VP_DROP_MISC);
return NULL;
}
veth = (struct vlan_ethhdr *)skb_push(skb, VLAN_HLEN);
/* Move the mac addresses to the beginning of the new header. */
memmove(skb->data, skb->data + VLAN_HLEN, 2 * ETH_ALEN);
skb->mac_header -= VLAN_HLEN;
/* first, the ethernet type */
veth->h_vlan_proto = htons(ETH_P_8021Q);
/* now, the TCI */
veth->h_vlan_TCI = htons(vlan_id);
skb_reset_mac_header(skb);
skb_reset_mac_len(skb);
return skb;
}
static int
linux_if_rx(struct vr_interface *vif, struct vr_packet *pkt)
{
int rc;
struct net_device *dev = (struct net_device *)vif->vif_os;
struct sk_buff *skb = vp_os_packet(pkt);
struct vr_ip *ip;
unsigned short network_off, transport_off, cksum_off = 0;
skb->data = pkt->vp_head + pkt->vp_data;
skb->len = pkt_len(pkt);
skb_set_tail_pointer(skb, pkt_head_len(pkt));
if (!dev) {
vif_drop_pkt(vif, pkt, false);
goto exit_rx;
}
(void)__sync_fetch_and_add(&dev->stats.rx_bytes, skb->len);
(void)__sync_fetch_and_add(&dev->stats.rx_packets, 1);
/* this is only needed for mirroring */
if ((pkt->vp_flags & VP_FLAG_FROM_DP) &&
(pkt->vp_flags & VP_FLAG_CSUM_PARTIAL)) {
network_off = pkt_get_network_header_off(pkt);
ip = (struct vr_ip *)(pkt_data_at_offset(pkt, network_off));
transport_off = network_off + (ip->ip_hl * 4);
if (ip->ip_proto == VR_IP_PROTO_TCP)
cksum_off = offsetof(struct vr_tcp, tcp_csum);
else if (ip->ip_proto == VR_IP_PROTO_UDP)
cksum_off = offsetof(struct vr_udp, udp_csum);
if (cksum_off)
*(unsigned short *)
(pkt_data_at_offset(pkt, transport_off + cksum_off))
= 0;
}
skb->protocol = eth_type_trans(skb, dev);
skb->pkt_type = PACKET_HOST;
rc = netif_rx(skb);
exit_rx:
return RX_HANDLER_CONSUMED;
}
struct vrouter_gso_cb {
void (*destructor)(struct sk_buff *skb);
};
static long
linux_inet_fragment(struct vr_interface *vif, struct sk_buff *skb,
unsigned short type)
{
struct iphdr *ip = ip_hdr(skb);
unsigned int ip_hlen = ip->ihl * 4;
bool fragmented = ntohs(ip->frag_off) & IP_MF ? true : false;
unsigned int offset = (ntohs(ip->frag_off) & IP_OFFSET) << 3;
unsigned short ip_id = ntohs(ip->id);
unsigned int payload_size = skb->len - skb->mac_len - ip_hlen;
unsigned int frag_size = skb->dev->mtu - skb->mac_len - ip_hlen;
unsigned int num_frags, last_frag_len;
struct sk_buff *segs;
netdev_features_t features;
features = netif_skb_features(skb);
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39))
features &= (~(NETIF_F_ALL_TSO | NETIF_F_UFO | NETIF_F_GSO));
#else
features &= ~(NETIF_F_TSO | NETIF_F_UFO | NETIF_F_GSO);
#endif
/*
* frag size has to be a multiple of 8 and last fragment has
* to be >= 64 bytes (approx)
*/
frag_size &= ~7U;
num_frags = payload_size / frag_size;
last_frag_len = payload_size % frag_size;
if (last_frag_len && last_frag_len < 64) {
frag_size -= ((64 - last_frag_len) / num_frags);
/*
* the previous division could have produced 0. to cover
* that case make some change to frag_size
*/
frag_size -= 1;
/* by doing this, we will get 8 bytes in the worst case */
frag_size &= ~7U;
}
skb_shinfo(skb)->gso_size = 0;
/*
* for packets that need checksum help, checksum has to be
* calculated here, since post fragmentation, checksum of
* individual fragments will be wrong
*/
if (skb->ip_summed == CHECKSUM_PARTIAL) {
if (skb_checksum_help(skb)) {
lh_pfree_skb(skb, VP_DROP_MISC);
return 0;
}
}
skb_shinfo(skb)->gso_size = frag_size;
/* pull till transport header */
skb_pull(skb, skb->mac_len + ip_hlen);
/*
* in 2.6.32-358.123.2.openstack.el6 kernel (and I guess all openstack
* kernels), the first field in the skb->cb is an offset field that is
* used to calculate header length. In those kernels, skb->cb is a
* structure of type skb_gso_cb with one field. Need to set that field
* to zero.
*
* This is equivalent to doing
*
* pkt->vp_head = NULL
*
* and hence access to packet structure beyond this point is suicidal
*/
memset(skb->cb, 0, sizeof(struct vrouter_gso_cb));
segs = skb_segment(skb, features);
if (IS_ERR(segs))
return PTR_ERR(segs);
kfree_skb(skb);
skb = segs;
do {
ip = ip_hdr(skb);
ip->id = htons(ip_id);
ip->frag_off = htons(offset >> 3);
if (skb->next != NULL || fragmented)
ip->frag_off |= htons(IP_MF);
offset += (skb->len - skb->mac_len - ip->ihl * 4);
ip->tot_len = htons(skb->len - skb->mac_len);
ip->check = 0;
ip->check = ip_fast_csum(skb_network_header(skb), ip->ihl);
} while ((skb = skb->next));
return linux_xmit_segments(vif, segs, type);
}
static int
linux_xmit(struct vr_interface *vif, struct sk_buff *skb,
unsigned short type)
{
if (vif->vif_type == VIF_TYPE_VIRTUAL &&
skb->ip_summed == CHECKSUM_NONE)
skb->ip_summed = CHECKSUM_UNNECESSARY;
if (vif->vif_type == VIF_TYPE_AGENT)
skb_shinfo(skb)->gso_size = 0;
if ((type == VP_TYPE_IPOIP) &&
(skb->len > skb->dev->mtu + skb->dev->hard_header_len))
return linux_inet_fragment(vif, skb, type);
return dev_queue_xmit(skb);
}
static int
linux_xmit_segment(struct vr_interface *vif, struct sk_buff *seg,
unsigned short type)
{
int err = -ENOMEM;
struct vr_ip *iph, *i_iph = NULL;
unsigned short iphlen;
unsigned short ethlen;
struct udphdr *udph;
unsigned short reason = 0;
/* we will do tunnel header updates after the fragmentation */
if (seg->len > seg->dev->mtu + seg->dev->hard_header_len
|| !vr_pkt_type_is_overlay(type)) {
return linux_xmit(vif, seg, type);
}
if (seg->dev->type == ARPHRD_ETHER) {
ethlen = ETH_HLEN;
} else {
ethlen = 0;
}
if (!pskb_may_pull(seg, ethlen + sizeof(struct vr_ip))) {
reason = VP_DROP_PULL;
goto exit_xmit;
}
iph = (struct vr_ip *)(seg->data + ethlen);
iphlen = (iph->ip_hl << 2);
if (!pskb_may_pull(seg, ethlen + iphlen)) {
reason = VP_DROP_PULL;
goto exit_xmit;
}
iph = (struct vr_ip *)(seg->data + ethlen);
iph->ip_len = htons(seg->len - ethlen);
if (type == VP_TYPE_IPOIP)
i_iph = (struct vr_ip *)skb_network_header(seg);
/*
* it is important that we copy the inner network header's
* ip id to outer. For now, agent diagnostics (traceroute)
* depends on this behavior.
*/
if (i_iph)
iph->ip_id = i_iph->ip_id;
else
iph->ip_id = htons(vr_generate_unique_ip_id());
iph->ip_csum = 0;
iph->ip_csum = ip_fast_csum(iph, iph->ip_hl);
if (iph->ip_proto == VR_IP_PROTO_UDP) {
if (!pskb_may_pull(seg, ethlen + iphlen +
sizeof(struct udphdr))) {
reason = VP_DROP_PULL;
goto exit_xmit;
}
if (vr_udp_coff) {
skb_set_network_header(seg, ethlen);
iph->ip_csum = 0;
skb_set_transport_header(seg, iphlen + ethlen);
if (!skb_partial_csum_set(seg, skb_transport_offset(seg),
offsetof(struct udphdr, check))) {
reason = VP_DROP_MISC;
goto exit_xmit;
}
udph = (struct udphdr *) skb_transport_header(seg);
udph->len = htons(seg->len - skb_transport_offset(seg));
iph->ip_csum = ip_fast_csum(iph, iph->ip_hl);
udph->check = ~csum_tcpudp_magic(iph->ip_saddr, iph->ip_daddr,
htons(udph->len),
IPPROTO_UDP, 0);
} else {
/*
* If we are encapsulating a L3/L2 packet in UDP, set the UDP
* checksum to 0 and let the NIC calculate the checksum of the
* inner packet (if the NIC supports it).
*/
udph = (struct udphdr *) (((char *)iph) + iphlen);
udph->len = htons(seg->len - (ethlen + iphlen));
udph->check = 0;
iph->ip_csum = 0;
iph->ip_csum = ip_fast_csum(iph, iph->ip_hl);
if ((vif->vif_flags & VIF_FLAG_TX_CSUM_OFFLOAD) == 0) {
if (seg->ip_summed == CHECKSUM_PARTIAL) {
skb_checksum_help(seg);
}
}
}
} else if (iph->ip_proto == VR_IP_PROTO_GRE) {
if ((vif->vif_flags & VIF_FLAG_TX_CSUM_OFFLOAD) == 0) {
if (seg->ip_summed == CHECKSUM_PARTIAL) {
skb_checksum_help(seg);
}
}
}
return linux_xmit(vif, seg, type);
exit_xmit:
lh_pfree_skb(seg, reason);
return err;
}
static int
linux_xmit_segments(struct vr_interface *vif, struct sk_buff *segs,
unsigned short type)
{
int err;
struct sk_buff *nskb = NULL;
do {
nskb = segs->next;
segs->next = NULL;
if ((err = linux_xmit_segment(vif, segs, type)))
break;
segs = nskb;
} while (segs);
segs = nskb;
while (segs) {
nskb = segs->next;
segs->next = NULL;
kfree_skb(segs);
segs = nskb;
}
return err;
}
/*
* linux_gso_xmit - perform segmentation of the inner packet in software
* and send each segment out the wire after fixing the outer header.
*/
static void
linux_gso_xmit(struct vr_interface *vif, struct sk_buff *skb,
unsigned short type)
{
netdev_features_t features;
struct sk_buff *segs;
unsigned short seg_size = skb_shinfo(skb)->gso_size;
struct iphdr *ip = ip_hdr(skb);
struct tcphdr *th;
struct net_device *ndev = (struct net_device *)vif->vif_os;
features = netif_skb_features(skb);
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39))
features &= (~(NETIF_F_ALL_TSO | NETIF_F_UFO | NETIF_F_GSO));
#else
features &= (~(NETIF_F_TSO | NETIF_F_UFO | NETIF_F_GSO));
#endif
seg_size += skb->mac_len + skb_network_header_len(skb);
/*
* We are trying to find whether the total size of the packet will
* overshoot the mtu. Above, we have accounted for the tunnel headers,
* the inner ip header, and the segment size. However, there is a
* subtle difference in deciding whether transport header is part of
* GSO size or not.
*
* For TCP, segment size (gso size) is the ip data length - tcp header
* length (since each segment goes with tcp header), while for udp, there
* are only fragments (and no segments) and the segment size (fragment
* size) is the ip data length adjusted to mtu (since udp header goes
* only with the first fragment). Hence the following condition
*/
if (ip->protocol == IPPROTO_TCP) {
th = tcp_hdr(skb);
seg_size += (th->doff * 4);
}
/*
* avoid fragmentation after segmentation.
*/
if (seg_size > ndev->mtu + ndev->hard_header_len) {
skb_shinfo(skb)->gso_size -= (seg_size - ndev->mtu -
ndev->hard_header_len);
if (ip->protocol == IPPROTO_UDP)
skb_shinfo(skb)->gso_size &= ~7;
}
segs = skb_gso_segment(skb, features);
kfree_skb(skb);
if ((IS_ERR(segs)) || (segs == NULL)) {
return;
}
linux_xmit_segments(vif, segs, type);
return;
}
#ifdef CONFIG_RPS
/*
* linux_get_rxq - get a receive queue for the packet on an interface that
* has RPS enabled. The receive queue is picked such that it is different
* from the current CPU core and the previous CPU core that handled the
* packet (if the previous core is specified). The receive queue has a 1-1
* mapping to the receiving CPU core (i.e. queue 1 corresponds to CPU core 0,
* queue 2 to CPU core 1 and so on). The CPU core is chosen such that it is
* on the same NUMA node as the current core (to minimize memory access
* latency across NUMA nodes), except that hyper-threads of the current
* and previous core are excluded as choices for the next CPU to process the
* packet.
*/
static void
linux_get_rxq(struct sk_buff *skb, u16 *rxq, unsigned int curr_cpu,
unsigned int prev_cpu)
{
unsigned int next_cpu;
int numa_node = cpu_to_node(curr_cpu);
const struct cpumask *node_cpumask = cpumask_of_node(numa_node);
struct cpumask noht_cpumask;
unsigned int num_cpus, cpu, count = 0;
__u32 rxhash;
/*
* We are running in softirq context, so CPUs can't be offlined
* underneath us. So, it is safe to use the NUMA node CPU bitmaps.
* Clear the bits corresponding to the current core and its hyperthreads
* in the node CPU mask.
*/
cpumask_andnot(&noht_cpumask, node_cpumask, cpu_sibling_mask(curr_cpu));
/*
* If the previous CPU is specified, clear the bits corresponding to
* that core and its hyperthreads in the CPU mask.
*/
if (prev_cpu && (prev_cpu <= nr_cpu_ids)) {
cpumask_andnot(&noht_cpumask, &noht_cpumask,
cpu_sibling_mask(prev_cpu-1));
}
num_cpus = cpumask_weight(&noht_cpumask);
if (num_cpus) {
rxhash = skb_get_rxhash(skb);
#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32))
next_cpu = ((u32)rxhash * num_cpus) >> 16;
#else
next_cpu = ((u64)rxhash * num_cpus) >> 32;
#endif
/*
* next_cpu is between 0 and (num_cpus - 1). Find the CPU corresponding
* to next_cpu in the CPU bitmask.
*/
for_each_cpu(cpu, &noht_cpumask) {
if (count == next_cpu) {
break;
}
count++;
}
if (cpu >= nr_cpu_ids) {
/*
* Shouldn't happen
*/
*rxq = curr_cpu;
} else {
*rxq = cpu;
}
} else {
/*
* Not enough CPU cores available in this NUMA node. Continue
* processing the packet on the same CPU core.
*/
*rxq = curr_cpu;
}
return;
}
#endif
/*
* linux_enqueue_pkt_for_gro - enqueue packet on a list of skbs and schedule a
* NAPI event on the NAPI structure of the vif.
*
*/
void
linux_enqueue_pkt_for_gro(struct sk_buff *skb, struct vr_interface *vif)
{
struct vr_interface *gro_vif;
struct vr_interface_stats *gro_vif_stats;
int in_intr_context;
#ifdef CONFIG_RPS
u16 rxq;
unsigned int curr_cpu = 0;
__u32 prev_cpu;
/*
* vr_perfr1 only takes effect if vr_perfr3 is not set. Also, if we are
* coming here after RPS (skb->dev is pkt_rps_dev), vr_perfr1 is a no-op
*/
if (vr_perfr1 && (!vr_perfr3) && (skb->dev != pkt_rps_dev)) {
curr_cpu = vr_get_cpu();
if (vr_perfq1) {
rxq = vr_perfq1;
} else {
linux_get_rxq(skb, &rxq, curr_cpu, 0);
}
skb_record_rx_queue(skb, rxq);
/*
* Store current CPU in rxhash of skb
*/
vr_skb_set_rxhash(skb, curr_cpu);
skb->dev = pkt_rps_dev;
/*
* Clear the vr_rps_t vif_idx field in the skb->cb. This is to handle
* the corner case of vr_perfr3 being enabled after a packet has
* been scheduled for RPS with vr_perfr1 set, but before the
* earlier RPS has completed. After RPS completes, linux_rx_handler()
* will drop the packet as vif_idx is 0 (which corresponds to pkt0).
*/
((vr_rps_t *)skb->cb)->vif_idx = 0;
netif_receive_skb(skb);
return;
}
if (vr_perfr2) {
if (vr_perfq2) {
rxq = vr_perfq2;
} else {
/*
* If RPS happened earlier (perfr1 or perfr3 is set),
* prev_cpu was already been set in skb->rxhash.
*/
prev_cpu = vr_skb_get_rxhash(skb);
vr_skb_set_rxhash(skb, 0);
linux_get_rxq(skb, &rxq, vr_get_cpu(),
(vr_perfr1 || vr_perfr3) ?
prev_cpu+1 : 0);
}
skb_record_rx_queue(skb, rxq);
} else {
skb_set_queue_mapping(skb, 0);
}
#endif /* CONFIG_RPS */
skb->dev = pkt_gro_dev;
gro_vif = pkt_gro_dev->ml_priv;
if (gro_vif) {
gro_vif_stats = vif_get_stats(gro_vif, vr_get_cpu());
if (gro_vif_stats) {
gro_vif_stats->vis_opackets++;
gro_vif_stats->vis_obytes += skb->len;
}
}
skb_queue_tail(&vif->vr_skb_inputq, skb);
/*
* napi_schedule may raise a softirq, so if we are not already in
* interrupt context (which is the case when we get here as a result of
* the agent enabling a flow for forwarding), ensure that the softirq is
* handled immediately.
*/
in_intr_context = in_interrupt();
if (!in_intr_context) {
local_bh_disable();
}
napi_schedule(&vif->vr_napi);
if (!in_intr_context) {
local_bh_enable();
}
return;
}
#if 0
static void __skb_dump_info(const char *prefix, const struct sk_buff *skb,
struct vr_interface *vif)
{
#ifdef CONFIG_XEN
int i, nr = skb_shinfo(skb)->nr_frags;
#endif
struct ethhdr *ethh = eth_hdr(skb);
struct iphdr *iph = NULL;
struct tcphdr *tcph = NULL;
printk("vif info: type=%d id=%d os_id=%d\n",
vif->vif_type, vif->vif_idx, vif->vif_os_idx);
printk(KERN_CRIT "%s: len is %#x (data:%#x mac:%#x) truesize %#x\n", prefix,
skb->len, skb->data_len, skb->mac_len, skb->truesize);
printk(KERN_CRIT "%s: linear:%s\n", prefix,
skb_is_nonlinear(skb) ? "No" : "Yes");
printk(KERN_CRIT "%s: data %p head %p tail %p end %p\n", prefix,
skb->data, skb->head, skb->tail, skb->end);
printk(KERN_CRIT "%s: flags are local_df:%d cloned:%d ip_summed:%d"
"nohdr:%d\n", prefix, skb->local_df, skb->cloned,
skb->ip_summed, skb->nohdr);
printk(KERN_CRIT "%s: nfctinfo:%d pkt_type:%d fclone:%d ipvs_property:%d\n",
prefix, skb->nfctinfo, skb->pkt_type,
skb->nohdr, skb->ipvs_property);
printk(KERN_CRIT "%s: shared info %p ref %#x\n", prefix,
skb_shinfo(skb), atomic_read(&skb_shinfo(skb)->dataref));
printk(KERN_CRIT "%s: frag_list %p\n", prefix,
skb_shinfo(skb)->frag_list);
if (ethh) {
printk(KERN_CRIT "%s: eth: (%p) src:%pM dest:%pM proto %u\n",
prefix, ethh, ethh->h_source, ethh->h_dest, ntohs(ethh->h_proto));
if (ethh->h_proto == __constant_htons(ETH_P_IP))
iph = ip_hdr(skb);
} else
printk(KERN_CRIT "%s: eth: header not present\n", prefix);
if (iph) {
printk(KERN_CRIT "%s: ip: (%p) saddr "NIPQUAD_FMT" daddr "NIPQUAD_FMT"\
protocol %d frag_off %d\n", prefix, iph, NIPQUAD(iph->saddr),
NIPQUAD(iph->daddr), iph->protocol, iph->frag_off);
if (iph->protocol == IPPROTO_TCP)
tcph = tcp_hdr(skb);
} else
printk(KERN_CRIT "%s: ip: header not present\n", prefix);
if (tcph) {
printk(KERN_CRIT "%s: tcp: (%p) source %d dest %d seq %u ack %u\n",
prefix, tcph, ntohs(tcph->source), ntohs(tcph->dest),
ntohl(tcph->seq), ntohl(tcph->ack_seq));
} else
printk(KERN_CRIT "%s: tcp: header not present\n", prefix);
#ifdef CONFIG_XEN
printk(KERN_CRIT "%s: nr_frags %d\n", prefix, nr);
for(i=0; i<nr; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
unsigned long pfn = page_to_pfn(frag->page);
unsigned long mfn = pfn_to_mfn(pfn);
printk(KERN_CRIT "%s: %d/%d page:%p count:%d offset:%#x size:%#x \
virt:%p pfn:%#lx mfn:%#lx%s flags:%lx%s%s)\n",
prefix, i + 1, nr, frag->page,
atomic_read(&frag->page->_count),
frag->page_offset, frag->size,
phys_to_virt(page_to_pseudophys(frag->page)), pfn, mfn,
phys_to_machine_mapping_valid(pfn) ? "" : "(BAD)",
frag->page->flags,
PageForeign(frag->page) ? " FOREIGN" : "",
PageBlkback(frag->page) ? " BLKBACK" : "");
}
#endif
}
#endif
static int
linux_if_tx(struct vr_interface *vif, struct vr_packet *pkt)
{
struct net_device *dev = (struct net_device *)vif->vif_os;
struct sk_buff *skb = vp_os_packet(pkt);
struct skb_shared_info *sinfo;
struct vr_ip *ip;
struct vr_ip6 *ip6;
int proto;
unsigned short network_off, transport_off, cksum_off;
#if CONFIG_XEN && (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32))
unsigned char *data;
#endif
skb->data = pkt_data(pkt);
skb->len = pkt_len(pkt);
skb_set_tail_pointer(skb, pkt_head_len(pkt));
skb->dev = dev;
if (!dev) {
vif_drop_pkt(vif, pkt, false);
return 0;
}
if ((pkt->vp_flags & VP_FLAG_GRO) &&
(vif->vif_type == VIF_TYPE_VIRTUAL)) {
#if CONFIG_XEN && (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32))
if (unlikely(skb_headroom(skb) < ETH_HLEN)) {
struct sk_buff *nskb = skb_realloc_headroom(skb, LL_RESERVED_SPACE(dev));
if (!nskb) {
vif_drop_pkt(vif, pkt, false);
if (net_ratelimit())
printk(KERN_WARNING
"Insufficient memory: %s %d\n",
__FUNCTION__, __LINE__);
return -ENOMEM;
}
memcpy(nskb->data - VR_MPLS_HDR_LEN, skb->data - VR_MPLS_HDR_LEN,
VR_MPLS_HDR_LEN);
kfree_skb(skb);
skb = nskb;
}
data = skb_push(skb, ETH_HLEN);
memset(data, 0xFE, ETH_HLEN - VR_MPLS_HDR_LEN);
skb_reset_mac_header(skb);
#else
skb_push(skb, VR_MPLS_HDR_LEN);
skb_reset_mac_header(skb);
#endif
if (!skb_pull(skb, pkt->vp_network_h - (skb->data - skb->head))) {
vif_drop_pkt(vif, pkt, false);
return 0;
}
skb_reset_network_header(skb);
linux_enqueue_pkt_for_gro(skb, vif);
return 0;
}
skb_reset_mac_header(skb);
/*
* Set the network header and trasport header of skb only if the type is
* IP (tunnel or non tunnel). This is required for those packets where
* a new buffer is added at the head. Also, set it for packets from the
* agent, which get sent to the NIC driver (to handle cases where the
* NIC has hw vlan acceleration enabled).
*/
if (pkt->vp_type == VP_TYPE_AGENT) {
network_off = pkt_get_inner_network_header_off(pkt);
if (network_off) {
skb_set_network_header(skb, (network_off - skb_headroom(skb)));
skb_reset_mac_len(skb);
}
} else if (vr_pkt_type_is_overlay(pkt->vp_type)) {
network_off = pkt_get_inner_network_header_off(pkt);
if (network_off) {
ip = (struct vr_ip *)(pkt_data_at_offset(pkt, network_off));
if (!vr_ip_is_ip6(ip)) {
transport_off = network_off + (ip->ip_hl * 4);
proto = ip->ip_proto;
} else {
ip6 = (struct vr_ip6 *)ip;
transport_off = network_off + sizeof(struct vr_ip6);
proto = ip6->ip6_nxt;
}
skb_set_network_header(skb, (network_off - skb_headroom(skb)));
skb_reset_mac_len(skb);
skb_set_transport_header(skb, (transport_off - skb_headroom(skb)));
/*
* Manipulate partial checksum fields.
* There are cases like mirroring where the UDP headers are newly added
* and skb needs to be filled with proper offsets. The vr_packet's fields
* are latest values and they need to be reflected in skb
*/
if (pkt->vp_flags & VP_FLAG_CSUM_PARTIAL) {
cksum_off = skb->csum_offset;
if (proto == VR_IP_PROTO_TCP)
cksum_off = offsetof(struct vr_tcp, tcp_csum);
else if (proto == VR_IP_PROTO_UDP)
cksum_off = offsetof(struct vr_udp, udp_csum);
skb_partial_csum_set(skb, (transport_off - skb_headroom(skb)), cksum_off);
}
/*
* Invoke segmentation only incase of both vr_packet and skb having gso
*/
if ((pkt->vp_flags & VP_FLAG_GSO) && skb_is_gso(skb)) {
/*
* it is possible that when we mirrored the packet, the inner
* packet was meant to be GSO-ed, and that would have been a
* TCP packet. Since we carried over the gso type from the inner
* packet, the value will be wrong, and that's where the following
* check comes into picture
*/
if (proto == VR_IP_PROTO_UDP) {
sinfo = skb_shinfo(skb);
if (!(sinfo->gso_type & SKB_GSO_UDP)) {
sinfo->gso_type &= ~(SKB_GSO_TCPV4 | SKB_GSO_TCP_ECN |
SKB_GSO_TCPV6 | SKB_GSO_FCOE);
sinfo->gso_type |= SKB_GSO_UDP;
}
}
if (vif->vif_type == VIF_TYPE_PHYSICAL) {
linux_gso_xmit(vif, skb, pkt->vp_type);
return 0;
}
}
}
}
linux_xmit_segment(vif, skb, pkt->vp_type);
return 0;
}
inline struct vr_packet *
linux_get_packet(struct sk_buff *skb, struct vr_interface *vif)
{
struct vr_packet *pkt;
unsigned int length;
pkt = (struct vr_packet *)skb->cb;
pkt->vp_cpu = vr_get_cpu();
pkt->vp_head = skb->head;
length = skb_tail_pointer(skb) - skb->head;
if (length >= (1 << (sizeof(pkt->vp_tail) * 8)))
goto drop;
pkt->vp_tail = length;
length = skb->data - skb->head;
if (length >= (1 << (sizeof(pkt->vp_data) * 8)))
goto drop;
pkt->vp_data = length;
length = skb_end_pointer(skb) - skb->head;
if (length >= (1 << (sizeof(pkt->vp_end) * 8)))
goto drop;
pkt->vp_end = length;
pkt->vp_len = skb_headlen(skb);
pkt->vp_if = vif;
pkt->vp_network_h = pkt->vp_inner_network_h = 0;
pkt->vp_nh = NULL;
pkt->vp_flags = 0;
if (skb->ip_summed == CHECKSUM_PARTIAL)
pkt->vp_flags |= VP_FLAG_CSUM_PARTIAL;
pkt->vp_ttl = 64;
pkt->vp_type = VP_TYPE_NULL;
return pkt;
drop:
vr_pfree(pkt, VP_DROP_INVALID_PACKET);
return NULL;
}
int
linux_to_vr(struct vr_interface *vif, struct sk_buff *skb)
{
struct vr_packet *pkt;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
return 0;
pkt = linux_get_packet(skb, vif);
if (!pkt)
return 0;
vif->vif_rx(vif, pkt, VLAN_ID_INVALID);
return 0;
}
bool
linux_ip_proto_pull(struct iphdr *iph)
{
__u8 proto = iph->protocol;
if ((proto == VR_IP_PROTO_TCP) ||
(proto == VR_IP_PROTO_UDP) ||
(proto == VR_IP_PROTO_ICMP)) {
return true;
}
return false;
}
static bool
linux_ipv6_proto_pull(struct ipv6hdr *ip6h)
{
__u8 proto = ip6h->nexthdr;
if ((proto == VR_IP_PROTO_TCP) ||
(proto == VR_IP_PROTO_UDP) ||
(proto == VR_IP_PROTO_ICMP6)) {
return true;
}
return false;
}
static int
linux_pull_outer_headers(struct sk_buff *skb)
{
struct vlan_hdr *vhdr;
uint16_t proto, offset, ip_proto = 0;
struct iphdr *iph = NULL;
struct ipv6hdr *ip6h = NULL;
struct vr_icmp *icmph;
offset = skb->mac_len;
proto = skb->protocol;
while (proto == htons(ETH_P_8021Q)) {
offset += sizeof(struct vlan_hdr);
if (!pskb_may_pull(skb, offset))
goto pull_fail;
vhdr = (struct vlan_hdr *)(skb->data + offset);
proto = vhdr->h_vlan_encapsulated_proto;
}
if (likely(proto == htons(ETH_P_IP))) {
skb_set_network_header(skb, offset);
offset += sizeof(struct iphdr);
if (!pskb_may_pull(skb, offset))
goto pull_fail;
iph = ip_hdr(skb);
offset += (iph->ihl * 4) - sizeof(struct iphdr);
if (!pskb_may_pull(skb, offset))
goto pull_fail;
iph = ip_hdr(skb);
if (linux_ip_proto_pull(iph) &&
vr_ip_transport_header_valid((struct vr_ip *)iph)) {
ip_proto = iph->protocol;
}
} else if (proto == htons(ETH_P_IPV6)) {
skb_set_network_header(skb, offset);
offset += sizeof(struct ipv6hdr);
if (!pskb_may_pull(skb, offset))
goto pull_fail;
ip6h = ipv6_hdr(skb);
if (linux_ipv6_proto_pull(ip6h)) {
ip_proto = ip6h->nexthdr;
}
} else if (proto == htons(ETH_P_ARP)) {
offset += sizeof(struct vr_arp);
if (!pskb_may_pull(skb, offset))
goto pull_fail;
}
if (iph || ip6h) {
/*
* this covers both regular port number offsets that come in
* the first 4 bytes and the icmp header
*/
offset += sizeof(struct vr_icmp);
if (!pskb_may_pull(skb, offset))
goto pull_fail;
if (iph)
iph = ip_hdr(skb);
else
ip6h = ipv6_hdr(skb);
if (ip_proto == VR_IP_PROTO_ICMP) {
if (vr_icmp_error((struct vr_icmp *)((unsigned char *)iph +
(iph->ihl * 4)))) {
iph = (struct iphdr *)(skb->data + offset);
offset += sizeof(struct iphdr);
if (!pskb_may_pull(skb, offset))
goto pull_fail;
iph = (struct iphdr *)(skb->data + offset - sizeof(struct iphdr));
if (linux_ip_proto_pull(iph)) {
offset += (iph->ihl * 4) - sizeof(struct iphdr) +
sizeof(struct vr_icmp);
if (!pskb_may_pull(skb, offset))
goto pull_fail;
}
}
} else if (ip_proto == VR_IP_PROTO_ICMP6) {
icmph = (struct vr_icmp *) ((char *)ip6h + sizeof(struct ipv6hdr));
if (icmph->icmp_type == VR_ICMP6_TYPE_NEIGH_SOL) {
/* ICMP options size for neighbor solicit is 24 bytes */
offset += 24;
if (!pskb_may_pull(skb, offset))
goto pull_fail;
}
}
}
return 0;
pull_fail:
return -1;
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39))
rx_handler_result_t
linux_rx_handler(struct sk_buff **pskb)
{
int ret;
unsigned short vlan_id = VLAN_ID_INVALID;
struct sk_buff *skb = *pskb;
struct vr_packet *pkt;
struct net_device *dev = skb->dev;
struct vr_interface *vif;
unsigned int curr_cpu;
u16 rxq;
int rpsdev = 0;
struct vrouter *router;
/*
* If we did RPS immediately after the packet was received from the
* physical interface (vr_perfr3 is set), we are now running on a
* new core. Extract the vif information that was saved in the skb
* on the previous core.
*/
if (skb->dev == pkt_rps_dev) {
router = vrouter_get(((vr_rps_t *)skb->cb)->vif_rid);
if (router == NULL) {
goto error;
}
vif = __vrouter_get_interface(router,
((vr_rps_t *)skb->cb)->vif_idx);
if (vif && (vif->vif_type == VIF_TYPE_PHYSICAL) && vif->vif_os) {
dev = (struct net_device *) vif->vif_os;
rpsdev = 1;
} else {
goto error;
}
}
vif = rcu_dereference(dev->rx_handler_data);
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
return RX_HANDLER_PASS;
#ifdef CONFIG_RPS
/*
* Send the packet to another CPU core if vr_perfr3 is set. The new
* CPU core is chosen based on a hash of the outer header. This only needs
* to be done for packets arriving on a physical interface. Also, we
* only need to do this if RPS hasn't already happened.
*/
if (vr_perfr3 && (!rpsdev) && (vif->vif_type == VIF_TYPE_PHYSICAL)) {
curr_cpu = vr_get_cpu();
if (vr_perfq3) {
rxq = vr_perfq3;
} else {
linux_get_rxq(skb, &rxq, curr_cpu, 0);
}
skb_record_rx_queue(skb, rxq);
vr_skb_set_rxhash(skb, curr_cpu);
skb->dev = pkt_rps_dev;
/*
* Store vif information in skb for later retrieval
*/
((vr_rps_t *)skb->cb)->vif_idx = vif->vif_idx;
((vr_rps_t *)skb->cb)->vif_rid = vif->vif_rid;
netif_receive_skb(skb);
return RX_HANDLER_CONSUMED;
}
#endif
if (dev->type == ARPHRD_ETHER) {
skb_push(skb, skb->mac_len);
if (skb->vlan_tci & VLAN_TAG_PRESENT) {
if (!(skb = linux_skb_vlan_insert(skb,
skb->vlan_tci & 0xEFFF)))
return RX_HANDLER_CONSUMED;
vlan_id = skb->vlan_tci & 0xFFF;
skb->vlan_tci = 0;
}
} else {
if (skb_headroom(skb) < ETH_HLEN) {
ret = pskb_expand_head(skb, ETH_HLEN - skb_headroom(skb) +
ETH_HLEN + sizeof(struct agent_hdr), 0, GFP_ATOMIC);
if (ret)
goto error;
}
}
ret = linux_pull_outer_headers(skb);
if (ret < 0)
goto error;
pkt = linux_get_packet(skb, vif);
if (!pkt)
return RX_HANDLER_CONSUMED;
if (vif->vif_type == VIF_TYPE_PHYSICAL) {
if ((!(vif->vif_flags & VIF_FLAG_PROMISCOUS)) &&
(skb->pkt_type == PACKET_OTHERHOST)) {
vif_drop_pkt(vif, pkt, true);
return RX_HANDLER_CONSUMED;
}
}
ret = vif->vif_rx(vif, pkt, vlan_id);
if (!ret)
ret = RX_HANDLER_CONSUMED;
return ret;
error:
pkt = (struct vr_packet *)skb->cb;
vr_pfree(pkt, VP_DROP_MISC);
return RX_HANDLER_CONSUMED;
}
#else
#ifdef CONFIG_RPS
/*
* vr_do_rps_outer - perform RPS based on the outer header immediately after
* the packet is received from the physical interface.
*/
static void
vr_do_rps_outer(struct sk_buff *skb, struct vr_interface *vif)
{
unsigned int curr_cpu;
u16 rxq;
curr_cpu = vr_get_cpu();
if (vr_perfq3) {
rxq = vr_perfq3;
} else {
linux_get_rxq(skb, &rxq, curr_cpu, 0);
}
skb_record_rx_queue(skb, rxq);
vr_skb_set_rxhash(skb, curr_cpu);
skb->dev = pkt_rps_dev;
/*
* Store vif information in skb for later retrieval
*/
((vr_rps_t *)skb->cb)->vif_idx = vif->vif_idx;
((vr_rps_t *)skb->cb)->vif_rid = vif->vif_rid;
netif_receive_skb(skb);
return;
}
/*
* vr_get_vif_ptr - gets a pointer to the vif structure from the netdevice
* structure depending on whether vrouter uses the bridge or OVS hook.
*/
static struct vr_interface *
vr_get_vif_ptr(struct net_device *dev)
{
struct vr_interface *vif;
if (vr_use_linux_br) {
vif = (struct vr_interface *) rcu_dereference(dev->br_port);
} else {
vif = (struct vr_interface *) rcu_dereference(dev->ax25_ptr);
}
return vif;
}
/*
* vr_set_vif_ptr - sets a pointer to the vif structure in the netdevice
* structure depending on whether vrouter uses the bridge or OVS hook.
*/
void
vr_set_vif_ptr(struct net_device *dev, void *vif)
{
if (vr_use_linux_br) {
rcu_assign_pointer(dev->br_port, vif);
} else {
rcu_assign_pointer(dev->ax25_ptr, vif);
if (vif) {
dev->priv_flags |= IFF_OVS_DATAPATH;
} else {
dev->priv_flags &= (~IFF_OVS_DATAPATH);
}
}
return;
}
#endif
/*
* vr_post_rps_get_phys_dev - get the physical interface that the packet
* arrived on, after RPS is performed based on the outer header. Returns
* the interface pointer on success, NULL otherwise.
*/
static struct net_device *
vr_post_rps_outer_get_phys_dev(struct sk_buff *skb)
{
struct net_device *dev = NULL;
struct vrouter *router;
struct vr_interface *vif;
router = vrouter_get(((vr_rps_t *)skb->cb)->vif_rid);
if (router == NULL) {
return NULL;
}
vif = __vrouter_get_interface(router,
((vr_rps_t *)skb->cb)->vif_idx);
if (vif && (vif->vif_type == VIF_TYPE_PHYSICAL) && vif->vif_os) {
dev = (struct net_device *) vif->vif_os;
}
return dev;
}
/*
* vr_interface_common_hook
*
* Common function called by both bridge and OVS hooks in 2.6 kernels.
*/
static struct sk_buff *
vr_interface_common_hook(struct sk_buff *skb)
{
unsigned short vlan_id = VLAN_ID_INVALID;
struct vr_interface *vif;
struct vr_packet *pkt;
struct vlan_hdr *vhdr;
int rpsdev = 0;
int ret;
struct net_device *dev, *vdev;
/*
* LACP packets should go to the protocol handler. Hence do not
* claim those packets. This action is not needed in 3.x kernels
* because packets are claimed by the protocol handler from the
* component interface itself by means of netdev_rx_handler
*/
if (skb->protocol == __be16_to_cpu(ETH_P_SLOW))
return skb;
if (skb->dev == NULL) {
goto error;
}
dev = skb->dev;
if (vr_get_vif_ptr(skb->dev) == (&vr_reset_interface)) {
vdev = vhost_get_vhost_for_phys(skb->dev);
if (!vdev)
goto error;
skb->dev = vdev;
(void)__sync_fetch_and_add(&vdev->stats.rx_bytes, skb->len);
(void)__sync_fetch_and_add(&vdev->stats.rx_packets, 1);
return skb;
}
if (skb->dev == pkt_gro_dev) {
pkt_gro_dev_rx_handler(&skb);
return NULL;
} else if (skb->dev == pkt_rps_dev) {
if (!vr_perfr3) {
pkt_rps_dev_rx_handler(&skb);
return NULL;
}
dev = vr_post_rps_outer_get_phys_dev(skb);
if (dev == NULL) {
goto error;
}
rpsdev = 1;
vif = vr_get_vif_ptr(dev);
} else {
vif = vr_get_vif_ptr(skb->dev);
}
if (!vif)
goto error;
#if 0
if(vrouter_dbg) {
__skb_dump_info("vr_intf_br_hk:", skb, vif);
}
#endif
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
return skb;
#ifdef CONFIG_RPS
/*
* Send the packet to another CPU core if vr_perfr3 is set. The new
* CPU core is chosen based on a hash of the outer header. This only needs
* to be done for packets arriving on a physical interface. Also, we
* only need to do this if RPS hasn't already happened.
*/
if (vr_perfr3 && (!rpsdev) && (vif->vif_type == VIF_TYPE_PHYSICAL)) {
vr_do_rps_outer(skb, vif);
return NULL;
}
#endif
if (skb->protocol == htons(ETH_P_8021Q)) {
vhdr = (struct vlan_hdr *)skb->data;
vlan_id = ntohs(vhdr->h_vlan_TCI) & VLAN_VID_MASK;
}
if (dev->type == ARPHRD_ETHER) {
skb_push(skb, skb->mac_len);
} else {
if (skb_headroom(skb) < ETH_HLEN) {
ret = pskb_expand_head(skb, ETH_HLEN - skb_headroom(skb) +
ETH_HLEN + sizeof(struct agent_hdr), 0, GFP_ATOMIC);
if (ret)
goto error;
}
}
ret = linux_pull_outer_headers(skb);
if (ret < 0)
goto error;
pkt = linux_get_packet(skb, vif);
if (!pkt)
return NULL;
if (vif->vif_type == VIF_TYPE_PHYSICAL) {
if ((!(vif->vif_flags & VIF_FLAG_PROMISCOUS)) &&
(skb->pkt_type == PACKET_OTHERHOST)) {
vif_drop_pkt(vif, pkt, true);
return RX_HANDLER_CONSUMED;
}
}
vif->vif_rx(vif, pkt, vlan_id);
return NULL;
error:
pkt = (struct vr_packet *)skb->cb;
vr_pfree(pkt, VP_DROP_MISC);
return NULL;
}
/*
* vr_interface_bridge_hook
*
* Intercept packets received on virtual interfaces in kernel versions that
* do not support the netdev_rx_handler_register API. This makes the vrouter
* module incompatible with the bridge module.
*/
static struct sk_buff *
vr_interface_bridge_hook(struct net_bridge_port *port, struct sk_buff *skb)
{
return vr_interface_common_hook(skb);
}
/*
* vr_interface_ovs_hook
*
* Intercept packets received on virtual interfaces in kernel versions that
* do not support the netdev_rx_handler_register API. This makes the vrouter
* module incompatible with the openvswitch module.
*/
static struct sk_buff *
vr_interface_ovs_hook(struct sk_buff *skb)
{
return vr_interface_common_hook(skb);
}
#endif
/*
* both add tap and del tap can come from multiple contexts. one is
* obviously when interface is deleted from vrouter on explicit request
* from agent. other is when the physical interface underlying the
* vrouter interface dies, in which case we will be notified and
* have to take corrective actions. hence, it is vital that we check
* whether 'rtnl' was indeed locked before trying to acquire the lock
* and unlock iff we locked it in the first place.
*/
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36))
static int
linux_if_del_tap(struct vr_interface *vif)
{
struct net_device *dev;
if (vif->vif_type == VIF_TYPE_STATS)
return 0;
dev = (struct net_device *)vif->vif_os;
if (!dev)
return -EINVAL;
if (rcu_dereference(dev->rx_handler) == linux_rx_handler)
netdev_rx_handler_unregister(dev);
return 0;
}
#else
static int
linux_if_del_tap(struct vr_interface *vif)
{
struct net_device *dev;
if (vif->vif_type == VIF_TYPE_STATS)
return 0;
dev = (struct net_device *)vif->vif_os;
if (!dev)
return -EINVAL;
if (vr_get_vif_ptr(dev) == (void *)vif) {
if ((vif->vif_type == VIF_TYPE_PHYSICAL) &&
(vif->vif_flags & VIF_FLAG_VHOST_PHYS)) {
vr_set_vif_ptr(dev, &vr_reset_interface);
} else {
vr_set_vif_ptr(dev, NULL);
}
}
return 0;
}
#endif
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39))
static int
linux_if_add_tap(struct vr_interface *vif)
{
struct net_device *dev;
if (vif->vif_type == VIF_TYPE_STATS)
return 0;
if (vif->vif_name[0] == '\0')
return -ENODEV;
dev = (struct net_device *)vif->vif_os;
if (!dev)
return -EINVAL;
if ((vif->vif_type == VIF_TYPE_PHYSICAL) &&
(vif->vif_flags & VIF_FLAG_VHOST_PHYS)) {
if (rcu_dereference(dev->rx_handler) == vhost_rx_handler) {
netdev_rx_handler_unregister(dev);
}
}
return netdev_rx_handler_register(dev, linux_rx_handler, (void *)vif);
}
#else
static int
linux_if_add_tap(struct vr_interface *vif)
{
struct net_device *dev;
if (vif->vif_type == VIF_TYPE_STATS)
return 0;
if (vif->vif_name[0] == '\0')
return -ENODEV;
dev = (struct net_device *)vif->vif_os;
if (!dev)
return -EINVAL;
vr_set_vif_ptr(dev, (void *)vif);
return 0;
}
#endif
static int
linux_if_get_settings(struct vr_interface *vif,
struct vr_interface_settings *settings)
{
struct net_device *dev = (struct net_device *)vif->vif_os;
int ret = -EINVAL;
if (vif->vif_type != VIF_TYPE_PHYSICAL || !dev)
return ret;
rtnl_lock();
if (netif_running(dev)) {
struct ethtool_cmd cmd;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,2,0))
/* As per lxr, this API was introduced in 3.2.0 */
if (!(ret = __ethtool_get_settings(dev, &cmd))) {
settings->vis_speed = ethtool_cmd_speed(&cmd);
#else
cmd.cmd = ETHTOOL_GSET;
if (!(ret = dev_ethtool_get_settings(dev, &cmd))) {
settings->vis_speed = cmd.speed;
#endif
settings->vis_duplex = cmd.duplex;
}
}
rtnl_unlock();
return ret;
}
static unsigned int
linux_if_get_mtu(struct vr_interface *vif)
{
struct net_device *dev = (struct net_device *)vif->vif_os;
if (dev)
return dev->mtu;
else
return vif->vif_mtu;
}
static unsigned short
linux_if_get_encap(struct vr_interface *vif)
{
struct net_device *dev = (struct net_device *)vif->vif_os;
if (dev && (dev->type != ARPHRD_ETHER))
return VIF_ENCAP_TYPE_L3;
return VIF_ENCAP_TYPE_ETHER;
}
/*
* linux_if_tx_csum_offload - returns 1 if the device supports checksum offload
* on transmit for tunneled packets. Devices which have NETIF_F_HW_CSUM set
* are capable of doing this, but there are some devices (such as ixgbe) which
* support it even though they don't set NETIF_F_HW_CSUM.
*/
static int
linux_if_tx_csum_offload(struct net_device *dev)
{
const char *driver_name;
if (dev->features & NETIF_F_HW_CSUM) {
return 1;
}
if (dev->dev.parent) {
driver_name = dev_driver_string(dev->dev.parent);
if (driver_name && (!strncmp(driver_name, "ixgbe", 6))) {
return 1;
}
}
return 0;
}
static int
linux_if_del(struct vr_interface *vif)
{
if (vif_needs_dev(vif) && !vif->vif_os_idx)
return 0;
if (vif_is_vhost(vif))
vhost_if_del((struct net_device *)vif->vif_os);
else if (vif->vif_type == VIF_TYPE_PHYSICAL)
vhost_if_del_phys((struct net_device *)vif->vif_os);
else if (vif->vif_type == VIF_TYPE_VIRTUAL) {
/*
* if the napi structure was not initialised in the first place, we
* should not touch it now, since doing a netif_napi_del results in a
* crash. however, there are no reliable checks. hence, for now we
* will check for poll. ideally, we should not have had the napi
* structure itself in the interface structure and that would have
* clearly told us what to do with napi
*/
if (vif->vr_napi.poll) {
napi_disable(&vif->vr_napi);
netif_napi_del(&vif->vr_napi);
}
skb_queue_purge(&vif->vr_skb_inputq);
}
if (vif->vif_os) {
if (vif->vif_type == VIF_TYPE_STATS)
((struct net_device *)vif->vif_os)->ml_priv = NULL;
dev_put((struct net_device *)vif->vif_os);
}
vif->vif_os = NULL;
vif->vif_os_idx = 0;
return 0;
}
static int
linux_if_add(struct vr_interface *vif)
{
struct net_device *dev;
if (vif_needs_dev(vif)) {
if (!vif->vif_os_idx || vif->vif_name[0] == '\0') {
return -ENODEV;
}
}
if (vif->vif_os_idx) {
dev = dev_get_by_index(&init_net, vif->vif_os_idx);
if (!dev) {
return -ENODEV;
}
vif->vif_os = (void *)dev;
if (vif->vif_type == VIF_TYPE_PHYSICAL) {
if (linux_if_tx_csum_offload(dev)) {
vif->vif_flags |= VIF_FLAG_TX_CSUM_OFFLOAD;
}
}
if (vif->vif_type == VIF_TYPE_STATS)
dev->ml_priv = (void *)vif;
}
if (vif_is_vhost(vif))
vhost_if_add(vif);
if (vif->vif_type == VIF_TYPE_VIRTUAL) {
skb_queue_head_init(&vif->vr_skb_inputq);
netif_napi_add(pkt_gro_dev, &vif->vr_napi, vr_napi_poll, 64);
napi_enable(&vif->vr_napi);
}
return 0;
}
static void
linux_if_unlock(void)
{
rtnl_unlock();
return;
}
static void
linux_if_lock(void)
{
rtnl_lock();
return;
}
/*
* linux_pkt_dev_free_helper - free the packet device
*/
static void
linux_pkt_dev_free_helper(struct net_device **dev)
{
if (*dev == NULL) {
return;
}
unregister_netdev(*dev);
free_netdev(*dev);
*dev = NULL;
return;
}
/*
* linux_pkt_dev_free - free the packet device used for GRO/RPS
*/
static void
linux_pkt_dev_free(void)
{
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,39))
if (pkt_gro_dev) {
vr_set_vif_ptr(pkt_gro_dev, NULL);
}
#endif
linux_pkt_dev_free_helper(&pkt_gro_dev);
linux_pkt_dev_free_helper(&pkt_rps_dev);
return;
}
/*
* pkt_gro_dev_setup - fill in the relevant fields of the GRO packet device
*/
static void
pkt_gro_dev_setup(struct net_device *dev)
{
/*
* Initializing the interfaces with basic parameters to setup address
* families.
*/
random_ether_addr(dev->dev_addr);
dev->addr_len = ETH_ALEN;
/*
* The hard header length is used by the GRO code to compare the
* MAC header of the incoming packet with the MAC header of packets
* undergoing GRO at the moment. In our case, each vif will have a
* unique MPLS label associated with it, so we can use the MPLS header
* as the MAC header to combine packets destined for the same vif.
*/
dev->hard_header_len = VR_MPLS_HDR_LEN;
dev->type = ARPHRD_VOID;
dev->netdev_ops = &pkt_gro_dev_ops;
dev->features |= NETIF_F_GRO;
dev->mtu = 65535;
return;
}
/*
* pkt_rps_dev_setup - fill in the relevant fields of the RPS packet device
*/
static void
pkt_rps_dev_setup(struct net_device *dev)
{
/*
* Initializing the interfaces with basic parameters to setup address
* families.
*/
random_ether_addr(dev->dev_addr);
dev->addr_len = ETH_ALEN;
dev->hard_header_len = ETH_HLEN;
dev->type = ARPHRD_VOID;
dev->netdev_ops = &pkt_rps_dev_ops;
dev->mtu = 65535;
return;
}
/*
* linux_pkt_dev_init - initialize the packet device used for GRO. Returns
* pointer to packet device if no errors, NULL otherwise.
*/
static struct net_device *
linux_pkt_dev_init(char *name, void (*setup)(struct net_device *),
rx_handler_result_t (*handler)(struct sk_buff **))
{
int err = 0;
struct net_device *pdev = NULL;
if (!(pdev = alloc_netdev_mqs(0, name, setup,
1, num_present_cpus()))) {
vr_module_error(-ENOMEM, __FUNCTION__, __LINE__, 0);
return NULL;
}
rtnl_lock();
if ((err = register_netdevice(pdev))) {
vr_module_error(err, __FUNCTION__, __LINE__, 0);
} else {
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,39))
if ((err = netdev_rx_handler_register(pdev,
handler, NULL))) {
vr_module_error(err, __FUNCTION__, __LINE__, 0);
unregister_netdev(pdev);
}
#else
vr_set_vif_ptr(pdev, (void *) pdev);
#endif
}
rtnl_unlock();
if (err) {
free_netdev(pdev);
return NULL;
}
return pdev;
}
static rx_handler_result_t
pkt_gro_dev_rx_handler(struct sk_buff **pskb)
{
unsigned int label;
struct vr_nexthop *nh;
struct vr_interface *vif;
struct vr_interface *gro_vif;
struct vr_interface_stats *gro_vif_stats;
struct sk_buff *skb = *pskb;
struct vr_packet *pkt;
struct vrouter *router = vrouter_get(0);
struct vr_forwarding_md fmd;
pkt = linux_get_packet(skb, NULL);
if (!pkt)
return RX_HANDLER_CONSUMED;
gro_vif = skb->dev->ml_priv;
if (gro_vif) {
gro_vif_stats = vif_get_stats(gro_vif, pkt->vp_cpu);
if (gro_vif_stats) {
gro_vif_stats->vis_ipackets++;
gro_vif_stats->vis_ibytes += skb->len;
}
}
#if CONFIG_XEN && (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32))
label = ntohl(*((unsigned int *) (skb_mac_header(skb) + ETH_HLEN - VR_MPLS_HDR_LEN)));
#else
label = ntohl(*((unsigned int *) skb_mac_header(skb)));
#endif
label >>= VR_MPLS_LABEL_SHIFT;
if (label >= router->vr_max_labels) {
vr_pfree(pkt, VP_DROP_INVALID_LABEL);
return RX_HANDLER_CONSUMED;
}
nh = router->vr_ilm[label];
if (!nh) {
vr_pfree(pkt, VP_DROP_INVALID_LABEL);
return RX_HANDLER_CONSUMED;
}
vif = nh->nh_dev;
if ((vif == NULL) || (vif->vif_type != VIF_TYPE_VIRTUAL)) {
vr_pfree(pkt, VP_DROP_INVALID_IF);
return RX_HANDLER_CONSUMED;
}
/*
* since vif was not available when we did linux_get_packet, set vif
* manually here
*/
pkt->vp_if = vif;
pkt_set_network_header(pkt, pkt->vp_data);
pkt_set_inner_network_header(pkt, pkt->vp_data);
/*
* All flow handling has been done prior to GRO
*/
pkt->vp_flags |= VP_FLAG_FLOW_SET;
vr_init_forwarding_md(&fmd);
fmd.fmd_dvrf = nh->nh_dev->vif_vrf;
nh_output(pkt, nh, &fmd);
return RX_HANDLER_CONSUMED;
}
/*
* pkt_rps_dev_rx_handler - receive a packet after RPS
*/
static rx_handler_result_t
pkt_rps_dev_rx_handler(struct sk_buff **pskb)
{
struct sk_buff *skb = *pskb;
struct vr_packet *pkt;
unsigned int label;
struct vr_nexthop *nh;
struct vr_interface *vif;
struct vrouter *router = vrouter_get(0);
if (vr_perfr3) {
#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,32))
ASSERT(0);
#else
return linux_rx_handler(&skb);
#endif
}
pkt = (struct vr_packet *)skb->cb;
/*
* If RPS was scheduled earlier because of vr_perfr1 being set, the
* vif_idx in skb->cb should be 0. If it is non-zero, RPS was scheduled
* because of vr_perfr3 being set earlier (and now vr_perfr3 has been
* cleared). Drop the packet in this corner case.
*/
if (((vr_rps_t *)skb->cb)->vif_idx) {
vr_pfree(pkt, VP_DROP_MISC);
return RX_HANDLER_CONSUMED;
}
label = ntohl(*((unsigned int *) skb_mac_header(skb)));
label >>= VR_MPLS_LABEL_SHIFT;
if (label >= router->vr_max_labels) {
vr_pfree(pkt, VP_DROP_INVALID_LABEL);
return RX_HANDLER_CONSUMED;
}
nh = router->vr_ilm[label];
if (!nh) {
vr_pfree(pkt, VP_DROP_INVALID_NH);
return RX_HANDLER_CONSUMED;
}
vif = nh->nh_dev;
if ((vif == NULL) || (vif->vif_type != VIF_TYPE_VIRTUAL)) {
vr_pfree(pkt, VP_DROP_MISC);
return RX_HANDLER_CONSUMED;
}
linux_enqueue_pkt_for_gro(skb, vif);
return RX_HANDLER_CONSUMED;
}
/*
* vif_from_napi - given a NAPI structure, return the corresponding vif
*/
static struct vr_interface *
vif_from_napi(struct napi_struct *napi)
{
int offset;
struct vr_interface *vif;
offset = offsetof(struct vr_interface, vr_napi);
vif = (struct vr_interface *) (((char *)napi) - offset);
return vif;
}
/*
* vr_napi_poll - NAPI poll routine to receive packets and perform
* GRO.
*/
static int
vr_napi_poll(struct napi_struct *napi, int budget)
{
struct sk_buff *skb;
struct vr_interface *vif;
int quota = 0;
int ret;
struct vr_interface *gro_vif = NULL;
struct vr_interface_stats *gro_vif_stats = NULL;
vif = vif_from_napi(napi);
if (pkt_gro_dev) {
gro_vif = (struct vr_interface *)pkt_gro_dev->ml_priv;
if (gro_vif)
gro_vif_stats = vif_get_stats(gro_vif, vr_get_cpu());
}
while ((skb = skb_dequeue(&vif->vr_skb_inputq))) {
vr_skb_set_rxhash(skb, 0);
ret = napi_gro_receive(napi, skb);
if (ret == NET_RX_DROP) {
if (gro_vif_stats)
gro_vif_stats->vis_ierrors++;
}
quota++;
if (quota == budget) {
break;
}
}
if (quota != budget) {
napi_complete(napi);
return 0;
}
return budget;
}
struct vr_host_interface_ops vr_linux_interface_ops = {
.hif_lock = linux_if_lock,
.hif_unlock = linux_if_unlock,
.hif_add = linux_if_add,
.hif_del = linux_if_del,
.hif_add_tap = linux_if_add_tap,
.hif_del_tap = linux_if_del_tap,
.hif_tx = linux_if_tx,
.hif_rx = linux_if_rx,
.hif_get_settings = linux_if_get_settings,
.hif_get_mtu = linux_if_get_mtu,
.hif_get_encap = linux_if_get_encap,
};
static int
linux_if_notifier(struct notifier_block * __unused,
unsigned long event, void *arg)
{
/* for now, get router id 0 */
struct vrouter *router = vrouter_get(0);
struct vr_interface *agent_if, *eth_if;
struct net_device *dev;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,11,0))
struct netdev_notifier_info *info = (struct netdev_notifier_info *)arg;
dev = info->dev;
#else
dev = (struct net_device *)arg;
#endif
if (!router)
return NOTIFY_DONE;
agent_if = router->vr_agent_if;
if (event == NETDEV_UNREGISTER) {
if (agent_if) {
if (dev == (struct net_device *)agent_if->vif_os) {
vif_detach(agent_if);
agent_alive = false;
/* try xconnecting all vhost interfaces */
vhost_xconnect();
return NOTIFY_OK;
}
}
if ((eth_if = vif_find(router, dev->name)))
vif_detach(eth_if);
/* quite possible that there was no vif */
vhost_detach_phys(dev);
} else if (event == NETDEV_REGISTER) {
if ((eth_if = vif_find(router, dev->name))) {
eth_if->vif_os_idx = dev->ifindex;
vif_attach(eth_if);
}
/* quite possible that there was no vif */
vhost_attach_phys(dev);
}
return NOTIFY_DONE;
}
static struct notifier_block host_if_nb = {
.notifier_call = linux_if_notifier,
};
void
vr_host_vif_init(struct vrouter *router)
{
if (pkt_gro_dev)
vr_gro_vif_add(router, pkt_gro_dev->ifindex,
pkt_gro_dev->name);
return;
}
void
vr_host_interface_exit(void)
{
vhost_exit();
unregister_netdevice_notifier(&host_if_nb);
linux_pkt_dev_free();
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,39))
if (vr_use_linux_br) {
br_handle_frame_hook = NULL;
} else {
openvswitch_handle_frame_hook = NULL;
}
#endif
return;
}
static int
linux_pkt_dev_alloc(void)
{
if (pkt_gro_dev == NULL) {
pkt_gro_dev = linux_pkt_dev_init("pkt1", &pkt_gro_dev_setup,
&pkt_gro_dev_rx_handler);
if (pkt_gro_dev == NULL) {
vr_module_error(-ENOMEM, __FUNCTION__, __LINE__, 0);
return -ENOMEM;
}
}
if (pkt_rps_dev == NULL) {
pkt_rps_dev = linux_pkt_dev_init("pkt2", &pkt_rps_dev_setup,
&pkt_rps_dev_rx_handler);
if (pkt_rps_dev == NULL) {
vr_module_error(-ENOMEM, __FUNCTION__, __LINE__, 0);
return -ENOMEM;
}
}
return 0;
}
/*
* no error handling here. exit will be called in case of error returns
* where proper cleanups are done
*/
struct vr_host_interface_ops *
vr_host_interface_init(void)
{
int ret;
ret = linux_pkt_dev_alloc();
if (ret)
return NULL;
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,39))
if (vr_use_linux_br) {
br_handle_frame_hook = vr_interface_bridge_hook;
} else {
openvswitch_handle_frame_hook = vr_interface_ovs_hook;
}
#endif
vhost_init();
ret = register_netdevice_notifier(&host_if_nb);
if (ret) {
vr_module_error(ret, __FUNCTION__, __LINE__, 0);
return NULL;
}
return &vr_linux_interface_ops;
}
| bsd-2-clause |
lucaspcamargo/neiasound | src/nsoundbag.cpp | 1 | 1762 | // Copyright (C) 2015 Lucas Pires Camargo
//
// This file is part of neiasound - Qt-style OpenAL wrapper for games.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
// NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "nsoundbag.h"
nSoundBag::nSoundBag(nSoundFormat format, quint64 frames, int freq, QObject * parent):
QObject(parent)
{
m_frames = frames;
m_data_size = nSoundFormat_getFramesize(format)*frames;
m_data = new unsigned char[m_data_size];
m_frequency = freq;
m_format = format;
}
nSoundBag::~nSoundBag()
{
delete[] m_data;
}
| bsd-2-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.