Input:
static void disk_seqf_stop(struct seq_file *seqf, void *v)
{
	struct class_dev_iter *iter = seqf->private;

	/* stop is called even after start failed :-( */
	if (iter) {
		class_dev_iter_exit(iter);
		kfree(iter);
	}
}

static void disk_seqf_stop(struct seq_file *seqf, void *v)
{
	struct class_dev_iter *iter = seqf->private;

	/* stop is called even after start failed :-( */
	if (iter) {
		class_dev_iter_exit(iter);
		kfree(iter);
		seqf->private = NULL;
	}
}


Input:
ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)
{
    unsigned nSyms = darray_size(expr->keysym_list.syms);
    unsigned numEntries = darray_size(append->keysym_list.syms);

    darray_append(expr->keysym_list.symsMapIndex, nSyms);
    darray_append(expr->keysym_list.symsNumEntries, numEntries);
    darray_concat(expr->keysym_list.syms, append->keysym_list.syms);

    FreeStmt((ParseCommon *) &append);

    return expr;
}

ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)
{
    unsigned nSyms = darray_size(expr->keysym_list.syms);
    unsigned numEntries = darray_size(append->keysym_list.syms);

    darray_append(expr->keysym_list.symsMapIndex, nSyms);
    darray_append(expr->keysym_list.symsNumEntries, numEntries);
    darray_concat(expr->keysym_list.syms, append->keysym_list.syms);

    FreeStmt((ParseCommon *) append);

    return expr;
}


Input:
static int get_task_ioprio(struct task_struct *p)
{
	int ret;

	ret = security_task_getioprio(p);
	if (ret)
		goto out;
	ret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM);
	if (p->io_context)
		ret = p->io_context->ioprio;
out:
	return ret;
}

static int get_task_ioprio(struct task_struct *p)
{
	int ret;

	ret = security_task_getioprio(p);
	if (ret)
		goto out;
	ret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM);
	task_lock(p);
	if (p->io_context)
		ret = p->io_context->ioprio;
	task_unlock(p);
out:
	return ret;
}


Input:
static int hci_uart_set_proto(struct hci_uart *hu, int id)
{
	const struct hci_uart_proto *p;
	int err;

	p = hci_uart_get_proto(id);
	if (!p)
		return -EPROTONOSUPPORT;

	hu->proto = p;
	set_bit(HCI_UART_PROTO_READY, &hu->flags);

	err = hci_uart_register_dev(hu);
	if (err) {
		clear_bit(HCI_UART_PROTO_READY, &hu->flags);
		return err;
	}

	return 0;
}

static int hci_uart_set_proto(struct hci_uart *hu, int id)
{
	const struct hci_uart_proto *p;
	int err;

	p = hci_uart_get_proto(id);
	if (!p)
		return -EPROTONOSUPPORT;

	hu->proto = p;

	err = hci_uart_register_dev(hu);
	if (err) {
		return err;
	}

	set_bit(HCI_UART_PROTO_READY, &hu->flags);
	return 0;
}


Input:
PlayerGeneric::~PlayerGeneric()
{
	if (mixer)
		delete mixer;

	if (player)
	{
		if (mixer->isActive() && !mixer->isDeviceRemoved(player))
			mixer->removeDevice(player);
		delete player;
	}

	delete[] audioDriverName;

	delete listener;
}

PlayerGeneric::~PlayerGeneric()
{

	if (player)
	{
		if (mixer && mixer->isActive() && !mixer->isDeviceRemoved(player))
			mixer->removeDevice(player);
		delete player;
	}

	if (mixer)
		delete mixer;

	delete[] audioDriverName;

	delete listener;
}


Input:
struct net *get_net_ns_by_id(struct net *net, int id)
{
	struct net *peer;

	if (id < 0)
		return NULL;

	rcu_read_lock();
	spin_lock_bh(&net->nsid_lock);
	peer = idr_find(&net->netns_ids, id);
	if (peer)
		get_net(peer);
	spin_unlock_bh(&net->nsid_lock);
	rcu_read_unlock();

	return peer;
}

struct net *get_net_ns_by_id(struct net *net, int id)
{
	struct net *peer;

	if (id < 0)
		return NULL;

