instruction
stringclasses 1
value | input
stringlengths 93
3.53k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
|---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static inline const unsigned char *ReadResourceShort(const unsigned char *p,
unsigned short *quantum)
{
*quantum=(unsigned short) (*p++ << 8);
*quantum|=(unsigned short) (*p++ << 0);
return(p);
}static inline void WriteResourceLong(unsigned char *p,
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
|
static inline const unsigned char *ReadResourceShort(const unsigned char *p,
unsigned short *quantum)
{
*quantum=(unsigned short) (*p++) << 8;
*quantum|=(unsigned short) (*p++);
return(p);
| 169,948
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);
if (!config) {
LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
if (!config) {
LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();
if (!config) {
LOG_ERROR("%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))
unlink(LEGACY_CONFIG_FILE_PATH);
}
btif_config_remove_unpaired(config);
alarm_timer = alarm_new();
if (!alarm_timer) {
LOG_ERROR("%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
CWE ID: CWE-20
|
static future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);
if (!config) {
LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
if (!config) {
LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();
if (!config) {
LOG_ERROR("%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))
unlink(LEGACY_CONFIG_FILE_PATH);
}
btif_config_remove_unpaired(config);
// Cleanup temporary pairings if we have left guest mode
if (!is_restricted_mode())
btif_config_remove_restricted(config);
alarm_timer = alarm_new();
if (!alarm_timer) {
LOG_ERROR("%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
| 173,553
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int jas_stream_pad(jas_stream_t *stream, int n, int c)
{
int m;
m = n;
for (m = n; m > 0; --m) {
if (jas_stream_putc(stream, c) == EOF)
return n - m;
}
return n;
}
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
|
int jas_stream_pad(jas_stream_t *stream, int n, int c)
{
int m;
if (n < 0) {
jas_deprecated("negative count for jas_stream_pad");
}
m = n;
for (m = n; m > 0; --m) {
if (jas_stream_putc(stream, c) == EOF)
return n - m;
}
return n;
}
| 168,746
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = file->size;
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
|
static int read_public_key(RSA *rsa)
{
int r;
sc_path_t path;
sc_file_t *file;
u8 buf[2048], *p = buf;
size_t bufsize, keysize;
r = select_app_df();
if (r)
return 1;
sc_format_path("I1012", &path);
r = sc_select_file(card, &path, &file);
if (r) {
fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = MIN(file->size, sizeof buf);
sc_file_free(file);
r = sc_read_binary(card, 0, buf, bufsize, 0);
if (r < 0) {
fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r));
return 2;
}
bufsize = r;
do {
if (bufsize < 4)
return 3;
keysize = (p[0] << 8) | p[1];
if (keysize == 0)
break;
if (keysize < 3)
return 3;
if (p[2] == opt_key_num)
break;
p += keysize;
bufsize -= keysize;
} while (1);
if (keysize == 0) {
printf("Key number %d not found.\n", opt_key_num);
return 2;
}
return parse_public_key(p, keysize, rsa);
}
| 169,081
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: transform_enable(PNG_CONST char *name)
{
/* Everything starts out enabled, so if we see an 'enable' disabled
* everything else the first time round.
*/
static int all_disabled = 0;
int found_it = 0;
image_transform *list = image_transform_first;
while (list != &image_transform_end)
{
if (strcmp(list->name, name) == 0)
{
list->enable = 1;
found_it = 1;
}
else if (!all_disabled)
list->enable = 0;
list = list->list;
}
all_disabled = 1;
if (!found_it)
{
fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
name);
exit(99);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
transform_enable(PNG_CONST char *name)
image_transform_png_set_invert_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type & 4)
that->alpha_inverted = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_invert_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* Only has an effect on pixels with alpha: */
return (colour_type & 4) != 0;
}
IT(invert_alpha);
#undef PT
#define PT ITSTRUCT(invert_alpha)
#endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */
/* png_set_bgr */
#ifdef PNG_READ_BGR_SUPPORTED
/* Swap R,G,B channels to order B,G,R.
*
* png_set_bgr(png_structrp png_ptr)
*
* This only has an effect on RGB and RGBA pixels.
*/
static void
image_transform_png_set_bgr_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_bgr(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_bgr_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_RGBA)
that->swap_rgb = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_bgr_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_RGBA;
}
IT(bgr);
#undef PT
#define PT ITSTRUCT(bgr)
#endif /* PNG_READ_BGR_SUPPORTED */
/* png_set_swap_alpha */
#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED
/* Put the alpha channel first.
*
* png_set_swap_alpha(png_structrp png_ptr)
*
* This only has an effect on GA and RGBA pixels.
*/
static void
image_transform_png_set_swap_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_swap_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_swap_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_GA ||
that->colour_type == PNG_COLOR_TYPE_RGBA)
that->alpha_first = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_swap_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type == PNG_COLOR_TYPE_GA ||
colour_type == PNG_COLOR_TYPE_RGBA;
}
IT(swap_alpha);
#undef PT
#define PT ITSTRUCT(swap_alpha)
#endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */
/* png_set_swap */
#ifdef PNG_READ_SWAP_SUPPORTED
/* Byte swap 16-bit components.
*
* png_set_swap(png_structrp png_ptr)
*/
static void
image_transform_png_set_swap_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_swap(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_swap_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth == 16)
that->swap16 = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_swap_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth == 16;
}
IT(swap);
#undef PT
#define PT ITSTRUCT(swap)
#endif /* PNG_READ_SWAP_SUPPORTED */
#ifdef PNG_READ_FILLER_SUPPORTED
/* Add a filler byte to 8-bit Gray or 24-bit RGB images.
*
* png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags));
*
* Flags:
*
* PNG_FILLER_BEFORE
* PNG_FILLER_AFTER
*/
#define data ITDATA(filler)
static struct
{
png_uint_32 filler;
int flags;
} data;
static void
image_transform_png_set_filler_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Need a random choice for 'before' and 'after' as well as for the
* filler. The 'filler' value has all 32 bits set, but only bit_depth
* will be used. At this point we don't know bit_depth.
*/
RANDOMIZE(data.filler);
data.flags = random_choice();
png_set_filler(pp, data.filler, data.flags);
/* The standard display handling stuff also needs to know that
* there is a filler, so set that here.
*/
that->this.filler = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_filler_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth >= 8 &&
(that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_GRAY))
{
const unsigned int max = (1U << that->bit_depth)-1;
that->alpha = data.filler & max;
that->alphaf = ((double)that->alpha) / max;
that->alphae = 0;
/* The filler has been stored in the alpha channel, we must record
* that this has been done for the checking later on, the color
* type is faked to have an alpha channel, but libpng won't report
* this; the app has to know the extra channel is there and this
* was recording in standard_display::filler above.
*/
that->colour_type |= 4; /* alpha added */
that->alpha_first = data.flags == PNG_FILLER_BEFORE;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_filler_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_GRAY);
}
#undef data
IT(filler);
#undef PT
#define PT ITSTRUCT(filler)
/* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */
/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
#define data ITDATA(add_alpha)
static struct
{
png_uint_32 filler;
int flags;
} data;
static void
image_transform_png_set_add_alpha_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Need a random choice for 'before' and 'after' as well as for the
* filler. The 'filler' value has all 32 bits set, but only bit_depth
* will be used. At this point we don't know bit_depth.
*/
RANDOMIZE(data.filler);
data.flags = random_choice();
png_set_add_alpha(pp, data.filler, data.flags);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_add_alpha_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth >= 8 &&
(that->colour_type == PNG_COLOR_TYPE_RGB ||
that->colour_type == PNG_COLOR_TYPE_GRAY))
{
const unsigned int max = (1U << that->bit_depth)-1;
that->alpha = data.filler & max;
that->alphaf = ((double)that->alpha) / max;
that->alphae = 0;
that->colour_type |= 4; /* alpha added */
that->alpha_first = data.flags == PNG_FILLER_BEFORE;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_add_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB ||
colour_type == PNG_COLOR_TYPE_GRAY);
}
#undef data
IT(add_alpha);
#undef PT
#define PT ITSTRUCT(add_alpha)
#endif /* PNG_READ_FILLER_SUPPORTED */
/* png_set_packing */
#ifdef PNG_READ_PACK_SUPPORTED
/* Use 1 byte per pixel in 1, 2, or 4-bit depth files.
*
* png_set_packing(png_structrp png_ptr)
*
* This should only affect grayscale and palette images with less than 8 bits
* per pixel.
*/
static void
image_transform_png_set_packing_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_packing(pp);
that->unpacked = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_packing_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
/* The general expand case depends on what the colour type is,
* low bit-depth pixel values are unpacked into bytes without
* scaling, so sample_depth is not changed.
*/
if (that->bit_depth < 8) /* grayscale or palette */
that->bit_depth = 8;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_packing_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* Nothing should happen unless the bit depth is less than 8: */
return bit_depth < 8;
}
IT(packing);
#undef PT
#define PT ITSTRUCT(packing)
#endif /* PNG_READ_PACK_SUPPORTED */
/* png_set_packswap */
#ifdef PNG_READ_PACKSWAP_SUPPORTED
/* Swap pixels packed into bytes; reverses the order on screen so that
* the high order bits correspond to the rightmost pixels.
*
* png_set_packswap(png_structrp png_ptr)
*/
static void
image_transform_png_set_packswap_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_packswap(pp);
that->this.littleendian = 1;
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_packswap_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->bit_depth < 8)
that->littleendian = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_packswap_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth < 8;
}
IT(packswap);
#undef PT
#define PT ITSTRUCT(packswap)
#endif /* PNG_READ_PACKSWAP_SUPPORTED */
/* png_set_invert_mono */
#ifdef PNG_READ_INVERT_MONO_SUPPORTED
/* Invert the gray channel
*
* png_set_invert_mono(png_structrp png_ptr)
*/
static void
image_transform_png_set_invert_mono_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_invert_mono(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_invert_mono_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type & 4)
that->mono_inverted = 1;
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_invert_mono_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
/* Only has an effect on pixels with no colour: */
return (colour_type & 2) == 0;
}
IT(invert_mono);
#undef PT
#define PT ITSTRUCT(invert_mono)
#endif /* PNG_READ_INVERT_MONO_SUPPORTED */
#ifdef PNG_READ_SHIFT_SUPPORTED
/* png_set_shift(png_structp, png_const_color_8p true_bits)
*
* The output pixels will be shifted by the given true_bits
* values.
*/
#define data ITDATA(shift)
static png_color_8 data;
static void
image_transform_png_set_shift_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
/* Get a random set of shifts. The shifts need to do something
* to test the transform, so they are limited to the bit depth
* of the input image. Notice that in the following the 'gray'
* field is randomized independently. This acts as a check that
* libpng does use the correct field.
*/
const unsigned int depth = that->this.bit_depth;
data.red = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.green = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1);
data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1);
png_set_shift(pp, &data);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_shift_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
/* Copy the correct values into the sBIT fields, libpng does not do
* anything to palette data:
*/
if (that->colour_type != PNG_COLOR_TYPE_PALETTE)
{
that->sig_bits = 1;
/* The sBIT fields are reset to the values previously sent to
* png_set_shift according to the colour type.
* does.
*/
if (that->colour_type & 2) /* RGB channels */
{
that->red_sBIT = data.red;
that->green_sBIT = data.green;
that->blue_sBIT = data.blue;
}
else /* One grey channel */
that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray;
that->alpha_sBIT = data.alpha;
}
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_shift_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return colour_type != PNG_COLOR_TYPE_PALETTE;
}
IT(shift);
#undef PT
#define PT ITSTRUCT(shift)
#endif /* PNG_READ_SHIFT_SUPPORTED */
#ifdef THIS_IS_THE_PROFORMA
static void
image_transform_png_set_@_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_@(pp);
this->next->set(this->next, that, pp, pi);
}
static void
image_transform_png_set_@_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
this->next->mod(this->next, that, pp, display);
}
static int
image_transform_png_set_@_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
return 1;
}
IT(@);
#endif
/* This may just be 'end' if all the transforms are disabled! */
static image_transform *const image_transform_first = &PT;
static void
transform_enable(const char *name)
{
/* Everything starts out enabled, so if we see an 'enable' disabled
* everything else the first time round.
*/
static int all_disabled = 0;
int found_it = 0;
image_transform *list = image_transform_first;
while (list != &image_transform_end)
{
if (strcmp(list->name, name) == 0)
{
list->enable = 1;
found_it = 1;
}
else if (!all_disabled)
list->enable = 0;
list = list->list;
}
all_disabled = 1;
if (!found_it)
{
fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n",
name);
exit(99);
}
}
| 173,713
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SPL_METHOD(SplFileInfo, getFileInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(SplFileInfo, getFileInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
| 167,042
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: std::string TestFlashMessageLoop::TestBasics() {
message_loop_ = new pp::flash::MessageLoop(instance_);
pp::CompletionCallback callback = callback_factory_.NewCallback(
&TestFlashMessageLoop::QuitMessageLoopTask);
pp::Module::Get()->core()->CallOnMainThread(0, callback);
int32_t result = message_loop_->Run();
ASSERT_TRUE(message_loop_);
delete message_loop_;
message_loop_ = NULL;
ASSERT_EQ(PP_OK, result);
PASS();
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264
|
std::string TestFlashMessageLoop::TestBasics() {
message_loop_ = new pp::flash::MessageLoop(instance_);
pp::CompletionCallback callback = callback_factory_.NewCallback(
&TestFlashMessageLoop::QuitMessageLoopTask);
pp::Module::Get()->core()->CallOnMainThread(0, callback);
int32_t result = message_loop_->Run();
ASSERT_TRUE(message_loop_);
delete message_loop_;
message_loop_ = nullptr;
ASSERT_EQ(PP_OK, result);
PASS();
}
| 172,126
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void copyStereo8(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
*dst++ = src[1][i] << 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119
|
static void copyStereo8(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
*dst++ = src[1][i] << 8;
}
}
| 174,023
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: uint8_t* input() const {
return input_ + BorderTop() * kOuterBlockSize + BorderLeft();
}
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
|
uint8_t* input() const {
uint8_t *input() const {
#if CONFIG_VP9_HIGHBITDEPTH
if (UUT_->use_highbd_ == 0) {
return input_ + BorderTop() * kOuterBlockSize + BorderLeft();
} else {
return CONVERT_TO_BYTEPTR(input16_ + BorderTop() * kOuterBlockSize +
BorderLeft());
}
#else
return input_ + BorderTop() * kOuterBlockSize + BorderLeft();
#endif
}
| 174,510
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool AXTableCell::isColumnHeaderCell() const {
const AtomicString& scope = getAttribute(scopeAttr);
return equalIgnoringCase(scope, "col") ||
equalIgnoringCase(scope, "colgroup");
}
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 AXTableCell::isColumnHeaderCell() const {
const AtomicString& scope = getAttribute(scopeAttr);
return equalIgnoringASCIICase(scope, "col") ||
equalIgnoringASCIICase(scope, "colgroup");
}
| 171,932
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void *atomic_thread_inc_dec(void *context) {
struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
for (int i = 0; i < at->max_val; i++) {
usleep(1);
atomic_inc_prefix_s32(&at->data[i]);
usleep(1);
atomic_dec_prefix_s32(&at->data[i]);
}
return NULL;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
|
void *atomic_thread_inc_dec(void *context) {
struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
for (int i = 0; i < at->max_val; i++) {
TEMP_FAILURE_RETRY(usleep(1));
atomic_inc_prefix_s32(&at->data[i]);
TEMP_FAILURE_RETRY(usleep(1));
atomic_dec_prefix_s32(&at->data[i]);
}
return NULL;
}
| 173,491
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void DefragTrackerInit(DefragTracker *dt, Packet *p)
{
/* copy address */
COPY_ADDRESS(&p->src, &dt->src_addr);
COPY_ADDRESS(&p->dst, &dt->dst_addr);
if (PKT_IS_IPV4(p)) {
dt->id = (int32_t)IPV4_GET_IPID(p);
dt->af = AF_INET;
} else {
dt->id = (int32_t)IPV6_EXTHDR_GET_FH_ID(p);
dt->af = AF_INET6;
}
dt->vlan_id[0] = p->vlan_id[0];
dt->vlan_id[1] = p->vlan_id[1];
dt->policy = DefragGetOsPolicy(p);
dt->host_timeout = DefragPolicyGetHostTimeout(p);
dt->remove = 0;
dt->seen_last = 0;
TAILQ_INIT(&dt->frags);
(void) DefragTrackerIncrUsecnt(dt);
}
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
|
static void DefragTrackerInit(DefragTracker *dt, Packet *p)
{
/* copy address */
COPY_ADDRESS(&p->src, &dt->src_addr);
COPY_ADDRESS(&p->dst, &dt->dst_addr);
if (PKT_IS_IPV4(p)) {
dt->id = (int32_t)IPV4_GET_IPID(p);
dt->af = AF_INET;
} else {
dt->id = (int32_t)IPV6_EXTHDR_GET_FH_ID(p);
dt->af = AF_INET6;
}
dt->proto = IP_GET_IPPROTO(p);
dt->vlan_id[0] = p->vlan_id[0];
dt->vlan_id[1] = p->vlan_id[1];
dt->policy = DefragGetOsPolicy(p);
dt->host_timeout = DefragPolicyGetHostTimeout(p);
dt->remove = 0;
dt->seen_last = 0;
TAILQ_INIT(&dt->frags);
(void) DefragTrackerIncrUsecnt(dt);
}
| 168,293
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PluginInfoMessageFilter::Context::GrantAccess(
const ChromeViewHostMsg_GetPluginInfo_Status& status,
const FilePath& path) const {
if (status.value == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
status.value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay) {
ChromePluginServiceFilter::GetInstance()->AuthorizePlugin(
render_process_id_, path);
}
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287
|
void PluginInfoMessageFilter::Context::GrantAccess(
void PluginInfoMessageFilter::Context::MaybeGrantAccess(
const ChromeViewHostMsg_GetPluginInfo_Status& status,
const FilePath& path) const {
if (status.value == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
status.value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay) {
ChromePluginServiceFilter::GetInstance()->AuthorizePlugin(
render_process_id_, path);
}
}
| 171,472
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void nfs4_open_confirm_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (!data->rpc_done)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(&data->path, state, data->o_arg.open_flags);
out_free:
nfs4_opendata_put(data);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com>
CWE ID:
|
static void nfs4_open_confirm_release(void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state *state = NULL;
/* If this request hasn't been cancelled, do nothing */
if (data->cancelled == 0)
goto out_free;
/* In case of error, no cleanup! */
if (!data->rpc_done)
goto out_free;
state = nfs4_opendata_to_nfs4_state(data);
if (!IS_ERR(state))
nfs4_close_state(&data->path, state, data->o_arg.fmode);
out_free:
nfs4_opendata_put(data);
}
| 165,694
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt)
{
int n;
assert(cnt >= 0);
assert(buf);
JAS_DBGLOG(100, ("mem_read(%p, %p, %d)\n", obj, buf, cnt));
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
n = m->len_ - m->pos_;
cnt = JAS_MIN(n, cnt);
memcpy(buf, &m->buf_[m->pos_], cnt);
m->pos_ += cnt;
return cnt;
}
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 int mem_read(jas_stream_obj_t *obj, char *buf, int cnt)
{
ssize_t n;
assert(cnt >= 0);
assert(buf);
JAS_DBGLOG(100, ("mem_read(%p, %p, %d)\n", obj, buf, cnt));
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
n = m->len_ - m->pos_;
cnt = JAS_MIN(n, cnt);
memcpy(buf, &m->buf_[m->pos_], cnt);
m->pos_ += cnt;
return cnt;
}
| 168,749
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void LauncherView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
LayoutToIdealBounds();
FOR_EACH_OBSERVER(LauncherIconObserver, observers_,
OnLauncherIconPositionsChanged());
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
void LauncherView::OnBoundsChanged(const gfx::Rect& previous_bounds) {
LayoutToIdealBounds();
FOR_EACH_OBSERVER(LauncherIconObserver, observers_,
OnLauncherIconPositionsChanged());
if (IsShowingOverflowBubble())
overflow_bubble_->Hide();
}
| 170,894
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ThreadableBlobRegistry::unregisterBlobURL(const KURL& url)
{
if (BlobURL::getOrigin(url) == "null")
originMap()->remove(url.string());
if (isMainThread())
blobRegistry().unregisterBlobURL(url);
else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
callOnMainThread(&unregisterBlobURLTask, 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::unregisterBlobURL(const KURL& url)
void BlobRegistry::unregisterBlobURL(const KURL& url)
{
if (BlobURL::getOrigin(url) == "null")
originMap()->remove(url.string());
if (isMainThread()) {
if (WebBlobRegistry* registry = blobRegistry())
registry->unregisterBlobURL(url);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
callOnMainThread(&unregisterBlobURLTask, context.leakPtr());
}
}
| 170,690
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ContextualSearchFieldTrial::ContextualSearchFieldTrial()
: is_resolver_url_prefix_cached_(false),
is_surrounding_size_cached_(false),
surrounding_size_(0),
is_icing_surrounding_size_cached_(false),
icing_surrounding_size_(0),
is_send_base_page_url_disabled_cached_(false),
is_send_base_page_url_disabled_(false),
is_decode_mentions_disabled_cached_(false),
is_decode_mentions_disabled_(false),
is_now_on_tap_bar_integration_enabled_cached_(false),
is_now_on_tap_bar_integration_enabled_(false) {}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID:
|
ContextualSearchFieldTrial::ContextualSearchFieldTrial()
: is_resolver_url_prefix_cached_(false),
is_surrounding_size_cached_(false),
surrounding_size_(0),
is_icing_surrounding_size_cached_(false),
icing_surrounding_size_(0),
is_send_base_page_url_disabled_cached_(false),
is_send_base_page_url_disabled_(false),
is_decode_mentions_disabled_cached_(false),
is_decode_mentions_disabled_(false),
| 171,643
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram(
Reference ref) {
PersistentHistogramData* data =
memory_allocator_->GetAsObject<PersistentHistogramData>(ref);
const size_t length = memory_allocator_->GetAllocSize(ref);
if (!data || data->name[0] == '\0' ||
reinterpret_cast<char*>(data)[length - 1] != '\0' ||
data->samples_metadata.id == 0 || data->logged_metadata.id == 0 ||
(data->logged_metadata.id != data->samples_metadata.id &&
data->logged_metadata.id != data->samples_metadata.id + 1) ||
HashMetricName(data->name) != data->samples_metadata.id) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA);
NOTREACHED();
return nullptr;
}
return CreateHistogram(data);
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <bcwhite@chromium.org>
Reviewed-by: Alexei Svitkine <asvitkine@chromium.org>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264
|
std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram(
Reference ref) {
PersistentHistogramData* data =
memory_allocator_->GetAsObject<PersistentHistogramData>(ref);
const size_t length = memory_allocator_->GetAllocSize(ref);
if (!data || data->name[0] == '\0' ||
reinterpret_cast<char*>(data)[length - 1] != '\0' ||
data->samples_metadata.id == 0 || data->logged_metadata.id == 0 ||
(data->logged_metadata.id != data->samples_metadata.id &&
data->logged_metadata.id != data->samples_metadata.id + 1) ||
HashMetricName(data->name) != data->samples_metadata.id) {
NOTREACHED();
return nullptr;
}
return CreateHistogram(data);
}
| 172,134
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: getprivs_ret * get_privs_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp)
{
static getprivs_ret ret;
gss_buffer_desc client_name, service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_getprivs_ret, &ret);
if ((ret.code = new_server_handle(*arg, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
ret.code = kadm5_get_privs((void *)handle, &ret.privs);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_privs", client_name.value, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119
|
getprivs_ret * get_privs_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp)
{
static getprivs_ret ret;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_getprivs_ret, &ret);
if ((ret.code = new_server_handle(*arg, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
ret.code = kadm5_get_privs((void *)handle, &ret.privs);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_privs", client_name.value, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,517
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BrowserGpuChannelHostFactory::GpuChannelEstablishedOnIO(
EstablishRequest* request,
const IPC::ChannelHandle& channel_handle,
base::ProcessHandle gpu_process_handle,
const GPUInfo& gpu_info) {
request->channel_handle = channel_handle;
request->gpu_process_handle = gpu_process_handle;
request->gpu_info = gpu_info;
request->event.Signal();
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void BrowserGpuChannelHostFactory::GpuChannelEstablishedOnIO(
EstablishRequest* request,
const IPC::ChannelHandle& channel_handle,
const GPUInfo& gpu_info) {
request->channel_handle = channel_handle;
request->gpu_info = gpu_info;
request->event.Signal();
}
| 170,919
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
size_t *len,
struct iovec **iovec,
bool compat)
{
ssize_t ret;
*nr_segs = *len;
#ifdef CONFIG_COMPAT
if (compat)
ret = compat_rw_copy_check_uvector(rw,
(struct compat_iovec __user *)buf,
*nr_segs, UIO_FASTIOV, *iovec, iovec);
else
#endif
ret = rw_copy_check_uvector(rw,
(struct iovec __user *)buf,
*nr_segs, UIO_FASTIOV, *iovec, iovec);
if (ret < 0)
return ret;
/* len now reflect bytes instead of segs */
*len = ret;
return 0;
}
Commit Message: aio: lift iov_iter_init() into aio_setup_..._rw()
the only non-trivial detail is that we do it before rw_verify_area(),
so we'd better cap the length ourselves in aio_setup_single_rw()
case (for vectored case rw_copy_check_uvector() will do that for us).
Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
CWE ID:
|
static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
size_t *len,
struct iovec **iovec,
bool compat,
struct iov_iter *iter)
{
ssize_t ret;
*nr_segs = *len;
#ifdef CONFIG_COMPAT
if (compat)
ret = compat_rw_copy_check_uvector(rw,
(struct compat_iovec __user *)buf,
*nr_segs, UIO_FASTIOV, *iovec, iovec);
else
#endif
ret = rw_copy_check_uvector(rw,
(struct iovec __user *)buf,
*nr_segs, UIO_FASTIOV, *iovec, iovec);
if (ret < 0)
return ret;
/* len now reflect bytes instead of segs */
*len = ret;
iov_iter_init(iter, rw, *iovec, *nr_segs, *len);
return 0;
}
| 170,003
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void GetPreviewDataForIndex(int index,
scoped_refptr<base::RefCountedBytes>* data) {
if (index != printing::COMPLETE_PREVIEW_DOCUMENT_INDEX &&
index < printing::FIRST_PAGE_INDEX) {
return;
}
PreviewPageDataMap::iterator it = page_data_map_.find(index);
if (it != page_data_map_.end())
*data = it->second.get();
}
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 GetPreviewDataForIndex(int index,
scoped_refptr<base::RefCountedBytes>* data) {
if (IsInvalidIndex(index))
return;
PreviewPageDataMap::iterator it = page_data_map_.find(index);
if (it != page_data_map_.end())
*data = it->second.get();
}
| 170,822
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
char task_path[64];
//// Attach to a thread, and verify that it's still a member of the given process
snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir);
if (!d) {
ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno));
return;
}
struct dirent* de;
while ((de = readdir(d.get())) != NULL) {
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
continue;
}
char* end;
pid_t tid = strtoul(de->d_name, &end, 10);
if (*end) {
continue;
}
if (tid == main_tid) {
continue;
}
if (ptrace(PTRACE_ATTACH, tid, 0, 0) < 0) {
ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno));
continue;
}
tids.insert(tid);
}
}
Commit Message: debuggerd: verify that traced threads belong to the right process.
Fix two races in debuggerd's PTRACE_ATTACH logic:
1. The target thread in a crash dump request could exit between the
/proc/<pid>/task/<tid> check and the PTRACE_ATTACH.
2. Sibling threads could exit between listing /proc/<pid>/task and the
PTRACE_ATTACH.
Bug: http://b/29555636
Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591
CWE ID: CWE-264
|
static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
//// Attach to a thread, and verify that it's still a member of the given process
static bool ptrace_attach_thread(pid_t pid, pid_t tid) {
if (ptrace(PTRACE_ATTACH, tid, 0, 0) != 0) {
return false;
}
// Make sure that the task we attached to is actually part of the pid we're dumping.
if (!pid_contains_tid(pid, tid)) {
if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
ALOGE("debuggerd: failed to detach from thread '%d'", tid);
exit(1);
}
return false;
}
return true;
}
static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
char task_path[PATH_MAX];
if (snprintf(task_path, PATH_MAX, "/proc/%d/task", pid) >= PATH_MAX) {
ALOGE("debuggerd: task path overflow (pid = %d)\n", pid);
abort();
}
std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir);
if (!d) {
ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno));
return;
}
struct dirent* de;
while ((de = readdir(d.get())) != NULL) {
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
continue;
}
char* end;
pid_t tid = strtoul(de->d_name, &end, 10);
if (*end) {
continue;
}
if (tid == main_tid) {
continue;
}
if (!ptrace_attach_thread(pid, tid)) {
ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno));
continue;
}
tids.insert(tid);
}
}
| 173,406
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) {
if (current_input_method_.id != new_input_method.id) {
previous_input_method_ = current_input_method_;
current_input_method_ = new_input_method;
if (!input_method::SetCurrentKeyboardLayoutByName(
current_input_method_.keyboard_layout)) {
LOG(ERROR) << "Failed to change keyboard layout to "
<< current_input_method_.keyboard_layout;
}
ObserverListBase<Observer>::Iterator it(observers_);
Observer* first_observer = it.GetNext();
if (first_observer) {
first_observer->PreferenceUpdateNeeded(this,
previous_input_method_,
current_input_method_);
}
}
const size_t num_active_input_methods = GetNumActiveInputMethods();
FOR_EACH_OBSERVER(Observer, observers_,
InputMethodChanged(this,
current_input_method_,
num_active_input_methods));
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) {
void ChangeCurrentInputMethod(const input_method::InputMethodDescriptor&
new_input_method) {
if (current_input_method_.id != new_input_method.id) {
previous_input_method_ = current_input_method_;
current_input_method_ = new_input_method;
if (!input_method::SetCurrentKeyboardLayoutByName(
current_input_method_.keyboard_layout)) {
LOG(ERROR) << "Failed to change keyboard layout to "
<< current_input_method_.keyboard_layout;
}
ObserverListBase<InputMethodLibrary::Observer>::Iterator it(observers_);
InputMethodLibrary::Observer* first_observer = it.GetNext();
if (first_observer) {
first_observer->PreferenceUpdateNeeded(this,
previous_input_method_,
current_input_method_);
}
}
const size_t num_active_input_methods = GetNumActiveInputMethods();
FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_,
InputMethodChanged(this,
current_input_method_,
num_active_input_methods));
}
| 170,478
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int __glXDispSwap_CreateContext(__GLXclientState *cl, GLbyte *pc)
{
xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
__GLX_DECLARE_SWAP_VARIABLES;
__GLX_SWAP_SHORT(&req->length);
__GLX_SWAP_INT(&req->context);
__GLX_SWAP_INT(&req->visual);
return __glXDisp_CreateContext(cl, pc);
}
Commit Message:
CWE ID: CWE-20
|
int __glXDispSwap_CreateContext(__GLXclientState *cl, GLbyte *pc)
{
ClientPtr client = cl->client;
xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
__GLX_DECLARE_SWAP_VARIABLES;
REQUEST_SIZE_MATCH(xGLXCreateContextReq);
__GLX_SWAP_SHORT(&req->length);
__GLX_SWAP_INT(&req->context);
__GLX_SWAP_INT(&req->visual);
return __glXDisp_CreateContext(cl, pc);
}
| 165,269
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool Block::IsKey() const
{
return ((m_flags & static_cast<unsigned char>(1 << 7)) != 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
|
bool Block::IsKey() const
void Block::SetKey(bool bKey) {
if (bKey)
m_flags |= static_cast<unsigned char>(1 << 7);
else
m_flags &= 0x7F;
}
| 174,392
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BinaryUploadService::IsAuthorized(AuthorizationCallback callback) {
if (!timer_.IsRunning()) {
timer_.Start(FROM_HERE, base::TimeDelta::FromHours(24), this,
&BinaryUploadService::ResetAuthorizationData);
}
if (!can_upload_data_.has_value()) {
if (!pending_validate_data_upload_request_) {
std::string dm_token = GetDMToken();
if (dm_token.empty()) {
std::move(callback).Run(false);
return;
}
pending_validate_data_upload_request_ = true;
auto request = std::make_unique<ValidateDataUploadRequest>(base::BindOnce(
&BinaryUploadService::ValidateDataUploadRequestCallback,
weakptr_factory_.GetWeakPtr()));
request->set_dm_token(dm_token);
UploadForDeepScanning(std::move(request));
}
authorization_callbacks_.push_back(std::move(callback));
return;
}
std::move(callback).Run(can_upload_data_.value());
}
Commit Message: Migrate download_protection code to new DM token class.
Migrates RetrieveDMToken calls to use the new BrowserDMToken class.
Bug: 1020296
Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234
Commit-Queue: Dominique Fauteux-Chapleau <domfc@chromium.org>
Reviewed-by: Tien Mai <tienmai@chromium.org>
Reviewed-by: Daniel Rubery <drubery@chromium.org>
Cr-Commit-Position: refs/heads/master@{#714196}
CWE ID: CWE-20
|
void BinaryUploadService::IsAuthorized(AuthorizationCallback callback) {
if (!timer_.IsRunning()) {
timer_.Start(FROM_HERE, base::TimeDelta::FromHours(24), this,
&BinaryUploadService::ResetAuthorizationData);
}
if (!can_upload_data_.has_value()) {
if (!pending_validate_data_upload_request_) {
auto dm_token = GetDMToken();
if (!dm_token.is_valid()) {
std::move(callback).Run(false);
return;
}
pending_validate_data_upload_request_ = true;
auto request = std::make_unique<ValidateDataUploadRequest>(base::BindOnce(
&BinaryUploadService::ValidateDataUploadRequestCallback,
weakptr_factory_.GetWeakPtr()));
request->set_dm_token(dm_token.value());
UploadForDeepScanning(std::move(request));
}
authorization_callbacks_.push_back(std::move(callback));
return;
}
std::move(callback).Run(can_upload_data_.value());
}
| 172,355
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void NetworkHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_ = process_host;
host_ = frame_host;
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void NetworkHandler::SetRenderer(RenderProcessHost* process_host,
void NetworkHandler::SetRenderer(int render_process_host_id,
RenderFrameHostImpl* frame_host) {
RenderProcessHost* process_host =
RenderProcessHost::FromID(render_process_host_id);
if (process_host) {
storage_partition_ = process_host->GetStoragePartition();
browser_context_ = process_host->GetBrowserContext();
} else {
storage_partition_ = nullptr;
browser_context_ = nullptr;
}
host_ = frame_host;
}
| 172,763
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: UserSelectionScreen::UpdateAndReturnUserListForMojo() {
std::vector<ash::mojom::LoginUserInfoPtr> user_info_list;
const AccountId owner = GetOwnerAccountId();
const bool is_signin_to_add = IsSigninToAdd();
users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add);
user_auth_type_map_.clear();
for (user_manager::UserList::const_iterator it = users_to_send_.begin();
it != users_to_send_.end(); ++it) {
const AccountId& account_id = (*it)->GetAccountId();
bool is_owner = owner == account_id;
const bool is_public_account =
((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT);
const proximity_auth::mojom::AuthType initial_auth_type =
is_public_account
? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK
: (ShouldForceOnlineSignIn(*it)
? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN
: proximity_auth::mojom::AuthType::OFFLINE_PASSWORD);
user_auth_type_map_[account_id] = initial_auth_type;
ash::mojom::LoginUserInfoPtr login_user_info =
ash::mojom::LoginUserInfo::New();
const std::vector<std::string>* public_session_recommended_locales =
public_session_recommended_locales_.find(account_id) ==
public_session_recommended_locales_.end()
? nullptr
: &public_session_recommended_locales_[account_id];
FillUserMojoStruct(*it, is_owner, is_signin_to_add, initial_auth_type,
public_session_recommended_locales,
login_user_info.get());
login_user_info->can_remove = CanRemoveUser(*it);
if (is_public_account && LoginScreenClient::HasInstance()) {
LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts(
account_id, login_user_info->public_account_info->default_locale);
}
user_info_list.push_back(std::move(login_user_info));
}
return user_info_list;
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org>
Commit-Queue: Jacob Dufault <jdufault@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID:
|
UserSelectionScreen::UpdateAndReturnUserListForMojo() {
std::vector<ash::mojom::LoginUserInfoPtr> user_info_list;
const AccountId owner = GetOwnerAccountId();
const bool is_signin_to_add = IsSigninToAdd();
users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add);
user_auth_type_map_.clear();
for (const user_manager::User* user : users_to_send_) {
const AccountId& account_id = user->GetAccountId();
bool is_owner = owner == account_id;
const bool is_public_account =
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT;
const proximity_auth::mojom::AuthType initial_auth_type =
is_public_account
? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK
: (ShouldForceOnlineSignIn(user)
? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN
: proximity_auth::mojom::AuthType::OFFLINE_PASSWORD);
user_auth_type_map_[account_id] = initial_auth_type;
ash::mojom::LoginUserInfoPtr user_info = ash::mojom::LoginUserInfo::New();
user_info->basic_user_info = ash::mojom::UserInfo::New();
user_info->basic_user_info->type = user->GetType();
user_info->basic_user_info->account_id = user->GetAccountId();
user_info->basic_user_info->display_name =
base::UTF16ToUTF8(user->GetDisplayName());
user_info->basic_user_info->display_email = user->display_email();
user_info->basic_user_info->avatar = BuildMojoUserAvatarForUser(user);
user_info->auth_type = initial_auth_type;
user_info->is_signed_in = user->is_logged_in();
user_info->is_device_owner = is_owner;
user_info->can_remove = CanRemoveUser(user);
user_info->allow_fingerprint_unlock = AllowFingerprintForUser(user);
// Fill multi-profile data.
if (!is_signin_to_add) {
user_info->is_multiprofile_allowed = true;
} else {
GetMultiProfilePolicy(user, &user_info->is_multiprofile_allowed,
&user_info->multiprofile_policy);
}
// Fill public session data.
if (user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) {
user_info->public_account_info = ash::mojom::PublicAccountInfo::New();
std::string domain;
if (GetEnterpriseDomain(&domain))
user_info->public_account_info->enterprise_domain = domain;
const std::vector<std::string>* public_session_recommended_locales =
public_session_recommended_locales_.find(account_id) ==
public_session_recommended_locales_.end()
? nullptr
: &public_session_recommended_locales_[account_id];
std::string selected_locale;
bool has_multiple_locales;
std::unique_ptr<base::ListValue> available_locales =
GetPublicSessionLocales(public_session_recommended_locales,
&selected_locale, &has_multiple_locales);
DCHECK(available_locales);
user_info->public_account_info->available_locales =
lock_screen_utils::FromListValueToLocaleItem(
std::move(available_locales));
user_info->public_account_info->default_locale = selected_locale;
user_info->public_account_info->show_advanced_view = has_multiple_locales;
}
user_info->can_remove = CanRemoveUser(user);
if (is_public_account && LoginScreenClient::HasInstance()) {
LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts(
account_id, user_info->public_account_info->default_locale);
}
user_info_list.push_back(std::move(user_info));
}
return user_info_list;
}
| 172,204
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int ext4_get_block_write(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
handle_t *handle = NULL;
int ret = 0;
unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
int dio_credits;
ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
inode->i_ino, create);
/*
* ext4_get_block in prepare for a DIO write or buffer write.
* We allocate an uinitialized extent if blocks haven't been allocated.
* The extent will be converted to initialized after IO complete.
*/
create = EXT4_GET_BLOCKS_IO_CREATE_EXT;
if (max_blocks > DIO_MAX_BLOCKS)
max_blocks = DIO_MAX_BLOCKS;
dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
handle = ext4_journal_start(inode, dio_credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
create);
if (ret > 0) {
bh_result->b_size = (ret << inode->i_blkbits);
ret = 0;
}
ext4_journal_stop(handle);
out:
return ret;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <jiayingz@google.com>
Signed-off-by: "Theodore Ts'o" <tytso@mit.edu>
CWE ID:
|
static int ext4_get_block_write(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
handle_t *handle = ext4_journal_current_handle();
int ret = 0;
unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
int dio_credits;
int started = 0;
ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
inode->i_ino, create);
/*
* ext4_get_block in prepare for a DIO write or buffer write.
* We allocate an uinitialized extent if blocks haven't been allocated.
* The extent will be converted to initialized after IO complete.
*/
create = EXT4_GET_BLOCKS_IO_CREATE_EXT;
if (!handle) {
if (max_blocks > DIO_MAX_BLOCKS)
max_blocks = DIO_MAX_BLOCKS;
dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
handle = ext4_journal_start(inode, dio_credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
goto out;
}
started = 1;
}
ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
create);
if (ret > 0) {
bh_result->b_size = (ret << inode->i_blkbits);
ret = 0;
}
if (started)
ext4_journal_stop(handle);
out:
return ret;
}
| 167,545
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool isNodeAriaVisible(Node* node) {
if (!node)
return false;
if (!node->isElementNode())
return false;
return equalIgnoringCase(toElement(node)->getAttribute(aria_hiddenAttr),
"false");
}
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 isNodeAriaVisible(Node* node) {
if (!node)
return false;
if (!node->isElementNode())
return false;
return equalIgnoringASCIICase(toElement(node)->getAttribute(aria_hiddenAttr),
"false");
}
| 171,929
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual void TreeNodeChanged(TreeModel* model, TreeModelNode* node) {
changed_count_++;
}
Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods.
BUG=None
TEST=None
R=sky@chromium.org
Review URL: http://codereview.chromium.org/7046093
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
|
virtual void TreeNodeChanged(TreeModel* model, TreeModelNode* node) {
virtual void TreeNodeChanged(TreeModel* model, TreeModelNode* node) OVERRIDE {
changed_count_++;
}
| 170,469
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void SetUpTestCase() {
input_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1;
output_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
}
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
|
static void SetUpTestCase() {
input_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1;
output_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
output_ref_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
#if CONFIG_VP9_HIGHBITDEPTH
input16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment,
(kInputBufferSize + 1) * sizeof(uint16_t))) + 1;
output16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t)));
output16_ref_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t)));
#endif
}
| 174,506
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int jpeg_size(unsigned char* data, unsigned int data_size,
int *width, int *height)
{
int i = 0;
if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 &&
data[i+2] == 0xFF && data[i+3] == 0xE0) {
i += 4;
if(i + 6 < data_size &&
data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' &&
data[i+5] == 'F' && data[i+6] == 0x00) {
unsigned short block_length = data[i] * 256 + data[i+1];
while(i<data_size) {
i+=block_length;
if((i + 1) >= data_size)
return -1;
if(data[i] != 0xFF)
return -1;
if(data[i+1] == 0xC0) {
*height = data[i+5]*256 + data[i+6];
*width = data[i+7]*256 + data[i+8];
return 0;
}
i+=2;
block_length = data[i] * 256 + data[i+1];
}
}
}
return -1;
}
Commit Message: jpeg: Fix another possible buffer overrun
Found via the clang libfuzzer
CWE ID: CWE-125
|
static int jpeg_size(unsigned char* data, unsigned int data_size,
int *width, int *height)
{
int i = 0;
if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 &&
data[i+2] == 0xFF && data[i+3] == 0xE0) {
i += 4;
if(i + 6 < data_size &&
data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' &&
data[i+5] == 'F' && data[i+6] == 0x00) {
unsigned short block_length = data[i] * 256 + data[i+1];
while(i<data_size) {
i+=block_length;
if((i + 1) >= data_size)
return -1;
if(data[i] != 0xFF)
return -1;
if(data[i+1] == 0xC0) {
*height = data[i+5]*256 + data[i+6];
*width = data[i+7]*256 + data[i+8];
return 0;
}
i+=2;
if (i + 1 < data_size)
block_length = data[i] * 256 + data[i+1];
}
}
}
return -1;
}
| 169,235
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: const unsigned char* Track::GetCodecPrivate(size_t& size) const
{
size = m_info.codecPrivateSize;
return m_info.codecPrivate;
}
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 unsigned char* Track::GetCodecPrivate(size_t& size) const
| 174,295
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
if (networks == NULL)
return false;
base::ThreadRestrictions::AssertIOAllowed();
ifaddrs* interfaces;
if (getifaddrs(&interfaces) < 0) {
PLOG(ERROR) << "getifaddrs";
return false;
}
std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter;
#if defined(OS_MACOSX) && !defined(OS_IOS)
ip_attributes_getter = base::MakeUnique<internal::IPAttributesGetterMac>();
#endif
bool result = internal::IfaddrsToNetworkInterfaceList(
policy, interfaces, ip_attributes_getter.get(), networks);
freeifaddrs(interfaces);
return result;
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <jbroman@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Reviewed-by: Bence Béky <bnc@chromium.org>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311
|
bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
if (networks == NULL)
return false;
base::ThreadRestrictions::AssertIOAllowed();
ifaddrs* interfaces;
if (getifaddrs(&interfaces) < 0) {
PLOG(ERROR) << "getifaddrs";
return false;
}
std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter;
#if defined(OS_MACOSX) && !defined(OS_IOS)
ip_attributes_getter = std::make_unique<internal::IPAttributesGetterMac>();
#endif
bool result = internal::IfaddrsToNetworkInterfaceList(
policy, interfaces, ip_attributes_getter.get(), networks);
freeifaddrs(interfaces);
return result;
}
| 173,265
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, int width, int height)
{
if (width == image->width) {
/* check for integer multiplication overflow */
int64_t check = ((int64_t) image->stride) * ((int64_t) height);
if (check != (int)check) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize stride(%d)*height(%d)", image->stride, height);
return NULL;
}
/* use the same stride, just change the length */
image->data = jbig2_renew(ctx, image->data, uint8_t, (int)check);
if (image->data == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not resize image buffer!");
return NULL;
}
if (height > image->height) {
memset(image->data + image->height * image->stride, 0, (height - image->height) * image->stride);
}
image->height = height;
} else {
/* we must allocate a new image buffer and copy */
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "jbig2_image_resize called with a different width (NYI)");
}
return NULL;
}
Commit Message:
CWE ID: CWE-119
|
jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, int width, int height)
jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, uint32_t width, uint32_t height)
{
if (width == image->width) {
/* check for integer multiplication overflow */
int64_t check = ((int64_t) image->stride) * ((int64_t) height);
if (check != (int)check) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize stride(%d)*height(%d)", image->stride, height);
return NULL;
}
/* use the same stride, just change the length */
image->data = jbig2_renew(ctx, image->data, uint8_t, (int)check);
if (image->data == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not resize image buffer!");
return NULL;
}
if (height > image->height) {
memset(image->data + image->height * image->stride, 0, (height - image->height) * image->stride);
}
image->height = height;
} else {
/* we must allocate a new image buffer and copy */
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "jbig2_image_resize called with a different width (NYI)");
}
return NULL;
}
| 165,492
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PrintViewManager::PrintPreviewDone() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_NE(NOT_PREVIEWING, print_preview_state_);
if (print_preview_state_ == SCRIPTED_PREVIEW) {
auto& map = g_scripted_print_preview_closure_map.Get();
auto it = map.find(scripted_print_preview_rph_);
CHECK(it != map.end());
it->second.Run();
map.erase(it);
scripted_print_preview_rph_ = nullptr;
}
print_preview_state_ = NOT_PREVIEWING;
print_preview_rfh_ = nullptr;
}
Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated().
BUG=694382,698622
Review-Url: https://codereview.chromium.org/2742853003
Cr-Commit-Position: refs/heads/master@{#457363}
CWE ID: CWE-125
|
void PrintViewManager::PrintPreviewDone() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (print_preview_state_ == NOT_PREVIEWING)
return;
if (print_preview_state_ == SCRIPTED_PREVIEW) {
auto& map = g_scripted_print_preview_closure_map.Get();
auto it = map.find(scripted_print_preview_rph_);
CHECK(it != map.end());
it->second.Run();
map.erase(it);
scripted_print_preview_rph_ = nullptr;
}
print_preview_state_ = NOT_PREVIEWING;
print_preview_rfh_ = nullptr;
}
| 172,404
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: char* _multi_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc( len + 2 );
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
chr[ len ++ ] = '\0';
return chr;
}
Commit Message: New Pre Source
CWE ID: CWE-119
|
char* _multi_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return NULL;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc( len + 2 );
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
chr[ len ++ ] = '\0';
return chr;
}
| 169,313
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DocumentLoader::DidInstallNewDocument(Document* document) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(content_security_policy_.Release());
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(HTTPNames::Content_Language);
if (!header_content_language.IsEmpty()) {
size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(HTTPNames::Referrer_Policy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
Commit Message: Inherit CSP when self-navigating to local-scheme URL
As the linked bug example shows, we should inherit CSP when we navigate
to a local-scheme URL (even if we are in a main browsing context).
Bug: 799747
Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02
Reviewed-on: https://chromium-review.googlesource.com/c/1234337
Reviewed-by: Mike West <mkwst@chromium.org>
Commit-Queue: Andy Paicu <andypaicu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#597889}
CWE ID:
|
void DocumentLoader::DidInstallNewDocument(Document* document) {
void DocumentLoader::DidInstallNewDocument(
Document* document,
const ContentSecurityPolicy* previous_csp) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(content_security_policy_.Release(),
nullptr, previous_csp);
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(HTTPNames::Content_Language);
if (!header_content_language.IsEmpty()) {
size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(HTTPNames::Referrer_Policy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
| 172,617
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SecurityHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
if (enabled_ && host_)
AttachToRenderFrameHost();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <caseq@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
|
void SecurityHandler::SetRenderer(RenderProcessHost* process_host,
void SecurityHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
if (enabled_ && host_)
AttachToRenderFrameHost();
}
| 172,765
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: WebNotificationData ToWebNotificationData(
const PlatformNotificationData& platform_data) {
WebNotificationData web_data;
web_data.title = platform_data.title;
switch (platform_data.direction) {
case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT:
web_data.direction = WebNotificationData::DirectionLeftToRight;
break;
case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT:
web_data.direction = WebNotificationData::DirectionRightToLeft;
break;
case PlatformNotificationData::DIRECTION_AUTO:
web_data.direction = WebNotificationData::DirectionAuto;
break;
}
web_data.lang = blink::WebString::fromUTF8(platform_data.lang);
web_data.body = platform_data.body;
web_data.tag = blink::WebString::fromUTF8(platform_data.tag);
web_data.icon = blink::WebURL(platform_data.icon);
web_data.vibrate = platform_data.vibration_pattern;
web_data.timestamp = platform_data.timestamp.ToJsTime();
web_data.silent = platform_data.silent;
web_data.requireInteraction = platform_data.require_interaction;
web_data.data = platform_data.data;
blink::WebVector<blink::WebNotificationAction> resized(
platform_data.actions.size());
web_data.actions.swap(resized);
for (size_t i = 0; i < platform_data.actions.size(); ++i) {
web_data.actions[i].action =
blink::WebString::fromUTF8(platform_data.actions[i].action);
web_data.actions[i].title = platform_data.actions[i].title;
}
return web_data;
}
Commit Message: Notification actions may have an icon url.
This is behind a runtime flag for two reasons:
* The implementation is incomplete.
* We're still evaluating the API design.
Intent to Implement and Ship: Notification Action Icons
https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ
BUG=581336
Review URL: https://codereview.chromium.org/1644573002
Cr-Commit-Position: refs/heads/master@{#374649}
CWE ID:
|
WebNotificationData ToWebNotificationData(
const PlatformNotificationData& platform_data) {
WebNotificationData web_data;
web_data.title = platform_data.title;
switch (platform_data.direction) {
case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT:
web_data.direction = WebNotificationData::DirectionLeftToRight;
break;
case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT:
web_data.direction = WebNotificationData::DirectionRightToLeft;
break;
case PlatformNotificationData::DIRECTION_AUTO:
web_data.direction = WebNotificationData::DirectionAuto;
break;
}
web_data.lang = blink::WebString::fromUTF8(platform_data.lang);
web_data.body = platform_data.body;
web_data.tag = blink::WebString::fromUTF8(platform_data.tag);
web_data.icon = blink::WebURL(platform_data.icon);
web_data.vibrate = platform_data.vibration_pattern;
web_data.timestamp = platform_data.timestamp.ToJsTime();
web_data.silent = platform_data.silent;
web_data.requireInteraction = platform_data.require_interaction;
web_data.data = platform_data.data;
blink::WebVector<blink::WebNotificationAction> resized(
platform_data.actions.size());
web_data.actions.swap(resized);
for (size_t i = 0; i < platform_data.actions.size(); ++i) {
web_data.actions[i].action =
blink::WebString::fromUTF8(platform_data.actions[i].action);
web_data.actions[i].title = platform_data.actions[i].title;
web_data.actions[i].icon = blink::WebURL(platform_data.actions[i].icon);
}
return web_data;
}
| 171,632
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmGlobalEntry *ptr = NULL;
int buflen = bin->buf->length;
if (sec->payload_data + 32 > buflen) {
return NULL;
}
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && len < buflen && r < count) {
if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) {
return ret;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
goto beach;
}
r_list_append (ret, ptr);
r++;
}
return ret;
beach:
free (ptr);
return ret;
}
Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr
CWE ID: CWE-125
|
static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmGlobalEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
int buflen = bin->buf->length - (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && len < buflen && r < count) {
if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) {
return ret;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
goto beach;
}
r_list_append (ret, ptr);
r++;
}
return ret;
beach:
free (ptr);
return ret;
}
| 168,253
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RenderWidgetHostViewAura::InsertSyncPointAndACK(
int32 route_id, int gpu_host_id, bool presented,
ui::Compositor* compositor) {
uint32 sync_point = 0;
if (compositor) {
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
sync_point = factory->InsertSyncPoint();
}
RenderWidgetHostImpl::AcknowledgeBufferPresent(
route_id, gpu_host_id, presented, sync_point);
}
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
TBR=sky@chromium.org
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 RenderWidgetHostViewAura::InsertSyncPointAndACK(
const BufferPresentedParams& params) {
uint32 sync_point = 0;
// If we produced a texture, we have to synchronize with the consumer of
// that texture.
if (params.texture_to_produce) {
params.texture_to_produce->Produce();
sync_point = ImageTransportFactory::GetInstance()->InsertSyncPoint();
}
RenderWidgetHostImpl::AcknowledgeBufferPresent(
params.route_id, params.gpu_host_id, params.surface_handle, sync_point);
}
| 171,379
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ContentSuggestionsNotifierService::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterIntegerPref(
prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0);
registry->RegisterStringPref(kNotificationIDWithinCategory, std::string());
}
Commit Message: NTP: cap number of notifications/day
1 by default; Finch-configurable.
BUG=689465
Review-Url: https://codereview.chromium.org/2691023002
Cr-Commit-Position: refs/heads/master@{#450389}
CWE ID: CWE-399
|
void ContentSuggestionsNotifierService::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterIntegerPref(
prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0);
registry->RegisterIntegerPref(prefs::kContentSuggestionsNotificationsSentDay,
0);
registry->RegisterIntegerPref(
prefs::kContentSuggestionsNotificationsSentCount, 0);
registry->RegisterStringPref(kNotificationIDWithinCategory, std::string());
}
| 172,038
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void ExtensionTtsController::OnSpeechFinished(
int request_id, const std::string& error_message) {
if (!current_utterance_ || request_id != current_utterance_->id())
return;
current_utterance_->set_error(error_message);
FinishCurrentUtterance();
SpeakNextUtterance();
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void ExtensionTtsController::OnSpeechFinished(
| 170,383
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static bool add_free_nid(struct f2fs_sb_info *sbi, nid_t nid, bool build)
{
struct f2fs_nm_info *nm_i = NM_I(sbi);
struct free_nid *i;
struct nat_entry *ne;
int err;
/* 0 nid should not be used */
if (unlikely(nid == 0))
return false;
if (build) {
/* do not add allocated nids */
ne = __lookup_nat_cache(nm_i, nid);
if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) ||
nat_get_blkaddr(ne) != NULL_ADDR))
return false;
}
i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS);
i->nid = nid;
i->state = NID_NEW;
if (radix_tree_preload(GFP_NOFS)) {
kmem_cache_free(free_nid_slab, i);
return true;
}
spin_lock(&nm_i->nid_list_lock);
err = __insert_nid_to_list(sbi, i, FREE_NID_LIST, true);
spin_unlock(&nm_i->nid_list_lock);
radix_tree_preload_end();
if (err) {
kmem_cache_free(free_nid_slab, i);
return true;
}
return true;
}
Commit Message: f2fs: fix race condition in between free nid allocator/initializer
In below concurrent case, allocated nid can be loaded into free nid cache
and be allocated again.
Thread A Thread B
- f2fs_create
- f2fs_new_inode
- alloc_nid
- __insert_nid_to_list(ALLOC_NID_LIST)
- f2fs_balance_fs_bg
- build_free_nids
- __build_free_nids
- scan_nat_page
- add_free_nid
- __lookup_nat_cache
- f2fs_add_link
- init_inode_metadata
- new_inode_page
- new_node_page
- set_node_addr
- alloc_nid_done
- __remove_nid_from_list(ALLOC_NID_LIST)
- __insert_nid_to_list(FREE_NID_LIST)
This patch makes nat cache lookup and free nid list operation being atomical
to avoid this race condition.
Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>
Signed-off-by: Chao Yu <yuchao0@huawei.com>
Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org>
CWE ID: CWE-362
|
static bool add_free_nid(struct f2fs_sb_info *sbi, nid_t nid, bool build)
{
struct f2fs_nm_info *nm_i = NM_I(sbi);
struct free_nid *i, *e;
struct nat_entry *ne;
int err = -EINVAL;
bool ret = false;
/* 0 nid should not be used */
if (unlikely(nid == 0))
return false;
i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS);
i->nid = nid;
i->state = NID_NEW;
if (radix_tree_preload(GFP_NOFS))
goto err;
spin_lock(&nm_i->nid_list_lock);
if (build) {
/*
* Thread A Thread B
* - f2fs_create
* - f2fs_new_inode
* - alloc_nid
* - __insert_nid_to_list(ALLOC_NID_LIST)
* - f2fs_balance_fs_bg
* - build_free_nids
* - __build_free_nids
* - scan_nat_page
* - add_free_nid
* - __lookup_nat_cache
* - f2fs_add_link
* - init_inode_metadata
* - new_inode_page
* - new_node_page
* - set_node_addr
* - alloc_nid_done
* - __remove_nid_from_list(ALLOC_NID_LIST)
* - __insert_nid_to_list(FREE_NID_LIST)
*/
ne = __lookup_nat_cache(nm_i, nid);
if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) ||
nat_get_blkaddr(ne) != NULL_ADDR))
goto err_out;
e = __lookup_free_nid_list(nm_i, nid);
if (e) {
if (e->state == NID_NEW)
ret = true;
goto err_out;
}
}
ret = true;
err = __insert_nid_to_list(sbi, i, FREE_NID_LIST, true);
err_out:
spin_unlock(&nm_i->nid_list_lock);
radix_tree_preload_end();
err:
if (err)
kmem_cache_free(free_nid_slab, i);
return ret;
}
| 169,379
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void CaptivePortalDetector::DetectCaptivePortal(
const GURL& url,
const DetectionCallback& detection_callback) {
DCHECK(CalledOnValidThread());
DCHECK(!FetchingURL());
DCHECK(detection_callback_.is_null());
detection_callback_ = detection_callback;
url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
url_fetcher_->SetAutomaticallyRetryOn5xx(false);
url_fetcher_->SetRequestContext(request_context_.get());
url_fetcher_->SetLoadFlags(
net::LOAD_BYPASS_CACHE |
net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
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 CaptivePortalDetector::DetectCaptivePortal(
const GURL& url,
const DetectionCallback& detection_callback) {
DCHECK(CalledOnValidThread());
DCHECK(!FetchingURL());
DCHECK(detection_callback_.is_null());
detection_callback_ = detection_callback;
url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
url_fetcher_->SetAutomaticallyRetryOn5xx(false);
url_fetcher_->SetRequestContext(request_context_.get());
data_use_measurement::DataUseUserData::AttachToFetcher(
url_fetcher_.get(),
data_use_measurement::DataUseUserData::CAPTIVE_PORTAL);
url_fetcher_->SetLoadFlags(
net::LOAD_BYPASS_CACHE |
net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
url_fetcher_->Start();
}
| 172,017
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int snd_compress_check_input(struct snd_compr_params *params)
{
/* first let's check the buffer parameter's */
if (params->buffer.fragment_size == 0 ||
params->buffer.fragments > SIZE_MAX / params->buffer.fragment_size)
return -EINVAL;
/* now codec parameters */
if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX)
return -EINVAL;
if (params->codec.ch_in == 0 || params->codec.ch_out == 0)
return -EINVAL;
return 0;
}
Commit Message: ALSA: compress: fix an integer overflow check
I previously added an integer overflow check here but looking at it now,
it's still buggy.
The bug happens in snd_compr_allocate_buffer(). We multiply
".fragments" and ".fragment_size" and that doesn't overflow but then we
save it in an unsigned int so it truncates the high bits away and we
allocate a smaller than expected size.
Fixes: b35cc8225845 ('ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()')
Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
CWE ID:
|
static int snd_compress_check_input(struct snd_compr_params *params)
{
/* first let's check the buffer parameter's */
if (params->buffer.fragment_size == 0 ||
params->buffer.fragments > INT_MAX / params->buffer.fragment_size)
return -EINVAL;
/* now codec parameters */
if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX)
return -EINVAL;
if (params->codec.ch_in == 0 || params->codec.ch_out == 0)
return -EINVAL;
return 0;
}
| 167,574
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long BlockEntry::GetIndex() const
{
return m_index;
}
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 BlockEntry::GetIndex() const
| 174,329
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
Commit Message: CVE-2017-13038/PPP: Do bounds checking.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by Katie Holly.
CWE ID: CWE-125
|
handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
if (length < 2) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
if (!ND_TTEST_16BITS(p)) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
| 167,844
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: PHP_METHOD(Phar, offsetGet)
{
char *fname, *error;
size_t fname_len;
zval zfname;
phar_entry_info *entry;
zend_string *sfname;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
return;
}
/* security is 0 here so that we can get a better error message than "entry doesn't exist" */
if (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:"");
} else {
if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname);
return;
}
if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname);
return;
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->archive->fname);
return;
}
if (entry->is_temp_dir) {
efree(entry->filename);
efree(entry);
}
sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, fname);
ZVAL_NEW_STR(&zfname, sfname);
spl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname);
zval_ptr_dtor(&zfname);
}
}
Commit Message:
CWE ID: CWE-20
|
PHP_METHOD(Phar, offsetGet)
{
char *fname, *error;
size_t fname_len;
zval zfname;
phar_entry_info *entry;
zend_string *sfname;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
return;
}
/* security is 0 here so that we can get a better error message than "entry doesn't exist" */
if (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:"");
} else {
if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname);
return;
}
if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname);
return;
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->archive->fname);
return;
}
if (entry->is_temp_dir) {
efree(entry->filename);
efree(entry);
}
sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, fname);
ZVAL_NEW_STR(&zfname, sfname);
spl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname);
zval_ptr_dtor(&zfname);
}
}
| 165,066
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function 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
TBR=sky@chromium.org
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. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
|
epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
| 169,055
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DrawingBuffer::ReadBackFramebuffer(unsigned char* pixels,
int width,
int height,
ReadbackOrder readback_order,
WebGLImageConversion::AlphaOp op) {
DCHECK(state_restorer_);
state_restorer_->SetPixelPackAlignmentDirty();
gl_->PixelStorei(GL_PACK_ALIGNMENT, 1);
gl_->ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
size_t buffer_size = 4 * width * height;
if (readback_order == kReadbackSkia) {
#if (SK_R32_SHIFT == 16) && !SK_B32_SHIFT
for (size_t i = 0; i < buffer_size; i += 4) {
std::swap(pixels[i], pixels[i + 2]);
}
#endif
}
if (op == WebGLImageConversion::kAlphaDoPremultiply) {
for (size_t i = 0; i < buffer_size; i += 4) {
pixels[i + 0] = std::min(255, pixels[i + 0] * pixels[i + 3] / 255);
pixels[i + 1] = std::min(255, pixels[i + 1] * pixels[i + 3] / 255);
pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255);
}
} else if (op != WebGLImageConversion::kAlphaDoNothing) {
NOTREACHED();
}
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
R=kbr@chromium.org,piman@chromium.org
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <piman@chromium.org>
Reviewed-by: Kenneth Russell <kbr@chromium.org>
Commit-Queue: Zhenyao Mo <zmo@chromium.org>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
|
void DrawingBuffer::ReadBackFramebuffer(unsigned char* pixels,
int width,
int height,
ReadbackOrder readback_order,
WebGLImageConversion::AlphaOp op) {
DCHECK(state_restorer_);
state_restorer_->SetPixelPackParametersDirty();
gl_->PixelStorei(GL_PACK_ALIGNMENT, 1);
if (webgl_version_ > kWebGL1) {
gl_->PixelStorei(GL_PACK_SKIP_ROWS, 0);
gl_->PixelStorei(GL_PACK_SKIP_PIXELS, 0);
gl_->PixelStorei(GL_PACK_ROW_LENGTH, 0);
state_restorer_->SetPixelPackBufferBindingDirty();
gl_->BindBuffer(GL_PIXEL_PACK_BUFFER, 0);
}
gl_->ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
size_t buffer_size = 4 * width * height;
if (readback_order == kReadbackSkia) {
#if (SK_R32_SHIFT == 16) && !SK_B32_SHIFT
for (size_t i = 0; i < buffer_size; i += 4) {
std::swap(pixels[i], pixels[i + 2]);
}
#endif
}
if (op == WebGLImageConversion::kAlphaDoPremultiply) {
for (size_t i = 0; i < buffer_size; i += 4) {
pixels[i + 0] = std::min(255, pixels[i + 0] * pixels[i + 3] / 255);
pixels[i + 1] = std::min(255, pixels[i + 1] * pixels[i + 3] / 255);
pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255);
}
} else if (op != WebGLImageConversion::kAlphaDoNothing) {
NOTREACHED();
}
}
| 172,294
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int Track::Info::Copy(Info& dst) const {
if (&dst == this)
return 0;
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0) {
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
int Track::Info::Copy(Info& dst) const {
if (&dst == this)
return 0;
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0) {
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = SafeArrayAlloc<unsigned char>(1, codecPrivateSize);
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
| 173,802
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: CWD_API void realpath_cache_del(const char *path, int path_len TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
return;
} else {
bucket = &(*bucket)->next;
}
}
}
/* }}} */
Commit Message:
CWE ID: CWE-190
|
CWD_API void realpath_cache_del(const char *path, int path_len TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
return;
} else {
bucket = &(*bucket)->next;
}
}
}
/* }}} */
| 164,982
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static aura::Window* OpenTestWindow(aura::Window* parent, bool modal) {
DCHECK(!modal || (modal && parent));
views::Widget* widget =
views::Widget::CreateWindowWithParent(new TestWindow(modal), parent);
widget->Show();
return widget->GetNativeView();
}
Commit Message: Removed requirement for ash::Window::transient_parent() presence for system modal dialogs.
BUG=130420
TEST=SystemModalContainerLayoutManagerTest.ModalTransientAndNonTransient
Review URL: https://chromiumcodereview.appspot.com/10514012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@140647 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
static aura::Window* OpenTestWindow(aura::Window* parent, bool modal) {
views::Widget* widget =
views::Widget::CreateWindowWithParent(new TestWindow(modal), parent);
widget->Show();
return widget->GetNativeView();
}
| 170,802
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: long Chapters::Display::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05) { // ChapterString ID
status = UnserializeString(pReader, pos, size, m_string);
if (status)
return status;
} else if (id == 0x037C) { // ChapterLanguage ID
status = UnserializeString(pReader, pos, size, m_language);
if (status)
return status;
} else if (id == 0x037E) { // ChapterCountry ID
status = UnserializeString(pReader, pos, size, m_country);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
long Chapters::Display::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05) { // ChapterString ID
status = UnserializeString(pReader, pos, size, m_string);
if (status)
return status;
} else if (id == 0x037C) { // ChapterLanguage ID
status = UnserializeString(pReader, pos, size, m_language);
if (status)
return status;
} else if (id == 0x037E) { // ChapterCountry ID
status = UnserializeString(pReader, pos, size, m_country);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
Tags::Tags(Segment* pSegment, long long payload_start, long long payload_size,
long long element_start, long long element_size)
: m_pSegment(pSegment),
m_start(payload_start),
m_size(payload_size),
m_element_start(element_start),
m_element_size(element_size),
m_tags(NULL),
m_tags_size(0),
m_tags_count(0) {}
Tags::~Tags() {
while (m_tags_count > 0) {
Tag& t = m_tags[--m_tags_count];
t.Clear();
}
delete[] m_tags;
}
long Tags::Parse() {
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start; // payload start
const long long stop = pos + m_size; // payload stop
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0)
return status;
if (size == 0) // 0 length tag, read another
continue;
if (id == 0x3373) { // Tag ID
status = ParseTag(pos, size);
if (status < 0)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
int Tags::GetTagCount() const { return m_tags_count; }
const Tags::Tag* Tags::GetTag(int idx) const {
if (idx < 0)
return NULL;
if (idx >= m_tags_count)
return NULL;
return m_tags + idx;
}
bool Tags::ExpandTagsArray() {
if (m_tags_size > m_tags_count)
return true; // nothing else to do
const int size = (m_tags_size == 0) ? 1 : 2 * m_tags_size;
Tag* const tags = new (std::nothrow) Tag[size];
if (tags == NULL)
return false;
for (int idx = 0; idx < m_tags_count; ++idx) {
m_tags[idx].ShallowCopy(tags[idx]);
}
delete[] m_tags;
m_tags = tags;
m_tags_size = size;
return true;
}
long Tags::ParseTag(long long pos, long long size) {
if (!ExpandTagsArray())
return -1;
Tag& t = m_tags[m_tags_count++];
t.Init();
return t.Parse(m_pSegment->m_pReader, pos, size);
}
Tags::Tag::Tag() {}
Tags::Tag::~Tag() {}
int Tags::Tag::GetSimpleTagCount() const { return m_simple_tags_count; }
const Tags::SimpleTag* Tags::Tag::GetSimpleTag(int index) const {
if (index < 0)
return NULL;
if (index >= m_simple_tags_count)
return NULL;
return m_simple_tags + index;
}
void Tags::Tag::Init() {
m_simple_tags = NULL;
m_simple_tags_size = 0;
m_simple_tags_count = 0;
}
void Tags::Tag::ShallowCopy(Tag& rhs) const {
rhs.m_simple_tags = m_simple_tags;
rhs.m_simple_tags_size = m_simple_tags_size;
rhs.m_simple_tags_count = m_simple_tags_count;
}
void Tags::Tag::Clear() {
while (m_simple_tags_count > 0) {
SimpleTag& d = m_simple_tags[--m_simple_tags_count];
d.Clear();
}
delete[] m_simple_tags;
m_simple_tags = NULL;
m_simple_tags_size = 0;
}
long Tags::Tag::Parse(IMkvReader* pReader, long long pos, long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0)
return status;
if (size == 0) // 0 length tag, read another
continue;
if (id == 0x27C8) { // SimpleTag ID
status = ParseSimpleTag(pReader, pos, size);
if (status < 0)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
long Tags::Tag::ParseSimpleTag(IMkvReader* pReader, long long pos,
long long size) {
if (!ExpandSimpleTagsArray())
return -1;
SimpleTag& st = m_simple_tags[m_simple_tags_count++];
st.Init();
return st.Parse(pReader, pos, size);
}
bool Tags::Tag::ExpandSimpleTagsArray() {
if (m_simple_tags_size > m_simple_tags_count)
return true; // nothing else to do
const int size = (m_simple_tags_size == 0) ? 1 : 2 * m_simple_tags_size;
SimpleTag* const displays = new (std::nothrow) SimpleTag[size];
if (displays == NULL)
return false;
for (int idx = 0; idx < m_simple_tags_count; ++idx) {
m_simple_tags[idx].ShallowCopy(displays[idx]);
}
delete[] m_simple_tags;
m_simple_tags = displays;
m_simple_tags_size = size;
return true;
}
Tags::SimpleTag::SimpleTag() {}
Tags::SimpleTag::~SimpleTag() {}
const char* Tags::SimpleTag::GetTagName() const { return m_tag_name; }
const char* Tags::SimpleTag::GetTagString() const { return m_tag_string; }
void Tags::SimpleTag::Init() {
m_tag_name = NULL;
m_tag_string = NULL;
}
void Tags::SimpleTag::ShallowCopy(SimpleTag& rhs) const {
rhs.m_tag_name = m_tag_name;
rhs.m_tag_string = m_tag_string;
}
void Tags::SimpleTag::Clear() {
delete[] m_tag_name;
m_tag_name = NULL;
delete[] m_tag_string;
m_tag_string = NULL;
}
long Tags::SimpleTag::Parse(IMkvReader* pReader, long long pos,
long long size) {
const long long stop = pos + size;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x5A3) { // TagName ID
status = UnserializeString(pReader, pos, size, m_tag_name);
if (status)
return status;
} else if (id == 0x487) { // TagString ID
status = UnserializeString(pReader, pos, size, m_tag_string);
if (status)
return status;
}
pos += size;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,841
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void WebPluginProxy::CreateCanvasFromHandle(
const TransportDIB::Handle& dib_handle,
const gfx::Rect& window_rect,
scoped_ptr<skia::PlatformCanvas>* canvas_out) {
HANDLE section;
DuplicateHandle(channel_->renderer_handle(), dib_handle, GetCurrentProcess(),
§ion,
STANDARD_RIGHTS_REQUIRED | FILE_MAP_READ | FILE_MAP_WRITE,
FALSE, 0);
scoped_ptr<skia::PlatformCanvas> canvas(new skia::PlatformCanvas);
if (!canvas->initialize(
window_rect.width(),
window_rect.height(),
true,
section)) {
canvas_out->reset();
}
canvas_out->reset(canvas.release());
CloseHandle(section);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
|
void WebPluginProxy::CreateCanvasFromHandle(
const TransportDIB::Handle& dib_handle,
const gfx::Rect& window_rect,
scoped_ptr<skia::PlatformCanvas>* canvas_out) {
scoped_ptr<skia::PlatformCanvas> canvas(new skia::PlatformCanvas);
if (!canvas->initialize(
window_rect.width(),
window_rect.height(),
true,
dib_handle)) {
canvas_out->reset();
}
canvas_out->reset(canvas.release());
CloseHandle(dib_handle);
}
| 170,952
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(navigation_handle);
if (!navigation_handle->IsInMainFrame() ||
navigation_handle->IsSameDocument()) {
return;
}
first_time_title_set_ = false;
first_time_favicon_set_ = false;
if (!navigation_handle->HasCommitted())
return;
const url::Origin new_origin =
url::Origin::Create(navigation_handle->GetURL());
if (writer_ && new_origin == writer_origin_)
return;
writer_.reset();
writer_origin_ = url::Origin();
if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
return;
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
DCHECK(profile);
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
DCHECK(data_store);
writer_ = data_store->GetWriterForOrigin(
new_origin,
ContentVisibilityToRCVisibility(web_contents()->GetVisibility()));
if (TabLoadTracker::Get()->GetLoadingState(web_contents()) ==
LoadingState::LOADED) {
writer_->NotifySiteLoaded();
}
writer_origin_ = new_origin;
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org>
Reviewed-by: François Doray <fdoray@chromium.org>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
|
void LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(navigation_handle);
if (!navigation_handle->IsInMainFrame() ||
navigation_handle->IsSameDocument()) {
return;
}
first_time_title_set_ = false;
first_time_favicon_set_ = false;
if (!navigation_handle->HasCommitted())
return;
const url::Origin new_origin =
url::Origin::Create(navigation_handle->GetURL());
if (writer_ && new_origin == writer_origin_)
return;
writer_.reset();
writer_origin_ = url::Origin();
if (!URLShouldBeStoredInLocalDatabase(navigation_handle->GetURL()))
return;
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
DCHECK(profile);
SiteCharacteristicsDataStore* data_store =
LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile);
DCHECK(data_store);
writer_ = data_store->GetWriterForOrigin(
new_origin,
ContentVisibilityToRCVisibility(web_contents()->GetVisibility()));
if (TabLoadTracker::Get()->GetLoadingState(web_contents()) ==
LoadingState::LOADED) {
writer_->NotifySiteLoaded();
}
writer_origin_ = new_origin;
}
| 172,216
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
RemoveInterstitialObservers(old_contents);
AddInterstitialObservers(new_contents->web_contents());
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
RemoveInterstitialObservers(old_contents->web_contents());
AddInterstitialObservers(new_contents->web_contents());
}
| 171,512
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: int res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200
|
int res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1; // "partition size" in spec
info->partitions=(char)(oggpack_read(opb,6)+1); // "classification" in spec
info->groupbook=(unsigned char)oggpack_read(opb,8); // "classbook" in spec
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
// According to the Vorbis spec (paragraph 8.6.2 "packet decode"), residue
// begin and end should be limited to the maximum possible vector size in
// case they exceed it. However doing that makes the decoder crash further
// down, so we return an error instead.
int limit = (info->type == 2 ? vi->channels : 1) * ci->blocksizes[1] / 2;
if (info->begin > info->end ||
info->end > limit) {
goto errout;
}
return 0;
errout:
res_clear_info(info);
return 1;
}
| 173,991
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static PassOwnPtr<AsyncFileSystemCallbacks> create(PassRefPtrWillBeRawPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
{
return adoptPtr(static_cast<AsyncFileSystemCallbacks*>(new CreateFileHelper(result, name, url, type)));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
|
static PassOwnPtr<AsyncFileSystemCallbacks> create(PassRefPtrWillBeRawPtr<CreateFileResult> result, const String& name, const KURL& url, FileSystemType type)
static PassOwnPtr<AsyncFileSystemCallbacks> create(CreateFileResult* result, const String& name, const KURL& url, FileSystemType type)
{
return adoptPtr(static_cast<AsyncFileSystemCallbacks*>(new CreateFileHelper(result, name, url, type)));
}
| 171,414
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
unsigned code_point;
ReadUTFChar(spec, &i, end, &code_point);
AppendUTF8Value(code_point, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
Commit Message: Percent-encode UTF8 characters in URL fragment identifiers.
This brings us into line with Firefox, Safari, and the spec.
Bug: 758523
Change-Id: I7e354ab441222d9fd08e45f0e70f91ad4e35fafe
Reviewed-on: https://chromium-review.googlesource.com/668363
Commit-Queue: Mike West <mkwst@chromium.org>
Reviewed-by: Jochen Eisinger <jochen@chromium.org>
Reviewed-by: Andy Paicu <andypaicu@chromium.org>
Cr-Commit-Position: refs/heads/master@{#507481}
CWE ID: CWE-79
|
void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
AppendUTF8EscapedChar(spec, &i, end, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
| 172,903
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int __init xfrm6_tunnel_init(void)
{
int rv;
rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);
if (rv < 0)
goto err;
rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);
if (rv < 0)
goto unreg;
rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);
if (rv < 0)
goto dereg6;
rv = xfrm6_tunnel_spi_init();
if (rv < 0)
goto dereg46;
rv = register_pernet_subsys(&xfrm6_tunnel_net_ops);
if (rv < 0)
goto deregspi;
return 0;
deregspi:
xfrm6_tunnel_spi_fini();
dereg46:
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
dereg6:
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
unreg:
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
err:
return rv;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
CWE ID: CWE-362
|
static int __init xfrm6_tunnel_init(void)
{
int rv;
xfrm6_tunnel_spi_kmem = kmem_cache_create("xfrm6_tunnel_spi",
sizeof(struct xfrm6_tunnel_spi),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!xfrm6_tunnel_spi_kmem)
return -ENOMEM;
rv = register_pernet_subsys(&xfrm6_tunnel_net_ops);
if (rv < 0)
goto out_pernet;
rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);
if (rv < 0)
goto out_type;
rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);
if (rv < 0)
goto out_xfrm6;
rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);
if (rv < 0)
goto out_xfrm46;
return 0;
out_xfrm46:
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
out_xfrm6:
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
out_type:
unregister_pernet_subsys(&xfrm6_tunnel_net_ops);
out_pernet:
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
return rv;
}
| 165,880
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
php_stream *file;
size_t memsize;
char *membuf;
off_t pos;
assert(ts != NULL);
if (!ts->innerstream) {
return FAILURE;
}
if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) {
return php_stream_cast(ts->innerstream, castas, ret, 0);
}
/* we are still using a memory based backing. If they are if we can be
* a FILE*, say yes because we can perform the conversion.
* If they actually want to perform the conversion, we need to switch
* the memory stream to a tmpfile stream */
if (ret == NULL && castas == PHP_STREAM_AS_STDIO) {
return SUCCESS;
}
/* say "no" to other stream forms */
if (ret == NULL) {
return FAILURE;
}
/* perform the conversion and then pass the request on to the innerstream */
membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize);
file = php_stream_fopen_tmpfile();
php_stream_write(file, membuf, memsize);
pos = php_stream_tell(ts->innerstream);
php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE);
ts->innerstream = file;
php_stream_encloses(stream, ts->innerstream);
php_stream_seek(ts->innerstream, pos, SEEK_SET);
return php_stream_cast(ts->innerstream, castas, ret, 1);
}
Commit Message:
CWE ID: CWE-20
|
static int php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
php_stream *file;
size_t memsize;
char *membuf;
off_t pos;
assert(ts != NULL);
if (!ts->innerstream) {
return FAILURE;
}
if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) {
return php_stream_cast(ts->innerstream, castas, ret, 0);
}
/* we are still using a memory based backing. If they are if we can be
* a FILE*, say yes because we can perform the conversion.
* If they actually want to perform the conversion, we need to switch
* the memory stream to a tmpfile stream */
if (ret == NULL && castas == PHP_STREAM_AS_STDIO) {
return SUCCESS;
}
/* say "no" to other stream forms */
if (ret == NULL) {
return FAILURE;
}
/* perform the conversion and then pass the request on to the innerstream */
membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize);
file = php_stream_fopen_tmpfile();
php_stream_write(file, membuf, memsize);
pos = php_stream_tell(ts->innerstream);
php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE);
ts->innerstream = file;
php_stream_encloses(stream, ts->innerstream);
php_stream_seek(ts->innerstream, pos, SEEK_SET);
return php_stream_cast(ts->innerstream, castas, ret, 1);
}
| 165,478
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: json_t *json_object(void)
{
json_object_t *object = jsonp_malloc(sizeof(json_object_t));
if(!object)
return NULL;
json_init(&object->json, JSON_OBJECT);
if(hashtable_init(&object->hashtable))
{
jsonp_free(object);
return NULL;
}
object->serial = 0;
object->visited = 0;
return &object->json;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310
|
json_t *json_object(void)
{
json_object_t *object = jsonp_malloc(sizeof(json_object_t));
if(!object)
return NULL;
if (!hashtable_seed) {
/* Autoseed */
json_object_seed(0);
}
json_init(&object->json, JSON_OBJECT);
if(hashtable_init(&object->hashtable))
{
jsonp_free(object);
return NULL;
}
object->serial = 0;
object->visited = 0;
return &object->json;
}
| 166,535
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PreconnectManager::Start(const GURL& url,
std::vector<PreconnectRequest> requests) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
const std::string host = url.host();
if (preresolve_info_.find(host) != preresolve_info_.end())
return;
auto iterator_and_whether_inserted = preresolve_info_.emplace(
host, std::make_unique<PreresolveInfo>(url, requests.size()));
PreresolveInfo* info = iterator_and_whether_inserted.first->second.get();
for (auto request_it = requests.begin(); request_it != requests.end();
++request_it) {
DCHECK(request_it->origin.GetOrigin() == request_it->origin);
PreresolveJobId job_id = preresolve_jobs_.Add(
std::make_unique<PreresolveJob>(std::move(*request_it), info));
queued_jobs_.push_back(job_id);
}
TryToLaunchPreresolveJobs();
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org>
Reviewed-by: Alex Ilin <alexilin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125
|
void PreconnectManager::Start(const GURL& url,
std::vector<PreconnectRequest> requests) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
const std::string host = url.host();
if (preresolve_info_.find(host) != preresolve_info_.end())
return;
auto iterator_and_whether_inserted = preresolve_info_.emplace(
host, std::make_unique<PreresolveInfo>(url, requests.size()));
PreresolveInfo* info = iterator_and_whether_inserted.first->second.get();
for (auto request_it = requests.begin(); request_it != requests.end();
++request_it) {
PreresolveJobId job_id = preresolve_jobs_.Add(
std::make_unique<PreresolveJob>(std::move(*request_it), info));
queued_jobs_.push_back(job_id);
}
TryToLaunchPreresolveJobs();
}
| 172,377
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void UsbFindDevicesFunction::OnGetDevicesComplete(
const std::vector<scoped_refptr<UsbDevice>>& devices) {
result_.reset(new base::ListValue());
barrier_ = base::BarrierClosure(
devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this));
for (const scoped_refptr<UsbDevice>& device : devices) {
if (device->vendor_id() != vendor_id_ ||
device->product_id() != product_id_) {
barrier_.Run();
} else {
device->OpenInterface(
interface_id_,
base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this));
}
}
}
Commit Message: Remove fallback when requesting a single USB interface.
This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The
permission broker now supports opening devices that are partially
claimed through the OpenPath method and RequestPathAccess will always
fail for these devices so the fallback path from RequestPathAccess to
OpenPath is always taken.
BUG=500057
Review URL: https://codereview.chromium.org/1227313003
Cr-Commit-Position: refs/heads/master@{#338354}
CWE ID: CWE-399
|
void UsbFindDevicesFunction::OnGetDevicesComplete(
const std::vector<scoped_refptr<UsbDevice>>& devices) {
result_.reset(new base::ListValue());
barrier_ = base::BarrierClosure(
devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this));
for (const scoped_refptr<UsbDevice>& device : devices) {
if (device->vendor_id() != vendor_id_ ||
device->product_id() != product_id_) {
barrier_.Run();
} else {
device->Open(base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this));
}
}
}
| 171,703
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: SPL_METHOD(GlobIterator, count)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {
RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
} else {
/* should not happen */
php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state");
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
|
SPL_METHOD(GlobIterator, count)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {
RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
} else {
/* should not happen */
php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state");
}
}
| 167,048
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
}
Commit Message:
CWE ID: CWE-200
|
xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->options &= ~XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
}
| 164,725
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void Cues::Init() const {
if (m_cue_points)
return;
assert(m_count == 0);
assert(m_preload_count == 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop) {
const long long idpos = pos;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x3B) // CuePoint ID
PreloadCuePoint(cue_points_size, idpos);
pos += size; // consume payload
assert(pos <= stop);
}
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
|
void Cues::Init() const {
bool Cues::Init() const {
if (m_cue_points)
return true;
if (m_count != 0 || m_preload_count != 0)
return false;
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop) {
const long long idpos = pos;
long len;
const long long id = ReadID(pReader, pos, len);
if (id < 0 || (pos + len) > stop) {
return false;
}
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
if (size < 0 || (pos + len > stop)) {
return false;
}
pos += len; // consume Size field
if (pos + size > stop) {
return false;
}
if (id == 0x3B) { // CuePoint ID
if (!PreloadCuePoint(cue_points_size, idpos))
return false;
}
pos += size; // skip payload
}
return true;
}
| 173,827
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: DataReductionProxySettings::DataReductionProxySettings()
: unreachable_(false),
deferred_initialization_(false),
prefs_(nullptr),
config_(nullptr),
clock_(base::DefaultClock::GetInstance()) {}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <waffles@chromium.org>
Reviewed-by: Tarun Bansal <tbansal@chromium.org>
Commit-Queue: Robert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
|
DataReductionProxySettings::DataReductionProxySettings()
: unreachable_(false),
deferred_initialization_(false),
prefs_(nullptr),
config_(nullptr),
clock_(base::DefaultClock::GetInstance()) {}
| 172,550
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void UpdateUI(const char* current_global_engine_id) {
DCHECK(current_global_engine_id);
const IBusEngineInfo* engine_info = NULL;
for (size_t i = 0; i < arraysize(kIBusEngines); ++i) {
if (kIBusEngines[i].name == std::string(current_global_engine_id)) {
engine_info = &kIBusEngines[i];
break;
}
}
if (!engine_info) {
LOG(ERROR) << current_global_engine_id
<< " is not found in the input method white-list.";
return;
}
InputMethodDescriptor current_input_method =
CreateInputMethodDescriptor(engine_info->name,
engine_info->longname,
engine_info->layout,
engine_info->language);
DLOG(INFO) << "Updating the UI. ID:" << current_input_method.id
<< ", keyboard_layout:" << current_input_method.keyboard_layout;
current_input_method_changed_(language_library_, current_input_method);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void UpdateUI(const char* current_global_engine_id) {
DCHECK(current_global_engine_id);
const IBusEngineInfo* engine_info = NULL;
for (size_t i = 0; i < arraysize(kIBusEngines); ++i) {
if (kIBusEngines[i].name == std::string(current_global_engine_id)) {
engine_info = &kIBusEngines[i];
break;
}
}
if (!engine_info) {
LOG(ERROR) << current_global_engine_id
<< " is not found in the input method white-list.";
return;
}
InputMethodDescriptor current_input_method =
CreateInputMethodDescriptor(engine_info->name,
engine_info->longname,
engine_info->layout,
engine_info->language);
VLOG(1) << "Updating the UI. ID:" << current_input_method.id
<< ", keyboard_layout:" << current_input_method.keyboard_layout;
FOR_EACH_OBSERVER(Observer, observers_,
OnCurrentInputMethodChanged(current_input_method));
}
| 170,552
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes)
{
ulg rowbytes;
/* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
* transparency chunks to full alpha channel; strip 16-bit-per-sample
* images to 8 bits per sample; and convert grayscale to RGB[A] */
/* GRR WARNING: grayscale needs to be expanded and channels reset! */
*pRowbytes = rowbytes = channels*width;
*pChannels = channels;
if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) {
return NULL;
}
Trace((stderr, "readpng_get_image: rowbytes = %ld, height = %ld\n", rowbytes, height));
/* now we can go ahead and just read the whole image */
fread(image_data, 1L, rowbytes*height, saved_infile);
return image_data;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
|
uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes)
{
ulg rowbytes;
/* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,
* transparency chunks to full alpha channel; strip 16-bit-per-sample
* images to 8 bits per sample; and convert grayscale to RGB[A] */
/* GRR WARNING: grayscale needs to be expanded and channels reset! */
*pRowbytes = rowbytes = channels*width;
*pChannels = channels;
if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) {
return NULL;
}
Trace((stderr, "readpng_get_image: rowbytes = %ld, height = %ld\n", rowbytes, height));
/* now we can go ahead and just read the whole image */
if (fread(image_data, 1L, rowbytes*height, saved_infile) <
rowbytes*height) {
free (image_data);
image_data = NULL;
return NULL;
}
return image_data;
}
| 173,572
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void PrintSettingsInitializerWin::InitPrintSettings(
HDC hdc,
const DEVMODE& dev_mode,
const PageRanges& new_ranges,
const std::wstring& new_device_name,
bool print_selection_only,
PrintSettings* print_settings) {
DCHECK(hdc);
DCHECK(print_settings);
print_settings->set_printer_name(dev_mode.dmDeviceName);
print_settings->set_device_name(new_device_name);
print_settings->ranges = new_ranges;
print_settings->set_landscape(dev_mode.dmOrientation == DMORIENT_LANDSCAPE);
print_settings->selection_only = print_selection_only;
int dpi = GetDeviceCaps(hdc, LOGPIXELSX);
print_settings->set_dpi(dpi);
const int kAlphaCaps = SB_CONST_ALPHA | SB_PIXEL_ALPHA;
print_settings->set_supports_alpha_blend(
(GetDeviceCaps(hdc, SHADEBLENDCAPS) & kAlphaCaps) == kAlphaCaps);
DCHECK_EQ(dpi, GetDeviceCaps(hdc, LOGPIXELSY));
DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0);
DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0);
gfx::Size physical_size_device_units(GetDeviceCaps(hdc, PHYSICALWIDTH),
GetDeviceCaps(hdc, PHYSICALHEIGHT));
gfx::Rect printable_area_device_units(GetDeviceCaps(hdc, PHYSICALOFFSETX),
GetDeviceCaps(hdc, PHYSICALOFFSETY),
GetDeviceCaps(hdc, HORZRES),
GetDeviceCaps(hdc, VERTRES));
print_settings->SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
void PrintSettingsInitializerWin::InitPrintSettings(
HDC hdc,
const DEVMODE& dev_mode,
const PageRanges& new_ranges,
const std::wstring& new_device_name,
bool print_selection_only,
PrintSettings* print_settings) {
DCHECK(hdc);
DCHECK(print_settings);
print_settings->set_printer_name(dev_mode.dmDeviceName);
print_settings->set_device_name(new_device_name);
print_settings->ranges = const_cast<PageRanges&>(new_ranges);
print_settings->set_landscape(dev_mode.dmOrientation == DMORIENT_LANDSCAPE);
print_settings->selection_only = print_selection_only;
int dpi = GetDeviceCaps(hdc, LOGPIXELSX);
print_settings->set_dpi(dpi);
const int kAlphaCaps = SB_CONST_ALPHA | SB_PIXEL_ALPHA;
print_settings->set_supports_alpha_blend(
(GetDeviceCaps(hdc, SHADEBLENDCAPS) & kAlphaCaps) == kAlphaCaps);
DCHECK_EQ(dpi, GetDeviceCaps(hdc, LOGPIXELSY));
DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0);
DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0);
gfx::Size physical_size_device_units(GetDeviceCaps(hdc, PHYSICALWIDTH),
GetDeviceCaps(hdc, PHYSICALHEIGHT));
gfx::Rect printable_area_device_units(GetDeviceCaps(hdc, PHYSICALOFFSETX),
GetDeviceCaps(hdc, PHYSICALOFFSETY),
GetDeviceCaps(hdc, HORZRES),
GetDeviceCaps(hdc, VERTRES));
print_settings->SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
}
| 170,265
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: AppCacheUpdateJob::~AppCacheUpdateJob() {
if (service_)
service_->RemoveObserver(this);
if (internal_state_ != COMPLETED)
Cancel();
DCHECK(!manifest_fetcher_);
DCHECK(pending_url_fetches_.empty());
DCHECK(!inprogress_cache_.get());
DCHECK(pending_master_entries_.empty());
DCHECK(master_entry_fetches_.empty());
if (group_)
group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE);
}
Commit Message: AppCache: fix a browser crashing bug that can happen during updates.
BUG=558589
Review URL: https://codereview.chromium.org/1463463003
Cr-Commit-Position: refs/heads/master@{#360967}
CWE ID:
|
AppCacheUpdateJob::~AppCacheUpdateJob() {
if (service_)
service_->RemoveObserver(this);
if (internal_state_ != COMPLETED)
Cancel();
DCHECK(!inprogress_cache_.get());
DCHECK(pending_master_entries_.empty());
// The job must not outlive any of its fetchers.
CHECK(!manifest_fetcher_);
CHECK(pending_url_fetches_.empty());
CHECK(master_entry_fetches_.empty());
if (group_)
group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE);
}
| 171,734
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void v9fs_walk(void *opaque)
{
int name_idx;
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
pdu_complete(pdu, err);
return ;
}
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
for (i = 0; i < nwnames; i++) {
err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);
if (err < 0) {
goto out_nofid;
}
if (name_is_illegal(wnames[i].data)) {
err = -ENOENT;
goto out_nofid;
}
offset += err;
}
} else if (nwnames > P9_MAXWELEM) {
err = -EINVAL;
goto out_nofid;
}
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
v9fs_path_init(&dpath);
v9fs_path_init(&path);
/*
* Both dpath and path initially poin to fidp.
* Needed to handle request with nwnames == 0
*/
v9fs_path_copy(&dpath, &fidp->path);
err = -ENOENT;
goto out_nofid;
}
Commit Message:
CWE ID: CWE-22
|
static void v9fs_walk(void *opaque)
{
int name_idx;
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
pdu_complete(pdu, err);
return ;
}
V9fsFidState *newfidp = NULL;
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
V9fsQID qid;
err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);
if (err < 0) {
for (i = 0; i < nwnames; i++) {
err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);
if (err < 0) {
goto out_nofid;
}
if (name_is_illegal(wnames[i].data)) {
err = -ENOENT;
goto out_nofid;
}
offset += err;
}
} else if (nwnames > P9_MAXWELEM) {
err = -EINVAL;
goto out_nofid;
}
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
v9fs_path_init(&dpath);
v9fs_path_init(&path);
/*
* Both dpath and path initially poin to fidp.
* Needed to handle request with nwnames == 0
*/
v9fs_path_copy(&dpath, &fidp->path);
err = -ENOENT;
goto out_nofid;
}
| 164,939
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
base::android::InitVM(vm);
if (!content::android::OnJNIOnLoadInit())
return -1;
content::SetContentMainDelegate(new content::ShellMainDelegate());
return JNI_VERSION_1_4;
}
Commit Message: Fix content_shell with network service enabled not loading pages.
This regressed in my earlier cl r528763.
This is a reland of r547221.
Bug: 833612
Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b
Reviewed-on: https://chromium-review.googlesource.com/1064702
Reviewed-by: Jay Civelli <jcivelli@chromium.org>
Commit-Queue: John Abd-El-Malek <jam@chromium.org>
Cr-Commit-Position: refs/heads/master@{#560011}
CWE ID: CWE-264
|
JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
base::android::InitVM(vm);
if (!content::android::OnJNIOnLoadInit())
return -1;
content::SetContentMainDelegate(new content::ShellMainDelegate(true));
return JNI_VERSION_1_4;
}
| 172,119
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void RenderWidgetHostViewAura::WasShown() {
if (!host_->is_hidden())
return;
host_->WasShown();
if (!current_surface_ && host_->is_accelerated_compositing_active() &&
!released_front_lock_.get()) {
released_front_lock_ = GetCompositor()->GetCompositorLock();
}
AdjustSurfaceProtection();
#if defined(OS_WIN)
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
#endif
}
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
TBR=sky@chromium.org
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 RenderWidgetHostViewAura::WasShown() {
if (!host_->is_hidden())
return;
host_->WasShown();
if (!current_surface_ && host_->is_accelerated_compositing_active() &&
!released_front_lock_.get()) {
released_front_lock_ = GetCompositor()->GetCompositorLock();
}
#if defined(OS_WIN)
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
#endif
}
| 171,389
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0));
RenderWidgetHostViewPort* view =
GetRenderWidgetHostViewFromSurfaceID(params.surface_id);
if (!view)
return;
delayed_send.Cancel();
view->AcceleratedSurfacePostSubBuffer(params, host_id_);
}
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
TBR=sky@chromium.org
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::OnAcceleratedSurfacePostSubBuffer(
const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) {
TRACE_EVENT0("renderer",
"GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer");
ScopedSendOnIOThread delayed_send(
host_id_,
new AcceleratedSurfaceMsg_BufferPresented(params.route_id,
params.surface_handle,
0));
RenderWidgetHostViewPort* view =
GetRenderWidgetHostViewFromSurfaceID(params.surface_id);
if (!view)
return;
delayed_send.Cancel();
view->AcceleratedSurfacePostSubBuffer(params, host_id_);
}
| 171,359
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
#ifdef AUTOKEY
filegen_register(statsdir, "cryptostats", &cryptostats);
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
filegen_register(statsdir, "timingstats", &timingstats);
#endif /* DEBUG_TIMING */
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
Commit Message: [Bug 1773] openssl not detected during ./configure.
[Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL.
CWE ID: CWE-20
|
init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
filegen_register(statsdir, "cryptostats", &cryptostats);
filegen_register(statsdir, "timingstats", &timingstats);
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
| 168,876
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void InspectorNetworkAgent::DidBlockRequest(
ExecutionContext* execution_context,
const ResourceRequest& request,
DocumentLoader* loader,
const FetchInitiatorInfo& initiator_info,
ResourceRequestBlockedReason reason) {
unsigned long identifier = CreateUniqueIdentifier();
WillSendRequestInternal(execution_context, identifier, loader, request,
ResourceResponse(), initiator_info);
String request_id = IdentifiersFactory::RequestId(identifier);
String protocol_reason = BuildBlockedReason(reason);
GetFrontend()->loadingFailed(
request_id, MonotonicallyIncreasingTime(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
String(), false, protocol_reason);
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
|
void InspectorNetworkAgent::DidBlockRequest(
ExecutionContext* execution_context,
const ResourceRequest& request,
DocumentLoader* loader,
const FetchInitiatorInfo& initiator_info,
ResourceRequestBlockedReason reason,
Resource::Type resource_type) {
unsigned long identifier = CreateUniqueIdentifier();
InspectorPageAgent::ResourceType type =
InspectorPageAgent::ToResourceType(resource_type);
WillSendRequestInternal(execution_context, identifier, loader, request,
ResourceResponse(), initiator_info, type);
String request_id = IdentifiersFactory::RequestId(identifier);
String protocol_reason = BuildBlockedReason(reason);
GetFrontend()->loadingFailed(
request_id, MonotonicallyIncreasingTime(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
String(), false, protocol_reason);
}
| 172,465
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_MODERATELY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"),
status);
deviation_characters_.freeze();
non_ascii_latin_letters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE(
"[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb\\u30fc]"), status);
kana_letters_exceptions_.freeze();
DCHECK(U_SUCCESS(status));
}
Commit Message: Block domain labels made of Cyrillic letters that look alike Latin
Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф.
BUG=683314
TEST=components_unittests --gtest_filter=U*IDN*
Review-Url: https://codereview.chromium.org/2683793010
Cr-Commit-Position: refs/heads/master@{#459226}
CWE ID: CWE-20
|
IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_MODERATELY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"),
status);
deviation_characters_.freeze();
non_ascii_latin_letters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE(
"[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb\\u30fc]"), status);
kana_letters_exceptions_.freeze();
// These Cyrillic letters look like Latin. A domain label entirely made of
// these letters is blocked as a simpliified whole-script-spoofable.
cyrillic_letters_latin_alike_ =
icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
}
| 172,389
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 8;
fwd_txfm_ref = fht8x8_ref;
}
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 SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 8;
fwd_txfm_ref = fht8x8_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
}
| 174,563
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {
const SkImageInfo& info = bitmap.info();
color_type = info.colorType();
alpha_type = info.alphaType();
width = info.width();
height = info.height();
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <tsepez@chromium.org>
Commit-Queue: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125
|
void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {
| 172,891
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
{
char tmp[256];
struct dpc_ctx *ctx = c;
switch (rr) {
case RR_A:
if (len != 4) return -1;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
break;
case RR_AAAA:
if (len != 16) return -1;
ctx->addrs[ctx->cnt].family = AF_INET6;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
break;
case RR_CNAME:
if (__dn_expand(packet, (const unsigned char *)packet + 512,
data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
strcpy(ctx->canon, tmp);
break;
}
return 0;
}
Commit Message:
CWE ID: CWE-119
|
static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
{
char tmp[256];
struct dpc_ctx *ctx = c;
if (ctx->cnt >= MAXADDRS) return -1;
switch (rr) {
case RR_A:
if (len != 4) return -1;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
break;
case RR_AAAA:
if (len != 16) return -1;
ctx->addrs[ctx->cnt].family = AF_INET6;
ctx->addrs[ctx->cnt].scopeid = 0;
memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
break;
case RR_CNAME:
if (__dn_expand(packet, (const unsigned char *)packet + 512,
data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
strcpy(ctx->canon, tmp);
break;
}
return 0;
}
| 164,652
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void xmlrpc_char_encode(char *outbuffer, const char *s1)
{
long unsigned int i;
unsigned char c;
char buf2[15];
mowgli_string_t *s = mowgli_string_create();
*buf2 = '\0';
*outbuffer = '\0';
if ((!(s1) || (*(s1) == '\0')))
{
return;
}
for (i = 0; s1[i] != '\0'; i++)
{
c = s1[i];
if (c > 127)
{
snprintf(buf2, sizeof buf2, "&#%d;", c);
s->append(s, buf2, strlen(buf2));
}
else if (c == '&')
{
s->append(s, "&", 5);
}
else if (c == '<')
{
s->append(s, "<", 4);
}
else if (c == '>')
{
s->append(s, ">", 4);
}
else if (c == '"')
{
s->append(s, """, 6);
}
else
{
s->append_char(s, c);
}
}
memcpy(outbuffer, s->str, XMLRPC_BUFSIZE);
}
Commit Message: Do not copy more bytes than were allocated
CWE ID: CWE-119
|
void xmlrpc_char_encode(char *outbuffer, const char *s1)
{
long unsigned int i;
unsigned char c;
char buf2[15];
mowgli_string_t *s = mowgli_string_create();
*buf2 = '\0';
*outbuffer = '\0';
if ((!(s1) || (*(s1) == '\0')))
{
return;
}
for (i = 0; s1[i] != '\0'; i++)
{
c = s1[i];
if (c > 127)
{
snprintf(buf2, sizeof buf2, "&#%d;", c);
s->append(s, buf2, strlen(buf2));
}
else if (c == '&')
{
s->append(s, "&", 5);
}
else if (c == '<')
{
s->append(s, "<", 4);
}
else if (c == '>')
{
s->append(s, ">", 4);
}
else if (c == '"')
{
s->append(s, """, 6);
}
else
{
s->append_char(s, c);
}
}
s->append_char(s, 0);
strncpy(outbuffer, s->str, XMLRPC_BUFSIZE);
}
| 167,260
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void GCInfoTable::Resize() {
static const int kGcInfoZapValue = 0x33;
const size_t kInitialSize = 512;
size_t new_size =
gc_info_table_size_ ? 2 * gc_info_table_size_ : kInitialSize;
DCHECK(new_size < GCInfoTable::kMaxIndex);
g_gc_info_table =
reinterpret_cast<GCInfo const**>(WTF::Partitions::FastRealloc(
g_gc_info_table, new_size * sizeof(GCInfo), "GCInfo"));
DCHECK(g_gc_info_table);
memset(reinterpret_cast<uint8_t*>(g_gc_info_table) +
gc_info_table_size_ * sizeof(GCInfo),
kGcInfoZapValue, (new_size - gc_info_table_size_) * sizeof(GCInfo));
gc_info_table_size_ = new_size;
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <mlippautz@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Cr-Commit-Position: refs/heads/master@{#560434}
CWE ID: CWE-362
|
void GCInfoTable::Resize() {
const size_t new_limit = (limit_) ? 2 * limit_ : ComputeInitialTableLimit();
const size_t old_committed_size = limit_ * kEntrySize;
const size_t new_committed_size = new_limit * kEntrySize;
CHECK(table_);
CHECK_EQ(0u, new_committed_size % base::kPageAllocationGranularity);
CHECK_GE(MaxTableSize(), limit_ * kEntrySize);
// Recommitting and zapping assumes byte-addressable storage.
uint8_t* const current_table_end =
reinterpret_cast<uint8_t*>(table_) + old_committed_size;
const size_t table_size_delta = new_committed_size - old_committed_size;
// Commit the new size and allow read/write.
// TODO(ajwong): SetSystemPagesAccess should be part of RecommitSystemPages to
// avoid having two calls here.
bool ok = base::SetSystemPagesAccess(current_table_end, table_size_delta,
base::PageReadWrite);
CHECK(ok);
ok = base::RecommitSystemPages(current_table_end, table_size_delta,
base::PageReadWrite);
CHECK(ok);
// Zap unused values.,
memset(current_table_end, kGcInfoZapValue, table_size_delta);
limit_ = new_limit;
}
| 173,136
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: ext4_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <jack@suse.cz>
Signed-off-by: Theodore Ts'o <tytso@mit.edu>
CWE ID: CWE-19
|
ext4_xattr_put_super(struct super_block *sb)
| 169,995
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void TabCountChangeObserver::TabDetachedAt(TabContents* contents,
int index) {
CheckTabCount();
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
|
void TabCountChangeObserver::TabDetachedAt(TabContents* contents,
void TabCountChangeObserver::TabDetachedAt(WebContents* contents,
int index) {
CheckTabCount();
}
| 171,504
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: String InspectorPageAgent::CachedResourceTypeJson(
const Resource& cached_resource) {
return ResourceTypeJson(CachedResourceType(cached_resource));
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <pfeldman@chromium.org>
Reviewed-by: Dmitry Gozman <dgozman@chromium.org>
Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
|
String InspectorPageAgent::CachedResourceTypeJson(
const Resource& cached_resource) {
return ResourceTypeJson(ToResourceType(cached_resource.GetType()));
}
| 172,470
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: void SubpelVarianceTest<vp9_subp_avg_variance_fn_t>::RefTest() {
for (int x = 0; x < 16; ++x) {
for (int y = 0; y < 16; ++y) {
for (int j = 0; j < block_size_; j++) {
src_[j] = rnd.Rand8();
sec_[j] = rnd.Rand8();
}
for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) {
ref_[j] = rnd.Rand8();
}
unsigned int sse1, sse2;
unsigned int var1;
REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y,
src_, width_, &sse1, sec_));
const unsigned int var2 = subpel_avg_variance_ref(ref_, src_, sec_,
log2width_, log2height_,
x, y, &sse2);
EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y;
EXPECT_EQ(var1, var2) << "at position " << x << ", " << y;
}
}
}
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 SubpelVarianceTest<vp9_subp_avg_variance_fn_t>::RefTest() {
void SubpelVarianceTest<SubpixAvgVarMxNFunc>::RefTest() {
for (int x = 0; x < 8; ++x) {
for (int y = 0; y < 8; ++y) {
if (!use_high_bit_depth_) {
for (int j = 0; j < block_size_; j++) {
src_[j] = rnd_.Rand8();
sec_[j] = rnd_.Rand8();
}
for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) {
ref_[j] = rnd_.Rand8();
}
#if CONFIG_VP9_HIGHBITDEPTH
} else {
for (int j = 0; j < block_size_; j++) {
CONVERT_TO_SHORTPTR(src_)[j] = rnd_.Rand16() & mask_;
CONVERT_TO_SHORTPTR(sec_)[j] = rnd_.Rand16() & mask_;
}
for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) {
CONVERT_TO_SHORTPTR(ref_)[j] = rnd_.Rand16() & mask_;
}
#endif // CONFIG_VP9_HIGHBITDEPTH
}
unsigned int sse1, sse2;
unsigned int var1;
ASM_REGISTER_STATE_CHECK(
var1 = subpel_variance_(ref_, width_ + 1, x, y,
src_, width_, &sse1, sec_));
const unsigned int var2 = subpel_avg_variance_ref(ref_, src_, sec_,
log2width_, log2height_,
x, y, &sse2,
use_high_bit_depth_,
bit_depth_);
EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y;
EXPECT_EQ(var1, var2) << "at position " << x << ", " << y;
}
}
}
| 174,588
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
|
status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput);
if (header == NULL) {
return BAD_VALUE;
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
| 173,526
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: static void copy_xauthority(void) {
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) < 0)
errExit("chown");
if (chmod(dest, S_IRUSR | S_IWUSR) < 0)
errExit("chmod");
unlink(src);
}
Commit Message: security fix
CWE ID: CWE-269
|
static void copy_xauthority(void) {
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user
fs_logger2("clone", dest);
unlink(src);
}
| 170,097
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: DownloadCoreServiceImpl::GetDownloadManagerDelegate() {
DownloadManager* manager = BrowserContext::GetDownloadManager(profile_);
if (download_manager_created_) {
DCHECK(static_cast<DownloadManagerDelegate*>(manager_delegate_.get()) ==
manager->GetDelegate());
return manager_delegate_.get();
}
download_manager_created_ = true;
if (!manager_delegate_.get())
manager_delegate_.reset(new ChromeDownloadManagerDelegate(profile_));
manager_delegate_->SetDownloadManager(manager);
#if BUILDFLAG(ENABLE_EXTENSIONS)
extension_event_router_.reset(
new extensions::ExtensionDownloadsEventRouter(profile_, manager));
#endif
if (!profile_->IsOffTheRecord()) {
history::HistoryService* history = HistoryServiceFactory::GetForProfile(
profile_, ServiceAccessType::EXPLICIT_ACCESS);
history->GetNextDownloadId(
manager_delegate_->GetDownloadIdReceiverCallback());
download_history_.reset(new DownloadHistory(
manager, std::unique_ptr<DownloadHistory::HistoryAdapter>(
new DownloadHistory::HistoryAdapter(history))));
}
download_ui_.reset(new DownloadUIController(
manager, std::unique_ptr<DownloadUIController::Delegate>()));
g_browser_process->download_status_updater()->AddManager(manager);
return manager_delegate_.get();
}
Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate.
DownloadManager has public SetDelegate method and tests and or other subsystems
can install their own implementations of the delegate.
Bug: 805905
Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8
TBR: tests updated to follow the API change.
Reviewed-on: https://chromium-review.googlesource.com/894702
Reviewed-by: David Vallet <dvallet@chromium.org>
Reviewed-by: Min Qin <qinmin@chromium.org>
Cr-Commit-Position: refs/heads/master@{#533515}
CWE ID: CWE-125
|
DownloadCoreServiceImpl::GetDownloadManagerDelegate() {
DownloadManager* manager = BrowserContext::GetDownloadManager(profile_);
if (download_manager_created_)
return manager_delegate_.get();
download_manager_created_ = true;
if (!manager_delegate_.get())
manager_delegate_.reset(new ChromeDownloadManagerDelegate(profile_));
manager_delegate_->SetDownloadManager(manager);
#if BUILDFLAG(ENABLE_EXTENSIONS)
extension_event_router_.reset(
new extensions::ExtensionDownloadsEventRouter(profile_, manager));
#endif
if (!profile_->IsOffTheRecord()) {
history::HistoryService* history = HistoryServiceFactory::GetForProfile(
profile_, ServiceAccessType::EXPLICIT_ACCESS);
history->GetNextDownloadId(
manager_delegate_->GetDownloadIdReceiverCallback());
download_history_.reset(new DownloadHistory(
manager, std::unique_ptr<DownloadHistory::HistoryAdapter>(
new DownloadHistory::HistoryAdapter(history))));
}
download_ui_.reset(new DownloadUIController(
manager, std::unique_ptr<DownloadUIController::Delegate>()));
DCHECK(g_browser_process->download_status_updater());
g_browser_process->download_status_updater()->AddManager(manager);
return manager_delegate_.get();
}
| 173,168
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: bool ParseRequestInfo(const struct mg_request_info* const request_info,
std::string* method,
std::vector<std::string>* path_segments,
DictionaryValue** parameters,
Response* const response) {
*method = request_info->request_method;
if (*method == "HEAD")
*method = "GET";
else if (*method == "PUT")
*method = "POST";
std::string uri(request_info->uri);
SessionManager* manager = SessionManager::GetInstance();
uri = uri.substr(manager->url_base().length());
base::SplitString(uri, '/', path_segments);
if (*method == "POST" && request_info->post_data_len > 0) {
VLOG(1) << "...parsing request body";
std::string json(request_info->post_data, request_info->post_data_len);
std::string error;
if (!ParseJSONDictionary(json, parameters, &error)) {
response->SetError(new Error(
kBadRequest,
"Failed to parse command data: " + error + "\n Data: " + json));
return false;
}
}
VLOG(1) << "Parsed " << method << " " << uri
<< std::string(request_info->post_data, request_info->post_data_len);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
bool ParseRequestInfo(const struct mg_request_info* const request_info,
std::string* method,
std::vector<std::string>* path_segments,
DictionaryValue** parameters,
Response* const response) {
*method = request_info->request_method;
if (*method == "HEAD")
*method = "GET";
else if (*method == "PUT")
*method = "POST";
std::string uri(request_info->uri);
SessionManager* manager = SessionManager::GetInstance();
uri = uri.substr(manager->url_base().length());
base::SplitString(uri, '/', path_segments);
if (*method == "POST" && request_info->post_data_len > 0) {
std::string json(request_info->post_data, request_info->post_data_len);
std::string error_msg;
scoped_ptr<Value> params(base::JSONReader::ReadAndReturnError(
json, true, NULL, &error_msg));
if (!params.get()) {
response->SetError(new Error(
kBadRequest,
"Failed to parse command data: " + error_msg + "\n Data: " + json));
return false;
}
if (!params->IsType(Value::TYPE_DICTIONARY)) {
response->SetError(new Error(
kBadRequest,
"Data passed in URL must be a dictionary. Data: " + json));
return false;
}
*parameters = static_cast<DictionaryValue*>(params.release());
}
return true;
}
| 170,456
|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
|
Code: std::string ChromeOSGetKeyboardOverlayId(const std::string& input_method_id) {
for (size_t i = 0; i < arraysize(kKeyboardOverlayMap); ++i) {
if (kKeyboardOverlayMap[i].input_method_id == input_method_id) {
return kKeyboardOverlayMap[i].keyboard_overlay_id;
}
}
return "";
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
|
std::string ChromeOSGetKeyboardOverlayId(const std::string& input_method_id) {
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
return true;
}
| 170,522
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.