instruction
stringclasses 1
value | input
stringlengths 90
9.3k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_wddx_serialize_object(wddx_packet *packet, zval *obj)
{
/* OBJECTS_FIXME */
zval **ent, *fname, **varname;
zval *retval = NULL;
const char *key;
ulong idx;
char tmp_buf[WDDX_BUF_LEN];
HashTable *objhash, *sleephash;
TSRMLS_FETCH();
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__sleep", 1);
/*
* We try to call __sleep() method on object. It's supposed to return an
* array of property names to be serialized.
*/
if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) {
if (retval && (sleephash = HASH_OF(retval))) {
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(sleephash);
zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS;
zend_hash_move_forward(sleephash)) {
if (Z_TYPE_PP(varname) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
continue;
}
if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) {
php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
} else {
uint key_len;
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(objhash);
zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(objhash)) {
if (*ent == obj) {
continue;
}
if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) {
const char *class_name, *prop_name;
zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name);
php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
Commit Message: Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle
Proper soltion would be to call serialize/unserialize and deal with the result,
but this requires more work that should be done by wddx maintainer (not me).
CWE ID: CWE-476 | static void php_wddx_serialize_object(wddx_packet *packet, zval *obj)
{
/* OBJECTS_FIXME */
zval **ent, *fname, **varname;
zval *retval = NULL;
const char *key;
ulong idx;
char tmp_buf[WDDX_BUF_LEN];
HashTable *objhash, *sleephash;
zend_class_entry *ce;
PHP_CLASS_ATTRIBUTES;
TSRMLS_FETCH();
PHP_SET_CLASS_ATTRIBUTES(obj);
ce = Z_OBJCE_P(obj);
if (!ce || ce->serialize || ce->unserialize) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be serialized", class_name);
PHP_CLEANUP_CLASS_ATTRIBUTES();
return;
}
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__sleep", 1);
/*
* We try to call __sleep() method on object. It's supposed to return an
* array of property names to be serialized.
*/
if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) {
if (retval && (sleephash = HASH_OF(retval))) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(sleephash);
zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS;
zend_hash_move_forward(sleephash)) {
if (Z_TYPE_PP(varname) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
continue;
}
if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) {
php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
} else {
uint key_len;
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(objhash);
zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(objhash)) {
if (*ent == obj) {
continue;
}
if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) {
const char *class_name, *prop_name;
zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name);
php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
PHP_CLEANUP_CLASS_ATTRIBUTES();
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
| 168,670 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct dentry *proc_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
int err;
struct super_block *sb;
struct pid_namespace *ns;
char *options;
if (flags & MS_KERNMOUNT) {
ns = (struct pid_namespace *)data;
options = NULL;
} else {
ns = task_active_pid_ns(current);
options = data;
/* Does the mounter have privilege over the pid namespace? */
if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
return ERR_PTR(-EPERM);
}
sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns);
if (IS_ERR(sb))
return ERR_CAST(sb);
if (!proc_parse_options(options, ns)) {
deactivate_locked_super(sb);
return ERR_PTR(-EINVAL);
}
if (!sb->s_root) {
err = proc_fill_super(sb);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
/* User space would break if executables appear on proc */
sb->s_iflags |= SB_I_NOEXEC;
}
return dget(sb->s_root);
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119 | static struct dentry *proc_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
int err;
struct super_block *sb;
struct pid_namespace *ns;
char *options;
if (flags & MS_KERNMOUNT) {
ns = (struct pid_namespace *)data;
options = NULL;
} else {
ns = task_active_pid_ns(current);
options = data;
/* Does the mounter have privilege over the pid namespace? */
if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
return ERR_PTR(-EPERM);
}
sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns);
if (IS_ERR(sb))
return ERR_CAST(sb);
/*
* procfs isn't actually a stacking filesystem; however, there is
* too much magic going on inside it to permit stacking things on
* top of it
*/
sb->s_stack_depth = FILESYSTEM_MAX_STACK_DEPTH;
if (!proc_parse_options(options, ns)) {
deactivate_locked_super(sb);
return ERR_PTR(-EINVAL);
}
if (!sb->s_root) {
err = proc_fill_super(sb);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
/* User space would break if executables appear on proc */
sb->s_iflags |= SB_I_NOEXEC;
}
return dget(sb->s_root);
}
| 167,444 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void pdf_load_pages_kids(FILE *fp, pdf_t *pdf)
{
int i, id, dummy;
char *buf, *c;
long start, sz;
start = ftell(fp);
/* Load all kids for all xref tables (versions) */
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0))
{
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
while (SAFE_F(fp, (fgetc(fp) != 't')))
; /* Iterate to trailer */
/* Get root catalog */
sz = pdf->xrefs[i].end - ftell(fp);
buf = malloc(sz + 1);
SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n");
buf[sz] = '\0';
if (!(c = strstr(buf, "/Root")))
{
free(buf);
continue;
}
/* Jump to catalog (root) */
id = atoi(c + strlen("/Root") + 1);
free(buf);
buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy);
if (!buf || !(c = strstr(buf, "/Pages")))
{
free(buf);
continue;
}
/* Start at the first Pages obj and get kids */
id = atoi(c + strlen("/Pages") + 1);
load_kids(fp, id, &pdf->xrefs[i]);
free(buf);
}
}
fseek(fp, start, SEEK_SET);
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787 | void pdf_load_pages_kids(FILE *fp, pdf_t *pdf)
{
int i, id, dummy;
char *buf, *c;
long start, sz;
start = ftell(fp);
/* Load all kids for all xref tables (versions) */
for (i=0; i<pdf->n_xrefs; i++)
{
if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0))
{
fseek(fp, pdf->xrefs[i].start, SEEK_SET);
while (SAFE_F(fp, (fgetc(fp) != 't')))
; /* Iterate to trailer */
/* Get root catalog */
sz = pdf->xrefs[i].end - ftell(fp);
buf = safe_calloc(sz + 1);
SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n");
buf[sz] = '\0';
if (!(c = strstr(buf, "/Root")))
{
free(buf);
continue;
}
/* Jump to catalog (root) */
id = atoi(c + strlen("/Root") + 1);
free(buf);
buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy);
if (!buf || !(c = strstr(buf, "/Pages")))
{
free(buf);
continue;
}
/* Start at the first Pages obj and get kids */
id = atoi(c + strlen("/Pages") + 1);
load_kids(fp, id, &pdf->xrefs[i]);
free(buf);
}
}
fseek(fp, start, SEEK_SET);
}
| 169,571 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Set(const std::string& addr, int value) {
base::AutoLock lock(lock_);
map_[addr] = value;
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void Set(const std::string& addr, int value) {
// Sets the |value| for |preview_id|.
void Set(int32 preview_id, int value) {
base::AutoLock lock(lock_);
map_[preview_id] = value;
}
| 170,842 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_background_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_byte colour_type, bit_depth;
png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
int expand;
png_color_16 back;
/* We need a background colour, because we don't know exactly what transforms
* have been set we have to supply the colour in the original file format and
* so we need to know what that is! The background colour is stored in the
* transform_display.
*/
RANDOMIZE(random_bytes);
/* Read the random value, for colour type 3 the background colour is actually
* expressed as a 24bit rgb, not an index.
*/
colour_type = that->this.colour_type;
if (colour_type == 3)
{
colour_type = PNG_COLOR_TYPE_RGB;
bit_depth = 8;
expand = 0; /* passing in an RGB not a pixel index */
}
else
{
bit_depth = that->this.bit_depth;
expand = 1;
}
image_pixel_init(&data, random_bytes, colour_type,
bit_depth, 0/*x*/, 0/*unused: palette*/);
/* Extract the background colour from this image_pixel, but make sure the
* unused fields of 'back' are garbage.
*/
RANDOMIZE(back);
if (colour_type & PNG_COLOR_MASK_COLOR)
{
back.red = (png_uint_16)data.red;
back.green = (png_uint_16)data.green;
back.blue = (png_uint_16)data.blue;
}
else
back.gray = (png_uint_16)data.red;
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
# else
png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
# endif
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_background_set(PNG_CONST image_transform *this,
image_transform_png_set_background_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_byte colour_type, bit_depth;
png_byte random_bytes[8]; /* 8 bytes - 64 bits - the biggest pixel */
int expand;
png_color_16 back;
/* We need a background colour, because we don't know exactly what transforms
* have been set we have to supply the colour in the original file format and
* so we need to know what that is! The background colour is stored in the
* transform_display.
*/
RANDOMIZE(random_bytes);
/* Read the random value, for colour type 3 the background colour is actually
* expressed as a 24bit rgb, not an index.
*/
colour_type = that->this.colour_type;
if (colour_type == 3)
{
colour_type = PNG_COLOR_TYPE_RGB;
bit_depth = 8;
expand = 0; /* passing in an RGB not a pixel index */
}
else
{
if (that->this.has_tRNS)
that->this.is_transparent = 1;
bit_depth = that->this.bit_depth;
expand = 1;
}
image_pixel_init(&data, random_bytes, colour_type,
bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/);
/* Extract the background colour from this image_pixel, but make sure the
* unused fields of 'back' are garbage.
*/
RANDOMIZE(back);
if (colour_type & PNG_COLOR_MASK_COLOR)
{
back.red = (png_uint_16)data.red;
back.green = (png_uint_16)data.green;
back.blue = (png_uint_16)data.blue;
}
else
back.gray = (png_uint_16)data.red;
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_background(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
# else
png_set_background_fixed(pp, &back, PNG_BACKGROUND_GAMMA_FILE, expand, 0);
# endif
this->next->set(this->next, that, pp, pi);
}
| 173,625 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void altivec_unavailable_exception(struct pt_regs *regs)
{
#if !defined(CONFIG_ALTIVEC)
if (user_mode(regs)) {
/* A user program has executed an altivec instruction,
but this kernel doesn't support altivec. */
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
return;
}
#endif
printk(KERN_EMERG "Unrecoverable VMX/Altivec Unavailable Exception "
"%lx at %lx\n", regs->trap, regs->nip);
die("Unrecoverable VMX/Altivec Unavailable Exception", regs, SIGABRT);
}
Commit Message: [POWERPC] Never panic when taking altivec exceptions from userspace
At the moment we rely on a cpu feature bit or a firmware property to
detect altivec. If we dont have either of these and the cpu does in fact
support altivec we can cause a panic from userspace.
It seems safer to always send a signal if we manage to get an 0xf20
exception from userspace.
Signed-off-by: Anton Blanchard <[email protected]>
Signed-off-by: Paul Mackerras <[email protected]>
CWE ID: CWE-19 | void altivec_unavailable_exception(struct pt_regs *regs)
{
if (user_mode(regs)) {
/* A user program has executed an altivec instruction,
but this kernel doesn't support altivec. */
_exception(SIGILL, regs, ILL_ILLOPC, regs->nip);
return;
}
printk(KERN_EMERG "Unrecoverable VMX/Altivec Unavailable Exception "
"%lx at %lx\n", regs->trap, regs->nip);
die("Unrecoverable VMX/Altivec Unavailable Exception", regs, SIGABRT);
}
| 168,920 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(RecursiveDirectoryIterator, getChildren)
{
zval *zpath, *zflags;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
spl_filesystem_object *subdir;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
MAKE_STD_ZVAL(zflags);
MAKE_STD_ZVAL(zpath);
ZVAL_LONG(zflags, intern->flags);
ZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1);
spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC);
zval_ptr_dtor(&zpath);
zval_ptr_dtor(&zflags);
subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC);
if (subdir) {
if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) {
subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
} else {
subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name);
subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len);
}
subdir->info_class = intern->info_class;
subdir->file_class = intern->file_class;
subdir->oth = intern->oth;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(RecursiveDirectoryIterator, getChildren)
{
zval *zpath, *zflags;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
spl_filesystem_object *subdir;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
MAKE_STD_ZVAL(zflags);
MAKE_STD_ZVAL(zpath);
ZVAL_LONG(zflags, intern->flags);
ZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1);
spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC);
zval_ptr_dtor(&zpath);
zval_ptr_dtor(&zflags);
subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC);
if (subdir) {
if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) {
subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
} else {
subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name);
subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len);
}
subdir->info_class = intern->info_class;
subdir->file_class = intern->file_class;
subdir->oth = intern->oth;
}
}
| 167,045 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
Commit Message: Fix always true condition (Thomas Jarosch)
CWE ID: CWE-119 | do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
| 167,628 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth)
{
memcpy(toBuffer, fromBuffer, bitWidth >> 3);
if ((bitWidth & 7) != 0)
{
unsigned int mask;
toBuffer += bitWidth >> 3;
fromBuffer += bitWidth >> 3;
/* The remaining bits are in the top of the byte, the mask is the bits to
* retain.
*/
mask = 0xff >> (bitWidth & 7);
*toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth)
row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth,
int littleendian)
{
memcpy(toBuffer, fromBuffer, bitWidth >> 3);
if ((bitWidth & 7) != 0)
{
unsigned int mask;
toBuffer += bitWidth >> 3;
fromBuffer += bitWidth >> 3;
if (littleendian)
mask = 0xff << (bitWidth & 7);
else
mask = 0xff >> (bitWidth & 7);
*toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask));
}
}
| 173,688 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string SanitizeRemoteBase(const std::string& value) {
GURL url(value);
std::string path = url.path();
std::vector<std::string> parts = base::SplitString(
path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
std::string revision = parts.size() > 2 ? parts[2] : "";
revision = SanitizeRevision(revision);
path = base::StringPrintf("/%s/%s/", kRemoteFrontendPath, revision.c_str());
return SanitizeFrontendURL(url, url::kHttpsScheme,
kRemoteFrontendDomain, path, false).spec();
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200 | std::string SanitizeRemoteBase(const std::string& value) {
| 172,462 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunFwdTxfm(int16_t *in, int16_t *out, int stride) {
void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride, tx_type_);
}
| 174,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static GIOChannel *irssi_ssl_get_iochannel(GIOChannel *handle, const char *mycert, const char *mypkey, const char *cafile, const char *capath, gboolean verify)
{
GIOSSLChannel *chan;
GIOChannel *gchan;
int fd;
SSL *ssl;
SSL_CTX *ctx = NULL;
g_return_val_if_fail(handle != NULL, NULL);
if(!ssl_ctx && !irssi_ssl_init())
return NULL;
if(!(fd = g_io_channel_unix_get_fd(handle)))
return NULL;
if (mycert && *mycert) {
char *scert = NULL, *spkey = NULL;
if ((ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
scert = convert_home(mycert);
if (mypkey && *mypkey)
spkey = convert_home(mypkey);
if (! SSL_CTX_use_certificate_file(ctx, scert, SSL_FILETYPE_PEM))
g_warning("Loading of client certificate '%s' failed", mycert);
else if (! SSL_CTX_use_PrivateKey_file(ctx, spkey ? spkey : scert, SSL_FILETYPE_PEM))
g_warning("Loading of private key '%s' failed", mypkey ? mypkey : mycert);
else if (! SSL_CTX_check_private_key(ctx))
g_warning("Private key does not match the certificate");
g_free(scert);
g_free(spkey);
}
if ((cafile && *cafile) || (capath && *capath)) {
char *scafile = NULL;
char *scapath = NULL;
if (! ctx && (ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
if (cafile && *cafile)
scafile = convert_home(cafile);
if (capath && *capath)
scapath = convert_home(capath);
if (! SSL_CTX_load_verify_locations(ctx, scafile, scapath)) {
g_warning("Could not load CA list for verifying SSL server certificate");
g_free(scafile);
g_free(scapath);
SSL_CTX_free(ctx);
return NULL;
}
g_free(scafile);
g_free(scapath);
verify = TRUE;
}
if (ctx == NULL)
ctx = ssl_ctx;
if(!(ssl = SSL_new(ctx)))
{
g_warning("Failed to allocate SSL structure");
return NULL;
}
if(!SSL_set_fd(ssl, fd))
{
g_warning("Failed to associate socket to SSL stream");
SSL_free(ssl);
if (ctx != ssl_ctx)
SSL_CTX_free(ctx);
return NULL;
}
SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
chan = g_new0(GIOSSLChannel, 1);
chan->fd = fd;
chan->giochan = handle;
chan->ssl = ssl;
chan->ctx = ctx;
chan->verify = verify;
gchan = (GIOChannel *)chan;
gchan->funcs = &irssi_ssl_channel_funcs;
g_io_channel_init(gchan);
gchan->is_readable = gchan->is_writeable = TRUE;
gchan->use_buffer = FALSE;
return gchan;
}
Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to
git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564
CWE ID: CWE-20 | static GIOChannel *irssi_ssl_get_iochannel(GIOChannel *handle, const char *mycert, const char *mypkey, const char *cafile, const char *capath, gboolean verify)
static GIOChannel *irssi_ssl_get_iochannel(GIOChannel *handle, const char *hostname, const char *mycert, const char *mypkey, const char *cafile, const char *capath, gboolean verify)
{
GIOSSLChannel *chan;
GIOChannel *gchan;
int fd;
SSL *ssl;
SSL_CTX *ctx = NULL;
g_return_val_if_fail(handle != NULL, NULL);
if(!ssl_ctx && !irssi_ssl_init())
return NULL;
if(!(fd = g_io_channel_unix_get_fd(handle)))
return NULL;
if (mycert && *mycert) {
char *scert = NULL, *spkey = NULL;
if ((ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
scert = convert_home(mycert);
if (mypkey && *mypkey)
spkey = convert_home(mypkey);
if (! SSL_CTX_use_certificate_file(ctx, scert, SSL_FILETYPE_PEM))
g_warning("Loading of client certificate '%s' failed", mycert);
else if (! SSL_CTX_use_PrivateKey_file(ctx, spkey ? spkey : scert, SSL_FILETYPE_PEM))
g_warning("Loading of private key '%s' failed", mypkey ? mypkey : mycert);
else if (! SSL_CTX_check_private_key(ctx))
g_warning("Private key does not match the certificate");
g_free(scert);
g_free(spkey);
}
if ((cafile && *cafile) || (capath && *capath)) {
char *scafile = NULL;
char *scapath = NULL;
if (! ctx && (ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
if (cafile && *cafile)
scafile = convert_home(cafile);
if (capath && *capath)
scapath = convert_home(capath);
if (! SSL_CTX_load_verify_locations(ctx, scafile, scapath)) {
g_warning("Could not load CA list for verifying SSL server certificate");
g_free(scafile);
g_free(scapath);
SSL_CTX_free(ctx);
return NULL;
}
g_free(scafile);
g_free(scapath);
verify = TRUE;
}
if (ctx == NULL)
ctx = ssl_ctx;
if(!(ssl = SSL_new(ctx)))
{
g_warning("Failed to allocate SSL structure");
return NULL;
}
if(!SSL_set_fd(ssl, fd))
{
g_warning("Failed to associate socket to SSL stream");
SSL_free(ssl);
if (ctx != ssl_ctx)
SSL_CTX_free(ctx);
return NULL;
}
SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
chan = g_new0(GIOSSLChannel, 1);
chan->fd = fd;
chan->giochan = handle;
chan->ssl = ssl;
chan->ctx = ctx;
chan->verify = verify;
chan->hostname = hostname;
gchan = (GIOChannel *)chan;
gchan->funcs = &irssi_ssl_channel_funcs;
g_io_channel_init(gchan);
gchan->is_readable = gchan->is_writeable = TRUE;
gchan->use_buffer = FALSE;
return gchan;
}
| 165,516 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id)
{
if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE))
IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u "
"addr %pM\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) {
IWL_DEBUG_ASSOC(priv,
"STA id %u addr %pM already present in uCode "
"(according to driver)\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
} else {
priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE;
IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
}
}
Commit Message: iwlwifi: Sanity check for sta_id
On my testing, I saw some strange behavior
[ 421.739708] iwlwifi 0000:01:00.0: ACTIVATE a non DRIVER active station id 148 addr 00:00:00:00:00:00
[ 421.739719] iwlwifi 0000:01:00.0: iwl_sta_ucode_activate Added STA id 148 addr 00:00:00:00:00:00 to uCode
not sure how it happen, but adding the sanity check to prevent memory
corruption
Signed-off-by: Wey-Yi Guy <[email protected]>
Signed-off-by: John W. Linville <[email protected]>
CWE ID: CWE-119 | static void iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id)
static int iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id)
{
if (sta_id >= IWLAGN_STATION_COUNT) {
IWL_ERR(priv, "invalid sta_id %u", sta_id);
return -EINVAL;
}
if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE))
IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u "
"addr %pM\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) {
IWL_DEBUG_ASSOC(priv,
"STA id %u addr %pM already present in uCode "
"(according to driver)\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
} else {
priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE;
IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n",
sta_id, priv->stations[sta_id].sta.sta.addr);
}
return 0;
}
| 169,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static unsigned int seedsize(struct crypto_alg *alg)
{
struct rng_alg *ralg = container_of(alg, struct rng_alg, base);
return alg->cra_rng.rng_make_random ?
alg->cra_rng.seedsize : ralg->seedsize;
}
Commit Message: crypto: rng - Remove old low-level rng interface
Now that all rng implementations have switched over to the new
interface, we can remove the old low-level interface.
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-476 | static unsigned int seedsize(struct crypto_alg *alg)
{
struct rng_alg *ralg = container_of(alg, struct rng_alg, base);
return ralg->seedsize;
}
| 167,735 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Chapters::Edition::Init()
{
m_atoms = NULL;
m_atoms_size = 0;
m_atoms_count = 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | void Chapters::Edition::Init()
m_displays = NULL;
m_displays_size = 0;
m_displays_count = 0;
}
| 174,386 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static __inline__ int scm_check_creds(struct ucred *creds)
{
const struct cred *cred = current_cred();
kuid_t uid = make_kuid(cred->user_ns, creds->uid);
kgid_t gid = make_kgid(cred->user_ns, creds->gid);
if (!uid_valid(uid) || !gid_valid(gid))
return -EINVAL;
if ((creds->pid == task_tgid_vnr(current) ||
ns_capable(current->nsproxy->pid_ns->user_ns, CAP_SYS_ADMIN)) &&
((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) ||
uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) &&
((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) ||
gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) {
return 0;
}
return -EPERM;
}
Commit Message: net: Check the correct namespace when spoofing pid over SCM_RIGHTS
This is a security bug.
The follow-up will fix nsproxy to discourage this type of issue from
happening again.
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Reviewed-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static __inline__ int scm_check_creds(struct ucred *creds)
{
const struct cred *cred = current_cred();
kuid_t uid = make_kuid(cred->user_ns, creds->uid);
kgid_t gid = make_kgid(cred->user_ns, creds->gid);
if (!uid_valid(uid) || !gid_valid(gid))
return -EINVAL;
if ((creds->pid == task_tgid_vnr(current) ||
ns_capable(task_active_pid_ns(current)->user_ns, CAP_SYS_ADMIN)) &&
((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) ||
uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) &&
((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) ||
gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) {
return 0;
}
return -EPERM;
}
| 165,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static unsigned short get_ushort(const unsigned char *data)
{
unsigned short val = *(const unsigned short *)data;
#ifdef OPJ_BIG_ENDIAN
val = ((val & 0xffU) << 8) | (val >> 8);
#endif
return val;
}
Commit Message: tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995)
CWE ID: CWE-787 | static unsigned short get_ushort(const unsigned char *data)
/* Returns a ushort from a little-endian serialized value */
static unsigned short get_tga_ushort(const unsigned char *data)
{
return data[0] | (data[1] << 8);
}
| 167,780 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DownloadController::StartAndroidDownloadInternal(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download, const DownloadInfo& info, bool allowed) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!allowed)
return;
WebContents* web_contents = wc_getter.Run();
if (!web_contents)
return;
base::string16 filename = net::GetSuggestedFilename(
info.url, info.content_disposition,
std::string(), // referrer_charset
std::string(), // suggested_name
info.original_mime_type,
default_file_name_);
ChromeDownloadDelegate::FromWebContents(web_contents)->RequestHTTPGetDownload(
info.url.spec(), info.user_agent,
info.content_disposition, info.original_mime_type,
info.cookie, info.referer, filename,
info.total_bytes, info.has_user_gesture,
must_download);
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254 | void DownloadController::StartAndroidDownloadInternal(
| 171,884 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXNodeObject::isPressed() const {
if (!isButton())
return false;
Node* node = this->getNode();
if (!node)
return false;
if (ariaRoleAttribute() == ToggleButtonRole) {
if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true") ||
equalIgnoringCase(getAttribute(aria_pressedAttr), "mixed"))
return true;
return false;
}
return node->isActive();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXNodeObject::isPressed() const {
if (!isButton())
return false;
Node* node = this->getNode();
if (!node)
return false;
if (ariaRoleAttribute() == ToggleButtonRole) {
if (equalIgnoringASCIICase(getAttribute(aria_pressedAttr), "true") ||
equalIgnoringASCIICase(getAttribute(aria_pressedAttr), "mixed"))
return true;
return false;
}
return node->isActive();
}
| 171,918 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::string16 FormatBookmarkURLForDisplay(const GURL& url) {
return url_formatter::FormatUrl(
url, url_formatter::kFormatUrlOmitAll &
~url_formatter::kFormatUrlOmitUsernamePassword,
net::UnescapeRule::SPACES, nullptr, nullptr, nullptr);
}
Commit Message: Prevent interpretating userinfo as url scheme when editing bookmarks
Chrome's Edit Bookmark dialog formats urls for display such that a
url of http://javascript:[email protected] is later converted to a
javascript url scheme, allowing persistence of a script injection
attack within the user's bookmarks.
This fix prevents such misinterpretations by always showing the
scheme when a userinfo component is present within the url.
BUG=639126
Review-Url: https://codereview.chromium.org/2368593002
Cr-Commit-Position: refs/heads/master@{#422467}
CWE ID: CWE-79 | base::string16 FormatBookmarkURLForDisplay(const GURL& url) {
// and trailing slash, and unescape most characters. However, it's
url_formatter::FormatUrlTypes format_types =
url_formatter::kFormatUrlOmitAll &
~url_formatter::kFormatUrlOmitUsernamePassword;
// If username is present, we must not omit the scheme because FixupURL() will
// subsequently interpret the username as a scheme. crbug.com/639126
if (url.has_username())
format_types &= ~url_formatter::kFormatUrlOmitHTTP;
return url_formatter::FormatUrl(url, format_types, net::UnescapeRule::SPACES,
nullptr, nullptr, nullptr);
}
| 172,103 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebDevToolsAgentImpl::clearBrowserCookies()
{
m_client->clearBrowserCookies();
}
Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser.
BUG=366585
Review URL: https://codereview.chromium.org/251183005
git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void WebDevToolsAgentImpl::clearBrowserCookies()
| 171,349 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, valid)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) {
RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval);
} else {
RETVAL_BOOL(!php_stream_eof(intern->u.file.stream));
}
} /* }}} */
/* {{{ proto string SplFileObject::fgets()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, valid)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) {
RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval);
} else {
RETVAL_BOOL(!php_stream_eof(intern->u.file.stream));
}
} /* }}} */
/* {{{ proto string SplFileObject::fgets()
| 167,053 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
{
int c;
int x, y;
int tox, toy;
int ydest;
int i;
int colorMap[gdMaxColors];
/* Stretch vectors */
int *stx, *sty;
if (overflow2(sizeof(int), srcW)) {
return;
}
if (overflow2(sizeof(int), srcH)) {
return;
}
stx = (int *) gdMalloc (sizeof (int) * srcW);
sty = (int *) gdMalloc (sizeof (int) * srcH);
/* Fixed by Mao Morimoto 2.0.16 */
for (i = 0; (i < srcW); i++) {
stx[i] = dstW * (i+1) / srcW - dstW * i / srcW ;
}
for (i = 0; (i < srcH); i++) {
sty[i] = dstH * (i+1) / srcH - dstH * i / srcH ;
}
for (i = 0; (i < gdMaxColors); i++) {
colorMap[i] = (-1);
}
toy = dstY;
for (y = srcY; (y < (srcY + srcH)); y++) {
for (ydest = 0; (ydest < sty[y - srcY]); ydest++) {
tox = dstX;
for (x = srcX; (x < (srcX + srcW)); x++) {
int nc = 0;
int mapTo;
if (!stx[x - srcX]) {
continue;
}
if (dst->trueColor) {
/* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */
if (!src->trueColor) {
int tmp = gdImageGetPixel (src, x, y);
mapTo = gdImageGetTrueColorPixel (src, x, y);
if (gdImageGetTransparent (src) == tmp) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
} else {
/* TK: old code follows */
mapTo = gdImageGetTrueColorPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == mapTo) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
}
} else {
c = gdImageGetPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == c) {
tox += stx[x - srcX];
continue;
}
if (src->trueColor) {
/* Remap to the palette available in the destination image. This is slow and works badly. */
mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c),
gdTrueColorGetGreen(c),
gdTrueColorGetBlue(c),
gdTrueColorGetAlpha (c));
} else {
/* Have we established a mapping for this color? */
if (colorMap[c] == (-1)) {
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
/* Find or create the best match */
/* 2.0.5: can't use gdTrueColorGetRed, etc with palette */
nc = gdImageColorResolveAlpha(dst, gdImageRed(src, c),
gdImageGreen(src, c),
gdImageBlue(src, c),
gdImageAlpha(src, c));
}
colorMap[c] = nc;
}
mapTo = colorMap[c];
}
}
for (i = 0; (i < stx[x - srcX]); i++) {
gdImageSetPixel (dst, tox, toy, mapTo);
tox++;
}
}
toy++;
}
}
gdFree (stx);
gdFree (sty);
}
Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow
CWE ID: CWE-190 | void gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
{
int c;
int x, y;
int tox, toy;
int ydest;
int i;
int colorMap[gdMaxColors];
/* Stretch vectors */
int *stx, *sty;
if (overflow2(sizeof(int), srcW)) {
return;
}
if (overflow2(sizeof(int), srcH)) {
return;
}
stx = (int *) gdMalloc (sizeof (int) * srcW);
sty = (int *) gdMalloc (sizeof (int) * srcH);
/* Fixed by Mao Morimoto 2.0.16 */
for (i = 0; (i < srcW); i++) {
stx[i] = dstW * (i+1) / srcW - dstW * i / srcW ;
}
for (i = 0; (i < srcH); i++) {
sty[i] = dstH * (i+1) / srcH - dstH * i / srcH ;
}
for (i = 0; (i < gdMaxColors); i++) {
colorMap[i] = (-1);
}
toy = dstY;
for (y = srcY; (y < (srcY + srcH)); y++) {
for (ydest = 0; (ydest < sty[y - srcY]); ydest++) {
tox = dstX;
for (x = srcX; (x < (srcX + srcW)); x++) {
int nc = 0;
int mapTo;
if (!stx[x - srcX]) {
continue;
}
if (dst->trueColor) {
/* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */
if (!src->trueColor) {
int tmp = gdImageGetPixel (src, x, y);
mapTo = gdImageGetTrueColorPixel (src, x, y);
if (gdImageGetTransparent (src) == tmp) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
} else {
/* TK: old code follows */
mapTo = gdImageGetTrueColorPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == mapTo) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
}
} else {
c = gdImageGetPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == c) {
tox += stx[x - srcX];
continue;
}
if (src->trueColor) {
/* Remap to the palette available in the destination image. This is slow and works badly. */
mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c),
gdTrueColorGetGreen(c),
gdTrueColorGetBlue(c),
gdTrueColorGetAlpha (c));
} else {
/* Have we established a mapping for this color? */
if (colorMap[c] == (-1)) {
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
/* Find or create the best match */
/* 2.0.5: can't use gdTrueColorGetRed, etc with palette */
nc = gdImageColorResolveAlpha(dst, gdImageRed(src, c),
gdImageGreen(src, c),
gdImageBlue(src, c),
gdImageAlpha(src, c));
}
colorMap[c] = nc;
}
mapTo = colorMap[c];
}
}
for (i = 0; (i < stx[x - srcX]); i++) {
gdImageSetPixel (dst, tox, toy, mapTo);
tox++;
}
}
toy++;
}
}
gdFree (stx);
gdFree (sty);
}
| 167,126 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void usb_serial_console_disconnect(struct usb_serial *serial)
{
if (serial->port[0] == usbcons_info.port) {
usb_serial_console_exit();
usb_serial_put(serial);
}
}
Commit Message: USB: serial: console: fix use-after-free on disconnect
A clean-up patch removing two redundant NULL-checks from the console
disconnect handler inadvertently also removed a third check. This could
lead to the struct usb_serial being prematurely freed by the console
code when a driver accepts but does not register any ports for an
interface which also lacks endpoint descriptors.
Fixes: 0e517c93dc02 ("USB: serial: console: clean up sanity checks")
Cc: stable <[email protected]> # 4.11
Reported-by: Andrey Konovalov <[email protected]>
Acked-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-416 | void usb_serial_console_disconnect(struct usb_serial *serial)
{
if (serial->port[0] && serial->port[0] == usbcons_info.port) {
usb_serial_console_exit();
usb_serial_put(serial);
}
}
| 170,012 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool FrameSelection::SetSelectionDeprecated(
const SelectionInDOMTree& passed_selection,
const SetSelectionData& options) {
DCHECK(IsAvailable());
passed_selection.AssertValidFor(GetDocument());
SelectionInDOMTree::Builder builder(passed_selection);
if (ShouldAlwaysUseDirectionalSelection(frame_))
builder.SetIsDirectional(true);
SelectionInDOMTree new_selection = builder.Build();
if (granularity_strategy_ && !options.DoNotClearStrategy())
granularity_strategy_->Clear();
granularity_ = options.Granularity();
if (options.ShouldCloseTyping())
TypingCommand::CloseTyping(frame_);
if (options.ShouldClearTypingStyle())
frame_->GetEditor().ClearTypingStyle();
const SelectionInDOMTree old_selection_in_dom_tree =
selection_editor_->GetSelectionInDOMTree();
if (old_selection_in_dom_tree == new_selection)
return false;
selection_editor_->SetSelection(new_selection);
ScheduleVisualUpdateForPaintInvalidationIfNeeded();
const Document& current_document = GetDocument();
frame_->GetEditor().RespondToChangedSelection(
old_selection_in_dom_tree.ComputeStartPosition(),
options.ShouldCloseTyping() ? TypingContinuation::kEnd
: TypingContinuation::kContinue);
DCHECK_EQ(current_document, GetDocument());
return true;
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <[email protected]>
Reviewed-by: Xiaocheng Hu <[email protected]>
Reviewed-by: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119 | bool FrameSelection::SetSelectionDeprecated(
const SelectionInDOMTree& passed_selection,
const SetSelectionData& options) {
DCHECK(IsAvailable());
passed_selection.AssertValidFor(GetDocument());
SelectionInDOMTree::Builder builder(passed_selection);
if (ShouldAlwaysUseDirectionalSelection(frame_))
builder.SetIsDirectional(true);
SelectionInDOMTree new_selection = builder.Build();
if (granularity_strategy_ && !options.DoNotClearStrategy())
granularity_strategy_->Clear();
granularity_ = options.Granularity();
if (options.ShouldCloseTyping())
TypingCommand::CloseTyping(frame_);
if (options.ShouldClearTypingStyle())
frame_->GetEditor().ClearTypingStyle();
const SelectionInDOMTree old_selection_in_dom_tree =
selection_editor_->GetSelectionInDOMTree();
const bool is_changed = old_selection_in_dom_tree != new_selection;
const bool should_show_handle = options.ShouldShowHandle();
if (!is_changed && is_handle_visible_ == should_show_handle)
return false;
if (is_changed)
selection_editor_->SetSelection(new_selection);
is_handle_visible_ = should_show_handle;
ScheduleVisualUpdateForPaintInvalidationIfNeeded();
const Document& current_document = GetDocument();
frame_->GetEditor().RespondToChangedSelection(
old_selection_in_dom_tree.ComputeStartPosition(),
options.ShouldCloseTyping() ? TypingContinuation::kEnd
: TypingContinuation::kContinue);
DCHECK_EQ(current_document, GetDocument());
return true;
}
| 171,760 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UpdateForDataChange(int days_since_last_update) {
MaintainContentLengthPrefsWindow(original_update_.Get(), kNumDaysInHistory);
MaintainContentLengthPrefsWindow(received_update_.Get(), kNumDaysInHistory);
if (days_since_last_update) {
MaintainContentLengthPrefsForDateChange(
original_update_.Get(), received_update_.Get(),
days_since_last_update);
}
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void UpdateForDataChange(int days_since_last_update) {
original_.UpdateForDataChange(days_since_last_update);
received_.UpdateForDataChange(days_since_last_update);
}
| 171,329 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
if (state->buf_kern_start == NULL) {
unsigned int offset = buf_start - (char *) base;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
if (ret < 0)
return ret;
}
startoff = state->buf_user_offset - startoff;
if (WARN_ON(*total < startoff))
return -EINVAL;
*total -= startoff;
return 0;
}
Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets
We need to make sure the offsets are not out of range of the
total size.
Also check that they are in ascending order.
The WARN_ON triggered by syzkaller (it sets panic_on_warn) is
changed to also bail out, no point in continuing parsing.
Briefly tested with simple ruleset of
-A INPUT --limit 1/s' --log
plus jump to custom chains using 32bit ebtables binary.
Reported-by: <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-787 | static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0; i < 4 ; ++i) {
if (offsets[i] >= *total)
return -EINVAL;
if (i == 0)
continue;
if (offsets[i-1] > offsets[i])
return -EINVAL;
}
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
if (state->buf_kern_start == NULL) {
unsigned int offset = buf_start - (char *) base;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
if (ret < 0)
return ret;
}
startoff = state->buf_user_offset - startoff;
if (WARN_ON(*total < startoff))
return -EINVAL;
*total -= startoff;
return 0;
}
| 169,358 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void reflectStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Element* impl = V8Element::toImpl(holder);
v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::reflectstringattributeAttr), info.GetIsolate());
}
Commit Message: binding: Removes unused code in templates/attributes.cpp.
Faking {{cpp_class}} and {{c8_class}} doesn't make sense.
Probably it made sense before the introduction of virtual
ScriptWrappable::wrap().
Checking the existence of window->document() doesn't seem
making sense to me, and CQ tests seem passing without the
check.
BUG=
Review-Url: https://codereview.chromium.org/2268433002
Cr-Commit-Position: refs/heads/master@{#413375}
CWE ID: CWE-189 | static void reflectStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceNode* impl = V8TestInterfaceNode::toImpl(holder);
v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::reflectstringattributeAttr), info.GetIsolate());
}
| 171,597 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DownloadRequestLimiter::TabDownloadState::SetDownloadStatusAndNotifyImpl(
DownloadStatus status,
ContentSetting setting) {
DCHECK((GetSettingFromDownloadStatus(status) == setting) ||
(GetDownloadStatusFromSetting(setting) == status))
<< "status " << status << " and setting " << setting
<< " do not correspond to each other";
ContentSetting last_setting = GetSettingFromDownloadStatus(status_);
DownloadUiStatus last_ui_status = ui_status_;
status_ = status;
ui_status_ = GetUiStatusFromDownloadStatus(status_, download_seen_);
if (!web_contents())
return;
if (last_setting == setting && last_ui_status == ui_status_)
return;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
content::Source<content::WebContents>(web_contents()),
content::NotificationService::NoDetails());
}
Commit Message: Don't reset TabDownloadState on history back/forward
Currently performing forward/backward on a tab will reset the TabDownloadState.
Which allows javascript code to do trigger multiple downloads.
This CL disables that behavior by not resetting the TabDownloadState on
forward/back.
It is still possible to reset the TabDownloadState through user gesture
or using browser initiated download.
BUG=848535
Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863
Reviewed-on: https://chromium-review.googlesource.com/1108959
Commit-Queue: Min Qin <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#574437}
CWE ID: | void DownloadRequestLimiter::TabDownloadState::SetDownloadStatusAndNotifyImpl(
DownloadStatus status,
ContentSetting setting) {
DCHECK((GetSettingFromDownloadStatus(status) == setting) ||
(GetDownloadStatusFromSetting(setting) == status))
<< "status " << status << " and setting " << setting
<< " do not correspond to each other";
ContentSetting last_setting = GetSettingFromDownloadStatus(status_);
DownloadUiStatus last_ui_status = ui_status_;
status_ = status;
ui_status_ = GetUiStatusFromDownloadStatus(status_, download_seen_);
if (!web_contents())
return;
if (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED) {
if (!initial_page_host_.empty())
restricted_hosts_.emplace(initial_page_host_);
}
if (last_setting == setting && last_ui_status == ui_status_)
return;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
content::Source<content::WebContents>(web_contents()),
content::NotificationService::NoDetails());
}
| 173,190 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mm_sshpam_init_ctx(Authctxt *authctxt)
{
Buffer m;
int success;
debug3("%s", __func__);
buffer_init(&m);
buffer_put_cstring(&m, authctxt->user);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pam_init_ctx failed", __func__);
buffer_free(&m);
return (NULL);
}
buffer_free(&m);
return (authctxt);
}
Commit Message: Don't resend username to PAM; it already has it.
Pointed out by Moritz Jodeit; ok dtucker@
CWE ID: CWE-20 | mm_sshpam_init_ctx(Authctxt *authctxt)
{
Buffer m;
int success;
debug3("%s", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pam_init_ctx failed", __func__);
buffer_free(&m);
return (NULL);
}
buffer_free(&m);
return (authctxt);
}
| 166,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long mkvparser::UnserializeFloat(
IMkvReader* pReader,
long long pos,
long long size_,
double& result)
{
assert(pReader);
assert(pos >= 0);
if ((size_ != 4) && (size_ != 8))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) //error
return status;
if (size == 4)
{
union
{
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;)
{
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
}
else
{
assert(size == 8);
union
{
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;)
{
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long mkvparser::UnserializeFloat(
{
signed char b;
const long status = pReader->Read(pos, 1, (unsigned char*)&b);
if (status < 0)
return status;
result = b;
++pos;
}
for (long i = 1; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return 0; // success
}
| 174,447 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
{
searchpath_t *search;
long len;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
for(search = fs_searchpaths; search; search = search->next)
{
len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
if(file == NULL)
{
if(len > 0)
return len;
}
else
{
if(len >= 0 && *file)
return len;
}
}
#ifdef FS_MISSING
if(missingFiles)
fprintf(missingFiles, "%s\n", filename);
#endif
if(file)
{
*file = 0;
return -1;
}
else
{
return 0;
}
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269 | long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
{
searchpath_t *search;
long len;
qboolean isLocalConfig;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG);
for(search = fs_searchpaths; search; search = search->next)
{
// autoexec.cfg and wolfconfig.cfg can only be loaded outside of pk3 files.
if (isLocalConfig && search->pack)
continue;
len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
if(file == NULL)
{
if(len > 0)
return len;
}
else
{
if(len >= 0 && *file)
return len;
}
}
#ifdef FS_MISSING
if(missingFiles)
fprintf(missingFiles, "%s\n", filename);
#endif
if(file)
{
*file = 0;
return -1;
}
else
{
return 0;
}
}
| 170,087 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int check_mtab(const char *progname, const char *devname,
const char *dir)
{
if (check_newline(progname, devname) == -1 ||
check_newline(progname, dir) == -1)
return EX_USAGE;
return 0;
}
Commit Message:
CWE ID: CWE-20 | static int check_mtab(const char *progname, const char *devname,
const char *dir)
{
if (check_newline(progname, devname) || check_newline(progname, dir))
return EX_USAGE;
return 0;
}
| 164,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: perform_transform_test(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
while (next_format(&colour_type, &bit_depth, &palette_number, 0))
{
png_uint_32 counter = 0;
size_t base_pos;
char name[64];
base_pos = safecat(name, sizeof name, 0, "transform:");
for (;;)
{
size_t pos = base_pos;
PNG_CONST image_transform *list = 0;
/* 'max' is currently hardwired to '1'; this should be settable on the
* command line.
*/
counter = image_transform_add(&list, 1/*max*/, counter,
name, sizeof name, &pos, colour_type, bit_depth);
if (counter == 0)
break;
/* The command line can change this to checking interlaced images. */
do
{
pm->repeat = 0;
transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
pm->interlace_type, 0, 0, 0), list, name);
if (fail(pm))
return;
}
while (pm->repeat);
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | perform_transform_test(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg,
pm->test_tRNS))
{
png_uint_32 counter = 0;
size_t base_pos;
char name[64];
base_pos = safecat(name, sizeof name, 0, "transform:");
for (;;)
{
size_t pos = base_pos;
const image_transform *list = 0;
/* 'max' is currently hardwired to '1'; this should be settable on the
* command line.
*/
counter = image_transform_add(&list, 1/*max*/, counter,
name, sizeof name, &pos, colour_type, bit_depth);
if (counter == 0)
break;
/* The command line can change this to checking interlaced images. */
do
{
pm->repeat = 0;
transform_test(pm, FILEID(colour_type, bit_depth, palette_number,
pm->interlace_type, 0, 0, 0), list, name);
if (fail(pm))
return;
}
while (pm->repeat);
}
}
}
| 173,684 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out)
{
#if 0
jp2_pclr_t *pclr = &box->data.pclr;
#endif
/* Eliminate warning about unused variable. */
box = 0;
out = 0;
return -1;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476 | static int jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out)
{
#if 0
jp2_pclr_t *pclr = &box->data.pclr;
#endif
/* Eliminate warning about unused variable. */
box = 0;
out = 0;
return -1;
}
| 168,324 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DataReductionProxyConfig::InitializeOnIOThread(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
WarmupURLFetcher::CreateCustomProxyConfigCallback
create_custom_proxy_config_callback,
NetworkPropertiesManager* manager,
const std::string& user_agent) {
DCHECK(thread_checker_.CalledOnValidThread());
network_properties_manager_ = manager;
network_properties_manager_->ResetWarmupURLFetchMetrics();
secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory));
warmup_url_fetcher_.reset(new WarmupURLFetcher(
create_custom_proxy_config_callback,
base::BindRepeating(
&DataReductionProxyConfig::HandleWarmupFetcherResponse,
base::Unretained(this)),
base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate,
base::Unretained(this)),
ui_task_runner_, user_agent));
AddDefaultProxyBypassRules();
network_connection_tracker_->AddNetworkConnectionObserver(this);
network_connection_tracker_->GetConnectionType(
&connection_type_,
base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged,
weak_factory_.GetWeakPtr()));
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | void DataReductionProxyConfig::InitializeOnIOThread(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
WarmupURLFetcher::CreateCustomProxyConfigCallback
create_custom_proxy_config_callback,
NetworkPropertiesManager* manager,
const std::string& user_agent) {
DCHECK(thread_checker_.CalledOnValidThread());
network_properties_manager_ = manager;
network_properties_manager_->ResetWarmupURLFetchMetrics();
if (!params::IsIncludedInHoldbackFieldTrial()) {
secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory));
warmup_url_fetcher_.reset(new WarmupURLFetcher(
create_custom_proxy_config_callback,
base::BindRepeating(
&DataReductionProxyConfig::HandleWarmupFetcherResponse,
base::Unretained(this)),
base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate,
base::Unretained(this)),
ui_task_runner_, user_agent));
}
AddDefaultProxyBypassRules();
network_connection_tracker_->AddNetworkConnectionObserver(this);
network_connection_tracker_->GetConnectionType(
&connection_type_,
base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged,
weak_factory_.GetWeakPtr()));
}
| 172,416 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"passwordsAndAutofillPageTitle",
IDS_SETTINGS_PASSWORDS_AND_AUTOFILL_PAGE_TITLE},
{"autofill", IDS_SETTINGS_AUTOFILL},
{"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS},
{"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED},
{"addresses", IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING},
{"addAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_ADD_TITLE},
{"editAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_EDIT_TITLE},
{"addressCountry", IDS_SETTINGS_AUTOFILL_ADDRESSES_COUNTRY},
{"addressPhone", IDS_SETTINGS_AUTOFILL_ADDRESSES_PHONE},
{"addressEmail", IDS_SETTINGS_AUTOFILL_ADDRESSES_EMAIL},
{"removeAddress", IDS_SETTINGS_ADDRESS_REMOVE},
{"creditCards", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_HEADING},
{"removeCreditCard", IDS_SETTINGS_CREDIT_CARD_REMOVE},
{"clearCreditCard", IDS_SETTINGS_CREDIT_CARD_CLEAR},
{"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL},
{"creditCardExpiration", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_DATE},
{"creditCardName", IDS_SETTINGS_NAME_ON_CREDIT_CARD},
{"creditCardNumber", IDS_SETTINGS_CREDIT_CARD_NUMBER},
{"creditCardExpirationMonth", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_MONTH},
{"creditCardExpirationYear", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_YEAR},
{"creditCardExpired", IDS_SETTINGS_CREDIT_CARD_EXPIRED},
{"editCreditCardTitle", IDS_SETTINGS_EDIT_CREDIT_CARD_TITLE},
{"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE},
{"autofillDetail", IDS_SETTINGS_AUTOFILL_DETAIL},
{"passwords", IDS_SETTINGS_PASSWORDS},
{"passwordsAutosigninLabel",
IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL},
{"passwordsAutosigninDescription",
IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC},
{"passwordsDetail", IDS_SETTINGS_PASSWORDS_DETAIL},
{"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING},
{"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING},
{"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION},
{"removePassword", IDS_SETTINGS_PASSWORD_REMOVE},
{"searchPasswords", IDS_SETTINGS_PASSWORD_SEARCH},
{"showPassword", IDS_SETTINGS_PASSWORD_SHOW},
{"hidePassword", IDS_SETTINGS_PASSWORD_HIDE},
{"passwordDetailsTitle", IDS_SETTINGS_PASSWORDS_VIEW_DETAILS_TITLE},
{"passwordViewDetails", IDS_SETTINGS_PASSWORD_DETAILS},
{"editPasswordWebsiteLabel", IDS_SETTINGS_PASSWORDS_WEBSITE},
{"editPasswordUsernameLabel", IDS_SETTINGS_PASSWORDS_USERNAME},
{"editPasswordPasswordLabel", IDS_SETTINGS_PASSWORDS_PASSWORD},
{"noAddressesFound", IDS_SETTINGS_ADDRESS_NONE},
{"noCreditCardsFound", IDS_SETTINGS_CREDIT_CARD_NONE},
{"noCreditCardsPolicy", IDS_SETTINGS_CREDIT_CARD_DISABLED},
{"noPasswordsFound", IDS_SETTINGS_PASSWORDS_NONE},
{"noExceptionsFound", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_NONE},
{"import", IDS_PASSWORD_MANAGER_IMPORT_BUTTON},
{"exportMenuItem", IDS_SETTINGS_PASSWORDS_EXPORT_MENU_ITEM},
{"undoRemovePassword", IDS_SETTINGS_PASSWORD_UNDO},
{"passwordDeleted", IDS_SETTINGS_PASSWORD_DELETED_PASSWORD},
{"exportPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORT_TITLE},
{"exportPasswordsDescription", IDS_SETTINGS_PASSWORDS_EXPORT_DESCRIPTION},
{"exportPasswords", IDS_SETTINGS_PASSWORDS_EXPORT},
{"exportingPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORTING_TITLE},
{"exportPasswordsTryAgain", IDS_SETTINGS_PASSWORDS_EXPORT_TRY_AGAIN},
{"exportPasswordsFailTitle",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TITLE},
{"exportPasswordsFailTips",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIPS},
{"exportPasswordsFailTipsEnoughSpace",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ENOUGH_SPACE},
{"exportPasswordsFailTipsAnotherFolder",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ANOTHER_FOLDER}};
html_source->AddString(
"managePasswordsLabel",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS,
base::ASCIIToUTF16(
password_manager::kPasswordManagerAccountDashboardURL)));
html_source->AddString("passwordManagerLearnMoreURL",
chrome::kPasswordManagerLearnMoreURL);
html_source->AddString("manageAddressesUrl",
autofill::payments::GetManageAddressesUrl(0).spec());
html_source->AddString("manageCreditCardsUrl",
autofill::payments::GetManageInstrumentsUrl(0).spec());
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
}
Commit Message: [md-settings] Clarify Password Saving and Autofill Toggles
This change clarifies the wording around the password saving and
autofill toggles.
Bug: 822465
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I91b31fe61cd0754239f7908e8c04c7e69b72f670
Reviewed-on: https://chromium-review.googlesource.com/970541
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Reviewed-by: Vaclav Brozek <[email protected]>
Reviewed-by: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#544661}
CWE ID: CWE-200 | void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"passwordsAndAutofillPageTitle",
IDS_SETTINGS_PASSWORDS_AND_AUTOFILL_PAGE_TITLE},
{"autofill", IDS_SETTINGS_AUTOFILL},
{"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS},
{"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED},
{"autofillFormsLabel", IDS_SETTINGS_AUTOFILL_TOGGLE_LABEL},
{"addresses", IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING},
{"addAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_ADD_TITLE},
{"editAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_EDIT_TITLE},
{"addressCountry", IDS_SETTINGS_AUTOFILL_ADDRESSES_COUNTRY},
{"addressPhone", IDS_SETTINGS_AUTOFILL_ADDRESSES_PHONE},
{"addressEmail", IDS_SETTINGS_AUTOFILL_ADDRESSES_EMAIL},
{"removeAddress", IDS_SETTINGS_ADDRESS_REMOVE},
{"creditCards", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_HEADING},
{"removeCreditCard", IDS_SETTINGS_CREDIT_CARD_REMOVE},
{"clearCreditCard", IDS_SETTINGS_CREDIT_CARD_CLEAR},
{"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL},
{"creditCardExpiration", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_DATE},
{"creditCardName", IDS_SETTINGS_NAME_ON_CREDIT_CARD},
{"creditCardNumber", IDS_SETTINGS_CREDIT_CARD_NUMBER},
{"creditCardExpirationMonth", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_MONTH},
{"creditCardExpirationYear", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_YEAR},
{"creditCardExpired", IDS_SETTINGS_CREDIT_CARD_EXPIRED},
{"editCreditCardTitle", IDS_SETTINGS_EDIT_CREDIT_CARD_TITLE},
{"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE},
{"autofillDetail", IDS_SETTINGS_AUTOFILL_DETAIL},
{"passwords", IDS_SETTINGS_PASSWORDS},
{"passwordsSavePasswordsLabel",
IDS_SETTINGS_PASSWORDS_SAVE_PASSWORDS_TOGGLE_LABEL},
{"passwordsAutosigninLabel",
IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL},
{"passwordsAutosigninDescription",
IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC},
{"passwordsDetail", IDS_SETTINGS_PASSWORDS_DETAIL},
{"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING},
{"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING},
{"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION},
{"removePassword", IDS_SETTINGS_PASSWORD_REMOVE},
{"searchPasswords", IDS_SETTINGS_PASSWORD_SEARCH},
{"showPassword", IDS_SETTINGS_PASSWORD_SHOW},
{"hidePassword", IDS_SETTINGS_PASSWORD_HIDE},
{"passwordDetailsTitle", IDS_SETTINGS_PASSWORDS_VIEW_DETAILS_TITLE},
{"passwordViewDetails", IDS_SETTINGS_PASSWORD_DETAILS},
{"editPasswordWebsiteLabel", IDS_SETTINGS_PASSWORDS_WEBSITE},
{"editPasswordUsernameLabel", IDS_SETTINGS_PASSWORDS_USERNAME},
{"editPasswordPasswordLabel", IDS_SETTINGS_PASSWORDS_PASSWORD},
{"noAddressesFound", IDS_SETTINGS_ADDRESS_NONE},
{"noCreditCardsFound", IDS_SETTINGS_CREDIT_CARD_NONE},
{"noCreditCardsPolicy", IDS_SETTINGS_CREDIT_CARD_DISABLED},
{"noPasswordsFound", IDS_SETTINGS_PASSWORDS_NONE},
{"noExceptionsFound", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_NONE},
{"import", IDS_PASSWORD_MANAGER_IMPORT_BUTTON},
{"exportMenuItem", IDS_SETTINGS_PASSWORDS_EXPORT_MENU_ITEM},
{"undoRemovePassword", IDS_SETTINGS_PASSWORD_UNDO},
{"passwordDeleted", IDS_SETTINGS_PASSWORD_DELETED_PASSWORD},
{"exportPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORT_TITLE},
{"exportPasswordsDescription", IDS_SETTINGS_PASSWORDS_EXPORT_DESCRIPTION},
{"exportPasswords", IDS_SETTINGS_PASSWORDS_EXPORT},
{"exportingPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORTING_TITLE},
{"exportPasswordsTryAgain", IDS_SETTINGS_PASSWORDS_EXPORT_TRY_AGAIN},
{"exportPasswordsFailTitle",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TITLE},
{"exportPasswordsFailTips",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIPS},
{"exportPasswordsFailTipsEnoughSpace",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ENOUGH_SPACE},
{"exportPasswordsFailTipsAnotherFolder",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ANOTHER_FOLDER}};
html_source->AddString(
"managePasswordsLabel",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS,
base::ASCIIToUTF16(
password_manager::kPasswordManagerAccountDashboardURL)));
html_source->AddString("passwordManagerLearnMoreURL",
chrome::kPasswordManagerLearnMoreURL);
html_source->AddString("manageAddressesUrl",
autofill::payments::GetManageAddressesUrl(0).spec());
html_source->AddString("manageCreditCardsUrl",
autofill::payments::GetManageInstrumentsUrl(0).spec());
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
}
| 172,794 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
png_colorp palette, int num_palette)
{
png_debug1(1, "in %s storage function", "PLTE");
if (png_ptr == NULL || info_ptr == NULL)
return;
if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
{
if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
png_error(png_ptr, "Invalid palette length");
else
{
png_warning(png_ptr, "Invalid palette length");
return;
}
}
/* It may not actually be necessary to set png_ptr->palette here;
* we do it for backward compatibility with the way the png_handle_tRNS
* function used to do the allocation.
*/
#ifdef PNG_FREE_ME_SUPPORTED
png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
#endif
/* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
* of num_palette entries, in case of an invalid PNG file that has
* too-large sample values.
*/
png_ptr->palette = (png_colorp)png_calloc(png_ptr,
PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color));
info_ptr->palette = png_ptr->palette;
info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
#ifdef PNG_FREE_ME_SUPPORTED
info_ptr->free_me |= PNG_FREE_PLTE;
#else
png_ptr->flags |= PNG_FLAG_FREE_PLTE;
#endif
info_ptr->valid |= PNG_INFO_PLTE;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
png_colorp palette, int num_palette)
{
png_uint_32 max_palette_length;
png_debug1(1, "in %s storage function", "PLTE");
if (png_ptr == NULL || info_ptr == NULL)
return;
max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
(1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
if (num_palette < 0 || num_palette > (int) max_palette_length)
{
if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
png_error(png_ptr, "Invalid palette length");
else
{
png_warning(png_ptr, "Invalid palette length");
return;
}
}
/* It may not actually be necessary to set png_ptr->palette here;
* we do it for backward compatibility with the way the png_handle_tRNS
* function used to do the allocation.
*/
#ifdef PNG_FREE_ME_SUPPORTED
png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
#endif
/* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
* of num_palette entries, in case of an invalid PNG file or incorrect
* call to png_set_PLTE() with too-large sample values.
*/
png_ptr->palette = (png_colorp)png_calloc(png_ptr,
PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color));
info_ptr->palette = png_ptr->palette;
info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
#ifdef PNG_FREE_ME_SUPPORTED
info_ptr->free_me |= PNG_FREE_PLTE;
#else
png_ptr->flags |= PNG_FLAG_FREE_PLTE;
#endif
info_ptr->valid |= PNG_INFO_PLTE;
}
| 172,183 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
Commit Message:
CWE ID: CWE-264 | static void set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
switch (bits_per_pixel) {
case 8:
case 16:
case 32:
break;
default:
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
| 164,902 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadUYVYImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
u,
v,
y1,
y2;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if ((image->columns % 2) != 0)
image->columns++;
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Accumulate UYVY, then unpack into two pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns >> 1); x++)
{
u=(unsigned char) ReadBlobByte(image);
y1=(unsigned char) ReadBlobByte(image);
v=(unsigned char) ReadBlobByte(image);
y2=(unsigned char) ReadBlobByte(image);
SetPixelRed(q,ScaleCharToQuantum(y1));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
SetPixelRed(q,ScaleCharToQuantum(y2));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetImageColorspace(image,YCbCrColorspace);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadUYVYImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
u,
v,
y1,
y2;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
if ((image->columns % 2) != 0)
image->columns++;
(void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Accumulate UYVY, then unpack into two pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns >> 1); x++)
{
u=(unsigned char) ReadBlobByte(image);
y1=(unsigned char) ReadBlobByte(image);
v=(unsigned char) ReadBlobByte(image);
y2=(unsigned char) ReadBlobByte(image);
SetPixelRed(q,ScaleCharToQuantum(y1));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
SetPixelRed(q,ScaleCharToQuantum(y2));
SetPixelGreen(q,ScaleCharToQuantum(u));
SetPixelBlue(q,ScaleCharToQuantum(v));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetImageColorspace(image,YCbCrColorspace);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_key) {
DCHECK(QuerySharedMemorySupport(display));
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shared_memory_key;
if (!XShmAttach(display, &shminfo))
NOTREACHED();
return shminfo.shmseg;
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_key) {
DCHECK(QuerySharedMemorySupport(display));
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shared_memory_key;
if (!XShmAttach(display, &shminfo)) {
LOG(WARNING) << "X failed to attach to shared memory segment "
<< shminfo.shmid;
NOTREACHED();
} else {
VLOG(1) << "X attached to shared memory segment " << shminfo.shmid;
}
return shminfo.shmseg;
}
| 171,593 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothOptionsHandler::DisplayPasskey(
chromeos::BluetoothDevice* device,
int passkey,
int entered) {
}
Commit Message: Implement methods for pairing of bluetooth devices.
BUG=chromium:100392,chromium:102139
TEST=
Review URL: http://codereview.chromium.org/8495018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void BluetoothOptionsHandler::DisplayPasskey(
chromeos::BluetoothDevice* device,
int passkey,
int entered) {
DictionaryValue params;
params.SetString("pairing", "bluetoothRemotePasskey");
params.SetInteger("passkey", passkey);
params.SetInteger("entered", entered);
SendDeviceNotification(device, ¶ms);
}
| 170,967 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t FLACParser::init()
{
mDecoder = FLAC__stream_decoder_new();
if (mDecoder == NULL) {
ALOGE("new failed");
return NO_INIT;
}
FLAC__stream_decoder_set_md5_checking(mDecoder, false);
FLAC__stream_decoder_set_metadata_ignore_all(mDecoder);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_STREAMINFO);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_PICTURE);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
FLAC__StreamDecoderInitStatus initStatus;
initStatus = FLAC__stream_decoder_init_stream(
mDecoder,
read_callback, seek_callback, tell_callback,
length_callback, eof_callback, write_callback,
metadata_callback, error_callback, (void *) this);
if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
ALOGE("init_stream failed %d", initStatus);
return NO_INIT;
}
if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) {
ALOGE("end_of_metadata failed");
return NO_INIT;
}
if (mStreamInfoValid) {
if (getChannels() == 0 || getChannels() > 8) {
ALOGE("unsupported channel count %u", getChannels());
return NO_INIT;
}
switch (getBitsPerSample()) {
case 8:
case 16:
case 24:
break;
default:
ALOGE("unsupported bits per sample %u", getBitsPerSample());
return NO_INIT;
}
switch (getSampleRate()) {
case 8000:
case 11025:
case 12000:
case 16000:
case 22050:
case 24000:
case 32000:
case 44100:
case 48000:
case 88200:
case 96000:
break;
default:
ALOGE("unsupported sample rate %u", getSampleRate());
return NO_INIT;
}
static const struct {
unsigned mChannels;
unsigned mBitsPerSample;
void (*mCopy)(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels);
} table[] = {
{ 1, 8, copyMono8 },
{ 2, 8, copyStereo8 },
{ 8, 8, copyMultiCh8 },
{ 1, 16, copyMono16 },
{ 2, 16, copyStereo16 },
{ 8, 16, copyMultiCh16 },
{ 1, 24, copyMono24 },
{ 2, 24, copyStereo24 },
{ 8, 24, copyMultiCh24 },
};
for (unsigned i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
if (table[i].mChannels >= getChannels() &&
table[i].mBitsPerSample == getBitsPerSample()) {
mCopy = table[i].mCopy;
break;
}
}
if (mTrackMetadata != 0) {
mTrackMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
mTrackMetadata->setInt32(kKeyChannelCount, getChannels());
mTrackMetadata->setInt32(kKeySampleRate, getSampleRate());
mTrackMetadata->setInt32(kKeyPcmEncoding, kAudioEncodingPcm16bit);
mTrackMetadata->setInt64(kKeyDuration,
(getTotalSamples() * 1000000LL) / getSampleRate());
}
} else {
ALOGE("missing STREAMINFO");
return NO_INIT;
}
if (mFileMetadata != 0) {
mFileMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
}
return OK;
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | status_t FLACParser::init()
{
mDecoder = FLAC__stream_decoder_new();
if (mDecoder == NULL) {
ALOGE("new failed");
return NO_INIT;
}
FLAC__stream_decoder_set_md5_checking(mDecoder, false);
FLAC__stream_decoder_set_metadata_ignore_all(mDecoder);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_STREAMINFO);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_PICTURE);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
FLAC__StreamDecoderInitStatus initStatus;
initStatus = FLAC__stream_decoder_init_stream(
mDecoder,
read_callback, seek_callback, tell_callback,
length_callback, eof_callback, write_callback,
metadata_callback, error_callback, (void *) this);
if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
ALOGE("init_stream failed %d", initStatus);
return NO_INIT;
}
if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) {
ALOGE("end_of_metadata failed");
return NO_INIT;
}
if (mStreamInfoValid) {
if (getChannels() == 0 || getChannels() > kMaxChannels) {
ALOGE("unsupported channel count %u", getChannels());
return NO_INIT;
}
switch (getBitsPerSample()) {
case 8:
case 16:
case 24:
break;
default:
ALOGE("unsupported bits per sample %u", getBitsPerSample());
return NO_INIT;
}
switch (getSampleRate()) {
case 8000:
case 11025:
case 12000:
case 16000:
case 22050:
case 24000:
case 32000:
case 44100:
case 48000:
case 88200:
case 96000:
break;
default:
ALOGE("unsupported sample rate %u", getSampleRate());
return NO_INIT;
}
static const struct {
unsigned mChannels;
unsigned mBitsPerSample;
void (*mCopy)(short *dst, const int * src[kMaxChannels], unsigned nSamples, unsigned nChannels);
} table[] = {
{ 1, 8, copyMono8 },
{ 2, 8, copyStereo8 },
{ 8, 8, copyMultiCh8 },
{ 1, 16, copyMono16 },
{ 2, 16, copyStereo16 },
{ 8, 16, copyMultiCh16 },
{ 1, 24, copyMono24 },
{ 2, 24, copyStereo24 },
{ 8, 24, copyMultiCh24 },
};
for (unsigned i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
if (table[i].mChannels >= getChannels() &&
table[i].mBitsPerSample == getBitsPerSample()) {
mCopy = table[i].mCopy;
break;
}
}
if (mTrackMetadata != 0) {
mTrackMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
mTrackMetadata->setInt32(kKeyChannelCount, getChannels());
mTrackMetadata->setInt32(kKeySampleRate, getSampleRate());
mTrackMetadata->setInt32(kKeyPcmEncoding, kAudioEncodingPcm16bit);
mTrackMetadata->setInt64(kKeyDuration,
(getTotalSamples() * 1000000LL) / getSampleRate());
}
} else {
ALOGE("missing STREAMINFO");
return NO_INIT;
}
if (mFileMetadata != 0) {
mFileMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
}
return OK;
}
| 174,025 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_linux_shareopts(const char *shareopts, char **plinux_opts)
{
int rc;
assert(plinux_opts != NULL);
*plinux_opts = NULL;
/* default options for Solaris shares */
(void) add_linux_shareopt(plinux_opts, "no_subtree_check", NULL);
(void) add_linux_shareopt(plinux_opts, "no_root_squash", NULL);
(void) add_linux_shareopt(plinux_opts, "mountpoint", NULL);
rc = foreach_nfs_shareopt(shareopts, get_linux_shareopts_cb,
plinux_opts);
if (rc != SA_OK) {
free(*plinux_opts);
*plinux_opts = NULL;
}
return (rc);
}
Commit Message: Move nfs.c:foreach_nfs_shareopt() to libshare.c:foreach_shareopt()
so that it can be (re)used in other parts of libshare.
CWE ID: CWE-200 | get_linux_shareopts(const char *shareopts, char **plinux_opts)
{
int rc;
assert(plinux_opts != NULL);
*plinux_opts = NULL;
/* default options for Solaris shares */
(void) add_linux_shareopt(plinux_opts, "no_subtree_check", NULL);
(void) add_linux_shareopt(plinux_opts, "no_root_squash", NULL);
(void) add_linux_shareopt(plinux_opts, "mountpoint", NULL);
rc = foreach_shareopt(shareopts, get_linux_shareopts_cb,
plinux_opts);
if (rc != SA_OK) {
free(*plinux_opts);
*plinux_opts = NULL;
}
return (rc);
}
| 170,134 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
{
if (origin && BlobURL::getOrigin(url) == "null")
originMap()->add(url.string(), origin);
if (isMainThread())
blobRegistry().registerBlobURL(url, srcURL);
else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
callOnMainThread(®isterBlobURLFromTask, context.leakPtr());
}
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
void BlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
{
if (origin && BlobURL::getOrigin(url) == "null")
originMap()->add(url.string(), origin);
if (isMainThread()) {
if (WebBlobRegistry* registry = blobRegistry())
registry->registerBlobURL(url, srcURL);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
callOnMainThread(®isterBlobURLFromTask, context.leakPtr());
}
}
| 170,685 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ProcessControlLaunchFailed() {
ADD_FAILURE();
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
}
Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated().
Bug: 844016
Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0
Reviewed-on: https://chromium-review.googlesource.com/1126576
Commit-Queue: Wez <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573131}
CWE ID: CWE-94 | void ProcessControlLaunchFailed() {
void ProcessControlLaunchFailed(base::OnceClosure on_done) {
ADD_FAILURE();
std::move(on_done).Run();
}
| 172,052 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData,
OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 x, y;
OPJ_UINT8 *pix;
const OPJ_UINT8 *beyond;
beyond = pData + stride * height;
pix = pData;
x = y = 0U;
while (y < height) {
int c = getc(IN);
if (c == EOF) {
break;
}
if (c) { /* encoded mode */
int j;
OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN);
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
}
} else { /* absolute mode */
c = getc(IN);
if (c == EOF) {
break;
}
if (c == 0x00) { /* EOL */
x = 0;
y++;
pix = pData + y * stride;
} else if (c == 0x01) { /* EOP */
break;
} else if (c == 0x02) { /* MOVE by dxdy */
c = getc(IN);
x += (OPJ_UINT32)c;
c = getc(IN);
y += (OPJ_UINT32)c;
pix = pData + y * stride + x;
} else { /* 03 .. 255 : absolute mode */
int j;
OPJ_UINT8 c1 = 0U;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
if ((j & 1) == 0) {
c1 = (OPJ_UINT8)getc(IN);
}
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
}
if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */
getc(IN);
}
}
}
} /* while(y < height) */
return OPJ_TRUE;
}
Commit Message: convertbmp: detect invalid file dimensions early
width/length dimensions read from bmp headers are not necessarily
valid. For instance they may have been maliciously set to very large
values with the intention to cause DoS (large memory allocation, stack
overflow). In these cases we want to detect the invalid size as early
as possible.
This commit introduces a counter which verifies that the number of
written bytes corresponds to the advertized width/length.
See commit 8ee335227bbc for details.
Signed-off-by: Young Xiao <[email protected]>
CWE ID: CWE-400 | static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData,
OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 x, y, written;
OPJ_UINT8 *pix;
const OPJ_UINT8 *beyond;
beyond = pData + stride * height;
pix = pData;
x = y = written = 0U;
while (y < height) {
int c = getc(IN);
if (c == EOF) {
break;
}
if (c) { /* encoded mode */
int j;
OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN);
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
written++;
}
} else { /* absolute mode */
c = getc(IN);
if (c == EOF) {
break;
}
if (c == 0x00) { /* EOL */
x = 0;
y++;
pix = pData + y * stride;
} else if (c == 0x01) { /* EOP */
break;
} else if (c == 0x02) { /* MOVE by dxdy */
c = getc(IN);
x += (OPJ_UINT32)c;
c = getc(IN);
y += (OPJ_UINT32)c;
pix = pData + y * stride + x;
} else { /* 03 .. 255 : absolute mode */
int j;
OPJ_UINT8 c1 = 0U;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
if ((j & 1) == 0) {
c1 = (OPJ_UINT8)getc(IN);
}
*pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
written++;
}
if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */
getc(IN);
}
}
}
} /* while(y < height) */
if (written != width * height) {
fprintf(stderr, "warning, image's actual size does not match advertized one\n");
return OPJ_FALSE;
}
return OPJ_TRUE;
}
| 170,210 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20 | void SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip,
bool SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
uint8_t *pBuf;
if (outHeader) {
if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) {
android_errorWriteLog(0x534e4554, "27569635");
return false;
}
pBuf = outHeader->pBuffer;
} else {
// mFlushOutBuffer always has the right size.
pBuf = mFlushOutBuffer;
}
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return true;
}
| 174,182 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int tls1_set_server_sigalgs(SSL *s)
{
int al;
size_t i;
/* Clear any shared sigtnature algorithms */
if (s->cert->shared_sigalgs) {
OPENSSL_free(s->cert->shared_sigalgs);
s->cert->shared_sigalgs = NULL;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].valid_flags = 0;
}
/* If sigalgs received process it. */
if (s->cert->peer_sigalgs) {
if (!tls1_process_sigalgs(s)) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
/* Fatal error is no shared signature algorithms */
if (!s->cert->shared_sigalgs) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
al = SSL_AD_ILLEGAL_PARAMETER;
goto err;
}
} else
ssl_cert_set_default_md(s->cert);
return 1;
err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
Commit Message:
CWE ID: | int tls1_set_server_sigalgs(SSL *s)
{
int al;
size_t i;
/* Clear any shared sigtnature algorithms */
if (s->cert->shared_sigalgs) {
OPENSSL_free(s->cert->shared_sigalgs);
s->cert->shared_sigalgs = NULL;
s->cert->shared_sigalgslen = 0;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].valid_flags = 0;
}
/* If sigalgs received process it. */
if (s->cert->peer_sigalgs) {
if (!tls1_process_sigalgs(s)) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
/* Fatal error is no shared signature algorithms */
if (!s->cert->shared_sigalgs) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
al = SSL_AD_ILLEGAL_PARAMETER;
goto err;
}
} else
ssl_cert_set_default_md(s->cert);
return 1;
err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
| 164,804 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebResourceService::StartFetch() {
ScheduleFetch(cache_update_delay_ms_);
prefs_->SetString(last_update_time_pref_name_,
base::DoubleToString(base::Time::Now().ToDoubleT()));
if (in_fetch_)
return;
in_fetch_ = true;
GURL web_resource_server =
application_locale_.empty()
? web_resource_server_
: google_util::AppendGoogleLocaleParam(web_resource_server_,
application_locale_);
DVLOG(1) << "WebResourceService StartFetch " << web_resource_server;
url_fetcher_ =
net::URLFetcher::Create(web_resource_server, net::URLFetcher::GET, this);
url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
url_fetcher_->SetRequestContext(request_context_.get());
url_fetcher_->Start();
}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
CWE ID: CWE-190 | void WebResourceService::StartFetch() {
ScheduleFetch(cache_update_delay_ms_);
prefs_->SetString(last_update_time_pref_name_,
base::DoubleToString(base::Time::Now().ToDoubleT()));
if (in_fetch_)
return;
in_fetch_ = true;
GURL web_resource_server =
application_locale_.empty()
? web_resource_server_
: google_util::AppendGoogleLocaleParam(web_resource_server_,
application_locale_);
DVLOG(1) << "WebResourceService StartFetch " << web_resource_server;
url_fetcher_ =
net::URLFetcher::Create(web_resource_server, net::URLFetcher::GET, this);
data_use_measurement::DataUseUserData::AttachToFetcher(
url_fetcher_.get(),
data_use_measurement::DataUseUserData::WEB_RESOURCE_SERVICE);
url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
url_fetcher_->SetRequestContext(request_context_.get());
url_fetcher_->Start();
}
| 172,020 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
kvm_queue_exception(vcpu, UD_VECTOR);
return EMULATE_FAIL;
}
Commit Message: KVM: X86: Don't report L2 emulation failures to user-space
This patch prevents that emulation failures which result
from emulating an instruction for an L2-Guest results in
being reported to userspace.
Without this patch a malicious L2-Guest would be able to
kill the L1 by triggering a race-condition between an vmexit
and the instruction emulator.
With this patch the L2 will most likely only kill itself in
this situation.
Signed-off-by: Joerg Roedel <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
CWE ID: CWE-362 | static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
int r = EMULATE_DONE;
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
if (!is_guest_mode(vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
r = EMULATE_FAIL;
}
kvm_queue_exception(vcpu, UD_VECTOR);
return r;
}
| 166,558 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Block* SimpleBlock::GetBlock() const
{
return &m_block;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Block* SimpleBlock::GetBlock() const
| 174,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, fgets)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) {
RETURN_FALSE;
}
RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1);
} /* }}} */
/* {{{ proto string SplFileObject::current()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, fgets)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) {
RETURN_FALSE;
}
RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1);
} /* }}} */
/* {{{ proto string SplFileObject::current()
| 167,054 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string GetUploadData(const std::string& brand) {
DCHECK(!brand.empty());
std::string data(kPostXml);
const std::string placeholder("__BRANDCODE_PLACEHOLDER__");
size_t placeholder_pos = data.find(placeholder);
DCHECK(placeholder_pos != std::string::npos);
data.replace(placeholder_pos, placeholder.size(), brand);
return data;
}
Commit Message: Use install_static::GetAppGuid instead of the hardcoded string in BrandcodeConfigFetcher.
Bug: 769756
Change-Id: Ifdcb0a5145ffad1d563562e2b2ea2390ff074cdc
Reviewed-on: https://chromium-review.googlesource.com/1213178
Reviewed-by: Dominic Battré <[email protected]>
Commit-Queue: Vasilii Sukhanov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#590275}
CWE ID: CWE-79 | std::string GetUploadData(const std::string& brand) {
std::string app_id(kDefaultAppID);
#if defined(OS_WIN)
app_id = install_static::UTF16ToUTF8(install_static::GetAppGuid());
#endif // defined(OS_WIN)
DCHECK(!brand.empty());
return base::StringPrintf(kPostXml, app_id.c_str(), brand.c_str());
}
| 172,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Document::InitSecurityContext(const DocumentInit& initializer) {
DCHECK(!GetSecurityOrigin());
if (!initializer.HasSecurityContext()) {
cookie_url_ = KURL(kParsedURLString, g_empty_string);
SetSecurityOrigin(SecurityOrigin::CreateUnique());
InitContentSecurityPolicy();
SetFeaturePolicy(g_empty_string);
return;
}
EnforceSandboxFlags(initializer.GetSandboxFlags());
SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());
if (initializer.InsecureNavigationsToUpgrade()) {
for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())
AddInsecureNavigationUpgrade(to_upgrade);
}
if (IsSandboxed(kSandboxOrigin)) {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::CreateUnique());
Document* owner = initializer.OwnerDocument();
if (owner) {
if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy())
GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true);
if (owner->GetSecurityOrigin()->CanLoadLocalResources())
GetSecurityOrigin()->GrantLoadLocalResources();
}
} else if (Document* owner = initializer.OwnerDocument()) {
cookie_url_ = owner->CookieURL();
SetSecurityOrigin(owner->GetSecurityOrigin());
} else {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::Create(url_));
}
if (initializer.IsHostedInReservedIPRange()) {
SetAddressSpace(GetSecurityOrigin()->IsLocalhost()
? kWebAddressSpaceLocal
: kWebAddressSpacePrivate);
} else if (GetSecurityOrigin()->IsLocal()) {
SetAddressSpace(kWebAddressSpaceLocal);
} else {
SetAddressSpace(kWebAddressSpacePublic);
}
if (ImportsController()) {
SetContentSecurityPolicy(
ImportsController()->Master()->GetContentSecurityPolicy());
} else {
InitContentSecurityPolicy();
}
if (GetSecurityOrigin()->HasSuborigin())
EnforceSuborigin(*GetSecurityOrigin()->GetSuborigin());
if (Settings* settings = initializer.GetSettings()) {
if (!settings->GetWebSecurityEnabled()) {
GetSecurityOrigin()->GrantUniversalAccess();
} else if (GetSecurityOrigin()->IsLocal()) {
if (settings->GetAllowUniversalAccessFromFileURLs()) {
GetSecurityOrigin()->GrantUniversalAccess();
} else if (!settings->GetAllowFileAccessFromFileURLs()) {
GetSecurityOrigin()->BlockLocalAccessFromLocalOrigin();
}
}
}
if (GetSecurityOrigin()->IsUnique() &&
SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())
GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true);
if (GetSecurityOrigin()->HasSuborigin())
EnforceSuborigin(*GetSecurityOrigin()->GetSuborigin());
SetFeaturePolicy(g_empty_string);
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732 | void Document::InitSecurityContext(const DocumentInit& initializer) {
DCHECK(!GetSecurityOrigin());
if (!initializer.HasSecurityContext()) {
cookie_url_ = KURL(kParsedURLString, g_empty_string);
SetSecurityOrigin(SecurityOrigin::CreateUnique());
InitContentSecurityPolicy();
SetFeaturePolicy(g_empty_string);
return;
}
EnforceSandboxFlags(initializer.GetSandboxFlags());
SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());
if (initializer.InsecureNavigationsToUpgrade()) {
for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())
AddInsecureNavigationUpgrade(to_upgrade);
}
ContentSecurityPolicy* policy_to_inherit = nullptr;
if (IsSandboxed(kSandboxOrigin)) {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::CreateUnique());
Document* owner = initializer.OwnerDocument();
if (owner) {
if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy())
GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true);
if (owner->GetSecurityOrigin()->CanLoadLocalResources())
GetSecurityOrigin()->GrantLoadLocalResources();
policy_to_inherit = owner->GetContentSecurityPolicy();
}
} else if (Document* owner = initializer.OwnerDocument()) {
cookie_url_ = owner->CookieURL();
SetSecurityOrigin(owner->GetSecurityOrigin());
policy_to_inherit = owner->GetContentSecurityPolicy();
} else {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::Create(url_));
}
if (initializer.IsHostedInReservedIPRange()) {
SetAddressSpace(GetSecurityOrigin()->IsLocalhost()
? kWebAddressSpaceLocal
: kWebAddressSpacePrivate);
} else if (GetSecurityOrigin()->IsLocal()) {
SetAddressSpace(kWebAddressSpaceLocal);
} else {
SetAddressSpace(kWebAddressSpacePublic);
}
if (ImportsController()) {
SetContentSecurityPolicy(
ImportsController()->Master()->GetContentSecurityPolicy());
} else {
InitContentSecurityPolicy(nullptr, policy_to_inherit);
}
if (GetSecurityOrigin()->HasSuborigin())
EnforceSuborigin(*GetSecurityOrigin()->GetSuborigin());
if (Settings* settings = initializer.GetSettings()) {
if (!settings->GetWebSecurityEnabled()) {
GetSecurityOrigin()->GrantUniversalAccess();
} else if (GetSecurityOrigin()->IsLocal()) {
if (settings->GetAllowUniversalAccessFromFileURLs()) {
GetSecurityOrigin()->GrantUniversalAccess();
} else if (!settings->GetAllowFileAccessFromFileURLs()) {
GetSecurityOrigin()->BlockLocalAccessFromLocalOrigin();
}
}
}
if (GetSecurityOrigin()->IsUnique() &&
SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())
GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true);
if (GetSecurityOrigin()->HasSuborigin())
EnforceSuborigin(*GetSecurityOrigin()->GetSuborigin());
SetFeaturePolicy(g_empty_string);
}
| 172,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: header_put_le_short (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2)
{ psf->header [psf->headindex++] = x ;
psf->header [psf->headindex++] = (x >> 8) ;
} ;
} /* header_put_le_short */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_put_le_short (SF_PRIVATE *psf, int x)
{ psf->header.ptr [psf->header.indx++] = x ;
psf->header.ptr [psf->header.indx++] = (x >> 8) ;
} /* header_put_le_short */
| 170,058 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: store_pool_delete(png_store *ps, store_pool *pool)
{
if (pool->list != NULL)
{
fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
++ps->nerrors;
do
{
store_memory *next = pool->list;
pool->list = next->next;
next->next = NULL;
fprintf(stderr, "\t%lu bytes @ %p\n",
(unsigned long)next->size, (PNG_CONST void*)(next+1));
/* The NULL means this will always return, even if the memory is
* corrupted.
*/
store_memory_free(NULL, pool, next);
}
while (pool->list != NULL);
}
/* And reset the other fields too for the next time. */
if (pool->max > pool->max_max) pool->max_max = pool->max;
pool->max = 0;
if (pool->current != 0) /* unexpected internal error */
fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
ps->test, pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
pool->current = 0;
if (pool->limit > pool->max_limit)
pool->max_limit = pool->limit;
pool->limit = 0;
if (pool->total > pool->max_total)
pool->max_total = pool->total;
pool->total = 0;
/* Get a new mark too. */
store_pool_mark(pool->mark);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | store_pool_delete(png_store *ps, store_pool *pool)
{
if (pool->list != NULL)
{
fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
++ps->nerrors;
do
{
store_memory *next = pool->list;
pool->list = next->next;
next->next = NULL;
fprintf(stderr, "\t%lu bytes @ %p\n",
(unsigned long)next->size, (const void*)(next+1));
/* The NULL means this will always return, even if the memory is
* corrupted.
*/
store_memory_free(NULL, pool, next);
}
while (pool->list != NULL);
}
/* And reset the other fields too for the next time. */
if (pool->max > pool->max_max) pool->max_max = pool->max;
pool->max = 0;
if (pool->current != 0) /* unexpected internal error */
fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
ps->test, pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
pool->current = 0;
if (pool->limit > pool->max_limit)
pool->max_limit = pool->limit;
pool->limit = 0;
if (pool->total > pool->max_total)
pool->max_total = pool->total;
pool->total = 0;
/* Get a new mark too. */
store_pool_mark(pool->mark);
}
| 173,707 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_1_6_dummy(kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr)
{
int i;
char *password = *passptr;
/* Old-style randkey operations disallowed tickets to start. */
if (!(mask & KADM5_ATTRIBUTES) ||
!(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX))
return;
/* The 1.6 dummy password was the octets 1..255. */
for (i = 0; (unsigned char) password[i] == i + 1; i++);
if (password[i] != '\0' || i != 255)
return;
/* This will make the caller use a random password instead. */
*passptr = NULL;
}
Commit Message: Null pointer deref in kadmind [CVE-2012-1013]
The fix for #6626 could cause kadmind to dereference a null pointer if
a create-principal request contains no password but does contain the
KRB5_KDB_DISALLOW_ALL_TIX flag (e.g. "addprinc -randkey -allow_tix
name"). Only clients authorized to create principals can trigger the
bug. Fix the bug by testing for a null password in check_1_6_dummy.
CVSSv2 vector: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C
[[email protected]: Minor style change and commit message]
ticket: 7152
target_version: 1.10.2
tags: pullup
CWE ID: | check_1_6_dummy(kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr)
{
int i;
char *password = *passptr;
/* Old-style randkey operations disallowed tickets to start. */
if (password == NULL || !(mask & KADM5_ATTRIBUTES) ||
!(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX))
return;
/* The 1.6 dummy password was the octets 1..255. */
for (i = 0; (unsigned char) password[i] == i + 1; i++);
if (password[i] != '\0' || i != 255)
return;
/* This will make the caller use a random password instead. */
*passptr = NULL;
}
| 165,646 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Smb4KMountJob::fillArgs(Smb4KShare *share, QMap<QString, QVariant>& map)
{
QString mount;
QStringList paths;
paths << "/bin";
paths << "/sbin";
paths << "/usr/bin";
paths << "/usr/sbin";
paths << "/usr/local/bin";
paths << "/usr/local/sbin";
for (int i = 0; i < paths.size(); ++i)
{
mount = KGlobal::dirs()->findExe("mount.cifs", paths.at(i));
if (!mount.isEmpty())
{
map.insert("mh_command", mount);
break;
}
else
{
continue;
}
}
if (mount.isEmpty())
{
paths << "/sbin";
paths << "/usr/bin";
paths << "/usr/sbin";
paths << "/usr/local/bin";
paths << "/usr/local/sbin";
}
QMap<QString, QString> global_options = globalSambaOptions();
Smb4KCustomOptions *options = Smb4KCustomOptionsManager::self()->findOptions(share);
break;
}
Commit Message:
CWE ID: CWE-20 | bool Smb4KMountJob::fillArgs(Smb4KShare *share, QMap<QString, QVariant>& map)
{
const QString mount = findMountExecutable();
if (mount.isEmpty())
{
paths << "/sbin";
paths << "/usr/bin";
paths << "/usr/sbin";
paths << "/usr/local/bin";
paths << "/usr/local/sbin";
}
map.insert("mh_command", mount);
QMap<QString, QString> global_options = globalSambaOptions();
Smb4KCustomOptions *options = Smb4KCustomOptionsManager::self()->findOptions(share);
break;
}
| 164,825 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HostCache::ClearForHosts(
const base::Callback<bool(const std::string&)>& host_filter) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (host_filter.is_null()) {
clear();
return;
}
base::TimeTicks now = base::TimeTicks::Now();
for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) {
EntryMap::iterator next_it = std::next(it);
if (host_filter.Run(it->first.hostname)) {
RecordErase(ERASE_CLEAR, now, it->second);
entries_.erase(it);
}
it = next_it;
}
}
Commit Message: Add PersistenceDelegate to HostCache
PersistenceDelegate is a new interface for persisting the contents of
the HostCache. This commit includes the interface itself, the logic in
HostCache for interacting with it, and a mock implementation of the
interface for testing. It does not include support for immediate data
removal since that won't be needed for the currently planned use case.
BUG=605149
Review-Url: https://codereview.chromium.org/2943143002
Cr-Commit-Position: refs/heads/master@{#481015}
CWE ID: | void HostCache::ClearForHosts(
const base::Callback<bool(const std::string&)>& host_filter) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (host_filter.is_null()) {
clear();
return;
}
bool changed = false;
base::TimeTicks now = base::TimeTicks::Now();
for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) {
EntryMap::iterator next_it = std::next(it);
if (host_filter.Run(it->first.hostname)) {
RecordErase(ERASE_CLEAR, now, it->second);
entries_.erase(it);
changed = true;
}
it = next_it;
}
if (delegate_ && changed)
delegate_->ScheduleWrite();
}
| 172,006 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int find_high_bit(unsigned int x)
{
int i;
for(i=31;i>=0;i--) {
if(x&(1<<i)) return i;
}
return 0;
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682 | static int find_high_bit(unsigned int x)
{
int i;
for(i=31;i>=0;i--) {
if(x&(1U<<(unsigned int)i)) return i;
}
return 0;
}
| 168,194 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Block::Lacing Block::GetLacing() const
{
const int value = int(m_flags & 0x06) >> 1;
return static_cast<Lacing>(value);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Block::Lacing Block::GetLacing() const
const long status = pReader->Read(pos, len, buf);
return status;
}
| 174,335 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Initialize(ChannelLayout channel_layout, int bits_per_channel) {
AudioParameters params(
media::AudioParameters::AUDIO_PCM_LINEAR, channel_layout,
kSamplesPerSecond, bits_per_channel, kRawDataSize);
algorithm_.Initialize(1, params, base::Bind(
&AudioRendererAlgorithmTest::EnqueueData, base::Unretained(this)));
EnqueueData();
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void Initialize(ChannelLayout channel_layout, int bits_per_channel) {
void Initialize(ChannelLayout channel_layout, int bits_per_channel,
int samples_per_second) {
static const int kFrames = kRawDataSize / ((kDefaultSampleBits / 8) *
ChannelLayoutToChannelCount(kDefaultChannelLayout));
AudioParameters params(
media::AudioParameters::AUDIO_PCM_LINEAR, channel_layout,
samples_per_second, bits_per_channel, kFrames);
algorithm_.Initialize(1, params, base::Bind(
&AudioRendererAlgorithmTest::EnqueueData, base::Unretained(this)));
EnqueueData();
}
| 171,534 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
size_t size;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {
return -1;
}
dec->numtiles = size;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
Commit Message: Ensure that not all tiles lie outside the image area.
CWE ID: CWE-20 | static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
size_t size;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) {
return -1;
}
dec->numtiles = size;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
| 168,737 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const
{
assert(pTrack);
const long long n = pTrack->GetNumber();
const TrackPosition* i = m_track_positions;
const TrackPosition* const j = i + m_track_positions_count;
while (i != j)
{
const TrackPosition& p = *i++;
if (p.m_track == n)
return &p;
}
return NULL; //no matching track number found
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const
const long long n = pTrack->GetNumber();
const TrackPosition* i = m_track_positions;
const TrackPosition* const j = i + m_track_positions_count;
while (i != j) {
const TrackPosition& p = *i++;
if (p.m_track == n)
return &p;
}
return NULL; // no matching track number found
}
| 174,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void btif_config_flush(void) {
assert(config != NULL);
assert(alarm_timer != NULL);
alarm_cancel(alarm_timer);
pthread_mutex_lock(&lock);
config_save(config, CONFIG_FILE_PATH);
pthread_mutex_unlock(&lock);
}
Commit Message: Fix crashes with lots of discovered LE devices
When loads of devices are discovered a config file which is too large
can be written out, which causes the BT daemon to crash on startup.
This limits the number of config entries for unpaired devices which
are initialized, and prevents a large number from being saved to the
filesystem.
Bug: 26071376
Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184
CWE ID: CWE-119 | void btif_config_flush(void) {
assert(config != NULL);
assert(alarm_timer != NULL);
alarm_cancel(alarm_timer);
btif_config_write();
}
| 173,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsMLU* mlu;
cmsUInt32Number Count, RecLen, NumOfWchar;
cmsUInt32Number SizeOfHeader;
cmsUInt32Number Len, Offset;
cmsUInt32Number i;
wchar_t* Block;
cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition;
*nItems = 0;
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
if (!_cmsReadUInt32Number(io, &RecLen)) return NULL;
if (RecLen != 12) {
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "multiLocalizedUnicodeType of len != 12 is not supported.");
return NULL;
}
mlu = cmsMLUalloc(self ->ContextID, Count);
if (mlu == NULL) return NULL;
mlu ->UsedEntries = Count;
SizeOfHeader = 12 * Count + sizeof(_cmsTagBase);
LargestPosition = 0;
for (i=0; i < Count; i++) {
if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error;
if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error;
if (!_cmsReadUInt32Number(io, &Len)) goto Error;
if (!_cmsReadUInt32Number(io, &Offset)) goto Error;
if (Offset < (SizeOfHeader + 8)) goto Error;
BeginOfThisString = Offset - SizeOfHeader - 8;
mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
EndOfThisString = BeginOfThisString + Len;
if (EndOfThisString > LargestPosition)
LargestPosition = EndOfThisString;
}
SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
if (SizeOfTag == 0)
{
Block = NULL;
NumOfWchar = 0;
}
else
{
Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag);
if (Block == NULL) goto Error;
NumOfWchar = SizeOfTag / sizeof(wchar_t);
if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error;
}
mlu ->MemPool = Block;
mlu ->PoolSize = SizeOfTag;
mlu ->PoolUsed = SizeOfTag;
*nItems = 1;
return (void*) mlu;
Error:
if (mlu) cmsMLUfree(mlu);
return NULL;
}
Commit Message: Added an extra check to MLU bounds
Thanks to Ibrahim el-sayed for spotting the bug
CWE ID: CWE-125 | void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag)
{
cmsMLU* mlu;
cmsUInt32Number Count, RecLen, NumOfWchar;
cmsUInt32Number SizeOfHeader;
cmsUInt32Number Len, Offset;
cmsUInt32Number i;
wchar_t* Block;
cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition;
*nItems = 0;
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
if (!_cmsReadUInt32Number(io, &RecLen)) return NULL;
if (RecLen != 12) {
cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "multiLocalizedUnicodeType of len != 12 is not supported.");
return NULL;
}
mlu = cmsMLUalloc(self ->ContextID, Count);
if (mlu == NULL) return NULL;
mlu ->UsedEntries = Count;
SizeOfHeader = 12 * Count + sizeof(_cmsTagBase);
LargestPosition = 0;
for (i=0; i < Count; i++) {
if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error;
if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error;
if (!_cmsReadUInt32Number(io, &Len)) goto Error;
if (!_cmsReadUInt32Number(io, &Offset)) goto Error;
if (Offset < (SizeOfHeader + 8)) goto Error;
if ((Offset + Len) > SizeOfTag + 8) goto Error;
BeginOfThisString = Offset - SizeOfHeader - 8;
mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
EndOfThisString = BeginOfThisString + Len;
if (EndOfThisString > LargestPosition)
LargestPosition = EndOfThisString;
}
SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
if (SizeOfTag == 0)
{
Block = NULL;
NumOfWchar = 0;
}
else
{
Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag);
if (Block == NULL) goto Error;
NumOfWchar = SizeOfTag / sizeof(wchar_t);
if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error;
}
mlu ->MemPool = Block;
mlu ->PoolSize = SizeOfTag;
mlu ->PoolUsed = SizeOfTag;
*nItems = 1;
return (void*) mlu;
Error:
if (mlu) cmsMLUfree(mlu);
return NULL;
}
| 168,512 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SyncManager::MaybeSetSyncTabsInNigoriNode(
ModelTypeSet enabled_types) {
DCHECK(thread_checker_.CalledOnValidThread());
data_->MaybeSetSyncTabsInNigoriNode(enabled_types);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void SyncManager::MaybeSetSyncTabsInNigoriNode(
| 170,794 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void logi_dj_recv_add_djhid_device(struct dj_receiver_dev *djrcv_dev,
struct dj_report *dj_report)
{
/* Called in delayed work context */
struct hid_device *djrcv_hdev = djrcv_dev->hdev;
struct usb_interface *intf = to_usb_interface(djrcv_hdev->dev.parent);
struct usb_device *usbdev = interface_to_usbdev(intf);
struct hid_device *dj_hiddev;
struct dj_device *dj_dev;
/* Device index goes from 1 to 6, we need 3 bytes to store the
* semicolon, the index, and a null terminator
*/
unsigned char tmpstr[3];
if (dj_report->report_params[DEVICE_PAIRED_PARAM_SPFUNCTION] &
SPFUNCTION_DEVICE_LIST_EMPTY) {
dbg_hid("%s: device list is empty\n", __func__);
djrcv_dev->querying_devices = false;
return;
}
if ((dj_report->device_index < DJ_DEVICE_INDEX_MIN) ||
(dj_report->device_index > DJ_DEVICE_INDEX_MAX)) {
dev_err(&djrcv_hdev->dev, "%s: invalid device index:%d\n",
__func__, dj_report->device_index);
return;
}
if (djrcv_dev->paired_dj_devices[dj_report->device_index]) {
/* The device is already known. No need to reallocate it. */
dbg_hid("%s: device is already known\n", __func__);
return;
}
dj_hiddev = hid_allocate_device();
if (IS_ERR(dj_hiddev)) {
dev_err(&djrcv_hdev->dev, "%s: hid_allocate_device failed\n",
__func__);
return;
}
dj_hiddev->ll_driver = &logi_dj_ll_driver;
dj_hiddev->dev.parent = &djrcv_hdev->dev;
dj_hiddev->bus = BUS_USB;
dj_hiddev->vendor = le16_to_cpu(usbdev->descriptor.idVendor);
dj_hiddev->product = le16_to_cpu(usbdev->descriptor.idProduct);
snprintf(dj_hiddev->name, sizeof(dj_hiddev->name),
"Logitech Unifying Device. Wireless PID:%02x%02x",
dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_MSB],
dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_LSB]);
usb_make_path(usbdev, dj_hiddev->phys, sizeof(dj_hiddev->phys));
snprintf(tmpstr, sizeof(tmpstr), ":%d", dj_report->device_index);
strlcat(dj_hiddev->phys, tmpstr, sizeof(dj_hiddev->phys));
dj_dev = kzalloc(sizeof(struct dj_device), GFP_KERNEL);
if (!dj_dev) {
dev_err(&djrcv_hdev->dev, "%s: failed allocating dj_device\n",
__func__);
goto dj_device_allocate_fail;
}
dj_dev->reports_supported = get_unaligned_le32(
dj_report->report_params + DEVICE_PAIRED_RF_REPORT_TYPE);
dj_dev->hdev = dj_hiddev;
dj_dev->dj_receiver_dev = djrcv_dev;
dj_dev->device_index = dj_report->device_index;
dj_hiddev->driver_data = dj_dev;
djrcv_dev->paired_dj_devices[dj_report->device_index] = dj_dev;
if (hid_add_device(dj_hiddev)) {
dev_err(&djrcv_hdev->dev, "%s: failed adding dj_device\n",
__func__);
goto hid_add_device_fail;
}
return;
hid_add_device_fail:
djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL;
kfree(dj_dev);
dj_device_allocate_fail:
hid_destroy_device(dj_hiddev);
}
Commit Message: HID: logitech: perform bounds checking on device_id early enough
device_index is a char type and the size of paired_dj_deivces is 7
elements, therefore proper bounds checking has to be applied to
device_index before it is used.
We are currently performing the bounds checking in
logi_dj_recv_add_djhid_device(), which is too late, as malicious device
could send REPORT_TYPE_NOTIF_DEVICE_UNPAIRED early enough and trigger the
problem in one of the report forwarding functions called from
logi_dj_raw_event().
Fix this by performing the check at the earliest possible ocasion in
logi_dj_raw_event().
Cc: [email protected]
Reported-by: Ben Hawkes <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-119 | static void logi_dj_recv_add_djhid_device(struct dj_receiver_dev *djrcv_dev,
struct dj_report *dj_report)
{
/* Called in delayed work context */
struct hid_device *djrcv_hdev = djrcv_dev->hdev;
struct usb_interface *intf = to_usb_interface(djrcv_hdev->dev.parent);
struct usb_device *usbdev = interface_to_usbdev(intf);
struct hid_device *dj_hiddev;
struct dj_device *dj_dev;
/* Device index goes from 1 to 6, we need 3 bytes to store the
* semicolon, the index, and a null terminator
*/
unsigned char tmpstr[3];
if (dj_report->report_params[DEVICE_PAIRED_PARAM_SPFUNCTION] &
SPFUNCTION_DEVICE_LIST_EMPTY) {
dbg_hid("%s: device list is empty\n", __func__);
djrcv_dev->querying_devices = false;
return;
}
if (djrcv_dev->paired_dj_devices[dj_report->device_index]) {
/* The device is already known. No need to reallocate it. */
dbg_hid("%s: device is already known\n", __func__);
return;
}
dj_hiddev = hid_allocate_device();
if (IS_ERR(dj_hiddev)) {
dev_err(&djrcv_hdev->dev, "%s: hid_allocate_device failed\n",
__func__);
return;
}
dj_hiddev->ll_driver = &logi_dj_ll_driver;
dj_hiddev->dev.parent = &djrcv_hdev->dev;
dj_hiddev->bus = BUS_USB;
dj_hiddev->vendor = le16_to_cpu(usbdev->descriptor.idVendor);
dj_hiddev->product = le16_to_cpu(usbdev->descriptor.idProduct);
snprintf(dj_hiddev->name, sizeof(dj_hiddev->name),
"Logitech Unifying Device. Wireless PID:%02x%02x",
dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_MSB],
dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_LSB]);
usb_make_path(usbdev, dj_hiddev->phys, sizeof(dj_hiddev->phys));
snprintf(tmpstr, sizeof(tmpstr), ":%d", dj_report->device_index);
strlcat(dj_hiddev->phys, tmpstr, sizeof(dj_hiddev->phys));
dj_dev = kzalloc(sizeof(struct dj_device), GFP_KERNEL);
if (!dj_dev) {
dev_err(&djrcv_hdev->dev, "%s: failed allocating dj_device\n",
__func__);
goto dj_device_allocate_fail;
}
dj_dev->reports_supported = get_unaligned_le32(
dj_report->report_params + DEVICE_PAIRED_RF_REPORT_TYPE);
dj_dev->hdev = dj_hiddev;
dj_dev->dj_receiver_dev = djrcv_dev;
dj_dev->device_index = dj_report->device_index;
dj_hiddev->driver_data = dj_dev;
djrcv_dev->paired_dj_devices[dj_report->device_index] = dj_dev;
if (hid_add_device(dj_hiddev)) {
dev_err(&djrcv_hdev->dev, "%s: failed adding dj_device\n",
__func__);
goto hid_add_device_fail;
}
return;
hid_add_device_fail:
djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL;
kfree(dj_dev);
dj_device_allocate_fail:
hid_destroy_device(dj_hiddev);
}
| 166,378 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void get_socket_name( char* buf, int len )
{
char* dpy = g_strdup(g_getenv("DISPLAY"));
if(dpy && *dpy)
{
char* p = strchr(dpy, ':');
for(++p; *p && *p != '.' && *p != '\n';)
++p;
if(*p)
*p = '\0';
}
g_snprintf( buf, len, "%s/.menu-cached-%s-%s", g_get_tmp_dir(),
dpy ? dpy : ":0", g_get_user_name() );
g_free(dpy);
}
Commit Message:
CWE ID: CWE-20 | static void get_socket_name( char* buf, int len )
{
char* dpy = g_strdup(g_getenv("DISPLAY"));
if(dpy && *dpy)
{
char* p = strchr(dpy, ':');
for(++p; *p && *p != '.' && *p != '\n';)
++p;
if(*p)
*p = '\0';
}
#if GLIB_CHECK_VERSION(2, 28, 0)
g_snprintf( buf, len, "%s/menu-cached-%s", g_get_user_runtime_dir(),
dpy ? dpy : ":0" );
#else
g_snprintf( buf, len, "%s/.menu-cached-%s-%s", g_get_tmp_dir(),
dpy ? dpy : ":0", g_get_user_name() );
#endif
g_free(dpy);
}
| 164,817 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease(
const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
view->AcceleratedSurfaceRelease(params.identifier);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease(
const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
view->AcceleratedSurfaceRelease();
}
| 171,360 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
Commit Message: smart_pkt: treat empty packet lines as error
The Git protocol does not specify what should happen in the case
of an empty packet line (that is a packet line "0004"). We
currently indicate success, but do not return a packet in the
case where we hit an empty line. The smart protocol was not
prepared to handle such packets in all cases, though, resulting
in a `NULL` pointer dereference.
Fix the issue by returning an error instead. As such kind of
packets is not even specified by upstream, this is the right
thing to do.
CWE ID: CWE-476 | int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* The Git protocol does not specify empty lines as part
* of the protocol. Not knowing what to do with an empty
* line, we should return an error upon hitting one.
*/
if (len == PKT_LEN_SIZE) {
giterr_set_str(GITERR_NET, "Invalid empty packet");
return GIT_ERROR;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
| 168,527 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
q=colormap;
if (image->colors <= 256)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);;
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff);
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/573
CWE ID: CWE-772 | static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
{
if (colormap != (unsigned char *) NULL)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
if (pixels != (unsigned char *) NULL)
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Write colormap to file.
*/
q=colormap;
if (image->colors <= 256)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green);
*q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) &
0xff);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8);
*q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) &
0xff);
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
| 167,976 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol)
{
struct snd_ctl_elem_id id;
unsigned int idx;
int err = -EINVAL;
if (! kcontrol)
return err;
if (snd_BUG_ON(!card || !kcontrol->info))
goto error;
id = kcontrol->id;
down_write(&card->controls_rwsem);
if (snd_ctl_find_id(card, &id)) {
up_write(&card->controls_rwsem);
dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n",
id.iface,
id.device,
id.subdevice,
id.name,
id.index);
err = -EBUSY;
goto error;
}
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
err = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return err;
}
Commit Message: ALSA: control: Don't access controls outside of protected regions
A control that is visible on the card->controls list can be freed at any time.
This means we must not access any of its memory while not holding the
controls_rw_lock. Otherwise we risk a use after free access.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: | int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol)
{
struct snd_ctl_elem_id id;
unsigned int idx;
unsigned int count;
int err = -EINVAL;
if (! kcontrol)
return err;
if (snd_BUG_ON(!card || !kcontrol->info))
goto error;
id = kcontrol->id;
down_write(&card->controls_rwsem);
if (snd_ctl_find_id(card, &id)) {
up_write(&card->controls_rwsem);
dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n",
id.iface,
id.device,
id.subdevice,
id.name,
id.index);
err = -EBUSY;
goto error;
}
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
err = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
count = kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return err;
}
| 166,292 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
}
Commit Message: Fixed memory overrun bug in gdImageScaleTwoPass
_gdContributionsCalc would compute a window size and then adjust
the left and right positions of the window to make a window within
that size. However, it was storing the values in the struct *before*
it made the adjustment. This change fixes that.
CWE ID: CWE-125 | static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
}
| 167,591 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: EBMLHeader::~EBMLHeader()
{
delete[] m_docType;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | EBMLHeader::~EBMLHeader()
void EBMLHeader::Init() {
m_version = 1;
m_readVersion = 1;
m_maxIdLength = 4;
m_maxSizeLength = 8;
if (m_docType) {
delete[] m_docType;
m_docType = NULL;
}
m_docTypeVersion = 1;
m_docTypeReadVersion = 1;
}
| 174,465 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo,
proto_tree *tree, dcerpc_info *di, guint8 *drep)
{
guint32 size;
int end_offset;
if (di->conformant_run)
return offset;
/* Dissect size and data */
offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep,
hf_keybuffer_size, &size);
end_offset = offset + (size*2);
if (end_offset < offset) {
/*
* Overflow - make the end offset one past the end of
* the packet data, so we throw an exception (as the
* size is almost certainly too big).
*/
end_offset = tvb_reported_length_remaining(tvb, offset) + 1;
}
while (offset < end_offset)
offset = dissect_spoolss_uint16uni(
tvb, offset, pinfo, tree, drep, NULL, hf_keybuffer);
return offset;
}
Commit Message: SPOOLSS: Try to avoid an infinite loop.
Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make
sure our offset always increments in dissect_spoolss_keybuffer.
Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793
Reviewed-on: https://code.wireshark.org/review/14687
Reviewed-by: Gerald Combs <[email protected]>
Petri-Dish: Gerald Combs <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-399 | dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo,
proto_tree *tree, dcerpc_info *di, guint8 *drep)
{
guint32 size;
int end_offset;
if (di->conformant_run)
return offset;
/* Dissect size and data */
offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep,
hf_keybuffer_size, &size);
end_offset = offset + (size*2);
if (end_offset < offset) {
/*
* Overflow - make the end offset one past the end of
* the packet data, so we throw an exception (as the
* size is almost certainly too big).
*/
end_offset = tvb_reported_length_remaining(tvb, offset) + 1;
}
while (offset > 0 && offset < end_offset) {
offset = dissect_spoolss_uint16uni(
tvb, offset, pinfo, tree, drep, NULL, hf_keybuffer);
}
return offset;
}
| 167,159 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
Commit Message: CVE-2017-12896/ISAKMP: Do bounds checks in isakmp_rfc3948_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
ND_TCHECK(bp[0]);
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
ND_TCHECK(bp[3]);
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
| 170,035 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void opj_get_all_encoding_parameters( const opj_image_t *p_image,
const opj_cp_t *p_cp,
OPJ_UINT32 tileno,
OPJ_INT32 * p_tx0,
OPJ_INT32 * p_tx1,
OPJ_INT32 * p_ty0,
OPJ_INT32 * p_ty1,
OPJ_UINT32 * p_dx_min,
OPJ_UINT32 * p_dy_min,
OPJ_UINT32 * p_max_prec,
OPJ_UINT32 * p_max_res,
OPJ_UINT32 ** p_resolutions )
{
/* loop*/
OPJ_UINT32 compno, resno;
/* pointers*/
const opj_tcp_t *tcp = 00;
const opj_tccp_t * l_tccp = 00;
const opj_image_comp_t * l_img_comp = 00;
/* to store l_dx, l_dy, w and h for each resolution and component.*/
OPJ_UINT32 * lResolutionPtr;
/* position in x and y of tile*/
OPJ_UINT32 p, q;
/* preconditions in debug*/
assert(p_cp != 00);
assert(p_image != 00);
assert(tileno < p_cp->tw * p_cp->th);
/* initializations*/
tcp = &p_cp->tcps [tileno];
l_tccp = tcp->tccps;
l_img_comp = p_image->comps;
/* position in x and y of tile*/
p = tileno % p_cp->tw;
q = tileno / p_cp->tw;
/* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */
*p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0);
*p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1);
*p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0);
*p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1);
/* max precision and resolution is 0 (can only grow)*/
*p_max_prec = 0;
*p_max_res = 0;
/* take the largest value for dx_min and dy_min*/
*p_dx_min = 0x7fffffff;
*p_dy_min = 0x7fffffff;
for (compno = 0; compno < p_image->numcomps; ++compno) {
/* aritmetic variables to calculate*/
OPJ_UINT32 l_level_no;
OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
OPJ_INT32 l_px0, l_py0, l_px1, py1;
OPJ_UINT32 l_product;
OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph;
lResolutionPtr = p_resolutions[compno];
l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);
if (l_tccp->numresolutions > *p_max_res) {
*p_max_res = l_tccp->numresolutions;
}
/* use custom size for precincts*/
l_level_no = l_tccp->numresolutions - 1;
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
/* precinct width and height*/
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
*lResolutionPtr++ = l_pdx;
*lResolutionPtr++ = l_pdy;
l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no));
l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no));
/* take the minimum size for l_dx for each comp and resolution*/
*p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx);
*p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy);
/* various calculations of extents*/
l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy);
*lResolutionPtr++ = l_pw;
*lResolutionPtr++ = l_ph;
l_product = l_pw * l_ph;
/* update precision*/
if (l_product > *p_max_prec) {
*p_max_prec = l_product;
}
--l_level_no;
}
++l_tccp;
++l_img_comp;
}
}
Commit Message: [trunk] fixed a buffer overflow in opj_tcd_init_decode_tile
Update issue 431
CWE ID: CWE-190 | void opj_get_all_encoding_parameters( const opj_image_t *p_image,
const opj_cp_t *p_cp,
OPJ_UINT32 tileno,
OPJ_INT32 * p_tx0,
OPJ_INT32 * p_tx1,
OPJ_INT32 * p_ty0,
OPJ_INT32 * p_ty1,
OPJ_UINT32 * p_dx_min,
OPJ_UINT32 * p_dy_min,
OPJ_UINT32 * p_max_prec,
OPJ_UINT32 * p_max_res,
OPJ_UINT32 ** p_resolutions )
{
/* loop*/
OPJ_UINT32 compno, resno;
/* pointers*/
const opj_tcp_t *tcp = 00;
const opj_tccp_t * l_tccp = 00;
const opj_image_comp_t * l_img_comp = 00;
/* to store l_dx, l_dy, w and h for each resolution and component.*/
OPJ_UINT32 * lResolutionPtr;
/* position in x and y of tile*/
OPJ_UINT32 p, q;
/* preconditions in debug*/
assert(p_cp != 00);
assert(p_image != 00);
assert(tileno < p_cp->tw * p_cp->th);
/* initializations*/
tcp = &p_cp->tcps [tileno];
l_tccp = tcp->tccps;
l_img_comp = p_image->comps;
/* position in x and y of tile*/
p = tileno % p_cp->tw;
q = tileno / p_cp->tw;
/* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */
*p_tx0 = (OPJ_INT32)opj_uint_max(p_cp->tx0 + p * p_cp->tdx, p_image->x0);
*p_tx1 = (OPJ_INT32)opj_uint_min(p_cp->tx0 + (p + 1) * p_cp->tdx, p_image->x1);
*p_ty0 = (OPJ_INT32)opj_uint_max(p_cp->ty0 + q * p_cp->tdy, p_image->y0);
*p_ty1 = (OPJ_INT32)opj_uint_min(p_cp->ty0 + (q + 1) * p_cp->tdy, p_image->y1);
/* max precision and resolution is 0 (can only grow)*/
*p_max_prec = 0;
*p_max_res = 0;
/* take the largest value for dx_min and dy_min*/
*p_dx_min = 0x7fffffff;
*p_dy_min = 0x7fffffff;
for (compno = 0; compno < p_image->numcomps; ++compno) {
/* aritmetic variables to calculate*/
OPJ_UINT32 l_level_no;
OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
OPJ_INT32 l_px0, l_py0, l_px1, py1;
OPJ_UINT32 l_product;
OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph;
lResolutionPtr = p_resolutions[compno];
l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);
if (l_tccp->numresolutions > *p_max_res) {
*p_max_res = l_tccp->numresolutions;
}
/* use custom size for precincts*/
l_level_no = l_tccp->numresolutions - 1;
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
/* precinct width and height*/
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
*lResolutionPtr++ = l_pdx;
*lResolutionPtr++ = l_pdy;
l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no));
l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no));
/* take the minimum size for l_dx for each comp and resolution*/
*p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx);
*p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy);
/* various calculations of extents*/
l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy);
*lResolutionPtr++ = l_pw;
*lResolutionPtr++ = l_ph;
l_product = l_pw * l_ph;
/* update precision*/
if (l_product > *p_max_prec) {
*p_max_prec = l_product;
}
--l_level_no;
}
++l_tccp;
++l_img_comp;
}
}
| 170,246 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::unique_ptr<views::Border> AutofillPopupBaseView::CreateBorder() {
auto border = std::make_unique<views::BubbleBorder>(
views::BubbleBorder::NONE, views::BubbleBorder::SMALL_SHADOW,
SK_ColorWHITE);
border->SetCornerRadius(GetCornerRadius());
border->set_md_shadow_elevation(
ChromeLayoutProvider::Get()->GetShadowElevationMetric(
views::EMPHASIS_MEDIUM));
return border;
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <[email protected]>
Reviewed-by: Vasilii Sukhanov <[email protected]>
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Tommy Martino <[email protected]>
Commit-Queue: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416 | std::unique_ptr<views::Border> AutofillPopupBaseView::CreateBorder() {
| 172,094 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DelayedExecutor::delayedExecute(const QString &udi)
{
Solid::Device device(udi);
QString exec = m_service.exec();
MacroExpander mx(device);
mx.expandMacros(exec);
KRun::runCommand(exec, QString(), m_service.icon(), 0);
deleteLater();
}
Commit Message:
CWE ID: CWE-78 | void DelayedExecutor::delayedExecute(const QString &udi)
{
Solid::Device device(udi);
QString exec = m_service.exec();
MacroExpander mx(device);
mx.expandMacrosShellQuote(exec);
KRun::runCommand(exec, QString(), m_service.icon(), 0);
deleteLater();
}
| 165,024 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_MSB,op_LSB;
int ret;
if (!data)
return 0;
memset (op, '\0', sizeof (RAnalOp));
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->jump = op->fail = -1;
op->ptr = op->val = -1;
op->size = 2;
op_MSB = anal->big_endian? data[0]: data[1];
op_LSB = anal->big_endian? data[1]: data[0];
ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
return ret;
}
Commit Message: Fix #9903 - oobread in RAnal.sh
CWE ID: CWE-125 | static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_MSB,op_LSB;
int ret;
if (!data || len < 2) {
return 0;
}
memset (op, '\0', sizeof (RAnalOp));
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->jump = op->fail = -1;
op->ptr = op->val = -1;
op->size = 2;
op_MSB = anal->big_endian? data[0]: data[1];
op_LSB = anal->big_endian? data[1]: data[0];
ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
return ret;
}
| 169,221 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: scoped_refptr<PermissionSet> UnpackPermissionSet(
const Permissions& permissions, std::string* error) {
APIPermissionSet apis;
std::vector<std::string>* permissions_list = permissions.permissions.get();
if (permissions_list) {
PermissionsInfo* info = PermissionsInfo::GetInstance();
for (std::vector<std::string>::iterator it = permissions_list->begin();
it != permissions_list->end(); ++it) {
if (it->find(kDelimiter) != std::string::npos) {
size_t delimiter = it->find(kDelimiter);
std::string permission_name = it->substr(0, delimiter);
std::string permission_arg = it->substr(delimiter + 1);
scoped_ptr<base::Value> permission_json(
base::JSONReader::Read(permission_arg));
if (!permission_json.get()) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
APIPermission* permission = NULL;
const APIPermissionInfo* bluetooth_device_permission_info =
info->GetByID(APIPermission::kBluetoothDevice);
const APIPermissionInfo* usb_device_permission_info =
info->GetByID(APIPermission::kUsbDevice);
if (permission_name == bluetooth_device_permission_info->name()) {
permission = new BluetoothDevicePermission(
bluetooth_device_permission_info);
} else if (permission_name == usb_device_permission_info->name()) {
permission = new UsbDevicePermission(usb_device_permission_info);
} else {
*error = kUnsupportedPermissionId;
return NULL;
}
CHECK(permission);
if (!permission->FromValue(permission_json.get())) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
apis.insert(permission);
} else {
const APIPermissionInfo* permission_info = info->GetByName(*it);
if (!permission_info) {
*error = ErrorUtils::FormatErrorMessage(
kUnknownPermissionError, *it);
return NULL;
}
apis.insert(permission_info->id());
}
}
}
URLPatternSet origins;
if (permissions.origins.get()) {
for (std::vector<std::string>::iterator it = permissions.origins->begin();
it != permissions.origins->end(); ++it) {
URLPattern origin(Extension::kValidHostPermissionSchemes);
URLPattern::ParseResult parse_result = origin.Parse(*it);
if (URLPattern::PARSE_SUCCESS != parse_result) {
*error = ErrorUtils::FormatErrorMessage(
kInvalidOrigin,
*it,
URLPattern::GetParseResultString(parse_result));
return NULL;
}
origins.AddPattern(origin);
}
}
return scoped_refptr<PermissionSet>(
new PermissionSet(apis, origins, URLPatternSet()));
}
Commit Message: Check prefs before allowing extension file access in the permissions API.
[email protected]
BUG=169632
Review URL: https://chromiumcodereview.appspot.com/11884008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | scoped_refptr<PermissionSet> UnpackPermissionSet(
const Permissions& permissions,
bool allow_file_access,
std::string* error) {
APIPermissionSet apis;
std::vector<std::string>* permissions_list = permissions.permissions.get();
if (permissions_list) {
PermissionsInfo* info = PermissionsInfo::GetInstance();
for (std::vector<std::string>::iterator it = permissions_list->begin();
it != permissions_list->end(); ++it) {
if (it->find(kDelimiter) != std::string::npos) {
size_t delimiter = it->find(kDelimiter);
std::string permission_name = it->substr(0, delimiter);
std::string permission_arg = it->substr(delimiter + 1);
scoped_ptr<base::Value> permission_json(
base::JSONReader::Read(permission_arg));
if (!permission_json.get()) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
APIPermission* permission = NULL;
const APIPermissionInfo* bluetooth_device_permission_info =
info->GetByID(APIPermission::kBluetoothDevice);
const APIPermissionInfo* usb_device_permission_info =
info->GetByID(APIPermission::kUsbDevice);
if (permission_name == bluetooth_device_permission_info->name()) {
permission = new BluetoothDevicePermission(
bluetooth_device_permission_info);
} else if (permission_name == usb_device_permission_info->name()) {
permission = new UsbDevicePermission(usb_device_permission_info);
} else {
*error = kUnsupportedPermissionId;
return NULL;
}
CHECK(permission);
if (!permission->FromValue(permission_json.get())) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
apis.insert(permission);
} else {
const APIPermissionInfo* permission_info = info->GetByName(*it);
if (!permission_info) {
*error = ErrorUtils::FormatErrorMessage(
kUnknownPermissionError, *it);
return NULL;
}
apis.insert(permission_info->id());
}
}
}
URLPatternSet origins;
if (permissions.origins.get()) {
for (std::vector<std::string>::iterator it = permissions.origins->begin();
it != permissions.origins->end(); ++it) {
int allowed_schemes = Extension::kValidHostPermissionSchemes;
if (!allow_file_access)
allowed_schemes &= ~URLPattern::SCHEME_FILE;
URLPattern origin(allowed_schemes);
URLPattern::ParseResult parse_result = origin.Parse(*it);
if (URLPattern::PARSE_SUCCESS != parse_result) {
*error = ErrorUtils::FormatErrorMessage(
kInvalidOrigin,
*it,
URLPattern::GetParseResultString(parse_result));
return NULL;
}
origins.AddPattern(origin);
}
}
return scoped_refptr<PermissionSet>(
new PermissionSet(apis, origins, URLPatternSet()));
}
| 171,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _dbus_header_byteswap (DBusHeader *header,
int new_order)
{
if (header->byte_order == new_order)
return;
_dbus_marshal_byteswap (&_dbus_header_signature_str,
0, header->byte_order,
new_order,
&header->data, 0);
header->byte_order = new_order;
}
Commit Message:
CWE ID: CWE-20 | _dbus_header_byteswap (DBusHeader *header,
int new_order)
{
unsigned char byte_order;
if (header->byte_order == new_order)
return;
byte_order = _dbus_string_get_byte (&header->data, BYTE_ORDER_OFFSET);
_dbus_assert (header->byte_order == byte_order);
_dbus_marshal_byteswap (&_dbus_header_signature_str,
0, header->byte_order,
new_order,
&header->data, 0);
_dbus_string_set_byte (&header->data, BYTE_ORDER_OFFSET, new_order);
header->byte_order = new_order;
}
| 164,686 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DefragVlanQinQTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *r = NULL;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(1, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(1, 1, 0, 'B', 8);
if (p2 == NULL)
goto end;
/* With no VLAN IDs set, packets should re-assemble. */
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)
goto end;
SCFree(r);
/* With mismatched VLANs, packets should not re-assemble. */
p1->vlan_id[0] = 1;
p2->vlan_id[0] = 1;
p1->vlan_id[1] = 1;
p2->vlan_id[1] = 2;
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)
goto end;
/* Pass. */
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
DefragDestroy();
return ret;
}
Commit Message: defrag - take protocol into account during re-assembly
The IP protocol was not being used to match fragments with
their packets allowing a carefully constructed packet
with a different protocol to be matched, allowing re-assembly
to complete, creating a packet that would not be re-assembled
by the destination host.
CWE ID: CWE-358 | DefragVlanQinQTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *r = NULL;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(IPPROTO_ICMP, 1, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(IPPROTO_ICMP, 1, 1, 0, 'B', 8);
if (p2 == NULL)
goto end;
/* With no VLAN IDs set, packets should re-assemble. */
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)
goto end;
SCFree(r);
/* With mismatched VLANs, packets should not re-assemble. */
p1->vlan_id[0] = 1;
p2->vlan_id[0] = 1;
p1->vlan_id[1] = 1;
p2->vlan_id[1] = 2;
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)
goto end;
/* Pass. */
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
DefragDestroy();
return ret;
}
| 168,305 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Value> source(GetSource(module_name));
if (source.IsEmpty() || source->IsUndefined()) {
Fatal(context_, "No source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::String> wrapped_source(
WrapSource(v8::Local<v8::String>::Cast(source)));
v8::Local<v8::String> v8_module_name;
if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name)) {
NOTREACHED() << "module_name is too long";
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Value> func_as_value =
RunString(wrapped_source, v8_module_name);
if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
Fatal(context_, "Bad source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value);
v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate());
gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
v8::Local<v8::Value> exports = v8::Object::New(GetIsolate());
v8::Local<v8::Object> natives(NewInstance());
CHECK(!natives.IsEmpty()); // this can fail if v8 has issues
v8::Local<v8::Value> args[] = {
GetPropertyUnsafe(v8_context, define_object, "define"),
GetPropertyUnsafe(v8_context, natives, "require",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireNative",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireAsync",
v8::NewStringType::kInternalized),
exports,
console::AsV8Object(GetIsolate()),
GetPropertyUnsafe(v8_context, natives, "privates",
v8::NewStringType::kInternalized),
context_->safe_builtins()->GetArray(),
context_->safe_builtins()->GetFunction(),
context_->safe_builtins()->GetJSON(),
context_->safe_builtins()->GetObjekt(),
context_->safe_builtins()->GetRegExp(),
context_->safe_builtins()->GetString(),
context_->safe_builtins()->GetError(),
};
{
v8::TryCatch try_catch(GetIsolate());
try_catch.SetCaptureMessage(true);
context_->CallFunction(func, arraysize(args), args);
if (try_catch.HasCaught()) {
HandleException(try_catch);
return v8::Undefined(GetIsolate());
}
}
return handle_scope.Escape(exports);
}
Commit Message: [Extensions] Don't allow built-in extensions code to be overridden
BUG=546677
Review URL: https://codereview.chromium.org/1417513003
Cr-Commit-Position: refs/heads/master@{#356654}
CWE ID: CWE-264 | v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Value> source(GetSource(module_name));
if (source.IsEmpty() || source->IsUndefined()) {
Fatal(context_, "No source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::String> wrapped_source(
WrapSource(v8::Local<v8::String>::Cast(source)));
v8::Local<v8::String> v8_module_name;
if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name)) {
NOTREACHED() << "module_name is too long";
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Value> func_as_value =
RunString(wrapped_source, v8_module_name);
if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
Fatal(context_, "Bad source for require(" + module_name + ")");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value);
v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate());
gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
v8::Local<v8::Object> exports = v8::Object::New(GetIsolate());
v8::Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New(
GetIsolate(),
&SetExportsProperty);
v8::Local<v8::String> v8_key;
if (!v8_helpers::ToV8String(GetIsolate(), "$set", &v8_key)) {
NOTREACHED();
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Function> function;
if (!tmpl->GetFunction(v8_context).ToLocal(&function)) {
NOTREACHED();
return v8::Undefined(GetIsolate());
}
exports->ForceSet(v8_key, function, v8::ReadOnly);
v8::Local<v8::Object> natives(NewInstance());
CHECK(!natives.IsEmpty()); // this can fail if v8 has issues
v8::Local<v8::Value> args[] = {
GetPropertyUnsafe(v8_context, define_object, "define"),
GetPropertyUnsafe(v8_context, natives, "require",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireNative",
v8::NewStringType::kInternalized),
GetPropertyUnsafe(v8_context, natives, "requireAsync",
v8::NewStringType::kInternalized),
exports,
console::AsV8Object(GetIsolate()),
GetPropertyUnsafe(v8_context, natives, "privates",
v8::NewStringType::kInternalized),
context_->safe_builtins()->GetArray(),
context_->safe_builtins()->GetFunction(),
context_->safe_builtins()->GetJSON(),
context_->safe_builtins()->GetObjekt(),
context_->safe_builtins()->GetRegExp(),
context_->safe_builtins()->GetString(),
context_->safe_builtins()->GetError(),
};
{
v8::TryCatch try_catch(GetIsolate());
try_catch.SetCaptureMessage(true);
context_->CallFunction(func, arraysize(args), args);
if (try_catch.HasCaught()) {
HandleException(try_catch);
return v8::Undefined(GetIsolate());
}
}
return handle_scope.Escape(exports);
}
| 172,287 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HeapAllocator::backingFree(void* address) {
if (!address)
return;
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return;
ASSERT(!state->isInGC());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
ASSERT(header->checkHeader());
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
state->promptlyFreed(header->gcInfoIndex());
arena->promptlyFreeObject(header);
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | void HeapAllocator::backingFree(void* address) {
if (!address)
return;
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return;
ASSERT(!state->isInGC());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
header->checkHeader();
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
state->promptlyFreed(header->gcInfoIndex());
arena->promptlyFreeObject(header);
}
| 172,706 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static sk_sp<SkImage> flipSkImageVertically(SkImage* input,
AlphaDisposition alphaOp) {
size_t width = static_cast<size_t>(input->width());
size_t height = static_cast<size_t>(input->height());
SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(),
(alphaOp == PremultiplyAlpha)
? kPremul_SkAlphaType
: kUnpremul_SkAlphaType);
size_t imageRowBytes = width * info.bytesPerPixel();
RefPtr<Uint8Array> imagePixels = copySkImageData(input, info);
if (!imagePixels)
return nullptr;
for (size_t i = 0; i < height / 2; i++) {
size_t topFirstElement = i * imageRowBytes;
size_t topLastElement = (i + 1) * imageRowBytes;
size_t bottomFirstElement = (height - 1 - i) * imageRowBytes;
std::swap_ranges(imagePixels->data() + topFirstElement,
imagePixels->data() + topLastElement,
imagePixels->data() + bottomFirstElement);
}
return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes);
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | static sk_sp<SkImage> flipSkImageVertically(SkImage* input,
AlphaDisposition alphaOp) {
unsigned width = static_cast<unsigned>(input->width());
unsigned height = static_cast<unsigned>(input->height());
SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(),
(alphaOp == PremultiplyAlpha)
? kPremul_SkAlphaType
: kUnpremul_SkAlphaType);
unsigned imageRowBytes = width * info.bytesPerPixel();
RefPtr<Uint8Array> imagePixels = copySkImageData(input, info);
if (!imagePixels)
return nullptr;
for (unsigned i = 0; i < height / 2; i++) {
unsigned topFirstElement = i * imageRowBytes;
unsigned topLastElement = (i + 1) * imageRowBytes;
unsigned bottomFirstElement = (height - 1 - i) * imageRowBytes;
std::swap_ranges(imagePixels->data() + topFirstElement,
imagePixels->data() + topLastElement,
imagePixels->data() + bottomFirstElement);
}
return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes);
}
| 172,502 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void oinf_entry_dump(GF_OperatingPointsInformation *ptr, FILE * trace)
{
u32 i, count;
if (!ptr) {
fprintf(trace, "<OperatingPointsInformation scalability_mask=\"Multiview|Spatial scalability|Auxilary|unknown\" num_profile_tier_level=\"\" num_operating_points=\"\" dependency_layers=\"\">\n");
fprintf(trace, " <ProfileTierLevel general_profile_space=\"\" general_tier_flag=\"\" general_profile_idc=\"\" general_profile_compatibility_flags=\"\" general_constraint_indicator_flags=\"\" />\n");
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"\" max_temporal_id=\"\" layer_count=\"\" minPicWidth=\"\" minPicHeight=\"\" maxPicWidth=\"\" maxPicHeight=\"\" maxChromaFormat=\"\" maxBitDepth=\"\" frame_rate_info_flag=\"\" bit_rate_info_flag=\"\" avgFrameRate=\"\" constantFrameRate=\"\" maxBitRate=\"\" avgBitRate=\"\"/>\n");
fprintf(trace, "<Layer dependent_layerID=\"\" num_layers_dependent_on=\"\" dependent_on_layerID=\"\" dimension_identifier=\"\"/>\n");
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
fprintf(trace, "<OperatingPointsInformation");
fprintf(trace, " scalability_mask=\"%u (", ptr->scalability_mask);
switch (ptr->scalability_mask) {
case 2:
fprintf(trace, "Multiview");
break;
case 4:
fprintf(trace, "Spatial scalability");
break;
case 8:
fprintf(trace, "Auxilary");
break;
default:
fprintf(trace, "unknown");
}
fprintf(trace, ")\" num_profile_tier_level=\"%u\"", gf_list_count(ptr->profile_tier_levels) );
fprintf(trace, " num_operating_points=\"%u\" dependency_layers=\"%u\"", gf_list_count(ptr->operating_points), gf_list_count(ptr->dependency_layers));
fprintf(trace, ">\n");
count=gf_list_count(ptr->profile_tier_levels);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i);
fprintf(trace, " <ProfileTierLevel general_profile_space=\"%u\" general_tier_flag=\"%u\" general_profile_idc=\"%u\" general_profile_compatibility_flags=\"%X\" general_constraint_indicator_flags=\""LLX"\" />\n", ptl->general_profile_space, ptl->general_tier_flag, ptl->general_profile_idc, ptl->general_profile_compatibility_flags, ptl->general_constraint_indicator_flags);
}
count=gf_list_count(ptr->operating_points);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"%u\"", op->output_layer_set_idx);
fprintf(trace, " max_temporal_id=\"%u\" layer_count=\"%u\"", op->max_temporal_id, op->layer_count);
fprintf(trace, " minPicWidth=\"%u\" minPicHeight=\"%u\"", op->minPicWidth, op->minPicHeight);
fprintf(trace, " maxPicWidth=\"%u\" maxPicHeight=\"%u\"", op->maxPicWidth, op->maxPicHeight);
fprintf(trace, " maxChromaFormat=\"%u\" maxBitDepth=\"%u\"", op->maxChromaFormat, op->maxBitDepth);
fprintf(trace, " frame_rate_info_flag=\"%u\" bit_rate_info_flag=\"%u\"", op->frame_rate_info_flag, op->bit_rate_info_flag);
if (op->frame_rate_info_flag)
fprintf(trace, " avgFrameRate=\"%u\" constantFrameRate=\"%u\"", op->avgFrameRate, op->constantFrameRate);
if (op->bit_rate_info_flag)
fprintf(trace, " maxBitRate=\"%u\" avgBitRate=\"%u\"", op->maxBitRate, op->avgBitRate);
fprintf(trace, "/>\n");
}
count=gf_list_count(ptr->dependency_layers);
for (i = 0; i < count; i++) {
u32 j;
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);
fprintf(trace, "<Layer dependent_layerID=\"%u\" num_layers_dependent_on=\"%u\"", dep->dependent_layerID, dep->num_layers_dependent_on);
if (dep->num_layers_dependent_on) {
fprintf(trace, " dependent_on_layerID=\"");
for (j = 0; j < dep->num_layers_dependent_on; j++)
fprintf(trace, "%d ", dep->dependent_on_layerID[j]);
fprintf(trace, "\"");
}
fprintf(trace, " dimension_identifier=\"");
for (j = 0; j < 16; j++)
if (ptr->scalability_mask & (1 << j))
fprintf(trace, "%d ", dep->dimension_identifier[j]);
fprintf(trace, "\"/>\n");
}
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125 | static void oinf_entry_dump(GF_OperatingPointsInformation *ptr, FILE * trace)
{
u32 i, count;
if (!ptr) {
fprintf(trace, "<OperatingPointsInformation scalability_mask=\"Multiview|Spatial scalability|Auxilary|unknown\" num_profile_tier_level=\"\" num_operating_points=\"\" dependency_layers=\"\">\n");
fprintf(trace, " <ProfileTierLevel general_profile_space=\"\" general_tier_flag=\"\" general_profile_idc=\"\" general_profile_compatibility_flags=\"\" general_constraint_indicator_flags=\"\" />\n");
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"\" max_temporal_id=\"\" layer_count=\"\" minPicWidth=\"\" minPicHeight=\"\" maxPicWidth=\"\" maxPicHeight=\"\" maxChromaFormat=\"\" maxBitDepth=\"\" frame_rate_info_flag=\"\" bit_rate_info_flag=\"\" avgFrameRate=\"\" constantFrameRate=\"\" maxBitRate=\"\" avgBitRate=\"\"/>\n");
fprintf(trace, "<Layer dependent_layerID=\"\" num_layers_dependent_on=\"\" dependent_on_layerID=\"\" dimension_identifier=\"\"/>\n");
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
fprintf(trace, "<OperatingPointsInformation");
fprintf(trace, " scalability_mask=\"%u (", ptr->scalability_mask);
switch (ptr->scalability_mask) {
case 2:
fprintf(trace, "Multiview");
break;
case 4:
fprintf(trace, "Spatial scalability");
break;
case 8:
fprintf(trace, "Auxilary");
break;
default:
fprintf(trace, "unknown");
}
fprintf(trace, ")\" num_profile_tier_level=\"%u\"", gf_list_count(ptr->profile_tier_levels) );
fprintf(trace, " num_operating_points=\"%u\" dependency_layers=\"%u\"", gf_list_count(ptr->operating_points), gf_list_count(ptr->dependency_layers));
fprintf(trace, ">\n");
count=gf_list_count(ptr->profile_tier_levels);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i);
fprintf(trace, " <ProfileTierLevel general_profile_space=\"%u\" general_tier_flag=\"%u\" general_profile_idc=\"%u\" general_profile_compatibility_flags=\"%X\" general_constraint_indicator_flags=\""LLX"\" />\n", ptl->general_profile_space, ptl->general_tier_flag, ptl->general_profile_idc, ptl->general_profile_compatibility_flags, ptl->general_constraint_indicator_flags);
}
count=gf_list_count(ptr->operating_points);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"%u\"", op->output_layer_set_idx);
fprintf(trace, " max_temporal_id=\"%u\" layer_count=\"%u\"", op->max_temporal_id, op->layer_count);
fprintf(trace, " minPicWidth=\"%u\" minPicHeight=\"%u\"", op->minPicWidth, op->minPicHeight);
fprintf(trace, " maxPicWidth=\"%u\" maxPicHeight=\"%u\"", op->maxPicWidth, op->maxPicHeight);
fprintf(trace, " maxChromaFormat=\"%u\" maxBitDepth=\"%u\"", op->maxChromaFormat, op->maxBitDepth);
fprintf(trace, " frame_rate_info_flag=\"%u\" bit_rate_info_flag=\"%u\"", op->frame_rate_info_flag, op->bit_rate_info_flag);
if (op->frame_rate_info_flag)
fprintf(trace, " avgFrameRate=\"%u\" constantFrameRate=\"%u\"", op->avgFrameRate, op->constantFrameRate);
if (op->bit_rate_info_flag)
fprintf(trace, " maxBitRate=\"%u\" avgBitRate=\"%u\"", op->maxBitRate, op->avgBitRate);
fprintf(trace, "/>\n");
}
count=gf_list_count(ptr->dependency_layers);
for (i = 0; i < count; i++) {
u32 j;
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);
fprintf(trace, "<Layer dependent_layerID=\"%u\" num_layers_dependent_on=\"%u\"", dep->dependent_layerID, dep->num_layers_dependent_on);
if (dep->num_layers_dependent_on) {
fprintf(trace, " dependent_on_layerID=\"");
for (j = 0; j < dep->num_layers_dependent_on; j++)
fprintf(trace, "%d ", dep->dependent_on_layerID[j]);
fprintf(trace, "\"");
}
fprintf(trace, " dimension_identifier=\"");
for (j = 0; j < 16; j++)
if (ptr->scalability_mask & (1 << j))
fprintf(trace, "%d ", dep->dimension_identifier[j]);
fprintf(trace, "\"/>\n");
}
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
| 169,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void V8RecursionScope::didLeaveScriptContext()
{
Microtask::performCheckpoint();
V8PerIsolateData::from(m_isolate)->runEndOfScopeTasks();
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254 | void V8RecursionScope::didLeaveScriptContext()
{
Microtask::performCheckpoint(m_isolate);
V8PerIsolateData::from(m_isolate)->runEndOfScopeTasks();
}
| 171,943 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int bochs_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVBochsState *s = bs->opaque;
uint32_t i;
struct bochs_header bochs;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs));
if (ret < 0) {
return ret;
}
if (strcmp(bochs.magic, HEADER_MAGIC) ||
strcmp(bochs.type, REDOLOG_TYPE) ||
strcmp(bochs.subtype, GROWING_TYPE) ||
((le32_to_cpu(bochs.version) != HEADER_VERSION) &&
(le32_to_cpu(bochs.version) != HEADER_V1))) {
error_setg(errp, "Image not in Bochs format");
return -EINVAL;
}
if (le32_to_cpu(bochs.version) == HEADER_V1) {
bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512;
} else {
bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512;
}
s->catalog_size = le32_to_cpu(bochs.catalog);
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap,
s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4);
s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512;
s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512;
s->extent_size = le32_to_cpu(bochs.extent);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
s->extent_size = le32_to_cpu(bochs.extent);
qemu_co_mutex_init(&s->lock);
return 0;
extent_index = offset / s->extent_size;
extent_offset = (offset % s->extent_size) / 512;
if (s->catalog_bitmap[extent_index] == 0xffffffff) {
return -1; /* not allocated */
}
bitmap_offset = s->data_offset + (512 * s->catalog_bitmap[extent_index] *
(s->extent_blocks + s->bitmap_blocks));
/* read in bitmap for current extent */
if (bdrv_pread(bs->file, bitmap_offset + (extent_offset / 8),
&bitmap_entry, 1) != 1) {
return -1;
}
if (!((bitmap_entry >> (extent_offset % 8)) & 1)) {
return -1; /* not allocated */
}
return bitmap_offset + (512 * (s->bitmap_blocks + extent_offset));
}
Commit Message:
CWE ID: CWE-190 | static int bochs_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVBochsState *s = bs->opaque;
uint32_t i;
struct bochs_header bochs;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs));
if (ret < 0) {
return ret;
}
if (strcmp(bochs.magic, HEADER_MAGIC) ||
strcmp(bochs.type, REDOLOG_TYPE) ||
strcmp(bochs.subtype, GROWING_TYPE) ||
((le32_to_cpu(bochs.version) != HEADER_VERSION) &&
(le32_to_cpu(bochs.version) != HEADER_V1))) {
error_setg(errp, "Image not in Bochs format");
return -EINVAL;
}
if (le32_to_cpu(bochs.version) == HEADER_V1) {
bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512;
} else {
bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512;
}
/* Limit to 1M entries to avoid unbounded allocation. This is what is
* needed for the largest image that bximage can create (~8 TB). */
s->catalog_size = le32_to_cpu(bochs.catalog);
if (s->catalog_size > 0x100000) {
error_setg(errp, "Catalog size is too large");
return -EFBIG;
}
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap,
s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4);
s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512;
s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512;
s->extent_size = le32_to_cpu(bochs.extent);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
s->extent_size = le32_to_cpu(bochs.extent);
if (s->catalog_size < bs->total_sectors / s->extent_size) {
error_setg(errp, "Catalog size is too small for this disk size");
ret = -EINVAL;
goto fail;
}
qemu_co_mutex_init(&s->lock);
return 0;
extent_index = offset / s->extent_size;
extent_offset = (offset % s->extent_size) / 512;
if (s->catalog_bitmap[extent_index] == 0xffffffff) {
return -1; /* not allocated */
}
bitmap_offset = s->data_offset + (512 * s->catalog_bitmap[extent_index] *
(s->extent_blocks + s->bitmap_blocks));
/* read in bitmap for current extent */
if (bdrv_pread(bs->file, bitmap_offset + (extent_offset / 8),
&bitmap_entry, 1) != 1) {
return -1;
}
if (!((bitmap_entry >> (extent_offset % 8)) & 1)) {
return -1; /* not allocated */
}
return bitmap_offset + (512 * (s->bitmap_blocks + extent_offset));
}
| 165,404 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copyTrespass(
short * /* dst */,
const int *const * /* src */,
unsigned /* nSamples */,
unsigned /* nChannels */) {
TRESPASS();
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyTrespass(
short * /* dst */,
const int *[FLACParser::kMaxChannels] /* src */,
unsigned /* nSamples */,
unsigned /* nChannels */) {
TRESPASS();
}
| 174,024 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long mem_seek(jas_stream_obj_t *obj, long offset, int origin)
{
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
long newpos;
JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin));
switch (origin) {
case SEEK_SET:
newpos = offset;
break;
case SEEK_END:
newpos = m->len_ - offset;
break;
case SEEK_CUR:
newpos = m->pos_ + offset;
break;
default:
abort();
break;
}
if (newpos < 0) {
return -1;
}
m->pos_ = newpos;
return m->pos_;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190 | static long mem_seek(jas_stream_obj_t *obj, long offset, int origin)
{
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
size_t newpos;
JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin));
switch (origin) {
case SEEK_SET:
newpos = offset;
break;
case SEEK_END:
newpos = m->len_ - offset;
break;
case SEEK_CUR:
newpos = m->pos_ + offset;
break;
default:
abort();
break;
}
if (newpos < 0) {
return -1;
}
m->pos_ = newpos;
return m->pos_;
}
| 168,751 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: server_input_global_request(int type, u_int32_t seq, void *ctxt)
{
char *rtype;
int want_reply;
int r, success = 0, allocated_listen_port = 0;
struct sshbuf *resp = NULL;
rtype = packet_get_string(NULL);
want_reply = packet_get_char();
debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
/* -R style forwarding */
if (strcmp(rtype, "tcpip-forward") == 0) {
struct passwd *pw;
struct Forward fwd;
pw = the_authctxt->pw;
if (pw == NULL || !the_authctxt->valid)
fatal("server_input_global_request: no/invalid user");
memset(&fwd, 0, sizeof(fwd));
fwd.listen_host = packet_get_string(NULL);
fwd.listen_port = (u_short)packet_get_int();
debug("server_input_global_request: tcpip-forward listen %s port %d",
fwd.listen_host, fwd.listen_port);
/* check permissions */
if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
no_port_forwarding_flag || options.disable_forwarding ||
(!want_reply && fwd.listen_port == 0) ||
(fwd.listen_port != 0 &&
!bind_permitted(fwd.listen_port, pw->pw_uid))) {
success = 0;
packet_send_debug("Server has disabled port forwarding.");
} else {
/* Start listening on the port */
success = channel_setup_remote_fwd_listener(&fwd,
&allocated_listen_port, &options.fwd_opts);
}
free(fwd.listen_host);
if ((resp = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new", __func__);
if (allocated_listen_port != 0 &&
(r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_host = packet_get_string(NULL);
fwd.listen_port = (u_short)packet_get_int();
debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
fwd.listen_host, fwd.listen_port);
success = channel_cancel_rport_listener(&fwd);
free(fwd.listen_host);
} else if (strcmp(rtype, "[email protected]") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_path = packet_get_string(NULL);
debug("server_input_global_request: streamlocal-forward listen path %s",
fwd.listen_path);
/* check permissions */
if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
|| no_port_forwarding_flag || options.disable_forwarding) {
success = 0;
packet_send_debug("Server has disabled port forwarding.");
} else {
/* Start listening on the socket */
success = channel_setup_remote_fwd_listener(
&fwd, NULL, &options.fwd_opts);
}
free(fwd.listen_path);
} else if (strcmp(rtype, "[email protected]") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_path = packet_get_string(NULL);
debug("%s: cancel-streamlocal-forward path %s", __func__,
fwd.listen_path);
success = channel_cancel_rport_listener(&fwd);
free(fwd.listen_path);
} else if (strcmp(rtype, "[email protected]") == 0) {
no_more_sessions = 1;
success = 1;
} else if (strcmp(rtype, "[email protected]") == 0) {
success = server_input_hostkeys_prove(&resp);
}
if (want_reply) {
packet_start(success ?
SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
if (success && resp != NULL)
ssh_packet_put_raw(active_state, sshbuf_ptr(resp),
sshbuf_len(resp));
packet_send();
packet_write_wait();
}
free(rtype);
sshbuf_free(resp);
return 0;
}
Commit Message: disable Unix-domain socket forwarding when privsep is disabled
CWE ID: CWE-264 | server_input_global_request(int type, u_int32_t seq, void *ctxt)
{
char *rtype;
int want_reply;
int r, success = 0, allocated_listen_port = 0;
struct sshbuf *resp = NULL;
rtype = packet_get_string(NULL);
want_reply = packet_get_char();
debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
/* -R style forwarding */
if (strcmp(rtype, "tcpip-forward") == 0) {
struct passwd *pw;
struct Forward fwd;
pw = the_authctxt->pw;
if (pw == NULL || !the_authctxt->valid)
fatal("server_input_global_request: no/invalid user");
memset(&fwd, 0, sizeof(fwd));
fwd.listen_host = packet_get_string(NULL);
fwd.listen_port = (u_short)packet_get_int();
debug("server_input_global_request: tcpip-forward listen %s port %d",
fwd.listen_host, fwd.listen_port);
/* check permissions */
if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
no_port_forwarding_flag || options.disable_forwarding ||
(!want_reply && fwd.listen_port == 0) ||
(fwd.listen_port != 0 &&
!bind_permitted(fwd.listen_port, pw->pw_uid))) {
success = 0;
packet_send_debug("Server has disabled port forwarding.");
} else {
/* Start listening on the port */
success = channel_setup_remote_fwd_listener(&fwd,
&allocated_listen_port, &options.fwd_opts);
}
free(fwd.listen_host);
if ((resp = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new", __func__);
if (allocated_listen_port != 0 &&
(r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_host = packet_get_string(NULL);
fwd.listen_port = (u_short)packet_get_int();
debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
fwd.listen_host, fwd.listen_port);
success = channel_cancel_rport_listener(&fwd);
free(fwd.listen_host);
} else if (strcmp(rtype, "[email protected]") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_path = packet_get_string(NULL);
debug("server_input_global_request: streamlocal-forward listen path %s",
fwd.listen_path);
/* check permissions */
if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
|| no_port_forwarding_flag || options.disable_forwarding ||
!use_privsep) {
success = 0;
packet_send_debug("Server has disabled port forwarding.");
} else {
/* Start listening on the socket */
success = channel_setup_remote_fwd_listener(
&fwd, NULL, &options.fwd_opts);
}
free(fwd.listen_path);
} else if (strcmp(rtype, "[email protected]") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_path = packet_get_string(NULL);
debug("%s: cancel-streamlocal-forward path %s", __func__,
fwd.listen_path);
success = channel_cancel_rport_listener(&fwd);
free(fwd.listen_path);
} else if (strcmp(rtype, "[email protected]") == 0) {
no_more_sessions = 1;
success = 1;
} else if (strcmp(rtype, "[email protected]") == 0) {
success = server_input_hostkeys_prove(&resp);
}
if (want_reply) {
packet_start(success ?
SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
if (success && resp != NULL)
ssh_packet_put_raw(active_state, sshbuf_ptr(resp),
sshbuf_len(resp));
packet_send();
packet_write_wait();
}
free(rtype);
sshbuf_free(resp);
return 0;
}
| 168,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: read_callback(png_structp pp, png_unknown_chunkp pc)
{
/* This function mimics the behavior of png_set_keep_unknown_chunks by
* returning '0' to keep the chunk and '1' to discard it.
*/
display *d = voidcast(display*, png_get_user_chunk_ptr(pp));
int chunk = findb(pc->name);
int keep, discard;
if (chunk < 0) /* not one in our list, so not a known chunk */
keep = d->keep;
else
{
keep = chunk_info[chunk].keep;
if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
{
/* See the comments in png.h - use the default for unknown chunks,
* do not keep known chunks.
*/
if (chunk_info[chunk].unknown)
keep = d->keep;
else
keep = PNG_HANDLE_CHUNK_NEVER;
}
}
switch (keep)
{
default:
fprintf(stderr, "%s(%s): %d: unrecognized chunk option\n", d->file,
d->test, chunk_info[chunk].keep);
display_exit(d);
case PNG_HANDLE_CHUNK_AS_DEFAULT:
case PNG_HANDLE_CHUNK_NEVER:
discard = 1/*handled; discard*/;
break;
case PNG_HANDLE_CHUNK_IF_SAFE:
case PNG_HANDLE_CHUNK_ALWAYS:
discard = 0/*not handled; keep*/;
break;
}
/* Also store information about this chunk in the display, the relevant flag
* is set if the chunk is to be kept ('not handled'.)
*/
if (chunk >= 0) if (!discard) /* stupidity to stop a GCC warning */
{
png_uint_32 flag = chunk_info[chunk].flag;
if (pc->location & PNG_AFTER_IDAT)
d->after_IDAT |= flag;
else
d->before_IDAT |= flag;
}
/* However if there is no support to store unknown chunks don't ask libpng to
* do it; there will be an png_error.
*/
# ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
return discard;
# else
return 1; /*handled; discard*/
# endif
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | read_callback(png_structp pp, png_unknown_chunkp pc)
{
/* This function mimics the behavior of png_set_keep_unknown_chunks by
* returning '0' to keep the chunk and '1' to discard it.
*/
display *d = voidcast(display*, png_get_user_chunk_ptr(pp));
int chunk = findb(pc->name);
int keep, discard;
if (chunk < 0) /* not one in our list, so not a known chunk */
keep = d->keep;
else
{
keep = chunk_info[chunk].keep;
if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
{
/* See the comments in png.h - use the default for unknown chunks,
* do not keep known chunks.
*/
if (chunk_info[chunk].unknown)
keep = d->keep;
else
keep = PNG_HANDLE_CHUNK_NEVER;
}
}
switch (keep)
{
default:
fprintf(stderr, "%s(%s): %d: unrecognized chunk option\n", d->file,
d->test, chunk_info[chunk].keep);
display_exit(d);
case PNG_HANDLE_CHUNK_AS_DEFAULT:
case PNG_HANDLE_CHUNK_NEVER:
discard = 1/*handled; discard*/;
break;
case PNG_HANDLE_CHUNK_IF_SAFE:
case PNG_HANDLE_CHUNK_ALWAYS:
discard = 0/*not handled; keep*/;
break;
}
/* Also store information about this chunk in the display, the relevant flag
* is set if the chunk is to be kept ('not handled'.)
*/
if (chunk >= 0) if (!discard) /* stupidity to stop a GCC warning */
{
png_uint_32 flag = chunk_info[chunk].flag;
if (pc->location & PNG_AFTER_IDAT)
d->after_IDAT |= flag;
else
d->before_IDAT |= flag;
}
/* However if there is no support to store unknown chunks don't ask libpng to
* do it; there will be an png_error.
*/
# ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
return discard;
# else
return 1; /*handled; discard*/
# endif
}
| 173,599 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs4_atomic_open(struct inode *dir, struct dentry *dentry, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct dentry *parent;
struct iattr attr;
struct rpc_cred *cred;
struct nfs4_state *state;
struct dentry *res;
if (nd->flags & LOOKUP_CREATE) {
attr.ia_mode = nd->intent.open.create_mode;
attr.ia_valid = ATTR_MODE;
if (!IS_POSIXACL(dir))
attr.ia_mode &= ~current->fs->umask;
} else {
attr.ia_valid = 0;
BUG_ON(nd->intent.open.flags & O_CREAT);
}
cred = rpc_lookup_cred();
if (IS_ERR(cred))
return (struct dentry *)cred;
parent = dentry->d_parent;
/* Protect against concurrent sillydeletes */
nfs_block_sillyrename(parent);
state = nfs4_do_open(dir, &path, nd->intent.open.flags, &attr, cred);
put_rpccred(cred);
if (IS_ERR(state)) {
if (PTR_ERR(state) == -ENOENT) {
d_add(dentry, NULL);
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
}
nfs_unblock_sillyrename(parent);
return (struct dentry *)state;
}
res = d_add_unique(dentry, igrab(state->inode));
if (res != NULL)
path.dentry = res;
nfs_set_verifier(path.dentry, nfs_save_change_attribute(dir));
nfs_unblock_sillyrename(parent);
nfs4_intent_set_file(nd, &path, state);
return res;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | nfs4_atomic_open(struct inode *dir, struct dentry *dentry, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct dentry *parent;
struct iattr attr;
struct rpc_cred *cred;
struct nfs4_state *state;
struct dentry *res;
fmode_t fmode = nd->intent.open.flags & (FMODE_READ | FMODE_WRITE | FMODE_EXEC);
if (nd->flags & LOOKUP_CREATE) {
attr.ia_mode = nd->intent.open.create_mode;
attr.ia_valid = ATTR_MODE;
if (!IS_POSIXACL(dir))
attr.ia_mode &= ~current->fs->umask;
} else {
attr.ia_valid = 0;
BUG_ON(nd->intent.open.flags & O_CREAT);
}
cred = rpc_lookup_cred();
if (IS_ERR(cred))
return (struct dentry *)cred;
parent = dentry->d_parent;
/* Protect against concurrent sillydeletes */
nfs_block_sillyrename(parent);
state = nfs4_do_open(dir, &path, fmode, nd->intent.open.flags, &attr, cred);
put_rpccred(cred);
if (IS_ERR(state)) {
if (PTR_ERR(state) == -ENOENT) {
d_add(dentry, NULL);
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
}
nfs_unblock_sillyrename(parent);
return (struct dentry *)state;
}
res = d_add_unique(dentry, igrab(state->inode));
if (res != NULL)
path.dentry = res;
nfs_set_verifier(path.dentry, nfs_save_change_attribute(dir));
nfs_unblock_sillyrename(parent);
nfs4_intent_set_file(nd, &path, state, fmode);
return res;
}
| 165,688 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, cpu_used_);
} else if (video->frame() == 3) {
vpx_active_map_t map = {0};
uint8_t active_map[9 * 13] = {
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1,
0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0,
};
map.cols = (kWidth + 15) / 16;
map.rows = (kHeight + 15) / 16;
ASSERT_EQ(map.cols, 13u);
ASSERT_EQ(map.rows, 9u);
map.active_map = active_map;
encoder->Control(VP8E_SET_ACTIVEMAP, &map);
} else if (video->frame() == 15) {
vpx_active_map_t map = {0};
map.cols = (kWidth + 15) / 16;
map.rows = (kHeight + 15) / 16;
map.active_map = NULL;
encoder->Control(VP8E_SET_ACTIVEMAP, &map);
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, cpu_used_);
} else if (video->frame() == 3) {
vpx_active_map_t map = vpx_active_map_t();
uint8_t active_map[9 * 13] = {
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1,
0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1,
1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0,
};
map.cols = (kWidth + 15) / 16;
map.rows = (kHeight + 15) / 16;
ASSERT_EQ(map.cols, 13u);
ASSERT_EQ(map.rows, 9u);
map.active_map = active_map;
encoder->Control(VP8E_SET_ACTIVEMAP, &map);
} else if (video->frame() == 15) {
vpx_active_map_t map = vpx_active_map_t();
map.cols = (kWidth + 15) / 16;
map.rows = (kHeight + 15) / 16;
map.active_map = NULL;
encoder->Control(VP8E_SET_ACTIVEMAP, &map);
}
}
| 174,501 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle)
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | void* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle || !SecIsValidHandle(handle))
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
}
| 167,604 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: KioskNextHomeInterfaceBrokerImpl::KioskNextHomeInterfaceBrokerImpl(
content::BrowserContext* context)
: connector_(content::BrowserContext::GetConnectorFor(context)->Clone()),
app_controller_(std::make_unique<AppControllerImpl>(
Profile::FromBrowserContext(context))) {}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | KioskNextHomeInterfaceBrokerImpl::KioskNextHomeInterfaceBrokerImpl(
content::BrowserContext* context)
| 172,091 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int mpeg4video_probe(AVProbeData *probe_packet)
{
uint32_t temp_buffer = -1;
int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;
int i;
for (i = 0; i < probe_packet->buf_size; i++) {
temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];
if ((temp_buffer & 0xffffff00) != 0x100)
continue;
if (temp_buffer == VOP_START_CODE)
VOP++;
else if (temp_buffer == VISUAL_OBJECT_START_CODE)
VISO++;
else if (temp_buffer < 0x120)
VO++;
else if (temp_buffer < 0x130)
VOL++;
else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&
!(0x1B9 < temp_buffer && temp_buffer < 0x1C4))
res++;
}
if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)
return AVPROBE_SCORE_EXTENSION;
return 0;
}
Commit Message: m4vdec: Check for non-startcode 00 00 00 sequences in probe
This makes the m4v detection less trigger-happy.
Bug-Id: 949
Signed-off-by: Diego Biurrun <[email protected]>
CWE ID: CWE-476 | static int mpeg4video_probe(AVProbeData *probe_packet)
{
uint32_t temp_buffer = -1;
int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;
int i;
for (i = 0; i < probe_packet->buf_size; i++) {
temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];
if (temp_buffer & 0xfffffe00)
continue;
if (temp_buffer < 2)
continue;
if (temp_buffer == VOP_START_CODE)
VOP++;
else if (temp_buffer == VISUAL_OBJECT_START_CODE)
VISO++;
else if (temp_buffer >= 0x100 && temp_buffer < 0x120)
VO++;
else if (temp_buffer >= 0x120 && temp_buffer < 0x130)
VOL++;
else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&
!(0x1B9 < temp_buffer && temp_buffer < 0x1C4))
res++;
}
if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)
return AVPROBE_SCORE_EXTENSION;
return 0;
}
| 168,768 |
Subsets and Splits