	rcu_read_lock();
	spin_lock_bh(&net->nsid_lock);
	peer = idr_find(&net->netns_ids, id);
	if (peer)
		peer = maybe_get_net(peer);
	spin_unlock_bh(&net->nsid_lock);
	rcu_read_unlock();

	return peer;
}


Input:
static int snd_seq_device_dev_free(struct snd_device *device)
{
	struct snd_seq_device *dev = device->device_data;

	put_device(&dev->dev);
	return 0;
}

static int snd_seq_device_dev_free(struct snd_device *device)
{
	struct snd_seq_device *dev = device->device_data;

	cancel_autoload_drivers();
	put_device(&dev->dev);
	return 0;
}


Input:
static int nntp_hcache_namer(const char *path, char *dest, size_t destlen)
{
  return snprintf(dest, destlen, "%s.hcache", path);
}

static int nntp_hcache_namer(const char *path, char *dest, size_t destlen)
{
  int count = snprintf(dest, destlen, "%s.hcache", path);

  /* Strip out any directories in the path */
  char *first = strchr(dest, '/');
  char *last = strrchr(dest, '/');
  if (first && last && (last > first))
  {
    memmove(first, last, strlen(last) + 1);
    count -= (last - first);
  }

  return count;
}


Input:
def _inject_file_into_fs(fs, path, contents):
    absolute_path = os.path.join(fs, path.lstrip('/'))
    parent_dir = os.path.dirname(absolute_path)
    utils.execute('mkdir', '-p', parent_dir, run_as_root=True)
    utils.execute('tee', absolute_path, process_input=contents,
          run_as_root=True)

def _inject_file_into_fs(fs, path, contents, append=False):
    absolute_path = _join_and_check_path_within_fs(fs, path.lstrip('/'))

    parent_dir = os.path.dirname(absolute_path)
    utils.execute('mkdir', '-p', parent_dir, run_as_root=True)

    args = []
    if append:
        args.append('-a')
    args.append(absolute_path)

    kwargs = dict(process_input=contents, run_as_root=True)

    utils.execute('tee', *args, **kwargs)


Input:
    def cut(self, key):
        try:
            self.etcd.delete(os.path.join(self.namespace, key))
        except etcd.EtcdKeyNotFound:
            return False
        except etcd.EtcdException as err:
            log_error("Error removing key %s: [%r]" % (key, repr(err)))
            raise CSStoreError('Error occurred while trying to cut key')
        return True

    def cut(self, key):
        try:
            self.etcd.delete(self._absolute_key(key))
        except etcd.EtcdKeyNotFound:
            return False
        except etcd.EtcdException as err:
            log_error("Error removing key %s: [%r]" % (key, repr(err)))
            raise CSStoreError('Error occurred while trying to cut key')
        return True


Input:
    def candidate_paths_for_url(self, url):
        for root, prefix in self.directories:
            if url.startswith(prefix):
                yield os.path.join(root, url[len(prefix):])

    def candidate_paths_for_url(self, url):
        for root, prefix in self.directories:
            if url.startswith(prefix):
                path = os.path.join(root, url[len(prefix):])
                if os.path.commonprefix((root, path)) == root:
                    yield path


Input:
def create_basename_core(basename):
    try:
        basename = basename.casefold()
    except Exception:
        basename = basename.lower()

    basename = basename.replace(' ', '-')
    basename = re.sub(r'<[^>]*>', r'', basename)
    basename = re.sub(r'[^a-z0-9\-]', r'', basename)
    basename = re.sub(r'\-\-', r'-', basename)
    basename = urllib.parse.quote_plus(basename)

    return basename

def create_basename_core(basename):
    try:
        basename = basename.casefold()
    except Exception:
        basename = basename.lower()

    basename = re.sub(r'[ \./]', r'-', basename)
    basename = re.sub(r'<[^>]*>', r'', basename)
    basename = re.sub(r'[^a-z0-9\-]', r'', basename)
    basename = re.sub(r'\-\-', r'-', basename)
    basename = urllib.parse.quote_plus(basename)

    return basename


