project
stringclasses 788
values | commit_id
stringlengths 6
81
| CVE ID
stringlengths 13
16
| CWE ID
stringclasses 126
values | func
stringlengths 14
482k
| vul
int8 0
1
|
---|---|---|---|---|---|
linux | ea8569194b43f0f01f0a84c689388542c7254a1f | CVE-2022-0617 | CWE-476 | int udf_expand_file_adinicb(struct inode *inode)
{
struct page *page;
char *kaddr;
struct udf_inode_info *iinfo = UDF_I(inode);
int err;
WARN_ON_ONCE(!inode_is_locked(inode));
if (!iinfo->i_lenAlloc) {
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
up_write(&iinfo->i_data_sem);
mark_inode_dirty(inode);
return 0;
}
/*
* Release i_data_sem so that we can lock a page - page lock ranks
* above i_data_sem. i_mutex still protects us against file changes.
*/
up_write(&iinfo->i_data_sem);
page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS);
if (!page)
return -ENOMEM;
if (!PageUptodate(page)) {
kaddr = kmap_atomic(page);
memset(kaddr + iinfo->i_lenAlloc, 0x00,
PAGE_SIZE - iinfo->i_lenAlloc);
memcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr,
iinfo->i_lenAlloc);
flush_dcache_page(page);
SetPageUptodate(page);
kunmap_atomic(kaddr);
}
down_write(&iinfo->i_data_sem);
memset(iinfo->i_data + iinfo->i_lenEAttr, 0x00,
iinfo->i_lenAlloc);
iinfo->i_lenAlloc = 0;
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
set_page_dirty(page);
unlock_page(page);
up_write(&iinfo->i_data_sem);
err = filemap_fdatawrite(inode->i_mapping);
if (err) {
/* Restore everything back so that we don't lose data... */
lock_page(page);
down_write(&iinfo->i_data_sem);
kaddr = kmap_atomic(page);
memcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size);
kunmap_atomic(kaddr);
unlock_page(page);
iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;
inode->i_data.a_ops = &udf_adinicb_aops;
up_write(&iinfo->i_data_sem);
}
put_page(page);
mark_inode_dirty(inode);
return err;
} | 1 |
gnutls | 1ffb827e45721ef56982d0ffd5c5de52376c428e | NOT_APPLICABLE | NOT_APPLICABLE | void gnutls_deinit(gnutls_session_t session)
{
unsigned int i;
if (session == NULL)
return;
/* remove auth info firstly */
_gnutls_free_auth_info(session);
_gnutls_handshake_internal_state_clear(session);
_gnutls_handshake_io_buffer_clear(session);
_gnutls_ext_free_session_data(session);
for (i = 0; i < MAX_EPOCH_INDEX; i++)
if (session->record_parameters[i] != NULL) {
_gnutls_epoch_free(session,
session->record_parameters[i]);
session->record_parameters[i] = NULL;
}
_gnutls_buffer_clear(&session->internals.handshake_hash_buffer);
_gnutls_buffer_clear(&session->internals.hb_remote_data);
_gnutls_buffer_clear(&session->internals.hb_local_data);
_gnutls_buffer_clear(&session->internals.record_presend_buffer);
_mbuffer_head_clear(&session->internals.record_buffer);
_mbuffer_head_clear(&session->internals.record_recv_buffer);
_mbuffer_head_clear(&session->internals.record_send_buffer);
_gnutls_free_datum(&session->internals.resumption_data);
gnutls_free(session->internals.rexts);
gnutls_free(session->internals.rsup);
gnutls_credentials_clear(session);
_gnutls_selected_certs_deinit(session);
gnutls_free(session);
} | 0 |
file | 2858eaf99f6cc5aae129bcbf1e24ad160240185f | NOT_APPLICABLE | NOT_APPLICABLE | toomany(struct magic_set *ms, const char *name, uint16_t num)
{
if (file_printf(ms, ", too many %s (%u)", name, num) == -1)
return -1;
return 1;
}
| 0 |
git | f66cf96d7c613a8129436a5d76ef7b74ee302436 | NOT_APPLICABLE | NOT_APPLICABLE | static unsigned hash_name(const char *name, int namelen)
{
unsigned val = 0;
unsigned char c;
while (namelen--) {
c = *name++;
val = ((val << 7) | (val >> 22)) ^ c;
}
return val;
} | 0 |
Chrome | 7cde8513c12a6e8ec5d1d1eb1cfd078d9adad3ef | NOT_APPLICABLE | NOT_APPLICABLE | PageInfoTest() { SetURL("http://www.example.com"); }
| 0 |
Chrome | f7b020b3d36def118881daa4402c44ca72271482 | NOT_APPLICABLE | NOT_APPLICABLE | void DateTimeSymbolicFieldElement::stepDown()
{
if (hasValue()) {
if (!indexIsInRange(--m_selectedIndex))
m_selectedIndex = m_maximumIndex;
} else
m_selectedIndex = m_maximumIndex;
updateVisibleValue(DispatchEvent);
}
| 0 |
ImageMagick | 94174beff065cb5683d09d79e992c3ebbdead311 | NOT_APPLICABLE | NOT_APPLICABLE | MagickExport Image *SketchImage(const Image *image,const double radius,
const double sigma,const double angle,ExceptionInfo *exception)
{
CacheView
*random_view;
Image
*blend_image,
*blur_image,
*dodge_image,
*random_image,
*sketch_image;
MagickBooleanType
status;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Sketch image.
*/
random_image=CloneImage(image,image->columns << 1,image->rows << 1,
MagickTrue,exception);
if (random_image == (Image *) NULL)
return((Image *) NULL);
status=MagickTrue;
random_info=AcquireRandomInfoThreadSet();
random_view=AcquireAuthenticCacheView(random_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) random_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) random_image->columns; x++)
{
double
value;
ssize_t
i;
value=GetPseudoRandomValue(random_info[id]);
for (i=0; i < (ssize_t) GetPixelChannels(random_image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=ClampToQuantum(QuantumRange*value);
}
q+=GetPixelChannels(random_image);
}
if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse)
status=MagickFalse;
}
random_view=DestroyCacheView(random_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
{
random_image=DestroyImage(random_image);
return(random_image);
}
blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception);
random_image=DestroyImage(random_image);
if (blur_image == (Image *) NULL)
return((Image *) NULL);
dodge_image=EdgeImage(blur_image,radius,exception);
blur_image=DestroyImage(blur_image);
if (dodge_image == (Image *) NULL)
return((Image *) NULL);
status=ClampImage(dodge_image,exception);
if (status != MagickFalse)
status=NormalizeImage(dodge_image,exception);
if (status != MagickFalse)
status=NegateImage(dodge_image,MagickFalse,exception);
if (status != MagickFalse)
status=TransformImage(&dodge_image,(char *) NULL,"50%",exception);
sketch_image=CloneImage(image,0,0,MagickTrue,exception);
if (sketch_image == (Image *) NULL)
{
dodge_image=DestroyImage(dodge_image);
return((Image *) NULL);
}
(void) CompositeImage(sketch_image,dodge_image,ColorDodgeCompositeOp,
MagickTrue,0,0,exception);
dodge_image=DestroyImage(dodge_image);
blend_image=CloneImage(image,0,0,MagickTrue,exception);
if (blend_image == (Image *) NULL)
{
sketch_image=DestroyImage(sketch_image);
return((Image *) NULL);
}
if (blend_image->alpha_trait != BlendPixelTrait)
(void) SetImageAlpha(blend_image,TransparentAlpha,exception);
(void) SetImageArtifact(blend_image,"compose:args","20x80");
(void) CompositeImage(sketch_image,blend_image,BlendCompositeOp,MagickTrue,
0,0,exception);
blend_image=DestroyImage(blend_image);
return(sketch_image);
} | 0 |
mod_auth_openidc | 132a4111bf3791e76437619a66336dce2ce4c79b | NOT_APPLICABLE | NOT_APPLICABLE | static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, const char *error,
const char *error_description) {
const char *prompt = oidc_proto_state_get_prompt(proto_state);
if (prompt != NULL)
prompt = apr_pstrdup(r->pool, prompt);
oidc_proto_state_destroy(proto_state);
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, DONE);
}
| 0 |
flatpak | 8279c5818425b6812523e3805bbe242fb6a5d961 | NOT_APPLICABLE | NOT_APPLICABLE | flatpak_dir_deploy (FlatpakDir *self,
const char *origin,
FlatpakDecomposed *ref,
const char *checksum_or_latest,
const char * const * subpaths,
const char * const * previous_ids,
GCancellable *cancellable,
GError **error)
{
g_autofree char *resolved_ref = NULL;
g_autofree char *ref_id = NULL;
g_autoptr(GFile) root = NULL;
g_autoptr(GFile) deploy_base = NULL;
g_autoptr(GFile) checkoutdir = NULL;
g_autoptr(GFile) bindir = NULL;
g_autofree char *checkoutdirpath = NULL;
g_autoptr(GFile) real_checkoutdir = NULL;
g_autoptr(GFile) dotref = NULL;
g_autoptr(GFile) files_etc = NULL;
g_autoptr(GFile) deploy_data_file = NULL;
g_autoptr(GVariant) commit_data = NULL;
g_autoptr(GBytes) deploy_data = NULL;
g_autoptr(GFile) export = NULL;
g_autoptr(GFile) extradir = NULL;
g_autoptr(GKeyFile) keyfile = NULL;
guint64 installed_size = 0;
OstreeRepoCheckoutAtOptions options = { 0, };
const char *checksum;
glnx_autofd int checkoutdir_dfd = -1;
g_autoptr(GFile) tmp_dir_template = NULL;
g_autofree char *tmp_dir_path = NULL;
const char *xa_ref = NULL;
g_autofree char *checkout_basename = NULL;
gboolean created_extra_data = FALSE;
g_autoptr(GVariant) commit_metadata = NULL;
g_auto(GLnxLockFile) lock = { 0, };
g_autoptr(GFile) metadata_file = NULL;
g_autofree char *metadata_contents = NULL;
gboolean is_oci;
if (!flatpak_dir_ensure_repo (self, cancellable, error))
return FALSE;
ref_id = flatpak_decomposed_dup_id (ref);
/* Keep a shared repo lock to avoid prunes removing objects we're relying on
* while we do the checkout. This could happen if the ref changes after we
* read its current value for the checkout. */
if (!flatpak_dir_repo_lock (self, &lock, LOCK_SH, cancellable, error))
return FALSE;
deploy_base = flatpak_dir_get_deploy_dir (self, ref);
if (checksum_or_latest == NULL)
{
g_debug ("No checksum specified, getting tip of %s from origin %s", flatpak_decomposed_get_ref (ref), origin);
resolved_ref = flatpak_dir_read_latest (self, origin, flatpak_decomposed_get_ref (ref), NULL, cancellable, error);
if (resolved_ref == NULL)
{
g_prefix_error (error, _("While trying to resolve ref %s: "), flatpak_decomposed_get_ref (ref));
return FALSE;
}
checksum = resolved_ref;
g_debug ("tip resolved to: %s", checksum);
}
else
{
checksum = checksum_or_latest;
g_debug ("Looking for checksum %s in local repo", checksum);
if (!ostree_repo_read_commit (self->repo, checksum, NULL, NULL, cancellable, NULL))
return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA, _("%s is not available"), flatpak_decomposed_get_ref (ref));
}
if (!ostree_repo_load_commit (self->repo, checksum, &commit_data, NULL, error))
return FALSE;
commit_metadata = g_variant_get_child_value (commit_data, 0);
checkout_basename = flatpak_dir_get_deploy_subdir (self, checksum, subpaths);
real_checkoutdir = g_file_get_child (deploy_base, checkout_basename);
if (g_file_query_exists (real_checkoutdir, cancellable))
return flatpak_fail_error (error, FLATPAK_ERROR_ALREADY_INSTALLED,
_("%s commit %s already installed"), flatpak_decomposed_get_ref (ref), checksum);
g_autofree char *template = g_strdup_printf (".%s-XXXXXX", checkout_basename);
tmp_dir_template = g_file_get_child (deploy_base, template);
tmp_dir_path = g_file_get_path (tmp_dir_template);
if (g_mkdtemp_full (tmp_dir_path, 0755) == NULL)
{
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
_("Can't create deploy directory"));
return FALSE;
}
checkoutdir = g_file_new_for_path (tmp_dir_path);
if (!ostree_repo_read_commit (self->repo, checksum, &root, NULL, cancellable, error))
{
g_prefix_error (error, _("Failed to read commit %s: "), checksum);
return FALSE;
}
if (!flatpak_repo_collect_sizes (self->repo, root, &installed_size, NULL, cancellable, error))
return FALSE;
options.mode = OSTREE_REPO_CHECKOUT_MODE_USER;
options.overwrite_mode = OSTREE_REPO_CHECKOUT_OVERWRITE_UNION_FILES;
options.enable_fsync = FALSE; /* We checkout to a temp dir and sync before moving it in place */
options.bareuseronly_dirs = TRUE; /* https://github.com/ostreedev/ostree/pull/927 */
checkoutdirpath = g_file_get_path (checkoutdir);
if (subpaths == NULL || *subpaths == NULL)
{
if (!ostree_repo_checkout_at (self->repo, &options,
AT_FDCWD, checkoutdirpath,
checksum,
cancellable, error))
{
g_prefix_error (error, _("While trying to checkout %s into %s: "), checksum, checkoutdirpath);
return FALSE;
}
}
else
{
g_autoptr(GFile) files = g_file_get_child (checkoutdir, "files");
int i;
if (!g_file_make_directory_with_parents (files, cancellable, error))
return FALSE;
options.subpath = "/metadata";
if (!ostree_repo_checkout_at (self->repo, &options,
AT_FDCWD, checkoutdirpath,
checksum,
cancellable, error))
{
g_prefix_error (error, _("While trying to checkout metadata subpath: "));
return FALSE;
}
for (i = 0; subpaths[i] != NULL; i++)
{
g_autofree char *subpath = g_build_filename ("/files", subpaths[i], NULL);
g_autofree char *dstpath = g_build_filename (checkoutdirpath, "/files", subpaths[i], NULL);
g_autofree char *dstpath_parent = g_path_get_dirname (dstpath);
g_autoptr(GFile) child = NULL;
child = g_file_resolve_relative_path (root, subpath);
if (!g_file_query_exists (child, cancellable))
{
g_debug ("subpath %s not in tree", subpaths[i]);
continue;
}
if (g_mkdir_with_parents (dstpath_parent, 0755))
{
glnx_set_error_from_errno (error);
return FALSE;
}
options.subpath = subpath;
if (!ostree_repo_checkout_at (self->repo, &options,
AT_FDCWD, dstpath,
checksum,
cancellable, error))
{
g_prefix_error (error, _("While trying to checkout subpath ‘%s’: "), subpath);
return FALSE;
}
}
}
/* Extract any extra data */
extradir = g_file_resolve_relative_path (checkoutdir, "files/extra");
if (!flatpak_rm_rf (extradir, cancellable, error))
{
g_prefix_error (error, _("While trying to remove existing extra dir: "));
return FALSE;
}
if (!extract_extra_data (self, checksum, extradir, &created_extra_data, cancellable, error))
return FALSE;
if (created_extra_data)
{
if (!apply_extra_data (self, checkoutdir, cancellable, error))
{
g_prefix_error (error, _("While trying to apply extra data: "));
return FALSE;
}
}
g_variant_lookup (commit_metadata, "xa.ref", "&s", &xa_ref);
if (xa_ref != NULL)
{
gboolean gpg_verify_summary;
if (!ostree_repo_remote_get_gpg_verify_summary (self->repo, origin, &gpg_verify_summary, error))
return FALSE;
if (gpg_verify_summary)
{
/* If we're using signed summaries, then the security is really due to the signatures on
* the summary, and the xa.ref is not needed for security. In particular, endless are
* currently using one single commit on multiple branches to handle devel/stable promotion.
* So, to support this we report branch discrepancies as a warning, rather than as an error.
* See https://github.com/flatpak/flatpak/pull/1013 for more discussion.
*/
FlatpakDecomposed *checkout_ref = ref;
g_autoptr(FlatpakDecomposed) commit_ref = NULL;
commit_ref = flatpak_decomposed_new_from_ref (xa_ref, error);
if (commit_ref == NULL)
{
g_prefix_error (error, _("Invalid commit ref %s: "), xa_ref);
return FALSE;
}
/* Fatal if kind/name/arch don't match. Warn for branch mismatch. */
if (!flatpak_decomposed_equal_except_branch (checkout_ref, commit_ref))
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,
_("Deployed ref %s does not match commit (%s)"),
flatpak_decomposed_get_ref (ref), xa_ref);
return FALSE;
}
if (strcmp (flatpak_decomposed_get_branch (checkout_ref), flatpak_decomposed_get_branch (commit_ref)) != 0)
g_warning (_("Deployed ref %s branch does not match commit (%s)"),
flatpak_decomposed_get_ref (ref), xa_ref);
}
else if (strcmp (flatpak_decomposed_get_ref (ref), xa_ref) != 0)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,
_("Deployed ref %s does not match commit (%s)"), flatpak_decomposed_get_ref (ref), xa_ref);
return FALSE;
}
}
keyfile = g_key_file_new ();
metadata_file = g_file_resolve_relative_path (checkoutdir, "metadata");
if (g_file_load_contents (metadata_file, NULL,
&metadata_contents, NULL, NULL, NULL))
{
if (!g_key_file_load_from_data (keyfile,
metadata_contents,
-1,
0, error))
return FALSE;
if (!flatpak_check_required_version (flatpak_decomposed_get_ref (ref), keyfile, error))
return FALSE;
}
/* Check the metadata in the commit to make sure it matches the actual
* deployed metadata, in case we relied on the one in the commit for
* a decision
* Note: For historical reason we don't enforce commits to contain xa.metadata
* since this was lacking in fedora builds.
*/
is_oci = flatpak_dir_get_remote_oci (self, origin);
if (!validate_commit_metadata (commit_data, flatpak_decomposed_get_ref (ref),
metadata_contents, !is_oci, error))
return FALSE;
dotref = g_file_resolve_relative_path (checkoutdir, "files/.ref");
if (!g_file_replace_contents (dotref, "", 0, NULL, FALSE,
G_FILE_CREATE_REPLACE_DESTINATION, NULL, cancellable, error))
return TRUE;
export = g_file_get_child (checkoutdir, "export");
/* Never export any binaries bundled with the app */
bindir = g_file_get_child (export, "bin");
if (!flatpak_rm_rf (bindir, cancellable, error))
return FALSE;
if (flatpak_decomposed_is_runtime (ref))
{
/* Ensure that various files exists as regular files in /usr/etc, as we
want to bind-mount over them */
files_etc = g_file_resolve_relative_path (checkoutdir, "files/etc");
if (g_file_query_exists (files_etc, cancellable))
{
char *etcfiles[] = {"passwd", "group", "machine-id" };
g_autoptr(GFile) etc_resolve_conf = g_file_get_child (files_etc, "resolv.conf");
int i;
for (i = 0; i < G_N_ELEMENTS (etcfiles); i++)
{
g_autoptr(GFile) etc_file = g_file_get_child (files_etc, etcfiles[i]);
GFileType type;
type = g_file_query_file_type (etc_file, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
cancellable);
if (type == G_FILE_TYPE_REGULAR)
continue;
if (type != G_FILE_TYPE_UNKNOWN)
{
/* Already exists, but not regular, probably symlink. Remove it */
if (!g_file_delete (etc_file, cancellable, error))
return FALSE;
}
if (!g_file_replace_contents (etc_file, "", 0, NULL, FALSE,
G_FILE_CREATE_REPLACE_DESTINATION,
NULL, cancellable, error))
return FALSE;
}
if (g_file_query_exists (etc_resolve_conf, cancellable) &&
!g_file_delete (etc_resolve_conf, cancellable, error))
return TRUE;
if (!g_file_make_symbolic_link (etc_resolve_conf,
"/run/host/monitor/resolv.conf",
cancellable, error))
return FALSE;
}
/* Runtime should never export anything */
if (!flatpak_rm_rf (export, cancellable, error))
return FALSE;
}
else /* is app */
{
g_autofree char *ref_arch = flatpak_decomposed_dup_arch (ref);
g_autofree char *ref_branch = flatpak_decomposed_dup_branch (ref);
g_autoptr(GFile) wrapper = g_file_get_child (bindir, ref_id);
g_autofree char *escaped_app = maybe_quote (ref_id);
g_autofree char *escaped_branch = maybe_quote (ref_branch);
g_autofree char *escaped_arch = maybe_quote (ref_arch);
g_autofree char *bin_data = NULL;
int r;
if (!flatpak_mkdir_p (bindir, cancellable, error))
return FALSE;
if (!flatpak_rewrite_export_dir (ref_id, ref_branch, ref_arch,
keyfile, previous_ids, export,
cancellable,
error))
return FALSE;
bin_data = g_strdup_printf ("#!/bin/sh\nexec %s/flatpak run --branch=%s --arch=%s %s \"$@\"\n",
FLATPAK_BINDIR, escaped_branch, escaped_arch, escaped_app);
if (!g_file_replace_contents (wrapper, bin_data, strlen (bin_data), NULL, FALSE,
G_FILE_CREATE_REPLACE_DESTINATION, NULL, cancellable, error))
return FALSE;
do
r = fchmodat (AT_FDCWD, flatpak_file_get_path_cached (wrapper), 0755, 0);
while (G_UNLIKELY (r == -1 && errno == EINTR));
if (r == -1)
return glnx_throw_errno_prefix (error, "fchmodat");
}
deploy_data = flatpak_dir_new_deploy_data (self,
checkoutdir,
commit_data,
commit_metadata,
keyfile,
ref_id,
origin,
checksum,
(char **) subpaths,
installed_size,
previous_ids);
/* Check the app is actually allowed to be used by this user. This can block
* on getting authorisation. */
if (!flatpak_dir_check_parental_controls (self, flatpak_decomposed_get_ref (ref), deploy_data, cancellable, error))
return FALSE;
deploy_data_file = g_file_get_child (checkoutdir, "deploy");
if (!flatpak_bytes_save (deploy_data_file, deploy_data, cancellable, error))
return FALSE;
if (!glnx_opendirat (AT_FDCWD, checkoutdirpath, TRUE, &checkoutdir_dfd, error))
return FALSE;
if (syncfs (checkoutdir_dfd) != 0)
{
glnx_set_error_from_errno (error);
return FALSE;
}
if (!g_file_move (checkoutdir, real_checkoutdir, G_FILE_COPY_NO_FALLBACK_FOR_MOVE,
cancellable, NULL, NULL, error))
return FALSE;
if (!flatpak_dir_set_active (self, ref, checkout_basename, cancellable, error))
return FALSE;
if (!flatpak_dir_update_deploy_ref (self, flatpak_decomposed_get_ref (ref), checksum, error))
return FALSE;
return TRUE;
} | 0 |
Chrome | 2bceda4948deeaed0a5a99305d0d488eb952f64f | NOT_APPLICABLE | NOT_APPLICABLE | void BluetoothRemoteGATTCharacteristic::ReadValueCallback(
ScriptPromiseResolver* resolver,
mojom::blink::WebBluetoothResult result,
const Optional<Vector<uint8_t>>& value) {
if (!resolver->getExecutionContext() ||
resolver->getExecutionContext()->isContextDestroyed())
return;
if (!getGatt()->RemoveFromActiveAlgorithms(resolver)) {
resolver->reject(BluetoothRemoteGATTUtils::CreateDOMException(
BluetoothRemoteGATTUtils::ExceptionType::kGATTServerDisconnected));
return;
}
if (result == mojom::blink::WebBluetoothResult::SUCCESS) {
DCHECK(value);
DOMDataView* domDataView =
BluetoothRemoteGATTUtils::ConvertWTFVectorToDataView(value.value());
setValue(domDataView);
resolver->resolve(domDataView);
} else {
resolver->reject(BluetoothError::take(resolver, result));
}
}
| 0 |
linux-2.6 | 8a0a9bd4db63bc45e3017bedeafbd88d0eb84d02 | NOT_APPLICABLE | NOT_APPLICABLE | static size_t account(struct entropy_store *r, size_t nbytes, int min,
int reserved)
{
unsigned long flags;
/* Hold lock while accounting */
spin_lock_irqsave(&r->lock, flags);
BUG_ON(r->entropy_count > r->poolinfo->POOLBITS);
DEBUG_ENT("trying to extract %d bits from %s\n",
nbytes * 8, r->name);
/* Can we pull enough? */
if (r->entropy_count / 8 < min + reserved) {
nbytes = 0;
} else {
/* If limited, never pull more than available */
if (r->limit && nbytes + reserved >= r->entropy_count / 8)
nbytes = r->entropy_count/8 - reserved;
if (r->entropy_count / 8 >= nbytes + reserved)
r->entropy_count -= nbytes*8;
else
r->entropy_count = reserved;
if (r->entropy_count < random_write_wakeup_thresh) {
wake_up_interruptible(&random_write_wait);
kill_fasync(&fasync, SIGIO, POLL_OUT);
}
}
DEBUG_ENT("debiting %d entropy credits from %s%s\n",
nbytes * 8, r->name, r->limit ? "" : " (unlimited)");
spin_unlock_irqrestore(&r->lock, flags);
return nbytes;
} | 0 |
qemu | eea750a5623ddac7a61982eec8f1c93481857578 | NOT_APPLICABLE | NOT_APPLICABLE | static int virtio_net_can_receive(NetClientState *nc)
{
VirtIONet *n = qemu_get_nic_opaque(nc);
VirtIODevice *vdev = VIRTIO_DEVICE(n);
VirtIONetQueue *q = virtio_net_get_subqueue(nc);
if (!vdev->vm_running) {
return 0;
}
if (nc->queue_index >= n->curr_queues) {
return 0;
}
if (!virtio_queue_ready(q->rx_vq) ||
!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
return 0;
}
return 1;
}
| 0 |
ImageMagick | 8187d2d8fd010d2d6b1a3a8edd935beec404dddc | CVE-2019-13299 | CWE-20 | static inline Quantum GetPixelChannel(const Image *magick_restrict image,
const PixelChannel channel,const Quantum *magick_restrict pixel)
{
if (image->channel_map[channel].traits == UndefinedPixelTrait)
return((Quantum) 0);
return(pixel[image->channel_map[channel].offset]);
} | 1 |
vim | dc5490e2cbc8c16022a23b449b48c1bd0083f366 | NOT_APPLICABLE | NOT_APPLICABLE | make_filter_cmd(
char_u *cmd, // command
char_u *itmp, // NULL or name of input file
char_u *otmp) // NULL or name of output file
{
char_u *buf;
long_u len;
#if defined(UNIX)
int is_fish_shell;
char_u *shell_name = get_isolated_shell_name();
if (shell_name == NULL)
return NULL;
// Account for fish's different syntax for subshells
is_fish_shell = (fnamecmp(shell_name, "fish") == 0);
vim_free(shell_name);
if (is_fish_shell)
len = (long_u)STRLEN(cmd) + 13; // "begin; " + "; end" + NUL
else
#endif
len = (long_u)STRLEN(cmd) + 3; // "()" + NUL
if (itmp != NULL)
len += (long_u)STRLEN(itmp) + 9; // " { < " + " } "
if (otmp != NULL)
len += (long_u)STRLEN(otmp) + (long_u)STRLEN(p_srr) + 2; // " "
buf = alloc(len);
if (buf == NULL)
return NULL;
#if defined(UNIX)
/*
* Put braces around the command (for concatenated commands) when
* redirecting input and/or output.
*/
if (itmp != NULL || otmp != NULL)
{
if (is_fish_shell)
vim_snprintf((char *)buf, len, "begin; %s; end", (char *)cmd);
else
vim_snprintf((char *)buf, len, "(%s)", (char *)cmd);
}
else
STRCPY(buf, cmd);
if (itmp != NULL)
{
STRCAT(buf, " < ");
STRCAT(buf, itmp);
}
#else
// For shells that don't understand braces around commands, at least allow
// the use of commands in a pipe.
if (*p_sxe != NUL && *p_sxq == '(')
{
if (itmp != NULL || otmp != NULL)
vim_snprintf((char *)buf, len, "(%s)", (char *)cmd);
else
STRCPY(buf, cmd);
if (itmp != NULL)
{
STRCAT(buf, " < ");
STRCAT(buf, itmp);
}
}
else
{
STRCPY(buf, cmd);
if (itmp != NULL)
{
char_u *p;
// If there is a pipe, we have to put the '<' in front of it.
// Don't do this when 'shellquote' is not empty, otherwise the
// redirection would be inside the quotes.
if (*p_shq == NUL)
{
p = find_pipe(buf);
if (p != NULL)
*p = NUL;
}
STRCAT(buf, " <"); // " < " causes problems on Amiga
STRCAT(buf, itmp);
if (*p_shq == NUL)
{
p = find_pipe(cmd);
if (p != NULL)
{
STRCAT(buf, " "); // insert a space before the '|' for DOS
STRCAT(buf, p);
}
}
}
}
#endif
if (otmp != NULL)
append_redir(buf, (int)len, p_srr, otmp);
return buf;
} | 0 |
linux | f63a8daa5812afef4f06c962351687e1ff9ccb2b | NOT_APPLICABLE | NOT_APPLICABLE | list_del_event(struct perf_event *event, struct perf_event_context *ctx)
{
struct perf_cpu_context *cpuctx;
WARN_ON_ONCE(event->ctx != ctx);
lockdep_assert_held(&ctx->lock);
/*
* We can have double detach due to exit/hot-unplug + close.
*/
if (!(event->attach_state & PERF_ATTACH_CONTEXT))
return;
event->attach_state &= ~PERF_ATTACH_CONTEXT;
if (is_cgroup_event(event)) {
ctx->nr_cgroups--;
cpuctx = __get_cpu_context(ctx);
/*
* if there are no more cgroup events
* then cler cgrp to avoid stale pointer
* in update_cgrp_time_from_cpuctx()
*/
if (!ctx->nr_cgroups)
cpuctx->cgrp = NULL;
}
if (has_branch_stack(event))
ctx->nr_branch_stack--;
ctx->nr_events--;
if (event->attr.inherit_stat)
ctx->nr_stat--;
list_del_rcu(&event->event_entry);
if (event->group_leader == event)
list_del_init(&event->group_entry);
update_group_times(event);
/*
* If event was in error state, then keep it
* that way, otherwise bogus counts will be
* returned on read(). The only way to get out
* of error state is by explicit re-enabling
* of the event
*/
if (event->state > PERF_EVENT_STATE_OFF)
event->state = PERF_EVENT_STATE_OFF;
ctx->generation++;
}
| 0 |
rsyslog | 80f88242982c9c6ad6ce8628fc5b94ea74051cf4 | NOT_APPLICABLE | NOT_APPLICABLE | if(pData->dynSrchType) {
CHKiRet(OMSRsetEntry(*ppOMSR, 1, ustrdup(pData->searchType),
OMSR_NO_RQD_TPL_OPTS));
if(pData->dynParent) {
CHKiRet(OMSRsetEntry(*ppOMSR, 2, ustrdup(pData->parent),
OMSR_NO_RQD_TPL_OPTS));
if(pData->dynBulkId) {
CHKiRet(OMSRsetEntry(*ppOMSR, 3, ustrdup(pData->bulkId),
OMSR_NO_RQD_TPL_OPTS));
}
} else {
if(pData->dynBulkId) {
CHKiRet(OMSRsetEntry(*ppOMSR, 2, ustrdup(pData->bulkId),
OMSR_NO_RQD_TPL_OPTS));
}
}
} else { | 0 |
Chrome | befb46ae3385fa13975521e9a2281e35805b339e | NOT_APPLICABLE | NOT_APPLICABLE | void FrameLoader::stopLoading(UnloadEventPolicy unloadEventPolicy, DatabasePolicy databasePolicy)
{
if (m_frame->document() && m_frame->document()->tokenizer())
m_frame->document()->tokenizer()->stopParsing();
if (unloadEventPolicy != UnloadEventPolicyNone) {
if (m_frame->document()) {
if (m_didCallImplicitClose && !m_wasUnloadEventEmitted) {
Node* currentFocusedNode = m_frame->document()->focusedNode();
if (currentFocusedNode)
currentFocusedNode->aboutToUnload();
m_unloadEventBeingDispatched = true;
if (m_frame->domWindow()) {
if (unloadEventPolicy == UnloadEventPolicyUnloadAndPageHide)
m_frame->domWindow()->dispatchEvent(PageTransitionEvent::create(EventNames().pagehideEvent, m_frame->document()->inPageCache()), m_frame->document());
if (!m_frame->document()->inPageCache())
m_frame->domWindow()->dispatchEvent(Event::create(eventNames().unloadEvent, false, false), m_frame->domWindow()->document());
}
m_unloadEventBeingDispatched = false;
if (m_frame->document())
m_frame->document()->updateStyleIfNeeded();
m_wasUnloadEventEmitted = true;
}
}
if (m_frame->document() && !m_frame->document()->inPageCache()) {
bool keepEventListeners = m_isDisplayingInitialEmptyDocument && m_provisionalDocumentLoader
&& m_frame->document()->securityOrigin()->isSecureTransitionTo(m_provisionalDocumentLoader->url());
if (!keepEventListeners)
m_frame->document()->removeAllEventListeners();
}
}
m_isComplete = true; // to avoid calling completed() in finishedParsing()
m_isLoadingMainResource = false;
m_didCallImplicitClose = true; // don't want that one either
if (m_frame->document() && m_frame->document()->parsing()) {
finishedParsing();
m_frame->document()->setParsing(false);
}
m_workingURL = KURL();
if (Document* doc = m_frame->document()) {
if (DocLoader* docLoader = doc->docLoader())
cache()->loader()->cancelRequests(docLoader);
#if ENABLE(DATABASE)
if (databasePolicy == DatabasePolicyStop)
doc->stopDatabases();
#endif
}
for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
child->loader()->stopLoading(unloadEventPolicy);
m_frame->redirectScheduler()->cancel();
}
| 0 |
FFmpeg | 8312e3fc9041027a33c8bc667bb99740fdf41dd5 | NOT_APPLICABLE | NOT_APPLICABLE | static int ape_read_close(AVFormatContext * s)
{
APEContext *ape = s->priv_data;
av_freep(&ape->frames);
av_freep(&ape->seektable);
return 0;
}
| 0 |
linux | 687cb0884a714ff484d038e9190edc874edcf146 | NOT_APPLICABLE | NOT_APPLICABLE | static void oom_reap_task(struct task_struct *tsk)
{
int attempts = 0;
struct mm_struct *mm = tsk->signal->oom_mm;
/* Retry the down_read_trylock(mmap_sem) a few times */
while (attempts++ < MAX_OOM_REAP_RETRIES && !__oom_reap_task_mm(tsk, mm))
schedule_timeout_idle(HZ/10);
if (attempts <= MAX_OOM_REAP_RETRIES)
goto done;
pr_info("oom_reaper: unable to reap pid:%d (%s)\n",
task_pid_nr(tsk), tsk->comm);
debug_show_all_locks();
done:
tsk->oom_reaper_list = NULL;
/*
* Hide this mm from OOM killer because it has been either reaped or
* somebody can't call up_write(mmap_sem).
*/
set_bit(MMF_OOM_SKIP, &mm->flags);
/* Drop a reference taken by wake_oom_reaper */
put_task_struct(tsk);
}
| 0 |
LibRaw | f1394822a0152ceed77815eafa5cac4e8baab10a | NOT_APPLICABLE | NOT_APPLICABLE | void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp)
{
int c;
if (tiff_samples == 2 && shot_select)
(*rp)++;
if (raw_image)
{
if (row < raw_height && col < raw_width)
RAW(row, col) = curve[**rp];
*rp += tiff_samples;
}
else
{
#ifdef LIBRAW_LIBRARY_BUILD
if (row < raw_height && col < raw_width)
FORC(tiff_samples)
image[row * raw_width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#else
if (row < height && col < width)
FORC(tiff_samples)
image[row * width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#endif
}
if (tiff_samples == 2 && shot_select)
(*rp)--;
} | 0 |
Chrome | 0aca6bc05a263ea9eafee515fc6ba14da94c1964 | NOT_APPLICABLE | NOT_APPLICABLE | PermissionsData::AccessType PermissionsData::GetPageAccess(
const Extension* extension,
const GURL& document_url,
int tab_id,
std::string* error) const {
base::AutoLock auto_lock(runtime_lock_);
const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id);
return CanRunOnPage(
extension, document_url, tab_id,
active_permissions_unsafe_->explicit_hosts(),
withheld_permissions_unsafe_->explicit_hosts(),
tab_permissions ? &tab_permissions->explicit_hosts() : nullptr, error);
}
| 0 |
mruby | 778500563a9f7ceba996937dc886bd8cde29b42b | NOT_APPLICABLE | NOT_APPLICABLE | mrb_fiber_yield(mrb_state *mrb, mrb_int len, const mrb_value *a)
{
struct mrb_context *c = mrb->c;
if (!c->prev) {
mrb_raise(mrb, E_FIBER_ERROR, "can't yield from root fiber");
}
fiber_check_cfunc(mrb, c);
c->prev->status = MRB_FIBER_RUNNING;
c->status = MRB_FIBER_SUSPENDED;
fiber_switch_context(mrb, c->prev);
c->prev = NULL;
if (c->vmexec) {
c->vmexec = FALSE;
mrb->c->ci->acc = CI_ACC_RESUMED;
}
MARK_CONTEXT_MODIFY(mrb->c);
return fiber_result(mrb, a, len);
}
| 0 |
linux | c4c896e1471aec3b004a693c689f60be3b17ac86 | NOT_APPLICABLE | NOT_APPLICABLE | static int sco_sock_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
lock_sock(sk);
if (!sk->sk_shutdown) {
sk->sk_shutdown = SHUTDOWN_MASK;
sco_sock_clear_timer(sk);
__sco_sock_close(sk);
if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime)
err = bt_sock_wait_state(sk, BT_CLOSED,
sk->sk_lingertime);
}
release_sock(sk);
return err;
}
| 0 |
libsoup | cbeeb7a0f7f0e8b16f2d382157496f9100218dea | NOT_APPLICABLE | NOT_APPLICABLE | soup_client_context_get_socket (SoupClientContext *client)
{
g_return_val_if_fail (client != NULL, NULL);
return client->sock;
} | 0 |
miniupnp | cb8a02af7a5677cf608e86d57ab04241cf34e24f | NOT_APPLICABLE | NOT_APPLICABLE | static void printMAPOpcodeVersion1(const uint8_t *buf)
{
char map_addr[INET6_ADDRSTRLEN];
syslog(LOG_DEBUG, "PCP MAP: v1 Opcode specific information. \n");
syslog(LOG_DEBUG, "MAP protocol: \t\t %d\n", (int)buf[0] );
syslog(LOG_DEBUG, "MAP int port: \t\t %d\n", (int)READNU16(buf+4));
syslog(LOG_DEBUG, "MAP ext port: \t\t %d\n", (int)READNU16(buf+6));
syslog(LOG_DEBUG, "MAP Ext IP: \t\t %s\n", inet_ntop(AF_INET6,
buf+8, map_addr, INET6_ADDRSTRLEN));
}
| 0 |
php-src | 0da8b8b801f9276359262f1ef8274c7812d3dfda?w=1 | NOT_APPLICABLE | NOT_APPLICABLE | static inline size_t php_mb3_int_to_char(unsigned char *buf, unsigned k)
{
assert(k <= 0xFFFFFFU);
/* one to three bytes */
if (k <= 0xFFU) { /* 1 */
buf[0] = k;
return 1U;
} else if (k <= 0xFFFFU) { /* 2 */
buf[0] = k >> 8;
buf[1] = k & 0xFFU;
return 2U;
} else {
buf[0] = k >> 16;
buf[1] = (k >> 8) & 0xFFU;
buf[2] = k & 0xFFU;
return 3U;
}
}
| 0 |
Chrome | 9c391ac04f9ac478c8b0e43b359c2b43a6c892ab | NOT_APPLICABLE | NOT_APPLICABLE | void HeadlessWebContentsImpl::DevToolsAgentHostDetached(
content::DevToolsAgentHost* agent_host) {
for (auto& observer : observers_)
observer.DevToolsClientDetached();
}
| 0 |
linux | 68cb695ccecf949d48949e72f8ce591fdaaa325c | NOT_APPLICABLE | NOT_APPLICABLE | static int efx_probe_channels(struct efx_nic *efx)
{
struct efx_channel *channel;
int rc;
/* Restart special buffer allocation */
efx->next_buffer_table = 0;
efx_for_each_channel(channel, efx) {
rc = efx_probe_channel(channel);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"failed to create channel %d\n",
channel->channel);
goto fail;
}
}
efx_set_channel_names(efx);
return 0;
fail:
efx_remove_channels(efx);
return rc;
}
| 0 |
trojita | 25fffa3e25cbad85bbca804193ad336b090a9ce1 | NOT_APPLICABLE | NOT_APPLICABLE | void ImapModelOpenConnectionTest::testCompressDeflateOk()
{
QCoreApplication::processEvents();
QCoreApplication::processEvents();
QVERIFY(SOCK->writtenStuff().isEmpty());
SOCK->fakeReading("* OK [capability imap4rev1] hi there\r\n");
QVERIFY(completedSpy->isEmpty());
QCoreApplication::processEvents();
QCoreApplication::processEvents();
QCoreApplication::processEvents();
QCoreApplication::processEvents();
QCoreApplication::processEvents();
QCOMPARE(SOCK->writtenStuff(), QByteArray("y0 LOGIN luzr sikrit\r\n"));
QCOMPARE(authSpy->size(), 1);
SOCK->fakeReading("y0 OK [CAPABILITY IMAP4rev1 compress=deflate id] logged in\r\n");
QCoreApplication::processEvents();
QCoreApplication::processEvents();
QCoreApplication::processEvents();
#if TROJITA_COMPRESS_DEFLATE
QCOMPARE(SOCK->writtenStuff(), QByteArray("y1 COMPRESS DEFLATE\r\n"));
SOCK->fakeReading("y1 OK compressing\r\n");
QCoreApplication::processEvents();
QCOMPARE(SOCK->writtenStuff(), QByteArray("[*** DEFLATE ***]"));
QCoreApplication::processEvents();
QCoreApplication::processEvents();
QCOMPARE(SOCK->writtenStuff(), QByteArray("y2 ID NIL\r\n"));
SOCK->fakeReading("* ID nil\r\ny2 OK you courious peer\r\n");
#else
QCOMPARE(SOCK->writtenStuff(), QByteArray("y1 ID NIL\r\n"));
SOCK->fakeReading("* ID nil\r\ny1 OK you courious peer\r\n");
#endif
QCoreApplication::processEvents();
QCoreApplication::processEvents();
QCOMPARE(completedSpy->size(), 1);
QVERIFY(failedSpy->isEmpty());
QCOMPARE(authSpy->size(), 1);
QVERIFY(SOCK->writtenStuff().isEmpty());
QVERIFY(startTlsUpgradeSpy->isEmpty());
} | 0 |
tor | 3cea86eb2fbb65949673eb4ba8ebb695c87a57ce | NOT_APPLICABLE | NOT_APPLICABLE | socks_request_set_socks5_error(socks_request_t *req,
socks5_reply_status_t reason)
{
req->replylen = 10;
memset(req->reply,0,10);
req->reply[0] = 0x05; // VER field.
req->reply[1] = reason; // REP field.
req->reply[3] = 0x01; // ATYP field.
}
| 0 |
Android | 590d1729883f700ab905cdc9ad850f3ddd7e1f56 | NOT_APPLICABLE | NOT_APPLICABLE | static i32 ComparePictures(const void *ptr1, const void *ptr2)
{
/* Variables */
dpbPicture_t *pic1, *pic2;
/* Code */
ASSERT(ptr1);
ASSERT(ptr2);
pic1 = (dpbPicture_t*)ptr1;
pic2 = (dpbPicture_t*)ptr2;
/* both are non-reference pictures, check if needed for display */
if (!IS_REFERENCE(*pic1) && !IS_REFERENCE(*pic2))
{
if (pic1->toBeDisplayed && !pic2->toBeDisplayed)
return(-1);
else if (!pic1->toBeDisplayed && pic2->toBeDisplayed)
return(1);
else
return(0);
}
/* only pic 1 needed for reference -> greater */
else if (!IS_REFERENCE(*pic2))
return(-1);
/* only pic 2 needed for reference -> greater */
else if (!IS_REFERENCE(*pic1))
return(1);
/* both are short term reference pictures -> check picNum */
else if (IS_SHORT_TERM(*pic1) && IS_SHORT_TERM(*pic2))
{
if (pic1->picNum > pic2->picNum)
return(-1);
else if (pic1->picNum < pic2->picNum)
return(1);
else
return(0);
}
/* only pic 1 is short term -> greater */
else if (IS_SHORT_TERM(*pic1))
return(-1);
/* only pic 2 is short term -> greater */
else if (IS_SHORT_TERM(*pic2))
return(1);
/* both are long term reference pictures -> check picNum (contains the
* longTermPicNum */
else
{
if (pic1->picNum > pic2->picNum)
return(1);
else if (pic1->picNum < pic2->picNum)
return(-1);
else
return(0);
}
}
| 0 |
Android | bae671597d47b9e5955c4cb742e468cebfd7ca6b | NOT_APPLICABLE | NOT_APPLICABLE | static void ConvertDoubleToSRational(double value, int *numerator,
int *denominator) {
int negative = 0;
if (value < 0) {
value = -value;
negative = 1;
}
unsigned int n, d;
float2urat(value, 0x7FFFFFFFU, &n, &d);
*numerator = (int)n;
*denominator = (int)d;
if (negative) {
*numerator = -*numerator;
}
}
| 0 |
qemu | 3251bdcf1c67427d964517053c3d185b46e618e8 | NOT_APPLICABLE | NOT_APPLICABLE | static void bmdma_start_dma(IDEDMA *dma, IDEState *s,
BlockCompletionFunc *dma_cb)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
bm->unit = s->unit;
bm->dma_cb = dma_cb;
bm->cur_prd_last = 0;
bm->cur_prd_addr = 0;
bm->cur_prd_len = 0;
bm->sector_num = ide_get_sector(s);
bm->nsector = s->nsector;
if (bm->status & BM_STATUS_DMAING) {
bm->dma_cb(bmdma_active_if(bm), 0);
}
}
| 0 |
linux | 4d06dd537f95683aba3651098ae288b7cbff8274 | NOT_APPLICABLE | NOT_APPLICABLE | static void cdc_ncm_set_dgram_size(struct usbnet *dev, int new_size)
{
struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
__le16 max_datagram_size;
u16 mbim_mtu;
int err;
/* set default based on descriptors */
ctx->max_datagram_size = clamp_t(u32, new_size,
cdc_ncm_min_dgram_size(dev),
CDC_NCM_MAX_DATAGRAM_SIZE);
/* inform the device about the selected Max Datagram Size? */
if (!(cdc_ncm_flags(dev) & USB_CDC_NCM_NCAP_MAX_DATAGRAM_SIZE))
goto out;
/* read current mtu value from device */
err = usbnet_read_cmd(dev, USB_CDC_GET_MAX_DATAGRAM_SIZE,
USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
0, iface_no, &max_datagram_size, 2);
if (err < 0) {
dev_dbg(&dev->intf->dev, "GET_MAX_DATAGRAM_SIZE failed\n");
goto out;
}
if (le16_to_cpu(max_datagram_size) == ctx->max_datagram_size)
goto out;
max_datagram_size = cpu_to_le16(ctx->max_datagram_size);
err = usbnet_write_cmd(dev, USB_CDC_SET_MAX_DATAGRAM_SIZE,
USB_TYPE_CLASS | USB_DIR_OUT | USB_RECIP_INTERFACE,
0, iface_no, &max_datagram_size, 2);
if (err < 0)
dev_dbg(&dev->intf->dev, "SET_MAX_DATAGRAM_SIZE failed\n");
out:
/* set MTU to max supported by the device if necessary */
dev->net->mtu = min_t(int, dev->net->mtu, ctx->max_datagram_size - cdc_ncm_eth_hlen(dev));
/* do not exceed operater preferred MTU */
if (ctx->mbim_extended_desc) {
mbim_mtu = le16_to_cpu(ctx->mbim_extended_desc->wMTU);
if (mbim_mtu != 0 && mbim_mtu < dev->net->mtu)
dev->net->mtu = mbim_mtu;
}
}
| 0 |
krb5 | 93b4a6306a0026cf1cc31ac4bd8a49ba5d034ba7 | NOT_APPLICABLE | NOT_APPLICABLE | kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code)
return code;
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
| 0 |
psutil | 3a9bccfd2c6d2e6538298cd3892058b1204056e0 | NOT_APPLICABLE | NOT_APPLICABLE | void init_psutil_posix(void)
#endif /* PY_MAJOR_VERSION */
{
#if PY_MAJOR_VERSION >= 3
PyObject *mod = PyModule_Create(&moduledef);
#else
PyObject *mod = Py_InitModule("_psutil_posix", mod_methods);
#endif
if (mod == NULL)
INITERR;
#if defined(PSUTIL_BSD) || defined(PSUTIL_OSX) || defined(PSUTIL_SUNOS) || defined(PSUTIL_AIX)
if (PyModule_AddIntConstant(mod, "AF_LINK", AF_LINK)) INITERR;
#endif
if (mod == NULL)
INITERR;
#if PY_MAJOR_VERSION >= 3
return mod;
#endif
} | 0 |
libavif | 0a8e7244d494ae98e9756355dfbfb6697ded2ff9 | NOT_APPLICABLE | NOT_APPLICABLE | static avifBool avifParseSampleSizeBox(avifSampleTable * sampleTable, const uint8_t * raw, size_t rawLen)
{
BEGIN_STREAM(s, raw, rawLen);
CHECK(avifROStreamReadAndEnforceVersion(&s, 0));
uint32_t allSamplesSize, sampleCount;
CHECK(avifROStreamReadU32(&s, &allSamplesSize)); // unsigned int(32) sample_size;
CHECK(avifROStreamReadU32(&s, &sampleCount)); // unsigned int(32) sample_count;
if (allSamplesSize > 0) {
sampleTable->allSamplesSize = allSamplesSize;
} else {
for (uint32_t i = 0; i < sampleCount; ++i) {
avifSampleTableSampleSize * sampleSize = (avifSampleTableSampleSize *)avifArrayPushPtr(&sampleTable->sampleSizes);
CHECK(avifROStreamReadU32(&s, &sampleSize->size)); // unsigned int(32) entry_size;
}
}
return AVIF_TRUE;
} | 0 |
libsndfile | 708e996c87c5fae77b104ccfeb8f6db784c32074 | NOT_APPLICABLE | NOT_APPLICABLE | format_from_extension (SF_PRIVATE *psf)
{ char *cptr ;
char buffer [16] ;
int format = 0 ;
if ((cptr = strrchr (psf->file.name.c, '.')) == NULL)
return 0 ;
cptr ++ ;
if (strlen (cptr) > sizeof (buffer) - 1)
return 0 ;
psf_strlcpy (buffer, sizeof (buffer), cptr) ;
buffer [sizeof (buffer) - 1] = 0 ;
/* Convert everything in the buffer to lower case. */
cptr = buffer ;
while (*cptr)
{ *cptr = tolower (*cptr) ;
cptr ++ ;
} ;
cptr = buffer ;
if (strcmp (cptr, "au") == 0)
{ psf->sf.channels = 1 ;
psf->sf.samplerate = 8000 ;
format = SF_FORMAT_RAW | SF_FORMAT_ULAW ;
}
else if (strcmp (cptr, "snd") == 0)
{ psf->sf.channels = 1 ;
psf->sf.samplerate = 8000 ;
format = SF_FORMAT_RAW | SF_FORMAT_ULAW ;
}
else if (strcmp (cptr, "vox") == 0 || strcmp (cptr, "vox8") == 0)
{ psf->sf.channels = 1 ;
psf->sf.samplerate = 8000 ;
format = SF_FORMAT_RAW | SF_FORMAT_VOX_ADPCM ;
}
else if (strcmp (cptr, "vox6") == 0)
{ psf->sf.channels = 1 ;
psf->sf.samplerate = 6000 ;
format = SF_FORMAT_RAW | SF_FORMAT_VOX_ADPCM ;
}
else if (strcmp (cptr, "gsm") == 0)
{ psf->sf.channels = 1 ;
psf->sf.samplerate = 8000 ;
format = SF_FORMAT_RAW | SF_FORMAT_GSM610 ;
}
/* For RAW files, make sure the dataoffset if set correctly. */
if ((SF_CONTAINER (format)) == SF_FORMAT_RAW)
psf->dataoffset = 0 ;
return format ;
} /* format_from_extension */
| 0 |
net-next | fdf5af0daf8019cec2396cdef8fb042d80fe71fa | NOT_APPLICABLE | NOT_APPLICABLE | static u8 tcp_sacktag_one(const struct sk_buff *skb, struct sock *sk,
struct tcp_sacktag_state *state,
int dup_sack, int pcount)
{
struct tcp_sock *tp = tcp_sk(sk);
u8 sacked = TCP_SKB_CB(skb)->sacked;
int fack_count = state->fack_count;
/* Account D-SACK for retransmitted packet. */
if (dup_sack && (sacked & TCPCB_RETRANS)) {
if (tp->undo_marker && tp->undo_retrans &&
after(TCP_SKB_CB(skb)->end_seq, tp->undo_marker))
tp->undo_retrans--;
if (sacked & TCPCB_SACKED_ACKED)
state->reord = min(fack_count, state->reord);
}
/* Nothing to do; acked frame is about to be dropped (was ACKed). */
if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
return sacked;
if (!(sacked & TCPCB_SACKED_ACKED)) {
if (sacked & TCPCB_SACKED_RETRANS) {
/* If the segment is not tagged as lost,
* we do not clear RETRANS, believing
* that retransmission is still in flight.
*/
if (sacked & TCPCB_LOST) {
sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
tp->lost_out -= pcount;
tp->retrans_out -= pcount;
}
} else {
if (!(sacked & TCPCB_RETRANS)) {
/* New sack for not retransmitted frame,
* which was in hole. It is reordering.
*/
if (before(TCP_SKB_CB(skb)->seq,
tcp_highest_sack_seq(tp)))
state->reord = min(fack_count,
state->reord);
/* SACK enhanced F-RTO (RFC4138; Appendix B) */
if (!after(TCP_SKB_CB(skb)->end_seq, tp->frto_highmark))
state->flag |= FLAG_ONLY_ORIG_SACKED;
}
if (sacked & TCPCB_LOST) {
sacked &= ~TCPCB_LOST;
tp->lost_out -= pcount;
}
}
sacked |= TCPCB_SACKED_ACKED;
state->flag |= FLAG_DATA_SACKED;
tp->sacked_out += pcount;
fack_count += pcount;
/* Lost marker hint past SACKed? Tweak RFC3517 cnt */
if (!tcp_is_fack(tp) && (tp->lost_skb_hint != NULL) &&
before(TCP_SKB_CB(skb)->seq,
TCP_SKB_CB(tp->lost_skb_hint)->seq))
tp->lost_cnt_hint += pcount;
if (fack_count > tp->fackets_out)
tp->fackets_out = fack_count;
}
/* D-SACK. We can detect redundant retransmission in S|R and plain R
* frames and clear it. undo_retrans is decreased above, L|R frames
* are accounted above as well.
*/
if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
sacked &= ~TCPCB_SACKED_RETRANS;
tp->retrans_out -= pcount;
}
return sacked;
} | 0 |
linux | 854e8bb1aa06c578c2c9145fa6bfe3680ef63b23 | NOT_APPLICABLE | NOT_APPLICABLE | static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK))
return;
clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
if (irr == -1)
return;
if (tpr >= irr)
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
}
| 0 |
Android | 866dc26ad4a98cc835d075b627326e7d7e52ffa1 | NOT_APPLICABLE | NOT_APPLICABLE | bool isJavaClassName(const StringPiece16& str) {
size_t pieces = 0;
for (const StringPiece16& piece : tokenize(str, u'.')) {
pieces++;
if (piece.empty()) {
return false;
}
if (piece.data()[0] == u'$' || piece.data()[piece.size() - 1] == u'$') {
return false;
}
if (findNonAlphaNumericAndNotInSet(piece, u"$_") != piece.end()) {
return false;
}
}
return pieces >= 2;
}
| 0 |
server | af810407f78b7f792a9bb8c47c8c532eb3b3a758 | NOT_APPLICABLE | NOT_APPLICABLE | bool Vers_parse_info::is_start(const Create_field &f) const
{
return f.flags & VERS_ROW_START;
} | 0 |
linux | 0e9a9a1ad619e7e987815d20262d36a2f95717ca | NOT_APPLICABLE | NOT_APPLICABLE | int search_dir(struct buffer_head *bh,
char *search_buf,
int buf_size,
struct inode *dir,
const struct qstr *d_name,
unsigned int offset,
struct ext4_dir_entry_2 **res_dir)
{
struct ext4_dir_entry_2 * de;
char * dlimit;
int de_len;
const char *name = d_name->name;
int namelen = d_name->len;
de = (struct ext4_dir_entry_2 *)search_buf;
dlimit = search_buf + buf_size;
while ((char *) de < dlimit) {
/* this code is executed quadratically often */
/* do minimal checking `by hand' */
if ((char *) de + namelen <= dlimit &&
ext4_match (namelen, name, de)) {
/* found a match - just to be sure, do a full check */
if (ext4_check_dir_entry(dir, NULL, de, bh, bh->b_data,
bh->b_size, offset))
return -1;
*res_dir = de;
return 1;
}
/* prevent looping on a bad block */
de_len = ext4_rec_len_from_disk(de->rec_len,
dir->i_sb->s_blocksize);
if (de_len <= 0)
return -1;
offset += de_len;
de = (struct ext4_dir_entry_2 *) ((char *) de + de_len);
}
return 0;
}
| 0 |
server | 8c34eab9688b4face54f15f89f5d62bdfd93b8a7 | NOT_APPLICABLE | NOT_APPLICABLE | simplify_joins(JOIN *join, List<TABLE_LIST> *join_list, COND *conds, bool top,
bool in_sj)
{
TABLE_LIST *table;
NESTED_JOIN *nested_join;
TABLE_LIST *prev_table= 0;
List_iterator<TABLE_LIST> li(*join_list);
bool straight_join= MY_TEST(join->select_options & SELECT_STRAIGHT_JOIN);
DBUG_ENTER("simplify_joins");
/*
Try to simplify join operations from join_list.
The most outer join operation is checked for conversion first.
*/
while ((table= li++))
{
table_map used_tables;
table_map not_null_tables= (table_map) 0;
if ((nested_join= table->nested_join))
{
/*
If the element of join_list is a nested join apply
the procedure to its nested join list first.
*/
if (table->on_expr)
{
Item *expr= table->on_expr;
/*
If an on expression E is attached to the table,
check all null rejected predicates in this expression.
If such a predicate over an attribute belonging to
an inner table of an embedded outer join is found,
the outer join is converted to an inner join and
the corresponding on expression is added to E.
*/
expr= simplify_joins(join, &nested_join->join_list,
expr, FALSE, in_sj || table->sj_on_expr);
if (!table->prep_on_expr || expr != table->on_expr)
{
DBUG_ASSERT(expr);
table->on_expr= expr;
table->prep_on_expr= expr->copy_andor_structure(join->thd);
}
}
nested_join->used_tables= (table_map) 0;
nested_join->not_null_tables=(table_map) 0;
conds= simplify_joins(join, &nested_join->join_list, conds, top,
in_sj || table->sj_on_expr);
used_tables= nested_join->used_tables;
not_null_tables= nested_join->not_null_tables;
/* The following two might become unequal after table elimination: */
nested_join->n_tables= nested_join->join_list.elements;
}
else
{
if (!table->prep_on_expr)
table->prep_on_expr= table->on_expr;
used_tables= table->get_map();
if (conds)
not_null_tables= conds->not_null_tables();
}
if (table->embedding)
{
table->embedding->nested_join->used_tables|= used_tables;
table->embedding->nested_join->not_null_tables|= not_null_tables;
}
if (!(table->outer_join & (JOIN_TYPE_LEFT | JOIN_TYPE_RIGHT)) ||
(used_tables & not_null_tables))
{
/*
For some of the inner tables there are conjunctive predicates
that reject nulls => the outer join can be replaced by an inner join.
*/
if (table->outer_join && !table->embedding && table->table)
table->table->maybe_null= FALSE;
table->outer_join= 0;
if (!(straight_join || table->straight))
{
table->dep_tables= 0;
TABLE_LIST *embedding= table->embedding;
while (embedding)
{
if (embedding->nested_join->join_list.head()->outer_join)
{
if (!embedding->sj_subq_pred)
table->dep_tables= embedding->dep_tables;
break;
}
embedding= embedding->embedding;
}
}
if (table->on_expr)
{
/* Add ON expression to the WHERE or upper-level ON condition. */
if (conds)
{
conds= and_conds(join->thd, conds, table->on_expr);
conds->top_level_item();
/* conds is always a new item as both cond and on_expr existed */
DBUG_ASSERT(!conds->is_fixed());
conds->fix_fields(join->thd, &conds);
}
else
conds= table->on_expr;
table->prep_on_expr= table->on_expr= 0;
}
}
/*
Only inner tables of non-convertible outer joins
remain with on_expr.
*/
if (table->on_expr)
{
table_map table_on_expr_used_tables= table->on_expr->used_tables();
table->dep_tables|= table_on_expr_used_tables;
if (table->embedding)
{
table->dep_tables&= ~table->embedding->nested_join->used_tables;
/*
Embedding table depends on tables used
in embedded on expressions.
*/
table->embedding->on_expr_dep_tables|= table_on_expr_used_tables;
}
else
table->dep_tables&= ~table->get_map();
}
if (prev_table)
{
/* The order of tables is reverse: prev_table follows table */
if (prev_table->straight || straight_join)
prev_table->dep_tables|= used_tables;
if (prev_table->on_expr)
{
prev_table->dep_tables|= table->on_expr_dep_tables;
table_map prev_used_tables= prev_table->nested_join ?
prev_table->nested_join->used_tables :
prev_table->get_map();
/*
If on expression contains only references to inner tables
we still make the inner tables dependent on the outer tables.
It would be enough to set dependency only on one outer table
for them. Yet this is really a rare case.
Note:
RAND_TABLE_BIT mask should not be counted as it
prevents update of inner table dependences.
For example it might happen if RAND() function
is used in JOIN ON clause.
*/
if (!((prev_table->on_expr->used_tables() &
~(OUTER_REF_TABLE_BIT | RAND_TABLE_BIT)) &
~prev_used_tables))
prev_table->dep_tables|= used_tables;
}
}
prev_table= table;
}
/*
Flatten nested joins that can be flattened.
no ON expression and not a semi-join => can be flattened.
*/
li.rewind();
while ((table= li++))
{
nested_join= table->nested_join;
if (table->sj_on_expr && !in_sj)
{
/*
If this is a semi-join that is not contained within another semi-join
leave it intact (otherwise it is flattened)
*/
/*
Make sure that any semi-join appear in
the join->select_lex->sj_nests list only once
*/
List_iterator_fast<TABLE_LIST> sj_it(join->select_lex->sj_nests);
TABLE_LIST *sj_nest;
while ((sj_nest= sj_it++))
{
if (table == sj_nest)
break;
}
if (sj_nest)
continue;
join->select_lex->sj_nests.push_back(table, join->thd->mem_root);
/*
Also, walk through semi-join children and mark those that are now
top-level
*/
TABLE_LIST *tbl;
List_iterator<TABLE_LIST> it(nested_join->join_list);
while ((tbl= it++))
{
if (!tbl->on_expr && tbl->table)
tbl->table->maybe_null= FALSE;
}
}
else if (nested_join && !table->on_expr)
{
TABLE_LIST *tbl;
List_iterator<TABLE_LIST> it(nested_join->join_list);
List<TABLE_LIST> repl_list;
while ((tbl= it++))
{
tbl->embedding= table->embedding;
if (!tbl->embedding && !tbl->on_expr && tbl->table)
tbl->table->maybe_null= FALSE;
tbl->join_list= table->join_list;
repl_list.push_back(tbl, join->thd->mem_root);
tbl->dep_tables|= table->dep_tables;
}
li.replace(repl_list);
}
}
DBUG_RETURN(conds);
} | 0 |
php | 124fb22a13fafa3648e4e15b4f207c7096d8155e | NOT_APPLICABLE | NOT_APPLICABLE | static int _rollback_transactions(zval *el)
{
PGconn *link;
PGresult *res;
int orig;
zend_resource *rsrc = Z_RES_P(el);
if (rsrc->type != le_plink)
return 0;
link = (PGconn *) rsrc->ptr;
if (PQ_SETNONBLOCKING(link, 0)) {
php_error_docref("ref.pgsql", E_NOTICE, "Cannot set connection to blocking mode");
return -1;
}
while ((res = PQgetResult(link))) {
PQclear(res);
}
#if HAVE_PGTRANSACTIONSTATUS && HAVE_PQPROTOCOLVERSION
if ((PQprotocolVersion(link) >= 3 && PQtransactionStatus(link) != PQTRANS_IDLE) || PQprotocolVersion(link) < 3)
#endif
{
orig = PGG(ignore_notices);
PGG(ignore_notices) = 1;
#if HAVE_PGTRANSACTIONSTATUS && HAVE_PQPROTOCOLVERSION
res = PQexec(link,"ROLLBACK;");
#else
res = PQexec(link,"BEGIN;");
PQclear(res);
res = PQexec(link,"ROLLBACK;");
#endif
PQclear(res);
PGG(ignore_notices) = orig;
}
return 0;
}
| 0 |
openssl | fa57f74a3941db6b2efb2f43c6add914ec83db20 | NOT_APPLICABLE | NOT_APPLICABLE | static int check_revocation(X509_STORE_CTX *ctx)
{
int i, last, ok;
if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
return 1;
if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
last = sk_X509_num(ctx->chain) - 1;
else
last = 0;
for (i = 0; i <= last; i++) {
ctx->error_depth = i;
ok = check_cert(ctx);
if (!ok)
return ok;
}
return 1;
} | 0 |
Chrome | 244c78b3f737f2cacab2d212801b0524cbcc3a7b | CVE-2011-2880 | CWE-399 | void CloudPolicySubsystem::StopAutoRetry() {
cloud_policy_controller_->StopAutoRetry();
device_token_fetcher_->StopAutoRetry();
data_store_->Reset();
}
| 1 |
rufus | c3c39f7f8a11f612c4ebf7affce25ec6928eb1cb | NOT_APPLICABLE | NOT_APPLICABLE | INT_PTR CALLBACK UpdateCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
int dy;
RECT rect;
REQRESIZE* rsz;
HWND hPolicy;
static HWND hFrequency, hBeta;
int32_t freq;
char update_policy_text[4096];
static BOOL resized_already = TRUE;
switch (message) {
case WM_INITDIALOG:
resized_already = FALSE;
hUpdatesDlg = hDlg;
apply_localization(IDD_UPDATE_POLICY, hDlg);
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
hFrequency = GetDlgItem(hDlg, IDC_UPDATE_FREQUENCY);
hBeta = GetDlgItem(hDlg, IDC_INCLUDE_BETAS);
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_013)), -1));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_030, lmprintf(MSG_014))), 86400));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_015)), 604800));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_016)), 2629800));
freq = ReadSetting32(SETTING_UPDATE_INTERVAL);
EnableWindow(GetDlgItem(hDlg, IDC_CHECK_NOW), (freq != 0));
EnableWindow(hBeta, (freq >= 0));
switch(freq) {
case -1:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 0));
break;
case 0:
case 86400:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 1));
break;
case 604800:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 2));
break;
case 2629800:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 3));
break;
default:
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_017)), freq));
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 4));
break;
}
IGNORE_RETVAL(ComboBox_AddStringU(hBeta, lmprintf(MSG_008)));
IGNORE_RETVAL(ComboBox_AddStringU(hBeta, lmprintf(MSG_009)));
IGNORE_RETVAL(ComboBox_SetCurSel(hBeta, ReadSettingBool(SETTING_INCLUDE_BETAS)?0:1));
hPolicy = GetDlgItem(hDlg, IDC_POLICY);
SendMessage(hPolicy, EM_AUTOURLDETECT, 1, 0);
static_sprintf(update_policy_text, update_policy, lmprintf(MSG_179|MSG_RTF),
lmprintf(MSG_180|MSG_RTF), lmprintf(MSG_181|MSG_RTF), lmprintf(MSG_182|MSG_RTF), lmprintf(MSG_183|MSG_RTF),
lmprintf(MSG_184|MSG_RTF), lmprintf(MSG_185|MSG_RTF), lmprintf(MSG_186|MSG_RTF));
SendMessageA(hPolicy, EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)update_policy_text);
SendMessage(hPolicy, EM_SETSEL, -1, -1);
SendMessage(hPolicy, EM_SETEVENTMASK, 0, ENM_LINK|ENM_REQUESTRESIZE);
SendMessageA(hPolicy, EM_SETBKGNDCOLOR, 0, (LPARAM)GetSysColor(COLOR_BTNFACE));
SendMessage(hPolicy, EM_REQUESTRESIZE, 0, 0);
break;
case WM_NOTIFY:
if ((((LPNMHDR)lParam)->code == EN_REQUESTRESIZE) && (!resized_already)) {
resized_already = TRUE;
hPolicy = GetDlgItem(hDlg, IDC_POLICY);
GetWindowRect(hPolicy, &rect);
dy = rect.bottom - rect.top;
rsz = (REQRESIZE *)lParam;
dy -= rsz->rc.bottom - rsz->rc.top + 6; // add the border
ResizeMoveCtrl(hDlg, hDlg, 0, 0, 0, -dy, 1.0f);
ResizeMoveCtrl(hDlg, hPolicy, 0, 0, 0, -dy, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_UPDATE_SETTINGS_GRP), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_UPDATE_FREQUENCY_TXT), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_UPDATE_FREQUENCY), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_INCLUDE_BETAS_TXT), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_INCLUDE_BETAS), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_CHECK_NOW_GRP), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_CHECK_NOW), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDCANCEL), 0, -dy, 0, 0, 1.0f);
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDCLOSE:
case IDCANCEL:
reset_localization(IDD_UPDATE_POLICY);
EndDialog(hDlg, LOWORD(wParam));
hUpdatesDlg = NULL;
return (INT_PTR)TRUE;
case IDC_CHECK_NOW:
CheckForUpdates(TRUE);
return (INT_PTR)TRUE;
case IDC_UPDATE_FREQUENCY:
if (HIWORD(wParam) != CBN_SELCHANGE)
break;
freq = (int32_t)ComboBox_GetItemData(hFrequency, ComboBox_GetCurSel(hFrequency));
WriteSetting32(SETTING_UPDATE_INTERVAL, (DWORD)freq);
EnableWindow(hBeta, (freq >= 0));
return (INT_PTR)TRUE;
case IDC_INCLUDE_BETAS:
if (HIWORD(wParam) != CBN_SELCHANGE)
break;
WriteSettingBool(SETTING_INCLUDE_BETAS, ComboBox_GetCurSel(hBeta) == 0);
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| 0 |
libxml2 | bdd66182ef53fe1f7209ab6535fda56366bd7ac9 | CVE-2016-3627 | CWE-20 | xmlStringGetNodeList(const xmlDoc *doc, const xmlChar *value) {
xmlNodePtr ret = NULL, last = NULL;
xmlNodePtr node;
xmlChar *val;
const xmlChar *cur = value;
const xmlChar *q;
xmlEntityPtr ent;
xmlBufPtr buf;
if (value == NULL) return(NULL);
buf = xmlBufCreateSize(0);
if (buf == NULL) return(NULL);
xmlBufSetAllocationScheme(buf, XML_BUFFER_ALLOC_HYBRID);
q = cur;
while (*cur != 0) {
if (cur[0] == '&') {
int charval = 0;
xmlChar tmp;
/*
* Save the current text.
*/
if (cur != q) {
if (xmlBufAdd(buf, q, cur - q))
goto out;
}
q = cur;
if ((cur[1] == '#') && (cur[2] == 'x')) {
cur += 3;
tmp = *cur;
while (tmp != ';') { /* Non input consuming loop */
if ((tmp >= '0') && (tmp <= '9'))
charval = charval * 16 + (tmp - '0');
else if ((tmp >= 'a') && (tmp <= 'f'))
charval = charval * 16 + (tmp - 'a') + 10;
else if ((tmp >= 'A') && (tmp <= 'F'))
charval = charval * 16 + (tmp - 'A') + 10;
else {
xmlTreeErr(XML_TREE_INVALID_HEX, (xmlNodePtr) doc,
NULL);
charval = 0;
break;
}
cur++;
tmp = *cur;
}
if (tmp == ';')
cur++;
q = cur;
} else if (cur[1] == '#') {
cur += 2;
tmp = *cur;
while (tmp != ';') { /* Non input consuming loops */
if ((tmp >= '0') && (tmp <= '9'))
charval = charval * 10 + (tmp - '0');
else {
xmlTreeErr(XML_TREE_INVALID_DEC, (xmlNodePtr) doc,
NULL);
charval = 0;
break;
}
cur++;
tmp = *cur;
}
if (tmp == ';')
cur++;
q = cur;
} else {
/*
* Read the entity string
*/
cur++;
q = cur;
while ((*cur != 0) && (*cur != ';')) cur++;
if (*cur == 0) {
xmlTreeErr(XML_TREE_UNTERMINATED_ENTITY,
(xmlNodePtr) doc, (const char *) q);
goto out;
}
if (cur != q) {
/*
* Predefined entities don't generate nodes
*/
val = xmlStrndup(q, cur - q);
ent = xmlGetDocEntity(doc, val);
if ((ent != NULL) &&
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
if (xmlBufCat(buf, ent->content))
goto out;
} else {
/*
* Flush buffer so far
*/
if (!xmlBufIsEmpty(buf)) {
node = xmlNewDocText(doc, NULL);
node->content = xmlBufDetach(buf);
if (last == NULL) {
last = ret = node;
} else {
last = xmlAddNextSibling(last, node);
}
}
/*
* Create a new REFERENCE_REF node
*/
node = xmlNewReference(doc, val);
if (node == NULL) {
if (val != NULL) xmlFree(val);
goto out;
}
else if ((ent != NULL) && (ent->children == NULL)) {
xmlNodePtr temp;
ent->children = xmlStringGetNodeList(doc,
(const xmlChar*)node->content);
ent->owner = 1;
temp = ent->children;
while (temp) {
temp->parent = (xmlNodePtr)ent;
temp = temp->next;
}
}
if (last == NULL) {
last = ret = node;
} else {
last = xmlAddNextSibling(last, node);
}
}
xmlFree(val);
}
cur++;
q = cur;
}
if (charval != 0) {
xmlChar buffer[10];
int len;
len = xmlCopyCharMultiByte(buffer, charval);
buffer[len] = 0;
if (xmlBufCat(buf, buffer))
goto out;
charval = 0;
}
} else
cur++;
}
if ((cur != q) || (ret == NULL)) {
/*
* Handle the last piece of text.
*/
xmlBufAdd(buf, q, cur - q);
}
if (!xmlBufIsEmpty(buf)) {
node = xmlNewDocText(doc, NULL);
node->content = xmlBufDetach(buf);
if (last == NULL) {
ret = node;
} else {
xmlAddNextSibling(last, node);
}
}
out:
xmlBufFree(buf);
return(ret);
} | 1 |
jsish | 858da537bde4de9d8c92466d5a866505310bc328 | NOT_APPLICABLE | NOT_APPLICABLE | Jsi_EnumSpec *jsi_csEnumGet(Jsi_Interp *interp, const char *name)
{
Jsi_EnumSpec *sl, *spec = jsi_csGetEnum(interp, name);
if (spec) return spec;
Jsi_CData_Static *CData_Strs = interp->statics;
while (CData_Strs) {
sl = CData_Strs->enums;
while (sl->name) {
if (!Jsi_Strcmp(name, sl->name))
return sl;
sl++;
}
CData_Strs = CData_Strs->nextPtr;
}
return NULL;
} | 0 |
xserver | 3f0d3f4d97bce75c1828635c322b6560a45a037f | NOT_APPLICABLE | NOT_APPLICABLE | validGlxFBConfig(ClientPtr client, __GLXscreen *pGlxScreen, XID id,
__GLXconfig **config, int *err)
{
__GLXconfig *m;
for (m = pGlxScreen->fbconfigs; m != NULL; m = m->next)
if (m->fbconfigID == id) {
*config = m;
return TRUE;
}
client->errorValue = id;
*err = __glXError(GLXBadFBConfig);
return FALSE;
}
| 0 |
sysstat | 44c826602a3d7d899c728bd9e6c3488397c5009f | NOT_APPLICABLE | NOT_APPLICABLE | int get_svg_graph_nr(int ifd, char *file, struct file_magic *file_magic,
struct file_activity *file_actlst, struct tm *rectime,
int *views_per_row, int *nr_act_dispd)
{
int i, n, p, tot_g_nr = 0;
*nr_act_dispd = 0;
/* Count items in file */
if (!count_file_items(ifd, file, file_magic, file_actlst, rectime))
/* No record to display => No graph */
return 0;
for (i = 0; i < NR_ACT; i++) {
if (!id_seq[i])
continue;
p = get_activity_position(act, id_seq[i], EXIT_IF_NOT_FOUND);
if (!IS_SELECTED(act[p]->options) || !act[p]->g_nr)
continue;
(*nr_act_dispd)++;
if (PACK_VIEWS(flags)) {
/*
* One activity = one row with multiple views.
* Exception is A_MEMORY, for which one activity may be
* displayed in two rows if both memory *and* swap utilization
* have been selected.
*/
if ((act[p]->id == A_MEMORY) &&
(DISPLAY_MEMORY(act[p]->opt_flags) && DISPLAY_SWAP(act[p]->opt_flags))) {
n = 2;
}
else {
n = 1;
}
}
else {
/* One activity = multiple rows with only one view */
n = act[p]->g_nr;
}
if (ONE_GRAPH_PER_ITEM(act[p]->options)) {
n = n * act[p]->item_list_sz;
}
if (act[p]->g_nr > *views_per_row) {
*views_per_row = act[p]->g_nr;
}
tot_g_nr += n;
}
if (*views_per_row > MAX_VIEWS_ON_A_ROW) {
*views_per_row = MAX_VIEWS_ON_A_ROW;
}
return tot_g_nr;
} | 0 |
git | b44ebb19e3234c5dffe9869ceac5408bb44c2e20 | NOT_APPLICABLE | NOT_APPLICABLE | const char *setup_git_directory_gently(int *nongit_ok)
{
const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
static char cwd[PATH_MAX+1];
const char *gitdirenv;
const char *gitfile_dir;
int len, offset;
/*
* Let's assume that we are in a git repository.
* If it turns out later that we are somewhere else, the value will be
* updated accordingly.
*/
if (nongit_ok)
*nongit_ok = 0;
/*
* If GIT_DIR is set explicitly, we're not going
* to do any discovery, but we still do repository
* validation.
*/
gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
if (gitdirenv) {
if (PATH_MAX - 40 < strlen(gitdirenv))
die("'$%s' too big", GIT_DIR_ENVIRONMENT);
if (is_git_directory(gitdirenv)) {
static char buffer[1024 + 1];
const char *retval;
if (!work_tree_env) {
retval = set_work_tree(gitdirenv);
/* config may override worktree */
if (check_repository_format_gently(nongit_ok))
return NULL;
return retval;
}
if (check_repository_format_gently(nongit_ok))
return NULL;
retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
get_git_work_tree());
if (!retval || !*retval)
return NULL;
set_git_dir(make_absolute_path(gitdirenv));
if (chdir(work_tree_env) < 0)
die ("Could not chdir to %s", work_tree_env);
strcat(buffer, "/");
return retval;
}
if (nongit_ok) {
*nongit_ok = 1;
return NULL;
}
die("Not a git repository: '%s'", gitdirenv);
}
if (!getcwd(cwd, sizeof(cwd)-1))
die("Unable to read current working directory");
/*
* Test in the following order (relative to the cwd):
* - .git (file containing "gitdir: <path>")
* - .git/
* - ./ (bare)
* - ../.git
* - ../.git/
* - ../ (bare)
* - ../../.git/
* etc.
*/
offset = len = strlen(cwd);
for (;;) {
gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
if (gitfile_dir) {
if (set_git_dir(gitfile_dir))
die("Repository setup failed");
break;
}
if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
break;
if (is_git_directory(".")) {
inside_git_dir = 1;
if (!work_tree_env)
inside_work_tree = 0;
setenv(GIT_DIR_ENVIRONMENT, ".", 1);
check_repository_format_gently(nongit_ok);
return NULL;
}
chdir("..");
do {
if (!offset) {
if (nongit_ok) {
if (chdir(cwd))
die("Cannot come back to cwd");
*nongit_ok = 1;
return NULL;
}
die("Not a git repository");
}
} while (cwd[--offset] != '/');
}
inside_git_dir = 0;
if (!work_tree_env)
inside_work_tree = 1;
git_work_tree_cfg = xstrndup(cwd, offset);
if (check_repository_format_gently(nongit_ok))
return NULL;
if (offset == len)
return NULL;
/* Make "offset" point to past the '/', and add a '/' at the end */
offset++;
cwd[len++] = '/';
cwd[len] = 0;
return cwd + offset;
} | 0 |
FreeRDP | 2ee663f39dc8dac3d9988e847db19b2d7e3ac8c6 | CVE-2018-8789 | CWE-125 | int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
if ((fields->BufferOffset + fields->Len) > Stream_Length(s))
return -1;
fields->Buffer = (PBYTE) malloc(fields->Len);
if (!fields->Buffer)
return -1;
Stream_SetPosition(s, fields->BufferOffset);
Stream_Read(s, fields->Buffer, fields->Len);
}
return 1;
}
| 1 |
gnutls | d6972be33264ecc49a86cd0958209cd7363af1e9 | NOT_APPLICABLE | NOT_APPLICABLE | int gnutls_x509_policies_init(gnutls_x509_policies_t * policies)
{
*policies = gnutls_calloc(1, sizeof(struct gnutls_x509_policies_st));
if (*policies == NULL)
return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
return 0;
} | 0 |
Chrome | 18c5c5dcef9cfccff64f0c23f920ef22822271a9 | NOT_APPLICABLE | NOT_APPLICABLE | void ChromeContentBrowserClient::RenderProcessWillLaunch(
content::RenderProcessHost* host,
service_manager::mojom::ServiceRequest* service_request) {
int id = host->GetID();
Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
host->AddFilter(new ChromeRenderMessageFilter(id, profile));
#if BUILDFLAG(ENABLE_EXTENSIONS)
host->AddFilter(new cast::CastTransportHostFilter(profile));
#endif
#if BUILDFLAG(ENABLE_PRINTING)
host->AddFilter(new printing::PrintingMessageFilter(id, profile));
#endif
host->AddFilter(new prerender::PrerenderMessageFilter(id, profile));
host->AddFilter(new TtsMessageFilter(host->GetBrowserContext()));
WebRtcLoggingHandlerHost* webrtc_logging_handler_host =
new WebRtcLoggingHandlerHost(id, profile,
g_browser_process->webrtc_log_uploader());
host->AddFilter(webrtc_logging_handler_host);
host->SetUserData(
WebRtcLoggingHandlerHost::kWebRtcLoggingHandlerHostKey,
std::make_unique<base::UserDataAdapter<WebRtcLoggingHandlerHost>>(
webrtc_logging_handler_host));
AudioDebugRecordingsHandler* audio_debug_recordings_handler =
new AudioDebugRecordingsHandler(profile);
host->SetUserData(
AudioDebugRecordingsHandler::kAudioDebugRecordingsHandlerKey,
std::make_unique<base::UserDataAdapter<AudioDebugRecordingsHandler>>(
audio_debug_recordings_handler));
#if BUILDFLAG(ENABLE_NACL)
host->AddFilter(new nacl::NaClHostMessageFilter(id, profile->IsOffTheRecord(),
profile->GetPath()));
#endif
#if defined(OS_ANDROID)
host->AddFilter(
new cdm::CdmMessageFilterAndroid(!profile->IsOffTheRecord(), false));
host->SetUserData(
CrashMemoryMetricsCollector::kCrashMemoryMetricsCollectorKey,
std::make_unique<CrashMemoryMetricsCollector>(host));
#endif
Profile* original_profile = profile->GetOriginalProfile();
RendererUpdaterFactory::GetForProfile(original_profile)
->InitializeRenderer(host);
for (size_t i = 0; i < extra_parts_.size(); ++i)
extra_parts_[i]->RenderProcessWillLaunch(host);
service_manager::mojom::ServicePtr service;
*service_request = mojo::MakeRequest(&service);
service_manager::mojom::PIDReceiverPtr pid_receiver;
service_manager::Identity renderer_identity = host->GetChildIdentity();
ChromeService::GetInstance()->connector()->RegisterServiceInstance(
service_manager::Identity(chrome::mojom::kRendererServiceName,
renderer_identity.instance_group(),
renderer_identity.instance_id(),
base::Token::CreateRandom()),
std::move(service), mojo::MakeRequest(&pid_receiver));
}
| 0 |
linux | 2def2ef2ae5f3990aabdbe8a755911902707d268 | NOT_APPLICABLE | NOT_APPLICABLE | static int do_get_sock_timeout(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct compat_timeval __user *up;
struct timeval ktime;
mm_segment_t old_fs;
int len, err;
up = (struct compat_timeval __user *) optval;
if (get_user(len, optlen))
return -EFAULT;
if (len < sizeof(*up))
return -EINVAL;
len = sizeof(ktime);
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sock_getsockopt(sock, level, optname, (char *) &ktime, &len);
set_fs(old_fs);
if (!err) {
if (put_user(sizeof(*up), optlen) ||
!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
__put_user(ktime.tv_sec, &up->tv_sec) ||
__put_user(ktime.tv_usec, &up->tv_usec))
err = -EFAULT;
}
return err;
}
| 0 |
linux | 2a8859f373b0a86f0ece8ec8312607eacf12485d | NOT_APPLICABLE | NOT_APPLICABLE | static bool FNAME(gpte_changed)(struct kvm_vcpu *vcpu,
struct guest_walker *gw, int level)
{
pt_element_t curr_pte;
gpa_t base_gpa, pte_gpa = gw->pte_gpa[level - 1];
u64 mask;
int r, index;
if (level == PG_LEVEL_4K) {
mask = PTE_PREFETCH_NUM * sizeof(pt_element_t) - 1;
base_gpa = pte_gpa & ~mask;
index = (pte_gpa - base_gpa) / sizeof(pt_element_t);
r = kvm_vcpu_read_guest_atomic(vcpu, base_gpa,
gw->prefetch_ptes, sizeof(gw->prefetch_ptes));
curr_pte = gw->prefetch_ptes[index];
} else
r = kvm_vcpu_read_guest_atomic(vcpu, pte_gpa,
&curr_pte, sizeof(curr_pte));
return r || curr_pte != gw->ptes[level - 1];
} | 0 |
pesign | 12f16710ee44ef64ddb044a3523c3c4c4d90039a | NOT_APPLICABLE | NOT_APPLICABLE | generate_common_name(cms_context *cms, SECItem *der, char *cn_str)
{
CommonName cn;
SECItem cn_item;
int rc;
rc = generate_object_id(cms, &cn.oid, SEC_OID_AVA_COMMON_NAME);
if (rc < 0)
return rc;
rc = generate_string(cms, &cn.string, cn_str);
if (rc < 0)
return rc;
void *ret;
ret = SEC_ASN1EncodeItem(cms->arena, &cn_item, &cn, CommonNameTemplate);
if (ret == NULL)
cmsreterr(-1, cms, "could not encode common name");
SECItem cn_set;
SECItem *items[2] = {&cn_item, NULL};
rc = wrap_in_set(cms, &cn_set, items);
if (rc < 0)
return rc;
rc = wrap_in_seq(cms, der, &cn_set, 1);
if (rc < 0)
return rc;
return 0;
} | 0 |
linux | 93c647643b48f0131f02e45da3bd367d80443291 | NOT_APPLICABLE | NOT_APPLICABLE | static void deferred_put_nlk_sk(struct rcu_head *head)
{
struct netlink_sock *nlk = container_of(head, struct netlink_sock, rcu);
struct sock *sk = &nlk->sk;
kfree(nlk->groups);
nlk->groups = NULL;
if (!refcount_dec_and_test(&sk->sk_refcnt))
return;
if (nlk->cb_running && nlk->cb.done) {
INIT_WORK(&nlk->work, netlink_sock_destruct_work);
schedule_work(&nlk->work);
return;
}
sk_free(sk);
} | 0 |
linux | 8914a595110a6eca69a5e275b323f5d09e18f4f9 | NOT_APPLICABLE | NOT_APPLICABLE | static void bnx2x_handle_afex_cmd(struct bnx2x *bp, u32 cmd)
{
struct afex_stats afex_stats;
u32 func = BP_ABS_FUNC(bp);
u32 mf_config;
u16 vlan_val;
u32 vlan_prio;
u16 vif_id;
u8 allowed_prio;
u8 vlan_mode;
u32 addr_to_write, vifid, addrs, stats_type, i;
if (cmd & DRV_STATUS_AFEX_LISTGET_REQ) {
vifid = SHMEM2_RD(bp, afex_param1_to_driver[BP_FW_MB_IDX(bp)]);
DP(BNX2X_MSG_MCP,
"afex: got MCP req LISTGET_REQ for vifid 0x%x\n", vifid);
bnx2x_afex_handle_vif_list_cmd(bp, VIF_LIST_RULE_GET, vifid, 0);
}
if (cmd & DRV_STATUS_AFEX_LISTSET_REQ) {
vifid = SHMEM2_RD(bp, afex_param1_to_driver[BP_FW_MB_IDX(bp)]);
addrs = SHMEM2_RD(bp, afex_param2_to_driver[BP_FW_MB_IDX(bp)]);
DP(BNX2X_MSG_MCP,
"afex: got MCP req LISTSET_REQ for vifid 0x%x addrs 0x%x\n",
vifid, addrs);
bnx2x_afex_handle_vif_list_cmd(bp, VIF_LIST_RULE_SET, vifid,
addrs);
}
if (cmd & DRV_STATUS_AFEX_STATSGET_REQ) {
addr_to_write = SHMEM2_RD(bp,
afex_scratchpad_addr_to_write[BP_FW_MB_IDX(bp)]);
stats_type = SHMEM2_RD(bp,
afex_param1_to_driver[BP_FW_MB_IDX(bp)]);
DP(BNX2X_MSG_MCP,
"afex: got MCP req STATSGET_REQ, write to addr 0x%x\n",
addr_to_write);
bnx2x_afex_collect_stats(bp, (void *)&afex_stats, stats_type);
/* write response to scratchpad, for MCP */
for (i = 0; i < (sizeof(struct afex_stats)/sizeof(u32)); i++)
REG_WR(bp, addr_to_write + i*sizeof(u32),
*(((u32 *)(&afex_stats))+i));
/* send ack message to MCP */
bnx2x_fw_command(bp, DRV_MSG_CODE_AFEX_STATSGET_ACK, 0);
}
if (cmd & DRV_STATUS_AFEX_VIFSET_REQ) {
mf_config = MF_CFG_RD(bp, func_mf_config[func].config);
bp->mf_config[BP_VN(bp)] = mf_config;
DP(BNX2X_MSG_MCP,
"afex: got MCP req VIFSET_REQ, mf_config 0x%x\n",
mf_config);
/* if VIF_SET is "enabled" */
if (!(mf_config & FUNC_MF_CFG_FUNC_DISABLED)) {
/* set rate limit directly to internal RAM */
struct cmng_init_input cmng_input;
struct rate_shaping_vars_per_vn m_rs_vn;
size_t size = sizeof(struct rate_shaping_vars_per_vn);
u32 addr = BAR_XSTRORM_INTMEM +
XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(BP_FUNC(bp));
bp->mf_config[BP_VN(bp)] = mf_config;
bnx2x_calc_vn_max(bp, BP_VN(bp), &cmng_input);
m_rs_vn.vn_counter.rate =
cmng_input.vnic_max_rate[BP_VN(bp)];
m_rs_vn.vn_counter.quota =
(m_rs_vn.vn_counter.rate *
RS_PERIODIC_TIMEOUT_USEC) / 8;
__storm_memset_struct(bp, addr, size, (u32 *)&m_rs_vn);
/* read relevant values from mf_cfg struct in shmem */
vif_id =
(MF_CFG_RD(bp, func_mf_config[func].e1hov_tag) &
FUNC_MF_CFG_E1HOV_TAG_MASK) >>
FUNC_MF_CFG_E1HOV_TAG_SHIFT;
vlan_val =
(MF_CFG_RD(bp, func_mf_config[func].e1hov_tag) &
FUNC_MF_CFG_AFEX_VLAN_MASK) >>
FUNC_MF_CFG_AFEX_VLAN_SHIFT;
vlan_prio = (mf_config &
FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT;
vlan_val |= (vlan_prio << VLAN_PRIO_SHIFT);
vlan_mode =
(MF_CFG_RD(bp,
func_mf_config[func].afex_config) &
FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT;
allowed_prio =
(MF_CFG_RD(bp,
func_mf_config[func].afex_config) &
FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT;
/* send ramrod to FW, return in case of failure */
if (bnx2x_afex_func_update(bp, vif_id, vlan_val,
allowed_prio))
return;
bp->afex_def_vlan_tag = vlan_val;
bp->afex_vlan_mode = vlan_mode;
} else {
/* notify link down because BP->flags is disabled */
bnx2x_link_report(bp);
/* send INVALID VIF ramrod to FW */
bnx2x_afex_func_update(bp, 0xFFFF, 0, 0);
/* Reset the default afex VLAN */
bp->afex_def_vlan_tag = -1;
}
}
} | 0 |
Chrome | ce1446c00f0fd8f5a3b00727421be2124cb7370f | NOT_APPLICABLE | NOT_APPLICABLE | htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) {
if (ctxt->instate == XML_PARSER_EOF)
return(0);
if (ctxt->token != 0) {
*len = 0;
return(ctxt->token);
}
if (ctxt->charset == XML_CHAR_ENCODING_UTF8) {
/*
* We are supposed to handle UTF8, check it's valid
* From rfc2044: encoding of the Unicode values on UTF-8:
*
* UCS-4 range (hex.) UTF-8 octet sequence (binary)
* 0000 0000-0000 007F 0xxxxxxx
* 0000 0080-0000 07FF 110xxxxx 10xxxxxx
* 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
*
* Check for the 0x110000 limit too
*/
const unsigned char *cur = ctxt->input->cur;
unsigned char c;
unsigned int val;
c = *cur;
if (c & 0x80) {
if (cur[1] == 0) {
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
cur = ctxt->input->cur;
}
if ((cur[1] & 0xc0) != 0x80)
goto encoding_error;
if ((c & 0xe0) == 0xe0) {
if (cur[2] == 0) {
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
cur = ctxt->input->cur;
}
if ((cur[2] & 0xc0) != 0x80)
goto encoding_error;
if ((c & 0xf0) == 0xf0) {
if (cur[3] == 0) {
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
cur = ctxt->input->cur;
}
if (((c & 0xf8) != 0xf0) ||
((cur[3] & 0xc0) != 0x80))
goto encoding_error;
/* 4-byte code */
*len = 4;
val = (cur[0] & 0x7) << 18;
val |= (cur[1] & 0x3f) << 12;
val |= (cur[2] & 0x3f) << 6;
val |= cur[3] & 0x3f;
} else {
/* 3-byte code */
*len = 3;
val = (cur[0] & 0xf) << 12;
val |= (cur[1] & 0x3f) << 6;
val |= cur[2] & 0x3f;
}
} else {
/* 2-byte code */
*len = 2;
val = (cur[0] & 0x1f) << 6;
val |= cur[1] & 0x3f;
}
if (!IS_CHAR(val)) {
htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
"Char 0x%X out of allowed range\n", val);
}
return(val);
} else {
if ((*ctxt->input->cur == 0) &&
(ctxt->input->cur < ctxt->input->end)) {
htmlParseErrInt(ctxt, XML_ERR_INVALID_CHAR,
"Char 0x%X out of allowed range\n", 0);
*len = 1;
return(' ');
}
/* 1-byte code */
*len = 1;
return((int) *ctxt->input->cur);
}
}
/*
* Assume it's a fixed length encoding (1) with
* a compatible encoding for the ASCII set, since
* XML constructs only use < 128 chars
*/
*len = 1;
if ((int) *ctxt->input->cur < 0x80)
return((int) *ctxt->input->cur);
/*
* Humm this is bad, do an automatic flow conversion
*/
{
xmlChar * guess;
xmlCharEncodingHandlerPtr handler;
guess = htmlFindEncoding(ctxt);
if (guess == NULL) {
xmlSwitchEncoding(ctxt, XML_CHAR_ENCODING_8859_1);
} else {
if (ctxt->input->encoding != NULL)
xmlFree((xmlChar *) ctxt->input->encoding);
ctxt->input->encoding = guess;
handler = xmlFindCharEncodingHandler((const char *) guess);
if (handler != NULL) {
xmlSwitchToEncoding(ctxt, handler);
} else {
htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING,
"Unsupported encoding %s", guess, NULL);
}
}
ctxt->charset = XML_CHAR_ENCODING_UTF8;
}
return(xmlCurrentChar(ctxt, len));
encoding_error:
/*
* If we detect an UTF8 error that probably mean that the
* input encoding didn't get properly advertized in the
* declaration header. Report the error and switch the encoding
* to ISO-Latin-1 (if you don't like this policy, just declare the
* encoding !)
*/
{
char buffer[150];
if (ctxt->input->end - ctxt->input->cur >= 4) {
snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n",
ctxt->input->cur[0], ctxt->input->cur[1],
ctxt->input->cur[2], ctxt->input->cur[3]);
} else {
snprintf(buffer, 149, "Bytes: 0x%02X\n", ctxt->input->cur[0]);
}
htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING,
"Input is not proper UTF-8, indicate encoding !\n",
BAD_CAST buffer, NULL);
}
ctxt->charset = XML_CHAR_ENCODING_8859_1;
*len = 1;
return((int) *ctxt->input->cur);
}
| 0 |
Chrome | 0aca6bc05a263ea9eafee515fc6ba14da94c1964 | NOT_APPLICABLE | NOT_APPLICABLE | ExtensionFunction::ResponseAction TabsGetSelectedFunction::Run() {
int window_id = extension_misc::kCurrentWindowId;
std::unique_ptr<tabs::GetSelected::Params> params(
tabs::GetSelected::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
if (params->window_id.get())
window_id = *params->window_id;
Browser* browser = NULL;
std::string error;
if (!GetBrowserFromWindowID(this, window_id, &browser, &error))
return RespondNow(Error(error));
TabStripModel* tab_strip = browser->tab_strip_model();
WebContents* contents = tab_strip->GetActiveWebContents();
if (!contents)
return RespondNow(Error(keys::kNoSelectedTabError));
return RespondNow(ArgumentList(
tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject(
contents, ExtensionTabUtil::kScrubTab, extension(), tab_strip,
tab_strip->active_index()))));
}
| 0 |
tensorflow | 6fc9141f42f6a72180ecd24021c3e6b36165fe0d | NOT_APPLICABLE | NOT_APPLICABLE | void Compute(OpKernelContext* context) override {
const Tensor& tensor_in_shape = context->input(0);
const Tensor& out_backprop = context->input(1);
OP_REQUIRES(
context,
tensor_in_shape.dims() == 1 && tensor_in_shape.NumElements() == 5,
errors::InvalidArgument("tensor_in must be 1-dimensional and 5 "
"elements"));
OP_REQUIRES(context, out_backprop.dims() == 5,
errors::InvalidArgument("out_backprop must be 5-dimensional"));
TensorShape output_shape;
auto shape_vec = tensor_in_shape.vec<int32>();
for (int64 i = 0; i < tensor_in_shape.NumElements(); ++i) {
output_shape.AddDim(shape_vec(i));
}
Tensor* output;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
// Dimension order for these arrays is x, y, z.
std::array<int64, 3> input_size{
{GetTensorDim(output_shape, data_format_, '2'),
GetTensorDim(output_shape, data_format_, '1'),
GetTensorDim(output_shape, data_format_, '0')}};
std::array<int64, 3> window{{GetTensorDim(ksize_, data_format_, '2'),
GetTensorDim(ksize_, data_format_, '1'),
GetTensorDim(ksize_, data_format_, '0')}};
std::array<int64, 3> stride{{GetTensorDim(stride_, data_format_, '2'),
GetTensorDim(stride_, data_format_, '1'),
GetTensorDim(stride_, data_format_, '0')}};
std::array<int64, 3> padding, out;
OP_REQUIRES_OK(context, Get3dOutputSize(input_size, window, stride,
padding_, &out, &padding));
LaunchAvgPooling3dGradOp<Device, T>::launch(
context, output_shape, out_backprop, window, stride, out, padding,
data_format_, output);
} | 0 |
radare2 | 04edfa82c1f3fa2bc3621ccdad2f93bdbf00e4f9 | NOT_APPLICABLE | NOT_APPLICABLE | bool test_r_str_lchr(void) {
const char* test = "radare2";
const char* out = r_str_lchr (test, 'r');
mu_assert_streq (out, "re2", "pointer to last r in radare2");
mu_end;
} | 0 |
monit | 328f60773057641c4b2075fab9820145e95b728c | NOT_APPLICABLE | NOT_APPLICABLE | static void print_service_rules_uploadbytes(HttpResponse res, Service_T s) {
for (Bandwidth_T bl = s->uploadbyteslist; bl; bl = bl->next) {
if (bl->range == Time_Second) {
StringBuffer_append(res->outputbuffer, "<tr class='rule'><td>Upload bytes</td><td>");
Util_printRule(res->outputbuffer, bl->action, "If %s %s/s", operatornames[bl->operator], Fmt_bytes2str(bl->limit, (char[10]){}));
} else {
StringBuffer_append(res->outputbuffer, "<tr class='rule'><td>Total upload bytes</td><td>");
Util_printRule(res->outputbuffer, bl->action, "If %s %s in last %d %s(s)", operatornames[bl->operator], Fmt_bytes2str(bl->limit, (char[10]){}), bl->rangecount, Util_timestr(bl->range));
}
StringBuffer_append(res->outputbuffer, "</td></tr>");
}
} | 0 |
rawstudio | 9c2cd3c93c05d009a91d84eedbb85873b0cb505d | NOT_APPLICABLE | NOT_APPLICABLE | rs_filter_graph(RSFilter *filter)
{
g_return_if_fail(RS_IS_FILTER(filter));
gchar *dot_filename;
gchar *png_filename;
gchar *command_line;
GString *str = g_string_new("digraph G {\n");
rs_filter_graph_helper(str, filter);
g_string_append_printf(str, "}\n");
/* Here we would like to use g_mkdtemp(), but due to a bug in upstream, that's impossible */
dot_filename = g_strdup_printf("/tmp/rs-filter-graph.%u", g_random_int());
png_filename = g_strdup_printf("%s.%u.png", dot_filename, g_random_int());
g_file_set_contents(dot_filename, str->str, str->len, NULL);
command_line = g_strdup_printf("dot -Tpng >%s <%s", png_filename, dot_filename);
if (0 != system(command_line))
g_warning("Calling dot failed");
g_free(command_line);
command_line = g_strdup_printf("gnome-open %s", png_filename);
if (0 != system(command_line))
g_warning("Calling gnome-open failed.");
g_free(command_line);
g_free(dot_filename);
g_free(png_filename);
g_string_free(str, TRUE);
}
| 0 |
savannah | 6305b869d86ff415a33576df6d43729673c66eee | NOT_APPLICABLE | NOT_APPLICABLE | gray_init_cells( RAS_ARG_ void* buffer,
long byte_size )
{
ras.buffer = buffer;
ras.buffer_size = byte_size;
ras.ycells = (PCell*) buffer;
ras.cells = NULL;
ras.max_cells = 0;
ras.num_cells = 0;
ras.area = 0;
ras.cover = 0;
ras.invalid = 1;
}
| 0 |
src | 6c3220444ed06b5796dedfd53a0f4becd903c0d1 | NOT_APPLICABLE | NOT_APPLICABLE | filter_data_next(uint64_t token, uint64_t reqid, const char *line)
{
struct filter_session *fs;
/* session can legitimately disappear on a resume */
if ((fs = tree_get(&sessions, reqid)) == NULL)
return;
filter_data_internal(fs, token, reqid, line);
} | 0 |
linux | b9a41d21dceadf8104812626ef85dc56ee8a60ed | NOT_APPLICABLE | NOT_APPLICABLE | int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
{
if (len > UINT_MAX) {
DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
(unsigned long long)len, UINT_MAX);
ti->error = "Maximum size of target IO is too large";
return -EINVAL;
}
ti->max_io_len = (uint32_t) len;
return 0;
}
| 0 |
exempi | baa4b8a02c1ffab9645d13f0bfb1c0d10d311a0c | NOT_APPLICABLE | NOT_APPLICABLE | bool PostScript_MetaHandler::ExtractDocInfoDict(IOBuffer &ioBuf)
{
XMP_Uns8 ch;
XMP_IO* fileRef = this->parent->ioRef;
XMP_Int64 endofDocInfo=(ioBuf.ptr-ioBuf.data)+ioBuf.filePos;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if ( IsWhitespace (*ioBuf.ptr))
{
if ( ! ( PostScript_Support::SkipTabsAndSpaces(fileRef, ioBuf))) return false;
if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsPdfmarkString.length() ) ) return false;
if ( ! CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsPdfmarkString.c_str()), kPSContainsPdfmarkString.length() ) ) return false;
while(true)
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
ch=*ioBuf.ptr;
--ioBuf.ptr;
if (ch=='/') break;//slash of /DOCINFO
}
while(true)
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (!IsWhitespace(*ioBuf.ptr)) break;
--ioBuf.ptr;
}
bool findingkey=false;
std::string key, value;
while(true)
{
XMP_Uns32 noOfMarks=0;
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (*ioBuf.ptr==')')
{
--ioBuf.ptr;
while(true)
{
if (*ioBuf.ptr=='(')
{
if(findingkey)
{
reverse(key.begin(), key.end());
reverse(value.begin(), value.end());
RegisterKeyValue(key,value);
}
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
--ioBuf.ptr;
findingkey=!findingkey;
break;
}
else
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (findingkey)
key+=*ioBuf.ptr;
else
value+=*ioBuf.ptr;
--ioBuf.ptr;
}
}
}
else if(*ioBuf.ptr=='[')
{
break;
}
else
{
while(true)
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (findingkey)
key+=*ioBuf.ptr;
else
value+=*ioBuf.ptr;
--ioBuf.ptr;
if (*ioBuf.ptr=='/')
{
if(findingkey)
{
reverse(key.begin(), key.end());
reverse(value.begin(), value.end());
RegisterKeyValue(key,value);
}
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
--ioBuf.ptr;
findingkey=!findingkey;
break;
}
else if(IsWhitespace(*ioBuf.ptr))
{
break;
}
}
}
while(true)
{
if ( ! PostScript_Support::RevCheckFileSpace ( fileRef, &ioBuf, 1 ) ) return false;
if (!IsWhitespace(*ioBuf.ptr)) break;
--ioBuf.ptr;
}
}
fileRef->Rewind();
FillBuffer (fileRef, endofDocInfo, &ioBuf );
return true;
}//white space not after DOCINFO
return false;
}
| 0 |
Chrome | 3298d3abf47b3a7a10e44c07d821c68a5c8aa935 | NOT_APPLICABLE | NOT_APPLICABLE | void WebGLRenderingContextBase::getHTMLOrOffscreenCanvas(
HTMLCanvasElementOrOffscreenCanvas& result) const {
if (canvas()) {
result.SetHTMLCanvasElement(static_cast<HTMLCanvasElement*>(Host()));
} else {
result.SetOffscreenCanvas(static_cast<OffscreenCanvas*>(Host()));
}
}
| 0 |
WAVM | 2de6cf70c5ef31e22ed119a25ac2daeefd3d18a1 | NOT_APPLICABLE | NOT_APPLICABLE | inline bool loadBinaryModule(const void* wasmBytes,
Uptr numBytes,
IR::Module& outModule,
Log::Category errorCategory = Log::error)
{
// Load the module from a binary WebAssembly file.
try
{
Timing::Timer loadTimer;
Serialization::MemoryInputStream stream((const U8*)wasmBytes, numBytes);
WASM::serialize(stream, outModule);
Timing::logRatePerSecond("Loaded WASM", loadTimer, numBytes / 1024.0 / 1024.0, "MB");
return true;
}
catch(Serialization::FatalSerializationException exception)
{
Log::printf(errorCategory,
"Error deserializing WebAssembly binary file:\n%s\n",
exception.message.c_str());
return false;
}
catch(IR::ValidationException exception)
{
Log::printf(errorCategory,
"Error validating WebAssembly binary file:\n%s\n",
exception.message.c_str());
return false;
}
catch(std::bad_alloc)
{
Log::printf(errorCategory, "Memory allocation failed: input is likely malformed\n");
return false;
}
} | 0 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | CVE-2016-1621 | CWE-119 | const Cluster* Segment::GetLast() const
{
if ((m_clusters == NULL) || (m_clusterCount <= 0))
return &m_eos;
const long idx = m_clusterCount - 1;
Cluster* const pCluster = m_clusters[idx];
assert(pCluster);
return pCluster;
}
| 1 |
tor | 56a7c5bc15e0447203a491c1ee37de9939ad1dcd | CVE-2017-0376 | CWE-617 | connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
edge_connection_t *conn,
crypt_path_t *layer_hint)
{
static int num_seen=0;
relay_header_t rh;
unsigned domain = layer_hint?LD_APP:LD_EXIT;
int reason;
int optimistic_data = 0; /* Set to 1 if we receive data on a stream
* that's in the EXIT_CONN_STATE_RESOLVING
* or EXIT_CONN_STATE_CONNECTING states. */
tor_assert(cell);
tor_assert(circ);
relay_header_unpack(&rh, cell->payload);
num_seen++;
log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
num_seen, rh.command, rh.stream_id);
if (rh.length > RELAY_PAYLOAD_SIZE) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Relay cell length field too long. Closing circuit.");
return - END_CIRC_REASON_TORPROTOCOL;
}
if (rh.stream_id == 0) {
switch (rh.command) {
case RELAY_COMMAND_BEGIN:
case RELAY_COMMAND_CONNECTED:
case RELAY_COMMAND_DATA:
case RELAY_COMMAND_END:
case RELAY_COMMAND_RESOLVE:
case RELAY_COMMAND_RESOLVED:
case RELAY_COMMAND_BEGIN_DIR:
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero "
"stream_id. Dropping.", (int)rh.command);
return 0;
default:
;
}
}
/* either conn is NULL, in which case we've got a control cell, or else
* conn points to the recognized stream. */
if (conn && !connection_state_is_open(TO_CONN(conn))) {
if (conn->base_.type == CONN_TYPE_EXIT &&
(conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
rh.command == RELAY_COMMAND_DATA) {
/* Allow DATA cells to be delivered to an exit node in state
* EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
* This speeds up HTTP, for example. */
optimistic_data = 1;
} else {
return connection_edge_process_relay_cell_not_open(
&rh, cell, circ, conn, layer_hint);
}
}
switch (rh.command) {
case RELAY_COMMAND_DROP:
return 0;
case RELAY_COMMAND_BEGIN:
case RELAY_COMMAND_BEGIN_DIR:
if (layer_hint &&
circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
log_fn(LOG_PROTOCOL_WARN, LD_APP,
"Relay begin request unsupported at AP. Dropping.");
return 0;
}
if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
log_fn(LOG_PROTOCOL_WARN, LD_APP,
"Relay begin request to Hidden Service "
"from intermediary node. Dropping.");
return 0;
}
if (conn) {
log_fn(LOG_PROTOCOL_WARN, domain,
"Begin cell for known stream. Dropping.");
return 0;
}
if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
/* Assign this circuit and its app-ward OR connection a unique ID,
* so that we can measure download times. The local edge and dir
* connection will be assigned the same ID when they are created
* and linked. */
static uint64_t next_id = 0;
circ->dirreq_id = ++next_id;
TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
}
return connection_exit_begin_conn(cell, circ);
case RELAY_COMMAND_DATA:
++stats_n_data_cells_received;
if (( layer_hint && --layer_hint->deliver_window < 0) ||
(!layer_hint && --circ->deliver_window < 0)) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"(relay data) circ deliver_window below 0. Killing.");
if (conn) {
/* XXXX Do we actually need to do this? Will killing the circuit
* not send an END and mark the stream for close as appropriate? */
connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
connection_mark_for_close(TO_CONN(conn));
}
return -END_CIRC_REASON_TORPROTOCOL;
}
log_debug(domain,"circ deliver_window now %d.", layer_hint ?
layer_hint->deliver_window : circ->deliver_window);
circuit_consider_sending_sendme(circ, layer_hint);
if (!conn) {
log_info(domain,"data cell dropped, unknown stream (streamid %d).",
rh.stream_id);
return 0;
}
if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"(relay data) conn deliver_window below 0. Killing.");
return -END_CIRC_REASON_TORPROTOCOL;
}
stats_n_data_bytes_received += rh.length;
connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
rh.length, TO_CONN(conn));
if (!optimistic_data) {
/* Only send a SENDME if we're not getting optimistic data; otherwise
* a SENDME could arrive before the CONNECTED.
*/
connection_edge_consider_sending_sendme(conn);
}
return 0;
case RELAY_COMMAND_END:
reason = rh.length > 0 ?
get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
if (!conn) {
log_info(domain,"end cell (%s) dropped, unknown stream.",
stream_end_reason_to_string(reason));
return 0;
}
/* XXX add to this log_fn the exit node's nickname? */
log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
"Removing stream.",
conn->base_.s,
stream_end_reason_to_string(reason),
conn->stream_id);
if (conn->base_.type == CONN_TYPE_AP) {
entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
if (entry_conn->socks_request &&
!entry_conn->socks_request->has_finished)
log_warn(LD_BUG,
"open stream hasn't sent socks answer yet? Closing.");
}
/* We just *got* an end; no reason to send one. */
conn->edge_has_sent_end = 1;
if (!conn->end_reason)
conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
if (!conn->base_.marked_for_close) {
/* only mark it if not already marked. it's possible to
* get the 'end' right around when the client hangs up on us. */
connection_mark_and_flush(TO_CONN(conn));
}
return 0;
case RELAY_COMMAND_EXTEND:
case RELAY_COMMAND_EXTEND2: {
static uint64_t total_n_extend=0, total_nonearly=0;
total_n_extend++;
if (rh.stream_id) {
log_fn(LOG_PROTOCOL_WARN, domain,
"'extend' cell received for non-zero stream. Dropping.");
return 0;
}
if (cell->command != CELL_RELAY_EARLY &&
!networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
#define EARLY_WARNING_INTERVAL 3600
static ratelim_t early_warning_limit =
RATELIM_INIT(EARLY_WARNING_INTERVAL);
char *m;
if (cell->command == CELL_RELAY) {
++total_nonearly;
if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
double percentage = ((double)total_nonearly)/total_n_extend;
percentage *= 100;
log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
"but not via RELAY_EARLY. Dropping.%s", m);
log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
"all EXTEND cells for this reason)", percentage);
tor_free(m);
}
} else {
log_fn(LOG_WARN, domain,
"EXTEND cell received, in a cell with type %d! Dropping.",
cell->command);
}
return 0;
}
return circuit_extend(cell, circ);
}
case RELAY_COMMAND_EXTENDED:
case RELAY_COMMAND_EXTENDED2:
if (!layer_hint) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"'extended' unsupported at non-origin. Dropping.");
return 0;
}
log_debug(domain,"Got an extended cell! Yay.");
{
extended_cell_t extended_cell;
if (extended_cell_parse(&extended_cell, rh.command,
(const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
rh.length)<0) {
log_warn(LD_PROTOCOL,
"Can't parse EXTENDED cell; killing circuit.");
return -END_CIRC_REASON_TORPROTOCOL;
}
if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
&extended_cell.created_cell)) < 0) {
log_warn(domain,"circuit_finish_handshake failed.");
return reason;
}
}
if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
log_info(domain,"circuit_send_next_onion_skin() failed.");
return reason;
}
return 0;
case RELAY_COMMAND_TRUNCATE:
if (layer_hint) {
log_fn(LOG_PROTOCOL_WARN, LD_APP,
"'truncate' unsupported at origin. Dropping.");
return 0;
}
if (circ->n_hop) {
if (circ->n_chan)
log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!");
extend_info_free(circ->n_hop);
circ->n_hop = NULL;
tor_free(circ->n_chan_create_cell);
circuit_set_state(circ, CIRCUIT_STATE_OPEN);
}
if (circ->n_chan) {
uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
circuit_clear_cell_queue(circ, circ->n_chan);
channel_send_destroy(circ->n_circ_id, circ->n_chan,
trunc_reason);
circuit_set_n_circid_chan(circ, 0, NULL);
}
log_debug(LD_EXIT, "Processed 'truncate', replying.");
{
char payload[1];
payload[0] = (char)END_CIRC_REASON_REQUESTED;
relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
payload, sizeof(payload), NULL);
}
return 0;
case RELAY_COMMAND_TRUNCATED:
if (!layer_hint) {
log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
"'truncated' unsupported at non-origin. Dropping.");
return 0;
}
circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
get_uint8(cell->payload + RELAY_HEADER_SIZE));
return 0;
case RELAY_COMMAND_CONNECTED:
if (conn) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"'connected' unsupported while open. Closing circ.");
return -END_CIRC_REASON_TORPROTOCOL;
}
log_info(domain,
"'connected' received, no conn attached anymore. Ignoring.");
return 0;
case RELAY_COMMAND_SENDME:
if (!rh.stream_id) {
if (layer_hint) {
if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
CIRCWINDOW_START_MAX) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Unexpected sendme cell from exit relay. "
"Closing circ.");
return -END_CIRC_REASON_TORPROTOCOL;
}
layer_hint->package_window += CIRCWINDOW_INCREMENT;
log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
layer_hint->package_window);
circuit_resume_edge_reading(circ, layer_hint);
} else {
if (circ->package_window + CIRCWINDOW_INCREMENT >
CIRCWINDOW_START_MAX) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Unexpected sendme cell from client. "
"Closing circ (window %d).",
circ->package_window);
return -END_CIRC_REASON_TORPROTOCOL;
}
circ->package_window += CIRCWINDOW_INCREMENT;
log_debug(LD_APP,
"circ-level sendme at non-origin, packagewindow %d.",
circ->package_window);
circuit_resume_edge_reading(circ, layer_hint);
}
return 0;
}
if (!conn) {
log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
rh.stream_id);
return 0;
}
conn->package_window += STREAMWINDOW_INCREMENT;
log_debug(domain,"stream-level sendme, packagewindow now %d.",
conn->package_window);
if (circuit_queue_streams_are_blocked(circ)) {
/* Still waiting for queue to flush; don't touch conn */
return 0;
}
connection_start_reading(TO_CONN(conn));
/* handle whatever might still be on the inbuf */
if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
/* (We already sent an end cell if possible) */
connection_mark_for_close(TO_CONN(conn));
return 0;
}
return 0;
case RELAY_COMMAND_RESOLVE:
if (layer_hint) {
log_fn(LOG_PROTOCOL_WARN, LD_APP,
"resolve request unsupported at AP; dropping.");
return 0;
} else if (conn) {
log_fn(LOG_PROTOCOL_WARN, domain,
"resolve request for known stream; dropping.");
return 0;
} else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
log_fn(LOG_PROTOCOL_WARN, domain,
"resolve request on circ with purpose %d; dropping",
circ->purpose);
return 0;
}
connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
return 0;
case RELAY_COMMAND_RESOLVED:
if (conn) {
log_fn(LOG_PROTOCOL_WARN, domain,
"'resolved' unsupported while open. Closing circ.");
return -END_CIRC_REASON_TORPROTOCOL;
}
log_info(domain,
"'resolved' received, no conn attached anymore. Ignoring.");
return 0;
case RELAY_COMMAND_ESTABLISH_INTRO:
case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
case RELAY_COMMAND_INTRODUCE1:
case RELAY_COMMAND_INTRODUCE2:
case RELAY_COMMAND_INTRODUCE_ACK:
case RELAY_COMMAND_RENDEZVOUS1:
case RELAY_COMMAND_RENDEZVOUS2:
case RELAY_COMMAND_INTRO_ESTABLISHED:
case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
rend_process_relay_cell(circ, layer_hint,
rh.command, rh.length,
cell->payload+RELAY_HEADER_SIZE);
return 0;
}
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received unknown relay command %d. Perhaps the other side is using "
"a newer version of Tor? Dropping.",
rh.command);
return 0; /* for forward compatibility, don't kill the circuit */
}
| 1 |
librsvg | 40af93e6eb1c94b90c3b9a0b87e0840e126bb8df | NOT_APPLICABLE | NOT_APPLICABLE | _rsvg_node_poly_set_atts (RsvgNode * self, RsvgHandle * ctx, RsvgPropertyBag * atts)
{
RsvgNodePoly *poly = (RsvgNodePoly *) self;
const char *klazz = NULL, *id = NULL, *value;
if (rsvg_property_bag_size (atts)) {
/* support for svg < 1.0 which used verts */
if ((value = rsvg_property_bag_lookup (atts, "verts"))
|| (value = rsvg_property_bag_lookup (atts, "points"))) {
if (poly->path)
rsvg_cairo_path_destroy (poly->path);
poly->path = _rsvg_node_poly_build_path (value,
RSVG_NODE_TYPE (self) == RSVG_NODE_TYPE_POLYGON);
}
if ((value = rsvg_property_bag_lookup (atts, "class")))
klazz = value;
if ((value = rsvg_property_bag_lookup (atts, "id"))) {
id = value;
rsvg_defs_register_name (ctx->priv->defs, value, self);
}
rsvg_parse_style_attrs (ctx, self->state,
RSVG_NODE_TYPE (self) == RSVG_NODE_TYPE_POLYLINE ? "polyline" : "polygon",
klazz, id, atts);
}
} | 0 |
libarchive | 3014e198 | NOT_APPLICABLE | NOT_APPLICABLE | make_boot_catalog(struct archive_write *a)
{
struct iso9660 *iso9660 = a->format_data;
unsigned char *block;
unsigned char *p;
uint16_t sum, *wp;
block = wb_buffptr(a);
memset(block, 0, LOGICAL_BLOCK_SIZE);
p = block;
/*
* Validation Entry
*/
/* Header ID */
p[0] = 1;
/* Platform ID */
p[1] = iso9660->el_torito.platform_id;
/* Reserved */
p[2] = p[3] = 0;
/* ID */
if (archive_strlen(&(iso9660->el_torito.id)) > 0)
strncpy((char *)p+4, iso9660->el_torito.id.s, 23);
p[27] = 0;
/* Checksum */
p[28] = p[29] = 0;
/* Key */
p[30] = 0x55;
p[31] = 0xAA;
sum = 0;
wp = (uint16_t *)block;
while (wp < (uint16_t *)&block[32])
sum += archive_le16dec(wp++);
set_num_721(&block[28], (~sum) + 1);
/*
* Initial/Default Entry
*/
p = &block[32];
/* Boot Indicator */
p[0] = 0x88;
/* Boot media type */
p[1] = iso9660->el_torito.media_type;
/* Load Segment */
if (iso9660->el_torito.media_type == BOOT_MEDIA_NO_EMULATION)
set_num_721(&p[2], iso9660->el_torito.boot_load_seg);
else
set_num_721(&p[2], 0);
/* System Type */
p[4] = iso9660->el_torito.system_type;
/* Unused */
p[5] = 0;
/* Sector Count */
if (iso9660->el_torito.media_type == BOOT_MEDIA_NO_EMULATION)
set_num_721(&p[6], iso9660->el_torito.boot_load_size);
else
set_num_721(&p[6], 1);
/* Load RBA */
set_num_731(&p[8],
iso9660->el_torito.boot->file->content.location);
/* Unused */
memset(&p[12], 0, 20);
return (wb_consume(a, LOGICAL_BLOCK_SIZE));
}
| 0 |
qemu | 070c4b92b8cd5390889716677a0b92444d6e087a | CVE-2016-7908 | CWE-399 | static void mcf_fec_do_tx(mcf_fec_state *s)
{
uint32_t addr;
uint32_t addr;
mcf_fec_bd bd;
int frame_size;
int len;
uint8_t frame[FEC_MAX_FRAME_SIZE];
uint8_t *ptr;
ptr = frame;
ptr = frame;
frame_size = 0;
addr = s->tx_descriptor;
while (1) {
mcf_fec_read_bd(&bd, addr);
DPRINTF("tx_bd %x flags %04x len %d data %08x\n",
addr, bd.flags, bd.length, bd.data);
/* Run out of descriptors to transmit. */
break;
}
len = bd.length;
if (frame_size + len > FEC_MAX_FRAME_SIZE) {
len = FEC_MAX_FRAME_SIZE - frame_size;
s->eir |= FEC_INT_BABT;
}
cpu_physical_memory_read(bd.data, ptr, len);
ptr += len;
frame_size += len;
if (bd.flags & FEC_BD_L) {
/* Last buffer in frame. */
DPRINTF("Sending packet\n");
qemu_send_packet(qemu_get_queue(s->nic), frame, len);
ptr = frame;
frame_size = 0;
s->eir |= FEC_INT_TXF;
}
s->eir |= FEC_INT_TXB;
bd.flags &= ~FEC_BD_R;
/* Write back the modified descriptor. */
mcf_fec_write_bd(&bd, addr);
/* Advance to the next descriptor. */
if ((bd.flags & FEC_BD_W) != 0) {
addr = s->etdsr;
} else {
addr += 8;
}
}
| 1 |
server | e1eb39a446c30b8459c39fd7f2ee1c55a36e97d2 | NOT_APPLICABLE | NOT_APPLICABLE | compress_worker_thread_func(void *arg)
{
comp_thread_ctxt_t *thd = (comp_thread_ctxt_t *) arg;
pthread_mutex_lock(&thd->ctrl_mutex);
pthread_mutex_lock(&thd->data_mutex);
thd->started = TRUE;
pthread_cond_signal(&thd->ctrl_cond);
pthread_mutex_unlock(&thd->ctrl_mutex);
while (1) {
thd->data_avail = FALSE;
pthread_cond_signal(&thd->data_cond);
while (!thd->data_avail && !thd->cancelled) {
pthread_cond_wait(&thd->data_cond, &thd->data_mutex);
}
if (thd->cancelled)
break;
thd->to_len = qlz_compress(thd->from, thd->to, thd->from_len,
&thd->state);
/* qpress uses 0x00010000 as the initial value, but its own
Adler-32 implementation treats the value differently:
1. higher order bits are the sum of all bytes in the sequence
2. lower order bits are the sum of resulting values at every
step.
So it's the other way around as compared to zlib's adler32().
That's why 0x00000001 is being passed here to be compatible
with qpress implementation. */
thd->adler = adler32(0x00000001, (uchar *) thd->to,
(uInt)thd->to_len);
}
pthread_mutex_unlock(&thd->data_mutex);
return NULL;
} | 0 |
cryptopp | 9425e16437439e68c7d96abef922167d68fafaff | NOT_APPLICABLE | NOT_APPLICABLE | void RWFunction::BERDecode(BufferedTransformation &bt)
{
BERSequenceDecoder seq(bt);
m_n.BERDecode(seq);
seq.MessageEnd();
} | 0 |
Chrome | 5c895ed26b096468eea6baa6584f2df65905b76b | NOT_APPLICABLE | NOT_APPLICABLE | PasswordAutofillAgent::FocusStateNotifier::FocusStateNotifier(
PasswordAutofillAgent* agent)
: agent_(agent) {}
| 0 |
suricata | d8634daf74c882356659addb65fb142b738a186b | CVE-2019-1010279 | CWE-347 | static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
Packet *p, Flow * const pflow)
{
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP);
/* cleanup pkt specific part of the patternmatcher */
PacketPatternCleanup(det_ctx);
if (pflow != NULL) {
/* update inspected tracker for raw reassembly */
if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) {
StreamReassembleRawUpdateProgress(pflow->protoctx, p,
det_ctx->raw_stream_progress);
DetectEngineCleanHCBDBuffers(det_ctx);
}
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP);
SCReturn;
}
| 1 |
ioq3 | f61fe5f6a0419ef4a88d46a128052f2e8352e85d | NOT_APPLICABLE | NOT_APPLICABLE | static sfxHandle_t S_AL_BufferFind(const char *filename)
{
// Look it up in the table
sfxHandle_t sfx = -1;
int i;
if ( !filename ) {
Com_Error( ERR_FATAL, "Sound name is NULL" );
}
if ( !filename[0] ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is empty\n" );
return 0;
}
if ( strlen( filename ) >= MAX_QPATH ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is too long: %s\n", filename );
return 0;
}
if ( filename[0] == '*' ) {
Com_Printf( S_COLOR_YELLOW "WARNING: Tried to load player sound directly: %s\n", filename );
return 0;
}
for(i = 0; i < numSfx; i++)
{
if(!Q_stricmp(knownSfx[i].filename, filename))
{
sfx = i;
break;
}
}
// Not found in table?
if(sfx == -1)
{
alSfx_t *ptr;
sfx = S_AL_BufferFindFree();
// Clear and copy the filename over
ptr = &knownSfx[sfx];
memset(ptr, 0, sizeof(*ptr));
ptr->masterLoopSrc = -1;
strcpy(ptr->filename, filename);
}
// Return the handle
return sfx;
} | 0 |
Android | 54cb02ad733fb71b1bdf78590428817fb780aff8 | NOT_APPLICABLE | NOT_APPLICABLE | status_t Parcel::writeByteArray(size_t len, const uint8_t *val) {
if (len > INT32_MAX) {
return BAD_VALUE;
}
if (!val) {
return writeInt32(-1);
}
status_t ret = writeInt32(static_cast<uint32_t>(len));
if (ret == NO_ERROR) {
ret = write(val, len * sizeof(*val));
}
return ret;
}
| 0 |
Chrome | 35eb28748d45b87695a69eceffaff73a0be476af | NOT_APPLICABLE | NOT_APPLICABLE | content::WebContents* web_contents() { return stub_->web_contents(); }
| 0 |
Android | 1171e7c047bf79e7c93342bb6a812c9edd86aa84 | NOT_APPLICABLE | NOT_APPLICABLE | virtual status_t useBuffer(
node_id node, OMX_U32 port_index, const sp<IMemory> ¶ms,
buffer_id *buffer) {
Parcel data, reply;
data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
data.writeInt32((int32_t)node);
data.writeInt32(port_index);
data.writeStrongBinder(params->asBinder());
remote()->transact(USE_BUFFER, data, &reply);
status_t err = reply.readInt32();
if (err != OK) {
*buffer = 0;
return err;
}
*buffer = (buffer_id)reply.readInt32();
return err;
}
| 0 |
linux | f8e9881c2aef1e982e5abc25c046820cd0b7cf64 | NOT_APPLICABLE | NOT_APPLICABLE | static unsigned int ip_sabotage_in(unsigned int hook, struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
if (skb->nf_bridge &&
!(skb->nf_bridge->mask & BRNF_NF_BRIDGE_PREROUTING)) {
return NF_STOP;
}
return NF_ACCEPT;
}
| 0 |
FreeRDP | 9fee4ae076b1ec97b97efb79ece08d1dab4df29a | NOT_APPLICABLE | NOT_APPLICABLE | unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
unsigned w, unsigned h)
{
size_t i;
ColorTree tree;
size_t numpixels = w * h;
if(lodepng_color_mode_equal(mode_out, mode_in))
{
size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
for(i = 0; i < numbytes; i++) out[i] = in[i];
return 0;
}
if(mode_out->colortype == LCT_PALETTE)
{
size_t palsize = 1u << mode_out->bitdepth;
if(mode_out->palettesize < palsize) palsize = mode_out->palettesize;
color_tree_init(&tree);
for(i = 0; i < palsize; i++)
{
unsigned char* p = &mode_out->palette[i * 4];
color_tree_add(&tree, p[0], p[1], p[2], p[3], i);
}
}
if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16)
{
for(i = 0; i < numpixels; i++)
{
unsigned short r = 0, g = 0, b = 0, a = 0;
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
rgba16ToPixel(out, i, mode_out, r, g, b, a);
}
}
else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA)
{
getPixelColorsRGBA8(out, numpixels, 1, in, mode_in);
}
else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB)
{
getPixelColorsRGBA8(out, numpixels, 0, in, mode_in);
}
else
{
unsigned char r = 0, g = 0, b = 0, a = 0;
for(i = 0; i < numpixels; i++)
{
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
}
}
if(mode_out->colortype == LCT_PALETTE)
{
color_tree_cleanup(&tree);
}
return 0; /*no error (this function currently never has one, but maybe OOM detection added later.)*/
} | 0 |
linux | c0a333d842ef67ac04adc72ff79dc1ccc3dca4ed | NOT_APPLICABLE | NOT_APPLICABLE | static ssize_t sof_dfsentry_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
#if IS_ENABLED(CONFIG_SND_SOC_SOF_DEBUG_IPC_FLOOD_TEST)
struct snd_sof_dfsentry *dfse = file->private_data;
struct snd_sof_dev *sdev = dfse->sdev;
unsigned long ipc_duration_ms = 0;
bool flood_duration_test = false;
unsigned long ipc_count = 0;
struct dentry *dentry;
int err;
#endif
size_t size;
char *string;
int ret;
string = kzalloc(count, GFP_KERNEL);
if (!string)
return -ENOMEM;
size = simple_write_to_buffer(string, count, ppos, buffer, count);
ret = size;
#if IS_ENABLED(CONFIG_SND_SOC_SOF_DEBUG_IPC_FLOOD_TEST)
/*
* write op is only supported for ipc_flood_count or
* ipc_flood_duration_ms debugfs entries atm.
* ipc_flood_count floods the DSP with the number of IPC's specified.
* ipc_duration_ms test floods the DSP for the time specified
* in the debugfs entry.
*/
dentry = file->f_path.dentry;
if (strcmp(dentry->d_name.name, "ipc_flood_count") &&
strcmp(dentry->d_name.name, "ipc_flood_duration_ms")) {
ret = -EINVAL;
goto out;
}
if (!strcmp(dentry->d_name.name, "ipc_flood_duration_ms"))
flood_duration_test = true;
/* test completion criterion */
if (flood_duration_test)
ret = kstrtoul(string, 0, &ipc_duration_ms);
else
ret = kstrtoul(string, 0, &ipc_count);
if (ret < 0)
goto out;
/* limit max duration/ipc count for flood test */
if (flood_duration_test) {
if (!ipc_duration_ms) {
ret = size;
goto out;
}
/* find the minimum. min() is not used to avoid warnings */
if (ipc_duration_ms > MAX_IPC_FLOOD_DURATION_MS)
ipc_duration_ms = MAX_IPC_FLOOD_DURATION_MS;
} else {
if (!ipc_count) {
ret = size;
goto out;
}
/* find the minimum. min() is not used to avoid warnings */
if (ipc_count > MAX_IPC_FLOOD_COUNT)
ipc_count = MAX_IPC_FLOOD_COUNT;
}
ret = pm_runtime_get_sync(sdev->dev);
if (ret < 0) {
dev_err_ratelimited(sdev->dev,
"error: debugfs write failed to resume %d\n",
ret);
pm_runtime_put_noidle(sdev->dev);
goto out;
}
/* flood test */
ret = sof_debug_ipc_flood_test(sdev, dfse, flood_duration_test,
ipc_duration_ms, ipc_count);
pm_runtime_mark_last_busy(sdev->dev);
err = pm_runtime_put_autosuspend(sdev->dev);
if (err < 0)
dev_err_ratelimited(sdev->dev,
"error: debugfs write failed to idle %d\n",
err);
/* return size if test is successful */
if (ret >= 0)
ret = size;
out:
#endif
kfree(string);
return ret;
} | 0 |
ceph | 92da834cababc4dddd5dbbab5837310478d1e6d4 | NOT_APPLICABLE | NOT_APPLICABLE | AWSGeneralAbstractor::get_auth_data_v4(const req_state* const s,
const bool using_qs) const
{
boost::string_view access_key_id;
boost::string_view signed_hdrs;
boost::string_view date;
boost::string_view credential_scope;
boost::string_view client_signature;
boost::string_view session_token;
int ret = rgw::auth::s3::parse_v4_credentials(s->info,
access_key_id,
credential_scope,
signed_hdrs,
client_signature,
date,
session_token,
using_qs);
if (ret < 0) {
throw ret;
}
/* craft canonical headers */
boost::optional<std::string> canonical_headers = \
get_v4_canonical_headers(s->info, signed_hdrs, using_qs);
if (canonical_headers) {
using sanitize = rgw::crypt_sanitize::log_content;
ldpp_dout(s, 10) << "canonical headers format = "
<< sanitize{*canonical_headers} << dendl;
} else {
throw -EPERM;
}
bool is_non_s3_op = false;
if (s->op_type == RGW_STS_GET_SESSION_TOKEN ||
s->op_type == RGW_STS_ASSUME_ROLE ||
s->op_type == RGW_STS_ASSUME_ROLE_WEB_IDENTITY ||
s->op_type == RGW_OP_CREATE_ROLE ||
s->op_type == RGW_OP_DELETE_ROLE ||
s->op_type == RGW_OP_GET_ROLE ||
s->op_type == RGW_OP_MODIFY_ROLE ||
s->op_type == RGW_OP_LIST_ROLES ||
s->op_type == RGW_OP_PUT_ROLE_POLICY ||
s->op_type == RGW_OP_GET_ROLE_POLICY ||
s->op_type == RGW_OP_LIST_ROLE_POLICIES ||
s->op_type == RGW_OP_DELETE_ROLE_POLICY ||
s->op_type == RGW_OP_PUT_USER_POLICY ||
s->op_type == RGW_OP_GET_USER_POLICY ||
s->op_type == RGW_OP_LIST_USER_POLICIES ||
s->op_type == RGW_OP_DELETE_USER_POLICY) {
is_non_s3_op = true;
}
const char* exp_payload_hash = nullptr;
string payload_hash;
if (is_non_s3_op) {
//For non s3 ops, we need to calculate the payload hash
payload_hash = s->info.args.get("PayloadHash");
exp_payload_hash = payload_hash.c_str();
} else {
/* Get the expected hash. */
exp_payload_hash = rgw::auth::s3::get_v4_exp_payload_hash(s->info);
}
/* Craft canonical URI. Using std::move later so let it be non-const. */
auto canonical_uri = rgw::auth::s3::get_v4_canonical_uri(s->info);
/* Craft canonical query string. std::moving later so non-const here. */
auto canonical_qs = rgw::auth::s3::get_v4_canonical_qs(s->info, using_qs);
/* Craft canonical request. */
auto canonical_req_hash = \
rgw::auth::s3::get_v4_canon_req_hash(s->cct,
s->info.method,
std::move(canonical_uri),
std::move(canonical_qs),
std::move(*canonical_headers),
signed_hdrs,
exp_payload_hash);
auto string_to_sign = \
rgw::auth::s3::get_v4_string_to_sign(s->cct,
AWS4_HMAC_SHA256_STR,
date,
credential_scope,
std::move(canonical_req_hash));
const auto sig_factory = std::bind(rgw::auth::s3::get_v4_signature,
credential_scope,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3);
/* Requests authenticated with the Query Parameters are treated as unsigned.
* From "Authenticating Requests: Using Query Parameters (AWS Signature
* Version 4)":
*
* You don't include a payload hash in the Canonical Request, because
* when you create a presigned URL, you don't know the payload content
* because the URL is used to upload an arbitrary payload. Instead, you
* use a constant string UNSIGNED-PAYLOAD.
*
* This means we have absolutely no business in spawning completer. Both
* aws4_auth_needs_complete and aws4_auth_streaming_mode are set to false
* by default. We don't need to change that. */
if (is_v4_payload_unsigned(exp_payload_hash) || is_v4_payload_empty(s) || is_non_s3_op) {
return {
access_key_id,
client_signature,
session_token,
std::move(string_to_sign),
sig_factory,
null_completer_factory
};
} else {
/* We're going to handle a signed payload. Be aware that even empty HTTP
* body (no payload) requires verification:
*
* The x-amz-content-sha256 header is required for all AWS Signature
* Version 4 requests. It provides a hash of the request payload. If
* there is no payload, you must provide the hash of an empty string. */
if (!is_v4_payload_streamed(exp_payload_hash)) {
ldpp_dout(s, 10) << "delaying v4 auth" << dendl;
/* payload in a single chunk */
switch (s->op_type)
{
case RGW_OP_CREATE_BUCKET:
case RGW_OP_PUT_OBJ:
case RGW_OP_PUT_ACLS:
case RGW_OP_PUT_CORS:
case RGW_OP_INIT_MULTIPART: // in case that Init Multipart uses CHUNK encoding
case RGW_OP_COMPLETE_MULTIPART:
case RGW_OP_SET_BUCKET_VERSIONING:
case RGW_OP_DELETE_MULTI_OBJ:
case RGW_OP_ADMIN_SET_METADATA:
case RGW_OP_SET_BUCKET_WEBSITE:
case RGW_OP_PUT_BUCKET_POLICY:
case RGW_OP_PUT_OBJ_TAGGING:
case RGW_OP_PUT_BUCKET_TAGGING:
case RGW_OP_PUT_BUCKET_REPLICATION:
case RGW_OP_PUT_LC:
case RGW_OP_SET_REQUEST_PAYMENT:
case RGW_OP_PUBSUB_NOTIF_CREATE:
case RGW_OP_PUT_BUCKET_OBJ_LOCK:
case RGW_OP_PUT_OBJ_RETENTION:
case RGW_OP_PUT_OBJ_LEGAL_HOLD:
case RGW_STS_GET_SESSION_TOKEN:
case RGW_STS_ASSUME_ROLE:
case RGW_OP_PUT_BUCKET_PUBLIC_ACCESS_BLOCK:
case RGW_OP_GET_BUCKET_PUBLIC_ACCESS_BLOCK:
case RGW_OP_DELETE_BUCKET_PUBLIC_ACCESS_BLOCK:
break;
default:
dout(10) << "ERROR: AWS4 completion for this operation NOT IMPLEMENTED" << dendl;
throw -ERR_NOT_IMPLEMENTED;
}
const auto cmpl_factory = std::bind(AWSv4ComplSingle::create,
s,
std::placeholders::_1);
return {
access_key_id,
client_signature,
session_token,
std::move(string_to_sign),
sig_factory,
cmpl_factory
};
} else {
/* IMHO "streamed" doesn't fit too good here. I would prefer to call
* it "chunked" but let's be coherent with Amazon's terminology. */
dout(10) << "body content detected in multiple chunks" << dendl;
/* payload in multiple chunks */
switch(s->op_type)
{
case RGW_OP_PUT_OBJ:
break;
default:
dout(10) << "ERROR: AWS4 completion for this operation NOT IMPLEMENTED (streaming mode)" << dendl;
throw -ERR_NOT_IMPLEMENTED;
}
dout(10) << "aws4 seed signature ok... delaying v4 auth" << dendl;
/* In the case of streamed payload client sets the x-amz-content-sha256
* to "STREAMING-AWS4-HMAC-SHA256-PAYLOAD" but uses "UNSIGNED-PAYLOAD"
* when constructing the Canonical Request. */
/* In the case of single-chunk upload client set the header's value is
* coherent with the one used for Canonical Request crafting. */
/* In the case of query string-based authentication there should be no
* x-amz-content-sha256 header and the value "UNSIGNED-PAYLOAD" is used
* for CanonReq. */
const auto cmpl_factory = std::bind(AWSv4ComplMulti::create,
s,
date,
credential_scope,
client_signature,
std::placeholders::_1);
return {
access_key_id,
client_signature,
session_token,
std::move(string_to_sign),
sig_factory,
cmpl_factory
};
}
}
} | 0 |
linux | 321027c1fe77f892f4ea07846aeae08cefbbb290 | NOT_APPLICABLE | NOT_APPLICABLE | static void perf_event_context_sched_in(struct perf_event_context *ctx,
struct task_struct *task)
{
struct perf_cpu_context *cpuctx;
cpuctx = __get_cpu_context(ctx);
if (cpuctx->task_ctx == ctx)
return;
perf_ctx_lock(cpuctx, ctx);
perf_pmu_disable(ctx->pmu);
/*
* We want to keep the following priority order:
* cpu pinned (that don't need to move), task pinned,
* cpu flexible, task flexible.
*/
cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
perf_event_sched_in(cpuctx, ctx, task);
perf_pmu_enable(ctx->pmu);
perf_ctx_unlock(cpuctx, ctx);
}
| 0 |
Chrome | 5925dff83699508b5e2735afb0297dfb310e159d | NOT_APPLICABLE | NOT_APPLICABLE | void Browser::EnumerateDirectoryHelper(TabContents* tab, int request_id,
const FilePath& path) {
ChildProcessSecurityPolicy* policy =
ChildProcessSecurityPolicy::GetInstance();
if (!policy->CanReadDirectory(tab->render_view_host()->process()->id(),
path)) {
return;
}
Profile* profile =
Profile::FromBrowserContext(tab->browser_context());
FileSelectHelper* file_select_helper = new FileSelectHelper(profile);
file_select_helper->EnumerateDirectory(request_id,
tab->render_view_host(),
path);
}
| 0 |
pcre2 | d4fa336fbcc388f89095b184ba6d99422cfc676c | NOT_APPLICABLE | NOT_APPLICABLE | static BOOL optimize_class(compiler_common *common, const sljit_u8 *bits, BOOL nclass, BOOL invert, jump_list **backtracks)
{
/* May destroy TMP1. */
if (optimize_class_ranges(common, bits, nclass, invert, backtracks))
return TRUE;
return optimize_class_chars(common, bits, nclass, invert, backtracks);
} | 0 |
poppler | 8b6dc55e530b2f5ede6b9dfb64aafdd1d5836492 | CVE-2013-1788 | CWE-119 | SplashPath *Splash::makeDashedPath(SplashPath *path) {
SplashPath *dPath;
SplashCoord lineDashTotal;
SplashCoord lineDashStartPhase, lineDashDist, segLen;
SplashCoord x0, y0, x1, y1, xa, ya;
GBool lineDashStartOn, lineDashOn, newPath;
int lineDashStartIdx, lineDashIdx;
int i, j, k;
lineDashTotal = 0;
for (i = 0; i < state->lineDashLength; ++i) {
lineDashTotal += state->lineDash[i];
}
if (lineDashTotal == 0) {
return new SplashPath();
}
lineDashStartPhase = state->lineDashPhase;
i = splashFloor(lineDashStartPhase / lineDashTotal);
lineDashStartPhase -= (SplashCoord)i * lineDashTotal;
lineDashStartOn = gTrue;
lineDashStartIdx = 0;
if (lineDashStartPhase > 0) {
while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) {
lineDashStartOn = !lineDashStartOn;
lineDashStartPhase -= state->lineDash[lineDashStartIdx];
++lineDashStartIdx;
}
}
dPath = new SplashPath();
while (i < path->length) {
for (j = i;
j < path->length - 1 && !(path->flags[j] & splashPathLast);
++j) ;
lineDashOn = lineDashStartOn;
lineDashIdx = lineDashStartIdx;
lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase;
newPath = gTrue;
for (k = i; k < j; ++k) {
x0 = path->pts[k].x;
y0 = path->pts[k].y;
x1 = path->pts[k+1].x;
y1 = path->pts[k+1].y;
segLen = splashDist(x0, y0, x1, y1);
while (segLen > 0) {
if (lineDashDist >= segLen) {
if (lineDashOn) {
if (newPath) {
dPath->moveTo(x0, y0);
newPath = gFalse;
}
dPath->lineTo(x1, y1);
}
lineDashDist -= segLen;
segLen = 0;
} else {
xa = x0 + (lineDashDist / segLen) * (x1 - x0);
ya = y0 + (lineDashDist / segLen) * (y1 - y0);
if (lineDashOn) {
if (newPath) {
dPath->moveTo(x0, y0);
newPath = gFalse;
}
dPath->lineTo(xa, ya);
}
x0 = xa;
y0 = ya;
segLen -= lineDashDist;
lineDashDist = 0;
}
if (lineDashDist <= 0) {
lineDashOn = !lineDashOn;
if (++lineDashIdx == state->lineDashLength) {
lineDashIdx = 0;
}
lineDashDist = state->lineDash[lineDashIdx];
newPath = gTrue;
}
}
}
i = j + 1;
}
if (dPath->length == 0) {
GBool allSame = gTrue;
for (int i = 0; allSame && i < path->length - 1; ++i) {
allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y;
}
if (allSame) {
x0 = path->pts[0].x;
y0 = path->pts[0].y;
dPath->moveTo(x0, y0);
dPath->lineTo(x0, y0);
}
}
return dPath;
}
| 1 |
linux | 667121ace9dbafb368618dbabcf07901c962ddac | NOT_APPLICABLE | NOT_APPLICABLE | static void fwnet_broadcast_stop(struct fwnet_device *dev)
{
if (dev->broadcast_state == FWNET_BROADCAST_ERROR)
return;
fw_iso_context_stop(dev->broadcast_rcv_context);
__fwnet_broadcast_stop(dev);
}
| 0 |
Chrome | 87c724d81f0210494211cd36814c4cb2cf4c4bd1 | NOT_APPLICABLE | NOT_APPLICABLE | void P2PSocketDispatcherHost::OnDestruct() const {
BrowserThread::DeleteOnIOThread::Destruct(this);
}
| 0 |
irssi-proxy | 85bbc05b21678e80423815d2ef1dfe26208491ab | NOT_APPLICABLE | NOT_APPLICABLE | static GIOStatus irssi_ssl_set_flags(GIOChannel *handle, GIOFlags flags, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_set_flags(handle, flags, gerr);
}
| 0 |
ImageMagick6 | 072d7b10dbe74d1cf4ec0d008990c1a28c076f9e | NOT_APPLICABLE | NOT_APPLICABLE | MagickExport Image *StatisticImageChannel(const Image *image,
const ChannelType channel,const StatisticType type,const size_t width,
const size_t height,ExceptionInfo *exception)
{
#define StatisticImageTag "Statistic/Image"
CacheView
*image_view,
*statistic_view;
Image
*statistic_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelList
**magick_restrict pixel_list;
size_t
neighbor_height,
neighbor_width;
ssize_t
y;
/*
Initialize statistics image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
statistic_image=CloneImage(image,0,0,MagickTrue,exception);
if (statistic_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse)
{
InheritException(exception,&statistic_image->exception);
statistic_image=DestroyImage(statistic_image);
return((Image *) NULL);
}
neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) :
width;
neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) :
height;
pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height);
if (pixel_list == (PixelList **) NULL)
{
statistic_image=DestroyImage(statistic_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Make each pixel the min / max / median / mode / etc. of the neighborhood.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
statistic_view=AcquireAuthenticCacheView(statistic_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,statistic_image,statistic_image->rows,1)
#endif
for (y=0; y < (ssize_t) statistic_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
const IndexPacket
*magick_restrict indexes;
const PixelPacket
*magick_restrict p;
IndexPacket
*magick_restrict statistic_indexes;
PixelPacket
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y-
(ssize_t) (neighbor_height/2L),image->columns+neighbor_width,
neighbor_height,exception);
q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view);
for (x=0; x < (ssize_t) statistic_image->columns; x++)
{
MagickPixelPacket
pixel;
const IndexPacket
*magick_restrict s;
const PixelPacket
*magick_restrict r;
ssize_t
u,
v;
r=p;
s=indexes+x;
ResetPixelList(pixel_list[id]);
for (v=0; v < (ssize_t) neighbor_height; v++)
{
for (u=0; u < (ssize_t) neighbor_width; u++)
InsertPixelList(image,r+u,s+u,pixel_list[id]);
r+=image->columns+neighbor_width;
s+=image->columns+neighbor_width;
}
GetMagickPixelPacket(image,&pixel);
SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+
neighbor_width*neighbor_height/2,&pixel);
switch (type)
{
case GradientStatistic:
{
MagickPixelPacket
maximum,
minimum;
GetMinimumPixelList(pixel_list[id],&pixel);
minimum=pixel;
GetMaximumPixelList(pixel_list[id],&pixel);
maximum=pixel;
pixel.red=MagickAbsoluteValue(maximum.red-minimum.red);
pixel.green=MagickAbsoluteValue(maximum.green-minimum.green);
pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue);
pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity);
if (image->colorspace == CMYKColorspace)
pixel.index=MagickAbsoluteValue(maximum.index-minimum.index);
break;
}
case MaximumStatistic:
{
GetMaximumPixelList(pixel_list[id],&pixel);
break;
}
case MeanStatistic:
{
GetMeanPixelList(pixel_list[id],&pixel);
break;
}
case MedianStatistic:
default:
{
GetMedianPixelList(pixel_list[id],&pixel);
break;
}
case MinimumStatistic:
{
GetMinimumPixelList(pixel_list[id],&pixel);
break;
}
case ModeStatistic:
{
GetModePixelList(pixel_list[id],&pixel);
break;
}
case NonpeakStatistic:
{
GetNonpeakPixelList(pixel_list[id],&pixel);
break;
}
case RootMeanSquareStatistic:
{
GetRootMeanSquarePixelList(pixel_list[id],&pixel);
break;
}
case StandardDeviationStatistic:
{
GetStandardDeviationPixelList(pixel_list[id],&pixel);
break;
}
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(pixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,StatisticImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
statistic_view=DestroyCacheView(statistic_view);
image_view=DestroyCacheView(image_view);
pixel_list=DestroyPixelListThreadSet(pixel_list);
if (status == MagickFalse)
statistic_image=DestroyImage(statistic_image);
return(statistic_image);
} | 0 |
netfilter | 2ae1099a42e6a0f06de305ca13a842ac83d4683e | NOT_APPLICABLE | NOT_APPLICABLE | void add_param_to_argv(char *parsestart, int line)
{
int quote_open = 0, escaped = 0;
struct xt_param_buf param = {};
char *curchar;
/* After fighting with strtok enough, here's now
* a 'real' parser. According to Rusty I'm now no
} else {
param_buffer[param_len++] = *curchar;
for (curchar = parsestart; *curchar; curchar++) {
if (quote_open) {
if (escaped) {
add_param(¶m, curchar);
escaped = 0;
continue;
} else if (*curchar == '\\') {
}
switch (*curchar) {
quote_open = 0;
*curchar = '"';
} else {
add_param(¶m, curchar);
continue;
}
} else {
continue;
}
break;
default:
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
case ' ':
case '\t':
case '\n':
if (!param.len) {
/* two spaces? */
continue;
}
break;
default:
/* regular character, copy to buffer */
add_param(¶m, curchar);
continue;
}
param.buffer[param.len] = '\0';
/* check if table name specified */
if ((param.buffer[0] == '-' &&
param.buffer[1] != '-' &&
strchr(param.buffer, 't')) ||
(!strncmp(param.buffer, "--t", 3) &&
!strncmp(param.buffer, "--table", strlen(param.buffer)))) {
xtables_error(PARAMETER_PROBLEM,
"The -t option (seen in line %u) cannot be used in %s.\n",
line, xt_params->program_name);
}
add_argv(param.buffer, 0);
param.len = 0;
}
| 0 |
linux | 42cb14b110a5698ccf26ce59c4441722605a3743 | NOT_APPLICABLE | NOT_APPLICABLE | static int move_to_new_page(struct page *newpage, struct page *page,
enum migrate_mode mode)
{
struct address_space *mapping;
int rc;
VM_BUG_ON_PAGE(!PageLocked(page), page);
VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
mapping = page_mapping(page);
if (!mapping)
rc = migrate_page(mapping, newpage, page, mode);
else if (mapping->a_ops->migratepage)
/*
* Most pages have a mapping and most filesystems provide a
* migratepage callback. Anonymous pages are part of swap
* space which also has its own migratepage callback. This
* is the most common path for page migration.
*/
rc = mapping->a_ops->migratepage(mapping, newpage, page, mode);
else
rc = fallback_migrate_page(mapping, newpage, page, mode);
/*
* When successful, old pagecache page->mapping must be cleared before
* page is freed; but stats require that PageAnon be left as PageAnon.
*/
if (rc == MIGRATEPAGE_SUCCESS) {
set_page_memcg(page, NULL);
if (!PageAnon(page))
page->mapping = NULL;
}
return rc;
}
| 0 |
Subsets and Splits