Input:
    def get(self, key):
        try:
            result = self.etcd.get(os.path.join(self.namespace, key))
        except etcd.EtcdException as err:
            log_error("Error fetching key %s: [%r]" % (key, repr(err)))
            raise CSStoreError('Error occurred while trying to get key')
        return result.value

    def get(self, key):
        try:
            result = self.etcd.get(self._absolute_key(key))
        except etcd.EtcdException as err:
            log_error("Error fetching key %s: [%r]" % (key, repr(err)))
            raise CSStoreError('Error occurred while trying to get key')
        return result.value


Input:
void dd_save_text(struct dump_dir *dd, const char *name, const char *data)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}

void dd_save_text(struct dump_dir *dd, const char *name, const char *data)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    if (!str_is_correct_filename(name))
        error_msg_and_die("Cannot save text. '%s' is not a valid file name", name);

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, strlen(data), dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}


Input:
void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}

void dd_save_binary(struct dump_dir* dd, const char* name, const char* data, unsigned size)
{
    if (!dd->locked)
        error_msg_and_die("dump_dir is not opened"); /* bug */

    if (!str_is_correct_filename(name))
        error_msg_and_die("Cannot save binary. '%s' is not a valid file name", name);

    char *full_path = concat_path_file(dd->dd_dirname, name);
    save_binary_file(full_path, data, size, dd->dd_uid, dd->dd_gid, dd->mode);
    free(full_path);
}


Input:
def pascal_case(value: str) -> str:
    return stringcase.pascalcase(value)

def pascal_case(value: str) -> str:
    return stringcase.pascalcase(_sanitize(value))


Input:
    @staticmethod
    def _download_file(bucket, filename, local_dir):
        key = bucket.get_key(filename)
        local_filename = os.path.join(local_dir, filename)
        key.get_contents_to_filename(local_filename)
        return local_filename

    @staticmethod
    def _download_file(bucket, filename, local_dir):
        key = bucket.get_key(filename)
        local_filename = os.path.join(local_dir, os.path.basename(filename))
        key.get_contents_to_filename(local_filename)
        return local_filename


Input:
def get_paths(base_path: pathlib.Path):
    data_file = pathlib.Path(str(base_path) + ".data")
    metadata_file = pathlib.Path(str(base_path) + ".meta")

    return data_file, metadata_file

def get_paths(root: str, sub_path: str) \
        -> typing.Tuple[pathlib.Path, pathlib.Path]:
    base_path = flask.safe_join(root, sub_path)
    data_file = pathlib.Path(base_path + ".data")
    metadata_file = pathlib.Path(base_path + ".meta")

    return data_file, metadata_file


Input:
def valid_id(opts, id_):
    '''
    Returns if the passed id is valid
    '''
    try:
        return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_)
    except (AttributeError, KeyError, TypeError) as e:
        return False

def valid_id(opts, id_):
    '''
    Returns if the passed id is valid
    '''
    try:
        if any(x in id_ for x in ('/', '\\', '\0')):
            return False
        return bool(clean_path(opts['pki_dir'], id_))
    except (AttributeError, KeyError, TypeError):
        return False


Input:
    def get(self, path):
        return static_file(path, self.get_base_path())

    def get(self, path):
        path = self.sanitize_path(path)
        base_paths = self.get_base_paths()
        if hasattr(base_paths, 'split'):
            # String, so go simple
            base_path = base_paths
        else:
            base_path = self.get_first_base(base_paths, path)
        return static_file(path, base_path)


Input:
int dd_exist(const struct dump_dir *dd, const char *path)
{
    char *full_path = concat_path_file(dd->dd_dirname, path);
    int ret = exist_file_dir(full_path);
    free(full_path);
    return ret;
}

int dd_exist(const struct dump_dir *dd, const char *path)
{
    if (!str_is_correct_filename(path))
        error_msg_and_die("Cannot test existence. '%s' is not a valid file name", path);

    char *full_path = concat_path_file(dd->dd_dirname, path);
    int ret = exist_file_dir(full_path);
    free(full_path);
    return ret;
}


Input:
def deleteKey(client):
	"""Deletes the specified key.
	Returns an error if the key doesn't exist
	"""
	global BAD_REQUEST
	global NOT_FOUND

	validateClient(client)

	client_pub_key = loadClientRSAKey(client)
	token_data = decodeRequestToken(request.data, client_pub_key)

	if re.search('[^a-zA-Z0-9]', token_data['key']):
		raise FoxlockError(BAD_REQUEST, 'Invalid key requested')

	try:
		os.remove('keys/%s/%s.key' % (client, token_data['key']))
	except FileNotFoundError:
		raise FoxlockError(NOT_FOUND, "Key '%s' not found" % token_data['key'])

	return "Key '%s' successfully deleted" % token_data['key']

def deleteKey(client):
	"""Deletes the specified key.
	Returns an error if the key doesn't exist
	"""
	global NOT_FOUND

	validateClient(client)
	client_pub_key = loadClientRSAKey(client)
	token_data = decodeRequestToken(request.data, client_pub_key)
	validateKeyName(token_data['key'])

	try:
		os.remove('keys/%s/%s.key' % (client, token_data['key']))
	except FileNotFoundError:
		raise FoxlockError(NOT_FOUND, "Key '%s' not found" % token_data['key'])

	return "Key '%s' successfully deleted" % token_data['key']


Input:
    def set(self, key, value, replace=False):
        path = os.path.join(self.namespace, key)
        try:
            self.etcd.write(path, value, prevExist=replace)
        except etcd.EtcdAlreadyExist as err:
            raise CSStoreExists(str(err))
        except etcd.EtcdException as err:
            log_error("Error storing key %s: [%r]" % (key, repr(err)))
            raise CSStoreError('Error occurred while trying to store key')

    def set(self, key, value, replace=False):
        path = self._absolute_key(key)
        try:
            self.etcd.write(path, value, prevExist=replace)
        except etcd.EtcdAlreadyExist as err:
            raise CSStoreExists(str(err))
        except etcd.EtcdException as err:
            log_error("Error storing key %s: [%r]" % (key, repr(err)))
            raise CSStoreError('Error occurred while trying to store key')


Input:
@register.filter
def json_dumps(value, indent=None):
    if isinstance(value, QuerySet):
        result = serialize('json', value, indent=indent)
    else:
        result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)

    return mark_safe(result)

@register.filter
def json_dumps(value, indent=None):
    if isinstance(value, QuerySet):
        result = serialize('json', value, indent=indent)
    else:
        result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)

    return mark_safe(force_text(result).translate(_safe_js_escapes))


Input:
    def htmlvalue(self, val):
        return self.block.render_basic(val)

    def htmlvalue(self, val):
        """
        Return an HTML representation of this block that is safe to be included
        in comparison views
        """
        return escape(text_from_html(self.block.render_basic(val)))


Input:
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = self.object.comment_set.all().order_by('-time')
        context['form'] = self.get_form()
        context['md'] = markdown(self.object.content,
                                 extensions=[
                                     'markdown.extensions.extra',
                                     'markdown.extensions.codehilite',
                                     'markdown.extensions.toc',
                                 ])

        return context

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = self.object.comment_set.all().order_by('-time')
        context['form'] = self.get_form()
        context['md'] = safe_md(self.object.content)

        return context


Input:
    @classmethod
    def simple_search(cls, query, using=None, index=None):
        es_search = cls.search(using=using, index=index)
        es_query = cls.get_es_query(query=query)
        highlighted_fields = [f.split('^', 1)[0] for f in cls.search_fields]

        es_search = es_search.query(es_query).highlight(*highlighted_fields)
        return es_search

    @classmethod
    def simple_search(cls, query, using=None, index=None):
        """
        Do a search without facets.

        This is used in:

        * The Docsearch API
        * The Project Admin Search page
        """

        es_search = cls.search(using=using, index=index)
        es_search = es_search.highlight_options(encoder='html')

        es_query = cls.get_es_query(query=query)
        highlighted_fields = [f.split('^', 1)[0] for f in cls.search_fields]
        es_search = es_search.query(es_query).highlight(*highlighted_fields)

        return es_search


Input:
def _keyify(key):
    return _key_pattern.sub(' ', key.lower())

def _keyify(key):
    key = escape(key.lower(), quote=True)
    return _key_pattern.sub(' ', key)


Input:
def make_eb_config(application_name, default_region):
    # Capture our current directory
    UTILS_DIR = os.path.dirname(os.path.abspath(__file__))
    # Create the jinja2 environment.
    # Notice the use of trim_blocks, which greatly helps control whitespace.
    j2_env = Environment(loader=FileSystemLoader(UTILS_DIR))
    return j2_env.get_template('templates/eb/config.yml').render(
        APPLICATION_NAME=application_name,
        DEFAULT_REGION=default_region
    )

def make_eb_config(application_name, default_region):
    # Capture our current directory
    UTILS_DIR = os.path.dirname(os.path.abspath(__file__))
    # Create the jinja2 environment.
    # Notice the use of trim_blocks, which greatly helps control whitespace.
    j2_env = Environment(loader=FileSystemLoader(UTILS_DIR), autoescape=True)
    return j2_env.get_template('templates/eb/config.yml').render(
        APPLICATION_NAME=application_name,
        DEFAULT_REGION=default_region
    )


Input:
    def mode_keepalive(self, request):
        """
        This is called by render_POST when the
        client is replying to the keepalive.
        """
        csessid = request.args.get('csessid')[0]
        self.last_alive[csessid] = (time.time(), False)
        return '""'

    def mode_keepalive(self, request):
        """
        This is called by render_POST when the
        client is replying to the keepalive.
        """
        csessid = cgi.escape(request.args['csessid'][0])
        self.last_alive[csessid] = (time.time(), False)
        return '""'


Input:
void Logger::addPeer(const QString &ip, bool blocked, const QString &reason)
{
    QWriteLocker locker(&lock);

    Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason };
    m_peers.push_back(temp);

    if (m_peers.size() >= MAX_LOG_MESSAGES)
        m_peers.pop_front();

    emit newLogPeer(temp);
}

void Logger::addPeer(const QString &ip, bool blocked, const QString &reason)
{
    QWriteLocker locker(&lock);

    Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), Utils::String::toHtmlEscaped(ip), blocked, Utils::String::toHtmlEscaped(reason) };
    m_peers.push_back(temp);

    if (m_peers.size() >= MAX_LOG_MESSAGES)
        m_peers.pop_front();

    emit newLogPeer(temp);
}


Input:
    def save(self):
        # copy the user's input from plain text to description to be processed
        self.description = self.description_plain_text
        if CE.settings.auto_cross_reference:
            self.auto_cross_ref()
        else:
            self.find_tag()
        self.slug = slugify(self.title)
        super().save()

    def save(self):
        # copy the user's input from plain text to description to be processed
        # uses bleach to remove potentially harmful HTML code
        self.description = bleach.clean(str(self.description_plain_text),
                                        tags=CE.settings.bleach_allowed,
                                        strip=True)
        if CE.settings.auto_cross_reference:
            self.auto_cross_ref()
        else:
            self.find_tag()
        self.slug = slugify(self.title)
        super().save()


Input:
    def mode_close(self, request):
        """
        This is called by render_POST when the client is signalling
        that it is about to be closed.

        Args:
            request (Request): Incoming request.

        """
        csessid = request.args.get('csessid')[0]
        try:
            sess = self.sessionhandler.sessions_from_csessid(csessid)[0]
            sess.sessionhandler.disconnect(sess)
        except IndexError:
            self.client_disconnect(csessid)
        return '""'

    def mode_close(self, request):
        """
        This is called by render_POST when the client is signalling
        that it is about to be closed.

        Args:
            request (Request): Incoming request.

        """
        csessid = cgi.escape(request.args['csessid'][0])
        try:
            sess = self.sessionhandler.sessions_from_csessid(csessid)[0]
            sess.sessionhandler.disconnect(sess)
        except IndexError:
            self.client_disconnect(csessid)
        return '""'


Input:
    def get_queryset(self, **kwargs):
        queryset = Article.objects.order_by('-time')
        for i in queryset:
            i.md = markdown(i.content, extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
                'markdown.extensions.toc',
            ])

        return queryset

    def get_queryset(self, **kwargs):
        queryset = Article.objects.order_by('-time')
        for i in queryset:
            i.md = safe_md(i.content)

        return queryset


Input:
void Logger::addMessage(const QString &message, const Log::MsgType &type)
{
    QWriteLocker locker(&lock);

    Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, message };
    m_messages.push_back(temp);

    if (m_messages.size() >= MAX_LOG_MESSAGES)
        m_messages.pop_front();

    emit newLogMessage(temp);
}

void Logger::addMessage(const QString &message, const Log::MsgType &type)
{
    QWriteLocker locker(&lock);

    Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, Utils::String::toHtmlEscaped(message) };
    m_messages.push_back(temp);

    if (m_messages.size() >= MAX_LOG_MESSAGES)
        m_messages.pop_front();

    emit newLogMessage(temp);
}


Input:
  @handler.unsupported_on_local_server
  @handler.get(handler.HTML)
  def get(self):
    """Handle a get request."""
    self.render(
        'login.html', {
            'apiKey': local_config.ProjectConfig().get('firebase.api_key'),
            'authDomain': auth.auth_domain(),
            'dest': self.request.get('dest'),
        })

  @handler.unsupported_on_local_server
  @handler.get(handler.HTML)
  def get(self):
    """Handle a get request."""
    dest = self.request.get('dest')
    base_handler.check_redirect_url(dest)

    self.render(
        'login.html', {
            'apiKey': local_config.ProjectConfig().get('firebase.api_key'),
            'authDomain': auth.auth_domain(),
            'dest': dest,
        })


Input:
    @property
    async def html_content(self):
        content = await self.content
        if not content:
            return ''
        return markdown(content)

    @property
    async def html_content(self):
        content = markupsafe.escape(await self.content)
        if not content:
            return ''
        return markdown(content)


Input:
    def get_context_data(self, *args, **kwargs):
        data = super().get_context_data(*args, **kwargs)

        if self.request.GET.get('back', None) is not None:
            data['back_link'] = self.request.GET['back']

        return data

    def get_context_data(self, *args, **kwargs):
        data = super().get_context_data(*args, **kwargs)

        back = self.request.GET.get('back', None)
        parsed_back_url = urllib.parse.urlparse(back)

        # We only allow blank scheme, e.g. relative urls to avoid reflected XSS
        if back is not None and parsed_back_url.scheme == "":
            data['back_link'] = back

        return data


Input:
    long WebPImage::getHeaderOffset(byte *data, long data_size,
                                    byte *header, long header_size) {
        long pos = -1;
        for (long i=0; i < data_size - header_size; i++) {
            if (memcmp(header, &data[i], header_size) == 0) {
                pos = i;
                break;
            }
        }
        return pos;
    }

    long WebPImage::getHeaderOffset(byte* data, long data_size, byte* header, long header_size)
    {
        if (data_size < header_size) { return -1; }
        long pos = -1;
        for (long i=0; i < data_size - header_size; i++) {
            if (memcmp(header, &data[i], header_size) == 0) {
                pos = i;
                break;
            }
        }
        return pos;
    }


Input:
int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)
{
	switch (mem->type) {
	case RXE_MEM_TYPE_DMA:
		return 0;

	case RXE_MEM_TYPE_MR:
	case RXE_MEM_TYPE_FMR:
		return ((iova < mem->iova) ||
			((iova + length) > (mem->iova + mem->length))) ?
			-EFAULT : 0;

	default:
		return -EFAULT;
	}
}

int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)
{
	switch (mem->type) {
	case RXE_MEM_TYPE_DMA:
		return 0;

	case RXE_MEM_TYPE_MR:
	case RXE_MEM_TYPE_FMR:
		if (iova < mem->iova ||
		    length > mem->length ||
		    iova > mem->iova + mem->length - length)
			return -EFAULT;
		return 0;

	default:
		return -EFAULT;
	}
}


Input:
SWFInput_readSBits(SWFInput input, int number)
{
	int num = SWFInput_readBits(input, number);

	if ( num & (1<<(number-1)) )
		return num - (1<<number);
	else
		return num;
}

SWFInput_readSBits(SWFInput input, int number)
{
	int num = SWFInput_readBits(input, number);

	if(number && num & (1<<(number-1)))
		return num - (1<<number);
	else
		return num;
}


Input:
authDigestNonceLink(digest_nonce_h * nonce)
{
    assert(nonce != NULL);
    ++nonce->references;
    debugs(29, 9, "nonce '" << nonce << "' now at '" << nonce->references << "'.");
}

authDigestNonceLink(digest_nonce_h * nonce)
{
    assert(nonce != NULL);
    ++nonce->references;
    assert(nonce->references != 0); // no overflows
    debugs(29, 9, "nonce '" << nonce << "' now at '" << nonce->references << "'.");
}