instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
png_size_t png_struct_size)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* to save current jump buffer */
#endif
int i = 0;
png_structp png_ptr=*ptr_ptr;
if (png_ptr == NULL)
return;
do
{
if (user_png_ver[i] != png_libpng_ver[i])
{
#ifdef PNG_LEGACY_SUPPORTED
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
#else
png_ptr->warning_fn = NULL;
png_warning(png_ptr,
"Application uses deprecated png_read_init() and should be"
" recompiled.");
break;
#endif
}
} while (png_libpng_ver[i++]);
png_debug(1, "in png_read_init_3");
#ifdef PNG_SETJMP_SUPPORTED
/* Save jump buffer and error functions */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
if (png_sizeof(png_struct) > png_struct_size)
{
png_destroy_struct(png_ptr);
*ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
png_ptr = *ptr_ptr;
}
/* Reset all variables to 0 */
png_memset(png_ptr, 0, png_sizeof(png_struct));
#ifdef PNG_SETJMP_SUPPORTED
/* Restore jump buffer */
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
/* Added at libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
png_ptr->user_width_max = PNG_USER_WIDTH_MAX;
png_ptr->user_height_max = PNG_USER_HEIGHT_MAX;
#endif
/* Initialize zbuf - compression buffer */
png_ptr->zbuf_size = PNG_ZBUF_SIZE;
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zstream.zfree = png_zfree;
png_ptr->zstream.opaque = (voidpf)png_ptr;
switch (inflateInit(&png_ptr->zstream))
{
case Z_OK: /* Do nothing */ break;
case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error");
break;
default: png_error(png_ptr, "Unknown zlib error");
}
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
png_size_t png_struct_size)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* to save current jump buffer */
#endif
int i = 0;
png_structp png_ptr=*ptr_ptr;
if (png_ptr == NULL)
return;
do
{
if (user_png_ver == NULL || user_png_ver[i] != png_libpng_ver[i])
{
#ifdef PNG_LEGACY_SUPPORTED
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
#else
png_ptr->warning_fn = NULL;
png_warning(png_ptr,
"Application uses deprecated png_read_init() and should be"
" recompiled.");
break;
#endif
}
} while (png_libpng_ver[i++]);
png_debug(1, "in png_read_init_3");
#ifdef PNG_SETJMP_SUPPORTED
/* Save jump buffer and error functions */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
if (png_sizeof(png_struct) > png_struct_size)
{
png_destroy_struct(png_ptr);
*ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
png_ptr = *ptr_ptr;
}
/* Reset all variables to 0 */
png_memset(png_ptr, 0, png_sizeof(png_struct));
#ifdef PNG_SETJMP_SUPPORTED
/* Restore jump buffer */
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
/* Added at libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
png_ptr->user_width_max = PNG_USER_WIDTH_MAX;
png_ptr->user_height_max = PNG_USER_HEIGHT_MAX;
#endif
/* Initialize zbuf - compression buffer */
png_ptr->zbuf_size = PNG_ZBUF_SIZE;
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zstream.zfree = png_zfree;
png_ptr->zstream.opaque = (voidpf)png_ptr;
switch (inflateInit(&png_ptr->zstream))
{
case Z_OK: /* Do nothing */ break;
case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error");
break;
default: png_error(png_ptr, "Unknown zlib error");
}
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
}
| 172,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void impeg2d_dec_pic_data_thread(dec_state_t *ps_dec)
{
WORD32 i4_continue_decode;
WORD32 i4_cur_row, temp;
UWORD32 u4_bits_read;
WORD32 i4_dequeue_job;
IMPEG2D_ERROR_CODES_T e_error;
i4_cur_row = ps_dec->u2_mb_y + 1;
i4_continue_decode = 1;
i4_dequeue_job = 1;
do
{
if(i4_cur_row > ps_dec->u2_num_vert_mb)
{
i4_continue_decode = 0;
break;
}
{
if((ps_dec->i4_num_cores> 1) && (i4_dequeue_job))
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
UWORD8 *pu1_buf;
e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1);
if(e_ret != IV_SUCCESS)
break;
if(CMD_PROCESS == s_job.i4_cmd)
{
pu1_buf = ps_dec->pu1_inp_bits_buf + s_job.i4_bistream_ofst;
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), pu1_buf,
(ps_dec->u4_num_inp_bytes - s_job.i4_bistream_ofst) + 8);
i4_cur_row = s_job.i2_start_mb_y;
ps_dec->i4_start_mb_y = s_job.i2_start_mb_y;
ps_dec->i4_end_mb_y = s_job.i2_end_mb_y;
ps_dec->u2_mb_x = 0;
ps_dec->u2_mb_y = ps_dec->i4_start_mb_y;
ps_dec->u2_num_mbs_left = (ps_dec->i4_end_mb_y - ps_dec->i4_start_mb_y) * ps_dec->u2_num_horiz_mb;
}
else
{
WORD32 start_row;
WORD32 num_rows;
start_row = s_job.i2_start_mb_y << 4;
num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size);
num_rows -= start_row;
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
start_row, num_rows);
break;
}
}
e_error = impeg2d_dec_slice(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
impeg2d_next_start_code(ps_dec);
}
}
/* Detecting next slice start code */
while(1)
{
u4_bits_read = impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,START_CODE_LEN);
temp = u4_bits_read & 0xFF;
i4_continue_decode = (((u4_bits_read >> 8) == 0x01) && (temp) && (temp <= 0xAF));
if(i4_continue_decode)
{
/* If the slice is from the same row, then continue decoding without dequeue */
if((temp - 1) == i4_cur_row)
{
i4_dequeue_job = 0;
break;
}
if(temp < ps_dec->i4_end_mb_y)
{
i4_cur_row = ps_dec->u2_mb_y;
}
else
{
i4_dequeue_job = 1;
}
break;
}
else
break;
}
}while(i4_continue_decode);
if(ps_dec->i4_num_cores > 1)
{
while(1)
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1);
if(e_ret != IV_SUCCESS)
break;
if(CMD_FMTCONV == s_job.i4_cmd)
{
WORD32 start_row;
WORD32 num_rows;
start_row = s_job.i2_start_mb_y << 4;
num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size);
num_rows -= start_row;
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
start_row, num_rows);
}
}
}
else
{
if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat)))
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
0, ps_dec->u2_vertical_size);
}
}
Commit Message: Fix for handling streams which resulted in negative num_mbs_left
Bug: 26070014
Change-Id: Id9f063a2c72a802d991b92abaf00ec687db5bb0f
CWE ID: CWE-119 | void impeg2d_dec_pic_data_thread(dec_state_t *ps_dec)
{
WORD32 i4_continue_decode;
WORD32 i4_cur_row, temp;
UWORD32 u4_bits_read;
WORD32 i4_dequeue_job;
IMPEG2D_ERROR_CODES_T e_error;
i4_cur_row = ps_dec->u2_mb_y + 1;
i4_continue_decode = 1;
i4_dequeue_job = 1;
do
{
if(i4_cur_row > ps_dec->u2_num_vert_mb)
{
i4_continue_decode = 0;
break;
}
{
if((ps_dec->i4_num_cores> 1) && (i4_dequeue_job))
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
UWORD8 *pu1_buf;
e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1);
if(e_ret != IV_SUCCESS)
break;
if(CMD_PROCESS == s_job.i4_cmd)
{
pu1_buf = ps_dec->pu1_inp_bits_buf + s_job.i4_bistream_ofst;
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), pu1_buf,
(ps_dec->u4_num_inp_bytes - s_job.i4_bistream_ofst) + 8);
i4_cur_row = s_job.i2_start_mb_y;
ps_dec->i4_start_mb_y = s_job.i2_start_mb_y;
ps_dec->i4_end_mb_y = s_job.i2_end_mb_y;
ps_dec->u2_mb_x = 0;
ps_dec->u2_mb_y = ps_dec->i4_start_mb_y;
ps_dec->u2_num_mbs_left = (ps_dec->i4_end_mb_y - ps_dec->i4_start_mb_y) * ps_dec->u2_num_horiz_mb;
}
else
{
WORD32 start_row;
WORD32 num_rows;
start_row = s_job.i2_start_mb_y << 4;
num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size);
num_rows -= start_row;
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
start_row, num_rows);
break;
}
}
e_error = impeg2d_dec_slice(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
impeg2d_next_start_code(ps_dec);
}
}
/* Detecting next slice start code */
while(1)
{
u4_bits_read = impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,START_CODE_LEN);
temp = u4_bits_read & 0xFF;
i4_continue_decode = (((u4_bits_read >> 8) == 0x01) && (temp) && (temp <= 0xAF));
if (1 == ps_dec->i4_num_cores && 0 == ps_dec->u2_num_mbs_left)
{
i4_continue_decode = 0;
android_errorWriteLog(0x534e4554, "26070014");
}
if(i4_continue_decode)
{
/* If the slice is from the same row, then continue decoding without dequeue */
if((temp - 1) == i4_cur_row)
{
i4_dequeue_job = 0;
break;
}
if(temp < ps_dec->i4_end_mb_y)
{
i4_cur_row = ps_dec->u2_mb_y;
}
else
{
i4_dequeue_job = 1;
}
break;
}
else
break;
}
}while(i4_continue_decode);
if(ps_dec->i4_num_cores > 1)
{
while(1)
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1);
if(e_ret != IV_SUCCESS)
break;
if(CMD_FMTCONV == s_job.i4_cmd)
{
WORD32 start_row;
WORD32 num_rows;
start_row = s_job.i2_start_mb_y << 4;
num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size);
num_rows -= start_row;
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
start_row, num_rows);
}
}
}
else
{
if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat)))
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
0, ps_dec->u2_vertical_size);
}
}
| 173,926 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void kgdb_hw_overflow_handler(struct perf_event *event, int nmi,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct task_struct *tsk = current;
int i;
for (i = 0; i < 4; i++)
if (breakinfo[i].enabled)
tsk->thread.debugreg6 |= (DR_TRAP0 << i);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static void kgdb_hw_overflow_handler(struct perf_event *event, int nmi,
static void kgdb_hw_overflow_handler(struct perf_event *event,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct task_struct *tsk = current;
int i;
for (i = 0; i < 4; i++)
if (breakinfo[i].enabled)
tsk->thread.debugreg6 |= (DR_TRAP0 << i);
}
| 165,823 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int snd_card_new(struct device *parent, int idx, const char *xid,
struct module *module, int extra_size,
struct snd_card **card_ret)
{
struct snd_card *card;
int err;
if (snd_BUG_ON(!card_ret))
return -EINVAL;
*card_ret = NULL;
if (extra_size < 0)
extra_size = 0;
card = kzalloc(sizeof(*card) + extra_size, GFP_KERNEL);
if (!card)
return -ENOMEM;
if (extra_size > 0)
card->private_data = (char *)card + sizeof(struct snd_card);
if (xid)
strlcpy(card->id, xid, sizeof(card->id));
err = 0;
mutex_lock(&snd_card_mutex);
if (idx < 0) /* first check the matching module-name slot */
idx = get_slot_from_bitmask(idx, module_slot_match, module);
if (idx < 0) /* if not matched, assign an empty slot */
idx = get_slot_from_bitmask(idx, check_empty_slot, module);
if (idx < 0)
err = -ENODEV;
else if (idx < snd_ecards_limit) {
if (test_bit(idx, snd_cards_lock))
err = -EBUSY; /* invalid */
} else if (idx >= SNDRV_CARDS)
err = -ENODEV;
if (err < 0) {
mutex_unlock(&snd_card_mutex);
dev_err(parent, "cannot find the slot for index %d (range 0-%i), error: %d\n",
idx, snd_ecards_limit - 1, err);
kfree(card);
return err;
}
set_bit(idx, snd_cards_lock); /* lock it */
if (idx >= snd_ecards_limit)
snd_ecards_limit = idx + 1; /* increase the limit */
mutex_unlock(&snd_card_mutex);
card->dev = parent;
card->number = idx;
card->module = module;
INIT_LIST_HEAD(&card->devices);
init_rwsem(&card->controls_rwsem);
rwlock_init(&card->ctl_files_rwlock);
INIT_LIST_HEAD(&card->controls);
INIT_LIST_HEAD(&card->ctl_files);
spin_lock_init(&card->files_lock);
INIT_LIST_HEAD(&card->files_list);
#ifdef CONFIG_PM
mutex_init(&card->power_lock);
init_waitqueue_head(&card->power_sleep);
#endif
device_initialize(&card->card_dev);
card->card_dev.parent = parent;
card->card_dev.class = sound_class;
card->card_dev.release = release_card_device;
card->card_dev.groups = card_dev_attr_groups;
err = kobject_set_name(&card->card_dev.kobj, "card%d", idx);
if (err < 0)
goto __error;
/* the control interface cannot be accessed from the user space until */
/* snd_cards_bitmask and snd_cards are set with snd_card_register */
err = snd_ctl_create(card);
if (err < 0) {
dev_err(parent, "unable to register control minors\n");
goto __error;
}
err = snd_info_card_create(card);
if (err < 0) {
dev_err(parent, "unable to create card info\n");
goto __error_ctl;
}
*card_ret = card;
return 0;
__error_ctl:
snd_device_free_all(card);
__error:
put_device(&card->card_dev);
return err;
}
Commit Message: ALSA: control: Protect user controls against concurrent access
The user-control put and get handlers as well as the tlv do not protect against
concurrent access from multiple threads. Since the state of the control is not
updated atomically it is possible that either two write operations or a write
and a read operation race against each other. Both can lead to arbitrary memory
disclosure. This patch introduces a new lock that protects user-controls from
concurrent access. Since applications typically access controls sequentially
than in parallel a single lock per card should be fine.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-362 | int snd_card_new(struct device *parent, int idx, const char *xid,
struct module *module, int extra_size,
struct snd_card **card_ret)
{
struct snd_card *card;
int err;
if (snd_BUG_ON(!card_ret))
return -EINVAL;
*card_ret = NULL;
if (extra_size < 0)
extra_size = 0;
card = kzalloc(sizeof(*card) + extra_size, GFP_KERNEL);
if (!card)
return -ENOMEM;
if (extra_size > 0)
card->private_data = (char *)card + sizeof(struct snd_card);
if (xid)
strlcpy(card->id, xid, sizeof(card->id));
err = 0;
mutex_lock(&snd_card_mutex);
if (idx < 0) /* first check the matching module-name slot */
idx = get_slot_from_bitmask(idx, module_slot_match, module);
if (idx < 0) /* if not matched, assign an empty slot */
idx = get_slot_from_bitmask(idx, check_empty_slot, module);
if (idx < 0)
err = -ENODEV;
else if (idx < snd_ecards_limit) {
if (test_bit(idx, snd_cards_lock))
err = -EBUSY; /* invalid */
} else if (idx >= SNDRV_CARDS)
err = -ENODEV;
if (err < 0) {
mutex_unlock(&snd_card_mutex);
dev_err(parent, "cannot find the slot for index %d (range 0-%i), error: %d\n",
idx, snd_ecards_limit - 1, err);
kfree(card);
return err;
}
set_bit(idx, snd_cards_lock); /* lock it */
if (idx >= snd_ecards_limit)
snd_ecards_limit = idx + 1; /* increase the limit */
mutex_unlock(&snd_card_mutex);
card->dev = parent;
card->number = idx;
card->module = module;
INIT_LIST_HEAD(&card->devices);
init_rwsem(&card->controls_rwsem);
rwlock_init(&card->ctl_files_rwlock);
mutex_init(&card->user_ctl_lock);
INIT_LIST_HEAD(&card->controls);
INIT_LIST_HEAD(&card->ctl_files);
spin_lock_init(&card->files_lock);
INIT_LIST_HEAD(&card->files_list);
#ifdef CONFIG_PM
mutex_init(&card->power_lock);
init_waitqueue_head(&card->power_sleep);
#endif
device_initialize(&card->card_dev);
card->card_dev.parent = parent;
card->card_dev.class = sound_class;
card->card_dev.release = release_card_device;
card->card_dev.groups = card_dev_attr_groups;
err = kobject_set_name(&card->card_dev.kobj, "card%d", idx);
if (err < 0)
goto __error;
/* the control interface cannot be accessed from the user space until */
/* snd_cards_bitmask and snd_cards are set with snd_card_register */
err = snd_ctl_create(card);
if (err < 0) {
dev_err(parent, "unable to register control minors\n");
goto __error;
}
err = snd_info_card_create(card);
if (err < 0) {
dev_err(parent, "unable to create card info\n");
goto __error_ctl;
}
*card_ret = card;
return 0;
__error_ctl:
snd_device_free_all(card);
__error:
put_device(&card->card_dev);
return err;
}
| 166,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, fwrite)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *str;
int str_len;
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) {
return;
}
if (ZEND_NUM_ARGS() > 1) {
str_len = MAX(0, MIN(length, str_len));
}
if (!str_len) {
RETURN_LONG(0);
}
RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len));
} /* }}} */
SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
if (length > INT_MAX) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX);
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
/* {{{ proto bool SplFileObject::fstat()
| 167,066 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_ablkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_blkcipher rblkcipher;
snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "ablkcipher");
snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s",
alg->cra_ablkcipher.geniv ?: "<default>");
rblkcipher.blocksize = alg->cra_blocksize;
rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize;
rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize;
rblkcipher.ivsize = alg->cra_ablkcipher.ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
sizeof(struct crypto_report_blkcipher), &rblkcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310 | static int crypto_ablkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_blkcipher rblkcipher;
strncpy(rblkcipher.type, "ablkcipher", sizeof(rblkcipher.type));
strncpy(rblkcipher.geniv, alg->cra_ablkcipher.geniv ?: "<default>",
sizeof(rblkcipher.geniv));
rblkcipher.blocksize = alg->cra_blocksize;
rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize;
rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize;
rblkcipher.ivsize = alg->cra_ablkcipher.ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,
sizeof(struct crypto_report_blkcipher), &rblkcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 166,061 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry,
const u8 *obj, size_t objlen, int depth)
{
void *parm = entry->parm;
int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj,
size_t nobjlen, int ndepth);
size_t *len = (size_t *) entry->arg;
int r = 0;
callback_func = parm;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n",
depth, depth, "", entry->name,
sc_dump_hex(obj, objlen > 16 ? 16 : objlen),
objlen > 16 ? "..." : "");
switch (entry->type) {
case SC_ASN1_STRUCT:
if (parm != NULL)
r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj,
objlen, NULL, NULL, 0, depth + 1);
break;
case SC_ASN1_NULL:
break;
case SC_ASN1_BOOLEAN:
if (parm != NULL) {
if (objlen != 1) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n",
objlen);
r = SC_ERROR_INVALID_ASN1_OBJECT;
} else
*((int *) parm) = obj[0] ? 1 : 0;
}
break;
case SC_ASN1_INTEGER:
case SC_ASN1_ENUMERATED:
if (parm != NULL) {
r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm);
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "",
entry->name, *((int *) entry->parm));
}
break;
case SC_ASN1_BIT_STRING_NI:
case SC_ASN1_BIT_STRING:
if (parm != NULL) {
int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0;
assert(len != NULL);
if (objlen < 1) {
r = SC_ERROR_INVALID_ASN1_OBJECT;
break;
}
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen-1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen-1;
parm = *buf;
}
r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert);
if (r >= 0) {
*len = r;
r = 0;
}
}
break;
case SC_ASN1_BIT_FIELD:
if (parm != NULL)
r = decode_bit_field(obj, objlen, (u8 *) parm, *len);
break;
case SC_ASN1_OCTET_STRING:
if (parm != NULL) {
size_t c;
assert(len != NULL);
/* Strip off padding zero */
if ((entry->flags & SC_ASN1_UNSIGNED)
&& obj[0] == 0x00 && objlen > 1) {
objlen--;
obj++;
}
/* Allocate buffer if needed */
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_GENERALIZEDTIME:
if (parm != NULL) {
size_t c;
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_OBJECT:
if (parm != NULL)
r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm);
break;
case SC_ASN1_PRINTABLESTRING:
case SC_ASN1_UTF8STRING:
if (parm != NULL) {
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen+1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen+1;
parm = *buf;
}
r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len);
if (entry->flags & SC_ASN1_ALLOC) {
*len -= 1;
}
}
break;
case SC_ASN1_PATH:
if (entry->parm != NULL)
r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth);
break;
case SC_ASN1_PKCS15_ID:
if (entry->parm != NULL) {
struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm;
size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen;
memcpy(id->value, obj, c);
id->len = c;
}
break;
case SC_ASN1_PKCS15_OBJECT:
if (entry->parm != NULL)
r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth);
break;
case SC_ASN1_ALGORITHM_ID:
if (entry->parm != NULL)
r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth);
break;
case SC_ASN1_SE_INFO:
if (entry->parm != NULL)
r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth);
break;
case SC_ASN1_CALLBACK:
if (entry->parm != NULL)
r = callback_func(ctx, entry->arg, obj, objlen, depth);
break;
default:
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name,
sc_strerror(r));
return r;
}
entry->flags |= SC_ASN1_PRESENT;
return 0;
}
Commit Message: Fixed out of bounds access in ASN.1 Octet string
Credit to OSS-Fuzz
CWE ID: CWE-119 | static int asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry,
const u8 *obj, size_t objlen, int depth)
{
void *parm = entry->parm;
int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj,
size_t nobjlen, int ndepth);
size_t *len = (size_t *) entry->arg;
int r = 0;
callback_func = parm;
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n",
depth, depth, "", entry->name,
sc_dump_hex(obj, objlen > 16 ? 16 : objlen),
objlen > 16 ? "..." : "");
switch (entry->type) {
case SC_ASN1_STRUCT:
if (parm != NULL)
r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj,
objlen, NULL, NULL, 0, depth + 1);
break;
case SC_ASN1_NULL:
break;
case SC_ASN1_BOOLEAN:
if (parm != NULL) {
if (objlen != 1) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1,
"invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n",
objlen);
r = SC_ERROR_INVALID_ASN1_OBJECT;
} else
*((int *) parm) = obj[0] ? 1 : 0;
}
break;
case SC_ASN1_INTEGER:
case SC_ASN1_ENUMERATED:
if (parm != NULL) {
r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm);
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "",
entry->name, *((int *) entry->parm));
}
break;
case SC_ASN1_BIT_STRING_NI:
case SC_ASN1_BIT_STRING:
if (parm != NULL) {
int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0;
assert(len != NULL);
if (objlen < 1) {
r = SC_ERROR_INVALID_ASN1_OBJECT;
break;
}
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen-1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen-1;
parm = *buf;
}
r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert);
if (r >= 0) {
*len = r;
r = 0;
}
}
break;
case SC_ASN1_BIT_FIELD:
if (parm != NULL)
r = decode_bit_field(obj, objlen, (u8 *) parm, *len);
break;
case SC_ASN1_OCTET_STRING:
if (parm != NULL) {
size_t c;
assert(len != NULL);
/* Strip off padding zero */
if ((entry->flags & SC_ASN1_UNSIGNED)
&& objlen > 1 && obj[0] == 0x00) {
objlen--;
obj++;
}
/* Allocate buffer if needed */
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_GENERALIZEDTIME:
if (parm != NULL) {
size_t c;
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
c = *len = objlen;
parm = *buf;
} else
c = objlen > *len ? *len : objlen;
memcpy(parm, obj, c);
*len = c;
}
break;
case SC_ASN1_OBJECT:
if (parm != NULL)
r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm);
break;
case SC_ASN1_PRINTABLESTRING:
case SC_ASN1_UTF8STRING:
if (parm != NULL) {
assert(len != NULL);
if (entry->flags & SC_ASN1_ALLOC) {
u8 **buf = (u8 **) parm;
*buf = malloc(objlen+1);
if (*buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
*len = objlen+1;
parm = *buf;
}
r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len);
if (entry->flags & SC_ASN1_ALLOC) {
*len -= 1;
}
}
break;
case SC_ASN1_PATH:
if (entry->parm != NULL)
r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth);
break;
case SC_ASN1_PKCS15_ID:
if (entry->parm != NULL) {
struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm;
size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen;
memcpy(id->value, obj, c);
id->len = c;
}
break;
case SC_ASN1_PKCS15_OBJECT:
if (entry->parm != NULL)
r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth);
break;
case SC_ASN1_ALGORITHM_ID:
if (entry->parm != NULL)
r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth);
break;
case SC_ASN1_SE_INFO:
if (entry->parm != NULL)
r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth);
break;
case SC_ASN1_CALLBACK:
if (entry->parm != NULL)
r = callback_func(ctx, entry->arg, obj, objlen, depth);
break;
default:
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type);
return SC_ERROR_INVALID_ASN1_OBJECT;
}
if (r) {
sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name,
sc_strerror(r));
return r;
}
entry->flags |= SC_ASN1_PRESENT;
return 0;
}
| 169,514 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
size_t pos, PNG_CONST char *msg)
{
if (pp != NULL && pp == ps->pread)
{
/* Reading a file */
pos = safecat(buffer, bufsize, pos, "read: ");
if (ps->current != NULL)
{
pos = safecat(buffer, bufsize, pos, ps->current->name);
pos = safecat(buffer, bufsize, pos, sep);
}
}
else if (pp != NULL && pp == ps->pwrite)
{
/* Writing a file */
pos = safecat(buffer, bufsize, pos, "write: ");
pos = safecat(buffer, bufsize, pos, ps->wname);
pos = safecat(buffer, bufsize, pos, sep);
}
else
{
/* Neither reading nor writing (or a memory error in struct delete) */
pos = safecat(buffer, bufsize, pos, "pngvalid: ");
}
if (ps->test[0] != 0)
{
pos = safecat(buffer, bufsize, pos, ps->test);
pos = safecat(buffer, bufsize, pos, sep);
}
pos = safecat(buffer, bufsize, pos, msg);
return pos;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize,
size_t pos, const char *msg)
{
if (pp != NULL && pp == ps->pread)
{
/* Reading a file */
pos = safecat(buffer, bufsize, pos, "read: ");
if (ps->current != NULL)
{
pos = safecat(buffer, bufsize, pos, ps->current->name);
pos = safecat(buffer, bufsize, pos, sep);
}
}
else if (pp != NULL && pp == ps->pwrite)
{
/* Writing a file */
pos = safecat(buffer, bufsize, pos, "write: ");
pos = safecat(buffer, bufsize, pos, ps->wname);
pos = safecat(buffer, bufsize, pos, sep);
}
else
{
/* Neither reading nor writing (or a memory error in struct delete) */
pos = safecat(buffer, bufsize, pos, "pngvalid: ");
}
if (ps->test[0] != 0)
{
pos = safecat(buffer, bufsize, pos, ps->test);
pos = safecat(buffer, bufsize, pos, sep);
}
pos = safecat(buffer, bufsize, pos, msg);
return pos;
}
| 173,706 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FaviconSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
FaviconService* favicon_service =
profile_->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (favicon_service) {
FaviconService::Handle handle;
if (path.empty()) {
SendDefaultResponse(request_id);
return;
}
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = favicon_service->GetFavicon(
GURL(path.substr(8)),
history::FAVICON,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
} else {
handle = favicon_service->GetFaviconForURL(
GURL(path),
icon_types_,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
}
cancelable_consumer_.SetClientData(favicon_service, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
Commit Message: ntp4: show larger favicons in most visited page
extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe).
BUG=none
TEST=manual
Review URL: http://codereview.chromium.org/7300017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void FaviconSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
FaviconService* favicon_service =
profile_->GetFaviconService(Profile::EXPLICIT_ACCESS);
if (favicon_service) {
if (path.empty()) {
SendDefaultResponse(request_id);
return;
}
FaviconService::Handle handle;
if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
handle = favicon_service->GetFavicon(
GURL(path.substr(8)),
history::FAVICON,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
} else {
GURL url;
if (path.size() > 5 && path.substr(0, 5) == "size/") {
size_t slash = path.find("/", 5);
std::string size = path.substr(5, slash - 5);
int pixel_size = atoi(size.c_str());
CHECK(pixel_size == 32 || pixel_size == 16) <<
"only 32x32 and 16x16 icons are supported";
request_size_map_[request_id] = pixel_size;
url = GURL(path.substr(slash + 1));
} else {
request_size_map_[request_id] = 16;
url = GURL(path);
}
// TODO(estade): fetch the requested size.
handle = favicon_service->GetFaviconForURL(
url,
icon_types_,
&cancelable_consumer_,
NewCallback(this, &FaviconSource::OnFaviconDataAvailable));
}
cancelable_consumer_.SetClientData(favicon_service, handle, request_id);
} else {
SendResponse(request_id, NULL);
}
}
| 170,368 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PluginChannel::~PluginChannel() {
if (renderer_handle_)
base::CloseProcessHandle(renderer_handle_);
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PluginReleaseCallback),
base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes));
}
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: | PluginChannel::~PluginChannel() {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PluginReleaseCallback),
base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes));
}
| 170,951 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AppCache::AppCache(AppCacheStorage* storage, int64_t cache_id)
: cache_id_(cache_id),
owning_group_(nullptr),
online_whitelist_all_(false),
is_complete_(false),
cache_size_(0),
storage_(storage) {
storage_->working_set()->AddCache(this);
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | AppCache::AppCache(AppCacheStorage* storage, int64_t cache_id)
: cache_id_(cache_id),
owning_group_(nullptr),
online_whitelist_all_(false),
is_complete_(false),
cache_size_(0),
padding_size_(0),
storage_(storage) {
storage_->working_set()->AddCache(this);
}
| 172,969 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *raw_data)
{
struct super_block *s;
struct ecryptfs_sb_info *sbi;
struct ecryptfs_dentry_info *root_info;
const char *err = "Getting sb failed";
struct inode *inode;
struct path path;
uid_t check_ruid;
int rc;
sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL);
if (!sbi) {
rc = -ENOMEM;
goto out;
}
rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid);
if (rc) {
err = "Error parsing options";
goto out;
}
s = sget(fs_type, NULL, set_anon_super, flags, NULL);
if (IS_ERR(s)) {
rc = PTR_ERR(s);
goto out;
}
rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY);
if (rc)
goto out1;
ecryptfs_set_superblock_private(s, sbi);
s->s_bdi = &sbi->bdi;
/* ->kill_sb() will take care of sbi after that point */
sbi = NULL;
s->s_op = &ecryptfs_sops;
s->s_d_op = &ecryptfs_dops;
err = "Reading sb failed";
rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path);
if (rc) {
ecryptfs_printk(KERN_WARNING, "kern_path() failed\n");
goto out1;
}
if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) {
rc = -EINVAL;
printk(KERN_ERR "Mount on filesystem of type "
"eCryptfs explicitly disallowed due to "
"known incompatibilities\n");
goto out_free;
}
if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) {
rc = -EPERM;
printk(KERN_ERR "Mount of device (uid: %d) not owned by "
"requested user (uid: %d)\n",
i_uid_read(path.dentry->d_inode),
from_kuid(&init_user_ns, current_uid()));
goto out_free;
}
ecryptfs_set_superblock_lower(s, path.dentry->d_sb);
/**
* Set the POSIX ACL flag based on whether they're enabled in the lower
* mount. Force a read-only eCryptfs mount if the lower mount is ro.
* Allow a ro eCryptfs mount even when the lower mount is rw.
*/
s->s_flags = flags & ~MS_POSIXACL;
s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL);
s->s_maxbytes = path.dentry->d_sb->s_maxbytes;
s->s_blocksize = path.dentry->d_sb->s_blocksize;
s->s_magic = ECRYPTFS_SUPER_MAGIC;
inode = ecryptfs_get_inode(path.dentry->d_inode, s);
rc = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_free;
s->s_root = d_make_root(inode);
if (!s->s_root) {
rc = -ENOMEM;
goto out_free;
}
rc = -ENOMEM;
root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL);
if (!root_info)
goto out_free;
/* ->kill_sb() will take care of root_info */
ecryptfs_set_dentry_private(s->s_root, root_info);
root_info->lower_path = path;
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
out_free:
path_put(&path);
out1:
deactivate_locked_super(s);
out:
if (sbi) {
ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat);
kmem_cache_free(ecryptfs_sb_info_cache, sbi);
}
printk(KERN_ERR "%s; rc = [%d]\n", err, rc);
return ERR_PTR(rc);
}
Commit Message: fs: limit filesystem stacking depth
Add a simple read-only counter to super_block that indicates how deep this
is in the stack of filesystems. Previously ecryptfs was the only stackable
filesystem and it explicitly disallowed multiple layers of itself.
Overlayfs, however, can be stacked recursively and also may be stacked
on top of ecryptfs or vice versa.
To limit the kernel stack usage we must limit the depth of the
filesystem stack. Initially the limit is set to 2.
Signed-off-by: Miklos Szeredi <[email protected]>
CWE ID: CWE-264 | static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *raw_data)
{
struct super_block *s;
struct ecryptfs_sb_info *sbi;
struct ecryptfs_dentry_info *root_info;
const char *err = "Getting sb failed";
struct inode *inode;
struct path path;
uid_t check_ruid;
int rc;
sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL);
if (!sbi) {
rc = -ENOMEM;
goto out;
}
rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid);
if (rc) {
err = "Error parsing options";
goto out;
}
s = sget(fs_type, NULL, set_anon_super, flags, NULL);
if (IS_ERR(s)) {
rc = PTR_ERR(s);
goto out;
}
rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY);
if (rc)
goto out1;
ecryptfs_set_superblock_private(s, sbi);
s->s_bdi = &sbi->bdi;
/* ->kill_sb() will take care of sbi after that point */
sbi = NULL;
s->s_op = &ecryptfs_sops;
s->s_d_op = &ecryptfs_dops;
err = "Reading sb failed";
rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path);
if (rc) {
ecryptfs_printk(KERN_WARNING, "kern_path() failed\n");
goto out1;
}
if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) {
rc = -EINVAL;
printk(KERN_ERR "Mount on filesystem of type "
"eCryptfs explicitly disallowed due to "
"known incompatibilities\n");
goto out_free;
}
if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) {
rc = -EPERM;
printk(KERN_ERR "Mount of device (uid: %d) not owned by "
"requested user (uid: %d)\n",
i_uid_read(path.dentry->d_inode),
from_kuid(&init_user_ns, current_uid()));
goto out_free;
}
ecryptfs_set_superblock_lower(s, path.dentry->d_sb);
/**
* Set the POSIX ACL flag based on whether they're enabled in the lower
* mount. Force a read-only eCryptfs mount if the lower mount is ro.
* Allow a ro eCryptfs mount even when the lower mount is rw.
*/
s->s_flags = flags & ~MS_POSIXACL;
s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL);
s->s_maxbytes = path.dentry->d_sb->s_maxbytes;
s->s_blocksize = path.dentry->d_sb->s_blocksize;
s->s_magic = ECRYPTFS_SUPER_MAGIC;
s->s_stack_depth = path.dentry->d_sb->s_stack_depth + 1;
rc = -EINVAL;
if (s->s_stack_depth > FILESYSTEM_MAX_STACK_DEPTH) {
pr_err("eCryptfs: maximum fs stacking depth exceeded\n");
goto out_free;
}
inode = ecryptfs_get_inode(path.dentry->d_inode, s);
rc = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_free;
s->s_root = d_make_root(inode);
if (!s->s_root) {
rc = -ENOMEM;
goto out_free;
}
rc = -ENOMEM;
root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL);
if (!root_info)
goto out_free;
/* ->kill_sb() will take care of root_info */
ecryptfs_set_dentry_private(s->s_root, root_info);
root_info->lower_path = path;
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
out_free:
path_put(&path);
out1:
deactivate_locked_super(s);
out:
if (sbi) {
ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat);
kmem_cache_free(ecryptfs_sb_info_cache, sbi);
}
printk(KERN_ERR "%s; rc = [%d]\n", err, rc);
return ERR_PTR(rc);
}
| 168,895 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static xmlDocPtr dom_document_parser(zval *id, int mode, char *source, int source_len, int options TSRMLS_DC) /* {{{ */
{
xmlDocPtr ret;
xmlParserCtxtPtr ctxt = NULL;
dom_doc_propsptr doc_props;
dom_object *intern;
php_libxml_ref_obj *document = NULL;
int validate, recover, resolve_externals, keep_blanks, substitute_ent;
int resolved_path_len;
int old_error_reporting = 0;
char *directory=NULL, resolved_path[MAXPATHLEN];
if (id != NULL) {
intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC);
document = intern->document;
}
doc_props = dom_get_doc_props(document);
validate = doc_props->validateonparse;
resolve_externals = doc_props->resolveexternals;
keep_blanks = doc_props->preservewhitespace;
substitute_ent = doc_props->substituteentities;
recover = doc_props->recover;
if (document == NULL) {
efree(doc_props);
}
xmlInitParser();
if (mode == DOM_LOAD_FILE) {
char *file_dest = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (file_dest) {
ctxt = xmlCreateFileParserCtxt(file_dest);
ctxt = xmlCreateMemoryParserCtxt(source, source_len);
}
if (ctxt == NULL) {
return(NULL);
}
/* If loading from memory, we need to set the base directory for the document */
if (mode != DOM_LOAD_FILE) {
#if HAVE_GETCWD
directory = VCWD_GETCWD(resolved_path, MAXPATHLEN);
#elif HAVE_GETWD
directory = VCWD_GETWD(resolved_path);
#endif
if (directory) {
if(ctxt->directory != NULL) {
xmlFree((char *) ctxt->directory);
}
resolved_path_len = strlen(resolved_path);
if (resolved_path[resolved_path_len - 1] != DEFAULT_SLASH) {
resolved_path[resolved_path_len] = DEFAULT_SLASH;
resolved_path[++resolved_path_len] = '\0';
}
ctxt->directory = (char *) xmlCanonicPath((const xmlChar *) resolved_path);
}
}
ctxt->vctxt.error = php_libxml_ctx_error;
ctxt->vctxt.warning = php_libxml_ctx_warning;
if (ctxt->sax != NULL) {
ctxt->sax->error = php_libxml_ctx_error;
ctxt->sax->warning = php_libxml_ctx_warning;
}
if (validate && ! (options & XML_PARSE_DTDVALID)) {
options |= XML_PARSE_DTDVALID;
}
if (resolve_externals && ! (options & XML_PARSE_DTDATTR)) {
options |= XML_PARSE_DTDATTR;
}
if (substitute_ent && ! (options & XML_PARSE_NOENT)) {
options |= XML_PARSE_NOENT;
}
if (keep_blanks == 0 && ! (options & XML_PARSE_NOBLANKS)) {
options |= XML_PARSE_NOBLANKS;
}
xmlCtxtUseOptions(ctxt, options);
ctxt->recovery = recover;
if (recover) {
old_error_reporting = EG(error_reporting);
EG(error_reporting) = old_error_reporting | E_WARNING;
}
xmlParseDocument(ctxt);
if (ctxt->wellFormed || recover) {
ret = ctxt->myDoc;
if (ctxt->recovery) {
EG(error_reporting) = old_error_reporting;
}
/* If loading from memory, set the base reference uri for the document */
if (ret && ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
return(ret);
}
/* }}} */
/* {{{ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) */
static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) {
zval *id;
xmlDoc *docp = NULL, *newdoc;
dom_doc_propsptr doc_prop;
dom_object *intern;
char *source;
int source_len, refcount, ret;
long options = 0;
id = getThis();
if (id != NULL && ! instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) {
id = NULL;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &options) == FAILURE) {
return;
}
if (!source_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input");
RETURN_FALSE;
}
newdoc = dom_document_parser(id, mode, source, source_len, options TSRMLS_CC);
if (!newdoc)
RETURN_FALSE;
if (id != NULL) {
intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC);
if (intern != NULL) {
docp = (xmlDocPtr) dom_object_get_node(intern);
doc_prop = NULL;
if (docp != NULL) {
php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC);
doc_prop = intern->document->doc_props;
intern->document->doc_props = NULL;
refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC);
if (refcount != 0) {
docp->_private = NULL;
}
}
intern->document = NULL;
if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) {
RETURN_FALSE;
}
intern->document->doc_props = doc_prop;
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC);
RETURN_TRUE;
} else {
DOM_RET_OBJ((xmlNodePtr) newdoc, &ret, NULL);
}
}
/* }}} end dom_parser_document */
/* {{{ proto DOMNode dom_document_load(string source [, int options]);
URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-load
Since: DOM Level 3
*/
PHP_METHOD(domdocument, load)
{
dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE);
}
/* }}} end dom_document_load */
/* {{{ proto DOMNode dom_document_loadxml(string source [, int options]);
URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-loadXML
Since: DOM Level 3
*/
PHP_METHOD(domdocument, loadXML)
{
dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING);
}
/* }}} end dom_document_loadxml */
/* {{{ proto int dom_document_save(string file);
Convenience method to save to file
*/
PHP_FUNCTION(dom_document_save)
{
zval *id;
xmlDoc *docp;
int file_len = 0, bytes, format, saveempty = 0;
dom_object *intern;
dom_doc_propsptr doc_props;
char *file;
long options = 0;
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &id, dom_document_class_entry, &file, &file_len, &options) == FAILURE) {
return;
}
if (file_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename");
RETURN_FALSE;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
/* encoding handled by property on doc */
doc_props = dom_get_doc_props(intern->document);
format = doc_props->formatoutput;
if (options & LIBXML_SAVE_NOEMPTYTAG) {
saveempty = xmlSaveNoEmptyTags;
xmlSaveNoEmptyTags = 1;
}
bytes = xmlSaveFormatFileEnc(file, docp, NULL, format);
if (options & LIBXML_SAVE_NOEMPTYTAG) {
xmlSaveNoEmptyTags = saveempty;
}
if (bytes == -1) {
RETURN_FALSE;
}
RETURN_LONG(bytes);
}
/* }}} end dom_document_save */
/* {{{ proto string dom_document_savexml([node n]);
URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML
Since: DOM Level 3
*/
PHP_FUNCTION(dom_document_savexml)
{
zval *id, *nodep = NULL;
xmlDoc *docp;
xmlNode *node;
xmlBufferPtr buf;
xmlChar *mem;
dom_object *intern, *nodeobj;
dom_doc_propsptr doc_props;
int size, format, saveempty = 0;
long options = 0;
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!l", &id, dom_document_class_entry, &nodep, dom_node_class_entry, &options) == FAILURE) {
return;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
doc_props = dom_get_doc_props(intern->document);
format = doc_props->formatoutput;
if (nodep != NULL) {
/* Dump contents of Node */
DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj);
if (node->doc != docp) {
php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC);
RETURN_FALSE;
}
buf = xmlBufferCreate();
if (!buf) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer");
RETURN_FALSE;
}
if (options & LIBXML_SAVE_NOEMPTYTAG) {
saveempty = xmlSaveNoEmptyTags;
xmlSaveNoEmptyTags = 1;
}
xmlNodeDump(buf, docp, node, 0, format);
if (options & LIBXML_SAVE_NOEMPTYTAG) {
xmlSaveNoEmptyTags = saveempty;
}
mem = (xmlChar*) xmlBufferContent(buf);
if (!mem) {
xmlBufferFree(buf);
RETURN_FALSE;
}
RETVAL_STRING(mem, 1);
xmlBufferFree(buf);
} else {
if (options & LIBXML_SAVE_NOEMPTYTAG) {
saveempty = xmlSaveNoEmptyTags;
xmlSaveNoEmptyTags = 1;
}
/* Encoding is handled from the encoding property set on the document */
xmlDocDumpFormatMemory(docp, &mem, &size, format);
if (options & LIBXML_SAVE_NOEMPTYTAG) {
xmlSaveNoEmptyTags = saveempty;
}
if (!size) {
RETURN_FALSE;
}
RETVAL_STRINGL(mem, size, 1);
xmlFree(mem);
}
}
/* }}} end dom_document_savexml */
static xmlNodePtr php_dom_free_xinclude_node(xmlNodePtr cur TSRMLS_DC) /* {{{ */
{
xmlNodePtr xincnode;
xincnode = cur;
cur = cur->next;
xmlUnlinkNode(xincnode);
php_libxml_node_free_resource(xincnode TSRMLS_CC);
return cur;
}
/* }}} */
static void php_dom_remove_xinclude_nodes(xmlNodePtr cur TSRMLS_DC) /* {{{ */
{
while(cur) {
if (cur->type == XML_XINCLUDE_START) {
cur = php_dom_free_xinclude_node(cur TSRMLS_CC);
/* XML_XINCLUDE_END node will be a sibling of XML_XINCLUDE_START */
while(cur && cur->type != XML_XINCLUDE_END) {
/* remove xinclude processing nodes from recursive xincludes */
if (cur->type == XML_ELEMENT_NODE) {
php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC);
}
cur = cur->next;
}
if (cur && cur->type == XML_XINCLUDE_END) {
cur = php_dom_free_xinclude_node(cur TSRMLS_CC);
}
} else {
if (cur->type == XML_ELEMENT_NODE) {
php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC);
}
cur = cur->next;
}
}
}
/* }}} */
/* {{{ proto int dom_document_xinclude([int options])
Substitutues xincludes in a DomDocument */
PHP_FUNCTION(dom_document_xinclude)
{
zval *id;
xmlDoc *docp;
xmlNodePtr root;
long flags = 0;
int err;
dom_object *intern;
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|l", &id, dom_document_class_entry, &flags) == FAILURE) {
return;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
err = xmlXIncludeProcessFlags(docp, flags);
/* XML_XINCLUDE_START and XML_XINCLUDE_END nodes need to be removed as these
are added via xmlXIncludeProcess to mark beginning and ending of xincluded document
but are not wanted in resulting document - must be done even if err as it could fail after
having processed some xincludes */
root = (xmlNodePtr) docp->children;
while(root && root->type != XML_ELEMENT_NODE && root->type != XML_XINCLUDE_START) {
root = root->next;
}
if (root) {
php_dom_remove_xinclude_nodes(root TSRMLS_CC);
}
if (err) {
RETVAL_LONG(err);
} else {
RETVAL_FALSE;
}
}
/* }}} */
/* {{{ proto boolean dom_document_validate();
Since: DOM extended
*/
PHP_FUNCTION(dom_document_validate)
{
zval *id;
xmlDoc *docp;
dom_object *intern;
xmlValidCtxt *cvp;
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) {
return;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
cvp = xmlNewValidCtxt();
cvp->userData = NULL;
cvp->error = (xmlValidityErrorFunc) php_libxml_error_handler;
cvp->warning = (xmlValidityErrorFunc) php_libxml_error_handler;
if (xmlValidateDocument(cvp, docp)) {
RETVAL_TRUE;
} else {
RETVAL_FALSE;
}
xmlFreeValidCtxt(cvp);
}
/* }}} */
#if defined(LIBXML_SCHEMAS_ENABLED)
static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
zval *id;
xmlDoc *docp;
dom_object *intern;
char *source = NULL, *valid_file = NULL;
int source_len = 0;
xmlSchemaParserCtxtPtr parser;
xmlSchemaPtr sptr;
xmlSchemaValidCtxtPtr vptr;
int is_valid;
char resolved_path[MAXPATHLEN + 1];
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Op", &id, dom_document_class_entry, &source, &source_len) == FAILURE) {
return;
}
if (source_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source");
RETURN_FALSE;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
switch (type) {
case DOM_LOAD_FILE:
valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (!valid_file) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema file source");
RETURN_FALSE;
}
parser = xmlSchemaNewParserCtxt(valid_file);
break;
case DOM_LOAD_STRING:
parser = xmlSchemaNewMemParserCtxt(source, source_len);
/* If loading from memory, we need to set the base directory for the document
but it is not apparent how to do that for schema's */
break;
default:
return;
}
xmlSchemaSetParserErrors(parser,
(xmlSchemaValidityErrorFunc) php_libxml_error_handler,
(xmlSchemaValidityWarningFunc) php_libxml_error_handler,
parser);
sptr = xmlSchemaParse(parser);
xmlSchemaFreeParserCtxt(parser);
if (!sptr) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema");
RETURN_FALSE;
}
docp = (xmlDocPtr) dom_object_get_node(intern);
vptr = xmlSchemaNewValidCtxt(sptr);
if (!vptr) {
xmlSchemaFree(sptr);
php_error(E_ERROR, "Invalid Schema Validation Context");
RETURN_FALSE;
}
xmlSchemaSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr);
is_valid = xmlSchemaValidateDoc(vptr, docp);
xmlSchemaFree(sptr);
xmlSchemaFreeValidCtxt(vptr);
if (is_valid == 0) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean dom_document_schema_validate_file(string filename); */
PHP_FUNCTION(dom_document_schema_validate_file)
{
_dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE);
}
/* }}} end dom_document_schema_validate_file */
/* {{{ proto boolean dom_document_schema_validate(string source); */
PHP_FUNCTION(dom_document_schema_validate_xml)
{
_dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING);
}
/* }}} end dom_document_schema_validate */
static void _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
zval *id;
xmlDoc *docp;
dom_object *intern;
char *source = NULL, *valid_file = NULL;
int source_len = 0;
xmlRelaxNGParserCtxtPtr parser;
xmlRelaxNGPtr sptr;
xmlRelaxNGValidCtxtPtr vptr;
int is_valid;
char resolved_path[MAXPATHLEN + 1];
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Op", &id, dom_document_class_entry, &source, &source_len) == FAILURE) {
return;
}
if (source_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source");
RETURN_FALSE;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
switch (type) {
case DOM_LOAD_FILE:
valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (!valid_file) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG file source");
RETURN_FALSE;
}
parser = xmlRelaxNGNewParserCtxt(valid_file);
break;
case DOM_LOAD_STRING:
parser = xmlRelaxNGNewMemParserCtxt(source, source_len);
/* If loading from memory, we need to set the base directory for the document
but it is not apparent how to do that for schema's */
break;
default:
return;
}
xmlRelaxNGSetParserErrors(parser,
(xmlRelaxNGValidityErrorFunc) php_libxml_error_handler,
(xmlRelaxNGValidityWarningFunc) php_libxml_error_handler,
parser);
sptr = xmlRelaxNGParse(parser);
xmlRelaxNGFreeParserCtxt(parser);
if (!sptr) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG");
RETURN_FALSE;
}
docp = (xmlDocPtr) dom_object_get_node(intern);
vptr = xmlRelaxNGNewValidCtxt(sptr);
if (!vptr) {
xmlRelaxNGFree(sptr);
php_error(E_ERROR, "Invalid RelaxNG Validation Context");
RETURN_FALSE;
}
xmlRelaxNGSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr);
is_valid = xmlRelaxNGValidateDoc(vptr, docp);
xmlRelaxNGFree(sptr);
xmlRelaxNGFreeValidCtxt(vptr);
if (is_valid == 0) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean dom_document_relaxNG_validate_file(string filename); */
PHP_FUNCTION(dom_document_relaxNG_validate_file)
{
_dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE);
}
/* }}} end dom_document_relaxNG_validate_file */
/* {{{ proto boolean dom_document_relaxNG_validate_xml(string source); */
PHP_FUNCTION(dom_document_relaxNG_validate_xml)
{
_dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING);
}
/* }}} end dom_document_relaxNG_validate_xml */
#endif
#if defined(LIBXML_HTML_ENABLED)
static void dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */
{
zval *id;
xmlDoc *docp = NULL, *newdoc;
dom_object *intern;
dom_doc_propsptr doc_prop;
char *source;
int source_len, refcount, ret;
long options = 0;
htmlParserCtxtPtr ctxt;
id = getThis();
id = getThis();
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &options) == FAILURE) {
return;
}
}
if (mode == DOM_LOAD_FILE) {
ctxt = htmlCreateFileParserCtxt(source, NULL);
} else {
source_len = xmlStrlen(source);
ctxt = htmlCreateMemoryParserCtxt(source, source_len);
}
if (!ctxt) {
RETURN_FALSE;
}
if (options) {
htmlCtxtUseOptions(ctxt, options);
}
ctxt->vctxt.error = php_libxml_ctx_error;
ctxt->vctxt.warning = php_libxml_ctx_warning;
if (ctxt->sax != NULL) {
ctxt->sax->error = php_libxml_ctx_error;
ctxt->sax->warning = php_libxml_ctx_warning;
}
htmlParseDocument(ctxt);
newdoc = ctxt->myDoc;
htmlFreeParserCtxt(ctxt);
if (!newdoc)
RETURN_FALSE;
if (id != NULL && instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) {
intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC);
if (intern != NULL) {
docp = (xmlDocPtr) dom_object_get_node(intern);
doc_prop = NULL;
if (docp != NULL) {
php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC);
doc_prop = intern->document->doc_props;
intern->document->doc_props = NULL;
refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC);
if (refcount != 0) {
docp->_private = NULL;
}
}
intern->document = NULL;
if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) {
RETURN_FALSE;
}
intern->document->doc_props = doc_prop;
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC);
RETURN_TRUE;
} else {
DOM_RET_OBJ((xmlNodePtr) newdoc, &ret, NULL);
}
}
/* }}} */
Commit Message:
CWE ID: CWE-254 | static xmlDocPtr dom_document_parser(zval *id, int mode, char *source, int source_len, int options TSRMLS_DC) /* {{{ */
{
xmlDocPtr ret;
xmlParserCtxtPtr ctxt = NULL;
dom_doc_propsptr doc_props;
dom_object *intern;
php_libxml_ref_obj *document = NULL;
int validate, recover, resolve_externals, keep_blanks, substitute_ent;
int resolved_path_len;
int old_error_reporting = 0;
char *directory=NULL, resolved_path[MAXPATHLEN];
if (id != NULL) {
intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC);
document = intern->document;
}
doc_props = dom_get_doc_props(document);
validate = doc_props->validateonparse;
resolve_externals = doc_props->resolveexternals;
keep_blanks = doc_props->preservewhitespace;
substitute_ent = doc_props->substituteentities;
recover = doc_props->recover;
if (document == NULL) {
efree(doc_props);
}
xmlInitParser();
if (mode == DOM_LOAD_FILE) {
if (CHECK_NULL_PATH(source, source_len)) {
return NULL;
}
char *file_dest = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (file_dest) {
ctxt = xmlCreateFileParserCtxt(file_dest);
ctxt = xmlCreateMemoryParserCtxt(source, source_len);
}
if (ctxt == NULL) {
return(NULL);
}
/* If loading from memory, we need to set the base directory for the document */
if (mode != DOM_LOAD_FILE) {
#if HAVE_GETCWD
directory = VCWD_GETCWD(resolved_path, MAXPATHLEN);
#elif HAVE_GETWD
directory = VCWD_GETWD(resolved_path);
#endif
if (directory) {
if(ctxt->directory != NULL) {
xmlFree((char *) ctxt->directory);
}
resolved_path_len = strlen(resolved_path);
if (resolved_path[resolved_path_len - 1] != DEFAULT_SLASH) {
resolved_path[resolved_path_len] = DEFAULT_SLASH;
resolved_path[++resolved_path_len] = '\0';
}
ctxt->directory = (char *) xmlCanonicPath((const xmlChar *) resolved_path);
}
}
ctxt->vctxt.error = php_libxml_ctx_error;
ctxt->vctxt.warning = php_libxml_ctx_warning;
if (ctxt->sax != NULL) {
ctxt->sax->error = php_libxml_ctx_error;
ctxt->sax->warning = php_libxml_ctx_warning;
}
if (validate && ! (options & XML_PARSE_DTDVALID)) {
options |= XML_PARSE_DTDVALID;
}
if (resolve_externals && ! (options & XML_PARSE_DTDATTR)) {
options |= XML_PARSE_DTDATTR;
}
if (substitute_ent && ! (options & XML_PARSE_NOENT)) {
options |= XML_PARSE_NOENT;
}
if (keep_blanks == 0 && ! (options & XML_PARSE_NOBLANKS)) {
options |= XML_PARSE_NOBLANKS;
}
xmlCtxtUseOptions(ctxt, options);
ctxt->recovery = recover;
if (recover) {
old_error_reporting = EG(error_reporting);
EG(error_reporting) = old_error_reporting | E_WARNING;
}
xmlParseDocument(ctxt);
if (ctxt->wellFormed || recover) {
ret = ctxt->myDoc;
if (ctxt->recovery) {
EG(error_reporting) = old_error_reporting;
}
/* If loading from memory, set the base reference uri for the document */
if (ret && ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
return(ret);
}
/* }}} */
/* {{{ static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) */
static void dom_parse_document(INTERNAL_FUNCTION_PARAMETERS, int mode) {
zval *id;
xmlDoc *docp = NULL, *newdoc;
dom_doc_propsptr doc_prop;
dom_object *intern;
char *source;
int source_len, refcount, ret;
long options = 0;
id = getThis();
if (id != NULL && ! instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) {
id = NULL;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &options) == FAILURE) {
return;
}
if (!source_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string supplied as input");
RETURN_FALSE;
}
newdoc = dom_document_parser(id, mode, source, source_len, options TSRMLS_CC);
if (!newdoc)
RETURN_FALSE;
if (id != NULL) {
intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC);
if (intern != NULL) {
docp = (xmlDocPtr) dom_object_get_node(intern);
doc_prop = NULL;
if (docp != NULL) {
php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC);
doc_prop = intern->document->doc_props;
intern->document->doc_props = NULL;
refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC);
if (refcount != 0) {
docp->_private = NULL;
}
}
intern->document = NULL;
if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) {
RETURN_FALSE;
}
intern->document->doc_props = doc_prop;
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC);
RETURN_TRUE;
} else {
DOM_RET_OBJ((xmlNodePtr) newdoc, &ret, NULL);
}
}
/* }}} end dom_parser_document */
/* {{{ proto DOMNode dom_document_load(string source [, int options]);
URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-load
Since: DOM Level 3
*/
PHP_METHOD(domdocument, load)
{
dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE);
}
/* }}} end dom_document_load */
/* {{{ proto DOMNode dom_document_loadxml(string source [, int options]);
URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-loadXML
Since: DOM Level 3
*/
PHP_METHOD(domdocument, loadXML)
{
dom_parse_document(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING);
}
/* }}} end dom_document_loadxml */
/* {{{ proto int dom_document_save(string file);
Convenience method to save to file
*/
PHP_FUNCTION(dom_document_save)
{
zval *id;
xmlDoc *docp;
int file_len = 0, bytes, format, saveempty = 0;
dom_object *intern;
dom_doc_propsptr doc_props;
char *file;
long options = 0;
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Os|l", &id, dom_document_class_entry, &file, &file_len, &options) == FAILURE) {
return;
}
if (file_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Filename");
RETURN_FALSE;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
/* encoding handled by property on doc */
doc_props = dom_get_doc_props(intern->document);
format = doc_props->formatoutput;
if (options & LIBXML_SAVE_NOEMPTYTAG) {
saveempty = xmlSaveNoEmptyTags;
xmlSaveNoEmptyTags = 1;
}
bytes = xmlSaveFormatFileEnc(file, docp, NULL, format);
if (options & LIBXML_SAVE_NOEMPTYTAG) {
xmlSaveNoEmptyTags = saveempty;
}
if (bytes == -1) {
RETURN_FALSE;
}
RETURN_LONG(bytes);
}
/* }}} end dom_document_save */
/* {{{ proto string dom_document_savexml([node n]);
URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML
Since: DOM Level 3
*/
PHP_FUNCTION(dom_document_savexml)
{
zval *id, *nodep = NULL;
xmlDoc *docp;
xmlNode *node;
xmlBufferPtr buf;
xmlChar *mem;
dom_object *intern, *nodeobj;
dom_doc_propsptr doc_props;
int size, format, saveempty = 0;
long options = 0;
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|O!l", &id, dom_document_class_entry, &nodep, dom_node_class_entry, &options) == FAILURE) {
return;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
doc_props = dom_get_doc_props(intern->document);
format = doc_props->formatoutput;
if (nodep != NULL) {
/* Dump contents of Node */
DOM_GET_OBJ(node, nodep, xmlNodePtr, nodeobj);
if (node->doc != docp) {
php_dom_throw_error(WRONG_DOCUMENT_ERR, dom_get_strict_error(intern->document) TSRMLS_CC);
RETURN_FALSE;
}
buf = xmlBufferCreate();
if (!buf) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not fetch buffer");
RETURN_FALSE;
}
if (options & LIBXML_SAVE_NOEMPTYTAG) {
saveempty = xmlSaveNoEmptyTags;
xmlSaveNoEmptyTags = 1;
}
xmlNodeDump(buf, docp, node, 0, format);
if (options & LIBXML_SAVE_NOEMPTYTAG) {
xmlSaveNoEmptyTags = saveempty;
}
mem = (xmlChar*) xmlBufferContent(buf);
if (!mem) {
xmlBufferFree(buf);
RETURN_FALSE;
}
RETVAL_STRING(mem, 1);
xmlBufferFree(buf);
} else {
if (options & LIBXML_SAVE_NOEMPTYTAG) {
saveempty = xmlSaveNoEmptyTags;
xmlSaveNoEmptyTags = 1;
}
/* Encoding is handled from the encoding property set on the document */
xmlDocDumpFormatMemory(docp, &mem, &size, format);
if (options & LIBXML_SAVE_NOEMPTYTAG) {
xmlSaveNoEmptyTags = saveempty;
}
if (!size) {
RETURN_FALSE;
}
RETVAL_STRINGL(mem, size, 1);
xmlFree(mem);
}
}
/* }}} end dom_document_savexml */
static xmlNodePtr php_dom_free_xinclude_node(xmlNodePtr cur TSRMLS_DC) /* {{{ */
{
xmlNodePtr xincnode;
xincnode = cur;
cur = cur->next;
xmlUnlinkNode(xincnode);
php_libxml_node_free_resource(xincnode TSRMLS_CC);
return cur;
}
/* }}} */
static void php_dom_remove_xinclude_nodes(xmlNodePtr cur TSRMLS_DC) /* {{{ */
{
while(cur) {
if (cur->type == XML_XINCLUDE_START) {
cur = php_dom_free_xinclude_node(cur TSRMLS_CC);
/* XML_XINCLUDE_END node will be a sibling of XML_XINCLUDE_START */
while(cur && cur->type != XML_XINCLUDE_END) {
/* remove xinclude processing nodes from recursive xincludes */
if (cur->type == XML_ELEMENT_NODE) {
php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC);
}
cur = cur->next;
}
if (cur && cur->type == XML_XINCLUDE_END) {
cur = php_dom_free_xinclude_node(cur TSRMLS_CC);
}
} else {
if (cur->type == XML_ELEMENT_NODE) {
php_dom_remove_xinclude_nodes(cur->children TSRMLS_CC);
}
cur = cur->next;
}
}
}
/* }}} */
/* {{{ proto int dom_document_xinclude([int options])
Substitutues xincludes in a DomDocument */
PHP_FUNCTION(dom_document_xinclude)
{
zval *id;
xmlDoc *docp;
xmlNodePtr root;
long flags = 0;
int err;
dom_object *intern;
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O|l", &id, dom_document_class_entry, &flags) == FAILURE) {
return;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
err = xmlXIncludeProcessFlags(docp, flags);
/* XML_XINCLUDE_START and XML_XINCLUDE_END nodes need to be removed as these
are added via xmlXIncludeProcess to mark beginning and ending of xincluded document
but are not wanted in resulting document - must be done even if err as it could fail after
having processed some xincludes */
root = (xmlNodePtr) docp->children;
while(root && root->type != XML_ELEMENT_NODE && root->type != XML_XINCLUDE_START) {
root = root->next;
}
if (root) {
php_dom_remove_xinclude_nodes(root TSRMLS_CC);
}
if (err) {
RETVAL_LONG(err);
} else {
RETVAL_FALSE;
}
}
/* }}} */
/* {{{ proto boolean dom_document_validate();
Since: DOM extended
*/
PHP_FUNCTION(dom_document_validate)
{
zval *id;
xmlDoc *docp;
dom_object *intern;
xmlValidCtxt *cvp;
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "O", &id, dom_document_class_entry) == FAILURE) {
return;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
cvp = xmlNewValidCtxt();
cvp->userData = NULL;
cvp->error = (xmlValidityErrorFunc) php_libxml_error_handler;
cvp->warning = (xmlValidityErrorFunc) php_libxml_error_handler;
if (xmlValidateDocument(cvp, docp)) {
RETVAL_TRUE;
} else {
RETVAL_FALSE;
}
xmlFreeValidCtxt(cvp);
}
/* }}} */
#if defined(LIBXML_SCHEMAS_ENABLED)
static void _dom_document_schema_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
zval *id;
xmlDoc *docp;
dom_object *intern;
char *source = NULL, *valid_file = NULL;
int source_len = 0;
xmlSchemaParserCtxtPtr parser;
xmlSchemaPtr sptr;
xmlSchemaValidCtxtPtr vptr;
int is_valid;
char resolved_path[MAXPATHLEN + 1];
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Op", &id, dom_document_class_entry, &source, &source_len) == FAILURE) {
return;
}
if (source_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source");
RETURN_FALSE;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
switch (type) {
case DOM_LOAD_FILE:
valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (!valid_file) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema file source");
RETURN_FALSE;
}
parser = xmlSchemaNewParserCtxt(valid_file);
break;
case DOM_LOAD_STRING:
parser = xmlSchemaNewMemParserCtxt(source, source_len);
/* If loading from memory, we need to set the base directory for the document
but it is not apparent how to do that for schema's */
break;
default:
return;
}
xmlSchemaSetParserErrors(parser,
(xmlSchemaValidityErrorFunc) php_libxml_error_handler,
(xmlSchemaValidityWarningFunc) php_libxml_error_handler,
parser);
sptr = xmlSchemaParse(parser);
xmlSchemaFreeParserCtxt(parser);
if (!sptr) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema");
RETURN_FALSE;
}
docp = (xmlDocPtr) dom_object_get_node(intern);
vptr = xmlSchemaNewValidCtxt(sptr);
if (!vptr) {
xmlSchemaFree(sptr);
php_error(E_ERROR, "Invalid Schema Validation Context");
RETURN_FALSE;
}
xmlSchemaSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr);
is_valid = xmlSchemaValidateDoc(vptr, docp);
xmlSchemaFree(sptr);
xmlSchemaFreeValidCtxt(vptr);
if (is_valid == 0) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean dom_document_schema_validate_file(string filename); */
PHP_FUNCTION(dom_document_schema_validate_file)
{
_dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE);
}
/* }}} end dom_document_schema_validate_file */
/* {{{ proto boolean dom_document_schema_validate(string source); */
PHP_FUNCTION(dom_document_schema_validate_xml)
{
_dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING);
}
/* }}} end dom_document_schema_validate */
static void _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */
{
zval *id;
xmlDoc *docp;
dom_object *intern;
char *source = NULL, *valid_file = NULL;
int source_len = 0;
xmlRelaxNGParserCtxtPtr parser;
xmlRelaxNGPtr sptr;
xmlRelaxNGValidCtxtPtr vptr;
int is_valid;
char resolved_path[MAXPATHLEN + 1];
if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "Op", &id, dom_document_class_entry, &source, &source_len) == FAILURE) {
return;
}
if (source_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Schema source");
RETURN_FALSE;
}
DOM_GET_OBJ(docp, id, xmlDocPtr, intern);
switch (type) {
case DOM_LOAD_FILE:
valid_file = _dom_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (!valid_file) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG file source");
RETURN_FALSE;
}
parser = xmlRelaxNGNewParserCtxt(valid_file);
break;
case DOM_LOAD_STRING:
parser = xmlRelaxNGNewMemParserCtxt(source, source_len);
/* If loading from memory, we need to set the base directory for the document
but it is not apparent how to do that for schema's */
break;
default:
return;
}
xmlRelaxNGSetParserErrors(parser,
(xmlRelaxNGValidityErrorFunc) php_libxml_error_handler,
(xmlRelaxNGValidityWarningFunc) php_libxml_error_handler,
parser);
sptr = xmlRelaxNGParse(parser);
xmlRelaxNGFreeParserCtxt(parser);
if (!sptr) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid RelaxNG");
RETURN_FALSE;
}
docp = (xmlDocPtr) dom_object_get_node(intern);
vptr = xmlRelaxNGNewValidCtxt(sptr);
if (!vptr) {
xmlRelaxNGFree(sptr);
php_error(E_ERROR, "Invalid RelaxNG Validation Context");
RETURN_FALSE;
}
xmlRelaxNGSetValidErrors(vptr, php_libxml_error_handler, php_libxml_error_handler, vptr);
is_valid = xmlRelaxNGValidateDoc(vptr, docp);
xmlRelaxNGFree(sptr);
xmlRelaxNGFreeValidCtxt(vptr);
if (is_valid == 0) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean dom_document_relaxNG_validate_file(string filename); */
PHP_FUNCTION(dom_document_relaxNG_validate_file)
{
_dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE);
}
/* }}} end dom_document_relaxNG_validate_file */
/* {{{ proto boolean dom_document_relaxNG_validate_xml(string source); */
PHP_FUNCTION(dom_document_relaxNG_validate_xml)
{
_dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING);
}
/* }}} end dom_document_relaxNG_validate_xml */
#endif
#if defined(LIBXML_HTML_ENABLED)
static void dom_load_html(INTERNAL_FUNCTION_PARAMETERS, int mode) /* {{{ */
{
zval *id;
xmlDoc *docp = NULL, *newdoc;
dom_object *intern;
dom_doc_propsptr doc_prop;
char *source;
int source_len, refcount, ret;
long options = 0;
htmlParserCtxtPtr ctxt;
id = getThis();
id = getThis();
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|l", &source, &source_len, &options) == FAILURE) {
return;
}
}
if (mode == DOM_LOAD_FILE) {
ctxt = htmlCreateFileParserCtxt(source, NULL);
} else {
source_len = xmlStrlen(source);
ctxt = htmlCreateMemoryParserCtxt(source, source_len);
}
if (!ctxt) {
RETURN_FALSE;
}
if (options) {
htmlCtxtUseOptions(ctxt, options);
}
ctxt->vctxt.error = php_libxml_ctx_error;
ctxt->vctxt.warning = php_libxml_ctx_warning;
if (ctxt->sax != NULL) {
ctxt->sax->error = php_libxml_ctx_error;
ctxt->sax->warning = php_libxml_ctx_warning;
}
htmlParseDocument(ctxt);
newdoc = ctxt->myDoc;
htmlFreeParserCtxt(ctxt);
if (!newdoc)
RETURN_FALSE;
if (id != NULL && instanceof_function(Z_OBJCE_P(id), dom_document_class_entry TSRMLS_CC)) {
intern = (dom_object *)zend_object_store_get_object(id TSRMLS_CC);
if (intern != NULL) {
docp = (xmlDocPtr) dom_object_get_node(intern);
doc_prop = NULL;
if (docp != NULL) {
php_libxml_decrement_node_ptr((php_libxml_node_object *) intern TSRMLS_CC);
doc_prop = intern->document->doc_props;
intern->document->doc_props = NULL;
refcount = php_libxml_decrement_doc_ref((php_libxml_node_object *)intern TSRMLS_CC);
if (refcount != 0) {
docp->_private = NULL;
}
}
intern->document = NULL;
if (php_libxml_increment_doc_ref((php_libxml_node_object *)intern, newdoc TSRMLS_CC) == -1) {
RETURN_FALSE;
}
intern->document->doc_props = doc_prop;
}
php_libxml_increment_node_ptr((php_libxml_node_object *)intern, (xmlNodePtr)newdoc, (void *)intern TSRMLS_CC);
RETURN_TRUE;
} else {
DOM_RET_OBJ((xmlNodePtr) newdoc, &ret, NULL);
}
}
/* }}} */
| 165,309 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)
return res;
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
BOOLEAN verifyLength,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength, verifyLength);
if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)
return res;
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
| 170,143 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t ZSTD_encodeSequences(
void* dst, size_t dstCapacity,
FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2)
{
#if DYNAMIC_BMI2
if (bmi2) {
return ZSTD_encodeSequences_bmi2(dst, dstCapacity,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq, longOffsets);
}
#endif
(void)bmi2;
return ZSTD_encodeSequences_default(dst, dstCapacity,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq, longOffsets);
}
Commit Message: fixed T36302429
CWE ID: CWE-362 | static size_t ZSTD_encodeSequences(
void* dst, size_t dstCapacity,
FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2)
{
DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity);
#if DYNAMIC_BMI2
if (bmi2) {
return ZSTD_encodeSequences_bmi2(dst, dstCapacity,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq, longOffsets);
}
#endif
(void)bmi2;
return ZSTD_encodeSequences_default(dst, dstCapacity,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq, longOffsets);
}
| 169,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::ParseBlockGroup(long long payload_size, long long& pos,
long& len) {
const long long payload_start = pos;
const long long payload_stop = pos + payload_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
if ((total >= 0) && (payload_stop > total))
return E_FILE_FORMAT_INVALID;
if (payload_stop > avail) {
len = static_cast<long>(payload_size);
return E_BUFFER_NOT_FULL;
}
long long discard_padding = 0;
while (pos < payload_stop) {
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > payload_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return static_cast<long>(id);
if (id == 0) // not a value ID
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID field
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > payload_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
pos += len; // consume size field
if (pos > payload_stop)
return E_FILE_FORMAT_INVALID;
if (size == 0) // weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if (id == 0x35A2) { // DiscardPadding
status = UnserializeInt(pReader, pos, size, discard_padding);
if (status < 0) // error
return status;
}
if (id != 0x21) { // sub-part of BlockGroup is not a Block
pos += size; // consume sub-part of block group
if (pos > payload_stop)
return E_FILE_FORMAT_INVALID;
continue;
}
const long long block_stop = pos + size;
if (block_stop > payload_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long track = ReadUInt(pReader, pos, len);
if (track < 0) // error
return static_cast<long>(track);
if (track == 0)
return E_FILE_FORMAT_INVALID;
#if 0
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return E_FILE_FORMAT_INVALID;
#endif
pos += len; // consume track number
if ((pos + 2) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 2) > avail) {
len = 2;
return E_BUFFER_NOT_FULL;
}
pos += 2; // consume timecode
if ((pos + 1) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
unsigned char flags;
status = pReader->Read(pos, 1, &flags);
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
pos = block_stop; // consume block-part of block group
assert(pos <= payload_stop);
}
assert(pos == payload_stop);
status = CreateBlock(0x20, // BlockGroup ID
payload_start, payload_size, discard_padding);
if (status != 0)
return status;
m_pos = payload_stop;
return 0; // success
}
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 Cluster::ParseBlockGroup(long long payload_size, long long& pos,
long& len) {
const long long payload_start = pos;
const long long payload_stop = pos + payload_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
if ((total >= 0) && (payload_stop > total))
return E_FILE_FORMAT_INVALID;
if (payload_stop > avail) {
len = static_cast<long>(payload_size);
return E_BUFFER_NOT_FULL;
}
long long discard_padding = 0;
while (pos < payload_stop) {
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > payload_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return static_cast<long>(id);
if (id == 0) // not a value ID
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID field
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > payload_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
pos += len; // consume size field
if (pos > payload_stop)
return E_FILE_FORMAT_INVALID;
if (size == 0) // weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if (id == 0x35A2) { // DiscardPadding
status = UnserializeInt(pReader, pos, size, discard_padding);
if (status < 0) // error
return status;
}
if (id != 0x21) { // sub-part of BlockGroup is not a Block
pos += size; // consume sub-part of block group
if (pos > payload_stop)
return E_FILE_FORMAT_INVALID;
continue;
}
const long long block_stop = pos + size;
if (block_stop > payload_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long track = ReadUInt(pReader, pos, len);
if (track < 0) // error
return static_cast<long>(track);
if (track == 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume track number
if ((pos + 2) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 2) > avail) {
len = 2;
return E_BUFFER_NOT_FULL;
}
pos += 2; // consume timecode
if ((pos + 1) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
unsigned char flags;
status = pReader->Read(pos, 1, &flags);
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
pos = block_stop; // consume block-part of block group
if (pos > payload_stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != payload_stop)
return E_FILE_FORMAT_INVALID;
status = CreateBlock(0x20, // BlockGroup ID
payload_start, payload_size, discard_padding);
if (status != 0)
return status;
m_pos = payload_stop;
return 0; // success
}
| 173,847 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(DirectoryIterator, getBasename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *suffix = 0, *fname;
int slen = 0;
size_t flen;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) {
return;
}
php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC);
RETURN_STRINGL(fname, flen, 0);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(DirectoryIterator, getBasename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *suffix = 0, *fname;
int slen = 0;
size_t flen;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) {
return;
}
php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC);
RETURN_STRINGL(fname, flen, 0);
}
| 167,034 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int test_mod_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_exp(d, a, b, c, ctx)) {
fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp(d, a, b, c, ctx))
return (0);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_zero(c);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus "
"succeeded\n");
return 0;
}
BN_set_word(c, 16);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus "
"succeeded\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL))
return (00);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
Commit Message:
CWE ID: CWE-200 | int test_mod_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_exp(d, a, b, c, ctx)) {
fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp(d, a, b, c, ctx))
return (0);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
/* Regression test for carry propagation bug in sqr8x_reduction */
BN_hex2bn(&a, "050505050505");
BN_hex2bn(&b, "02");
BN_hex2bn(&c,
"4141414141414141414141274141414141414141414141414141414141414141"
"4141414141414141414141414141414141414141414141414141414141414141"
"4141414141414141414141800000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000001");
BN_mod_exp(d, a, b, c, ctx);
BN_mul(e, a, a, ctx);
if (BN_cmp(d, e)) {
fprintf(stderr, "BN_mod_exp and BN_mul produce different results!\n");
return 0;
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_zero(c);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus "
"succeeded\n");
return 0;
}
BN_set_word(c, 16);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus "
"succeeded\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL))
return (00);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
| 164,721 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionVoidMethodWithArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 3)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->voidMethodWithArgs(intArg, strArg, objArg);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionVoidMethodWithArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 3)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->voidMethodWithArgs(intArg, strArg, objArg);
return JSValue::encode(jsUndefined());
}
| 170,610 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
if (pos + 8 > len) {
return op->size;
}
int min_val = (ut32)(UINT (data, pos + 4)),
max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
if (pos + 4 >= len) {
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
}
Commit Message: Fix #10296 - Heap out of bounds read in java_switch_op()
CWE ID: CWE-125 | static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
if (pos + 8 + 8 > len) {
return op->size;
}
const int min_val = (ut32)(UINT (data, pos + 4));
const int max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
if (pos + 4 >= len) {
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
}
| 169,198 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: InputMethodLibraryImpl()
: input_method_status_connection_(NULL),
should_launch_ime_(false),
ime_connected_(false),
defer_ime_startup_(false),
enable_auto_ime_shutdown_(true),
ibus_daemon_process_handle_(base::kNullProcessHandle),
#if !defined(TOUCH_UI)
initialized_successfully_(false),
candidate_window_controller_(NULL) {
#else
initialized_successfully_(false) {
#endif
notification_registrar_.Add(this, NotificationType::APP_TERMINATING,
NotificationService::AllSources());
}
bool Init() {
DCHECK(!initialized_successfully_) << "Already initialized";
if (!CrosLibrary::Get()->EnsureLoaded())
return false;
input_method_status_connection_ = chromeos::MonitorInputMethodStatus(
this,
&InputMethodChangedHandler,
&RegisterPropertiesHandler,
&UpdatePropertyHandler,
&ConnectionChangeHandler);
if (!input_method_status_connection_)
return false;
initialized_successfully_ = true;
return true;
}
virtual ~InputMethodLibraryImpl() {
}
virtual void AddObserver(Observer* observer) {
if (!observers_.size()) {
observer->FirstObserverIsAdded(this);
}
observers_.AddObserver(observer);
}
virtual void RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
virtual InputMethodDescriptors* GetActiveInputMethods() {
chromeos::InputMethodDescriptors* result =
new chromeos::InputMethodDescriptors;
for (size_t i = 0; i < active_input_method_ids_.size(); ++i) {
const std::string& input_method_id = active_input_method_ids_[i];
const InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
result->push_back(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
if (result->empty()) {
LOG(WARNING) << "No active input methods found.";
result->push_back(input_method::GetFallbackInputMethodDescriptor());
}
return result;
}
virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
return input_methods->size();
}
virtual InputMethodDescriptors* GetSupportedInputMethods() {
if (!initialized_successfully_) {
InputMethodDescriptors* result = new InputMethodDescriptors;
result->push_back(input_method::GetFallbackInputMethodDescriptor());
return result;
}
return chromeos::GetSupportedInputMethodDescriptors();
}
virtual void ChangeInputMethod(const std::string& input_method_id) {
tentative_current_input_method_id_ = input_method_id;
if (ibus_daemon_process_handle_ == base::kNullProcessHandle &&
chromeos::input_method::IsKeyboardLayout(input_method_id)) {
ChangeCurrentInputMethodFromId(input_method_id);
} else {
StartInputMethodDaemon();
if (!ChangeInputMethodViaIBus(input_method_id)) {
VLOG(1) << "Failed to change the input method to " << input_method_id
<< " (deferring)";
}
}
}
virtual void SetImePropertyActivated(const std::string& key,
bool activated) {
if (!initialized_successfully_)
return;
DCHECK(!key.empty());
chromeos::SetImePropertyActivated(
input_method_status_connection_, key.c_str(), activated);
}
virtual bool InputMethodIsActivated(const std::string& input_method_id) {
scoped_ptr<InputMethodDescriptors> active_input_method_descriptors(
GetActiveInputMethods());
for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) {
if (active_input_method_descriptors->at(i).id == input_method_id) {
return true;
}
}
return false;
}
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
value.type == ImeConfigValue::kValueTypeStringList) {
active_input_method_ids_ = value.string_list_value;
}
MaybeStartInputMethodDaemon(section, config_name, value);
const ConfigKeyType key = std::make_pair(section, config_name);
current_config_values_[key] = value;
if (ime_connected_) {
pending_config_requests_[key] = value;
FlushImeConfig();
}
MaybeStopInputMethodDaemon(section, config_name, value);
MaybeChangeCurrentKeyboardLayout(section, config_name, value);
return pending_config_requests_.empty();
}
virtual InputMethodDescriptor previous_input_method() const {
if (previous_input_method_.id.empty()) {
return input_method::GetFallbackInputMethodDescriptor();
}
return previous_input_method_;
}
virtual InputMethodDescriptor current_input_method() const {
if (current_input_method_.id.empty()) {
return input_method::GetFallbackInputMethodDescriptor();
}
return current_input_method_;
}
virtual const ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return chromeos::GetKeyboardOverlayId(input_method_id);
}
virtual void SendHandwritingStroke(const HandwritingStroke& stroke) {
if (!initialized_successfully_)
return;
chromeos::SendHandwritingStroke(input_method_status_connection_, stroke);
}
virtual void CancelHandwritingStrokes(int stroke_count) {
if (!initialized_successfully_)
return;
chromeos::CancelHandwriting(input_method_status_connection_, stroke_count);
}
private:
bool ContainOnlyOneKeyboardLayout(
const ImeConfigValue& value) {
return (value.type == ImeConfigValue::kValueTypeStringList &&
value.string_list_value.size() == 1 &&
chromeos::input_method::IsKeyboardLayout(
value.string_list_value[0]));
}
void MaybeStartInputMethodDaemon(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
value.type == ImeConfigValue::kValueTypeStringList &&
!value.string_list_value.empty()) {
if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) {
return;
}
const bool just_started = StartInputMethodDaemon();
if (!just_started) {
return;
}
if (tentative_current_input_method_id_.empty()) {
tentative_current_input_method_id_ = current_input_method_.id;
}
if (std::find(value.string_list_value.begin(),
value.string_list_value.end(),
tentative_current_input_method_id_)
== value.string_list_value.end()) {
tentative_current_input_method_id_.clear();
}
}
}
void MaybeStopInputMethodDaemon(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value) &&
enable_auto_ime_shutdown_) {
StopInputMethodDaemon();
}
}
void MaybeChangeCurrentKeyboardLayout(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value)) {
ChangeCurrentInputMethodFromId(value.string_list_value[0]);
}
}
bool ChangeInputMethodViaIBus(const std::string& input_method_id) {
if (!initialized_successfully_)
return false;
std::string input_method_id_to_switch = input_method_id;
if (!InputMethodIsActivated(input_method_id)) {
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
DCHECK(!input_methods->empty());
if (!input_methods->empty()) {
input_method_id_to_switch = input_methods->at(0).id;
LOG(INFO) << "Can't change the current input method to "
<< input_method_id << " since the engine is not preloaded. "
<< "Switch to " << input_method_id_to_switch << " instead.";
}
}
if (chromeos::ChangeInputMethod(input_method_status_connection_,
input_method_id_to_switch.c_str())) {
return true;
}
LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch;
return false;
}
void FlushImeConfig() {
if (!initialized_successfully_)
return;
bool active_input_methods_are_changed = false;
InputMethodConfigRequests::iterator iter =
pending_config_requests_.begin();
while (iter != pending_config_requests_.end()) {
const std::string& section = iter->first.first;
const std::string& config_name = iter->first.second;
ImeConfigValue& value = iter->second;
if (config_name == language_prefs::kPreloadEnginesConfigName &&
!tentative_current_input_method_id_.empty()) {
std::vector<std::string>::iterator engine_iter = std::find(
value.string_list_value.begin(),
value.string_list_value.end(),
tentative_current_input_method_id_);
if (engine_iter != value.string_list_value.end()) {
std::rotate(value.string_list_value.begin(),
engine_iter, // this becomes the new first element
value.string_list_value.end());
} else {
LOG(WARNING) << tentative_current_input_method_id_
<< " is not in preload_engines: " << value.ToString();
}
tentative_current_input_method_id_.erase();
}
if (chromeos::SetImeConfig(input_method_status_connection_,
section.c_str(),
config_name.c_str(),
value)) {
if (config_name == language_prefs::kPreloadEnginesConfigName) {
active_input_methods_are_changed = true;
VLOG(1) << "Updated preload_engines: " << value.ToString();
}
pending_config_requests_.erase(iter++);
} else {
break;
}
}
if (active_input_methods_are_changed) {
const size_t num_active_input_methods = GetNumActiveInputMethods();
FOR_EACH_OBSERVER(Observer, observers_,
ActiveInputMethodsChanged(this,
current_input_method_,
num_active_input_methods));
}
}
static void InputMethodChangedHandler(
void* object,
const chromeos::InputMethodDescriptor& current_input_method) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->ChangeCurrentInputMethod(current_input_method);
}
static void RegisterPropertiesHandler(
void* object, const ImePropertyList& prop_list) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->RegisterProperties(prop_list);
}
static void UpdatePropertyHandler(
void* object, const ImePropertyList& prop_list) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->UpdateProperty(prop_list);
}
static void ConnectionChangeHandler(void* object, bool connected) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->ime_connected_ = connected;
if (connected) {
input_method_library->pending_config_requests_.clear();
input_method_library->pending_config_requests_.insert(
input_method_library->current_config_values_.begin(),
input_method_library->current_config_values_.end());
input_method_library->FlushImeConfig();
input_method_library->ChangeInputMethod(
input_method_library->previous_input_method().id);
input_method_library->ChangeInputMethod(
input_method_library->current_input_method().id);
}
}
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));
}
void ChangeCurrentInputMethodFromId(const std::string& input_method_id) {
const chromeos::InputMethodDescriptor* descriptor =
chromeos::input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
ChangeCurrentInputMethod(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
void RegisterProperties(const ImePropertyList& prop_list) {
current_ime_properties_ = prop_list;
FOR_EACH_OBSERVER(Observer, observers_,
PropertyListChanged(this,
current_ime_properties_));
}
bool StartInputMethodDaemon() {
should_launch_ime_ = true;
return MaybeLaunchInputMethodDaemon();
}
void UpdateProperty(const ImePropertyList& prop_list) {
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
FOR_EACH_OBSERVER(Observer, observers_,
PropertyListChanged(this,
current_ime_properties_));
}
bool LaunchInputMethodProcess(const std::string& command_line,
base::ProcessHandle* process_handle) {
std::vector<std::string> argv;
base::file_handle_mapping_vector fds_to_remap;
base::ProcessHandle handle = base::kNullProcessHandle;
base::SplitString(command_line, ' ', &argv);
const bool result = base::LaunchApp(argv,
fds_to_remap, // no remapping
false, // wait
&handle);
if (!result) {
LOG(ERROR) << "Could not launch: " << command_line;
return false;
}
const base::ProcessId pid = base::GetProcId(handle);
g_child_watch_add(pid,
reinterpret_cast<GChildWatchFunc>(OnImeShutdown),
this);
*process_handle = handle;
VLOG(1) << command_line << " (PID=" << pid << ") is started";
return true;
}
bool MaybeLaunchInputMethodDaemon() {
if (!initialized_successfully_)
return false;
if (!should_launch_ime_) {
return false;
}
#if !defined(TOUCH_UI)
if (!candidate_window_controller_.get()) {
candidate_window_controller_.reset(new CandidateWindowController);
if (!candidate_window_controller_->Init()) {
LOG(WARNING) << "Failed to initialize the candidate window controller";
}
}
#endif
if (ibus_daemon_process_handle_ != base::kNullProcessHandle) {
return false; // ibus-daemon is already running.
}
const std::string ibus_daemon_command_line =
StringPrintf("%s --panel=disable --cache=none --restart --replace",
kIBusDaemonPath);
if (!LaunchInputMethodProcess(
ibus_daemon_command_line, &ibus_daemon_process_handle_)) {
LOG(ERROR) << "Failed to launch " << ibus_daemon_command_line;
return false;
}
return true;
}
static void OnImeShutdown(GPid pid,
gint status,
InputMethodLibraryImpl* library) {
if (library->ibus_daemon_process_handle_ != base::kNullProcessHandle &&
base::GetProcId(library->ibus_daemon_process_handle_) == pid) {
library->ibus_daemon_process_handle_ = base::kNullProcessHandle;
}
library->MaybeLaunchInputMethodDaemon();
}
void StopInputMethodDaemon() {
if (!initialized_successfully_)
return;
should_launch_ime_ = false;
if (ibus_daemon_process_handle_ != base::kNullProcessHandle) {
const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_);
if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) {
LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to "
<< "PID " << pid;
base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */);
}
VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated";
ibus_daemon_process_handle_ = base::kNullProcessHandle;
}
}
void SetDeferImeStartup(bool defer) {
VLOG(1) << "Setting DeferImeStartup to " << defer;
defer_ime_startup_ = defer;
}
void SetEnableAutoImeShutdown(bool enable) {
enable_auto_ime_shutdown_ = enable;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type.value == NotificationType::APP_TERMINATING) {
notification_registrar_.RemoveAll();
StopInputMethodDaemon();
#if !defined(TOUCH_UI)
candidate_window_controller_.reset(NULL);
#endif
}
}
InputMethodStatusConnection* input_method_status_connection_;
ObserverList<Observer> observers_;
InputMethodDescriptor previous_input_method_;
InputMethodDescriptor current_input_method_;
ImePropertyList current_ime_properties_;
typedef std::pair<std::string, std::string> ConfigKeyType;
typedef std::map<ConfigKeyType, ImeConfigValue> InputMethodConfigRequests;
InputMethodConfigRequests pending_config_requests_;
InputMethodConfigRequests current_config_values_;
NotificationRegistrar notification_registrar_;
bool should_launch_ime_;
bool ime_connected_;
bool defer_ime_startup_;
bool enable_auto_ime_shutdown_;
std::string tentative_current_input_method_id_;
base::ProcessHandle ibus_daemon_process_handle_;
bool initialized_successfully_;
#if !defined(TOUCH_UI)
scoped_ptr<CandidateWindowController> candidate_window_controller_;
#endif
std::vector<std::string> active_input_method_ids_;
DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryImpl);
};
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 | InputMethodLibraryImpl()
: ibus_controller_(NULL),
should_launch_ime_(false),
ime_connected_(false),
defer_ime_startup_(false),
enable_auto_ime_shutdown_(true),
ibus_daemon_process_handle_(base::kNullProcessHandle),
#if !defined(TOUCH_UI)
initialized_successfully_(false),
candidate_window_controller_(NULL) {
#else
initialized_successfully_(false) {
#endif
notification_registrar_.Add(this, NotificationType::APP_TERMINATING,
NotificationService::AllSources());
}
bool Init() {
DCHECK(!initialized_successfully_) << "Already initialized";
ibus_controller_ = input_method::IBusController::Create();
// The observer should be added before Connect() so we can capture the
// initial connection change.
ibus_controller_->AddObserver(this);
ibus_controller_->Connect();
initialized_successfully_ = true;
return true;
}
virtual ~InputMethodLibraryImpl() {
ibus_controller_->RemoveObserver(this);
}
virtual void AddObserver(InputMethodLibrary::Observer* observer) {
if (!observers_.size()) {
observer->FirstObserverIsAdded(this);
}
observers_.AddObserver(observer);
}
virtual void RemoveObserver(InputMethodLibrary::Observer* observer) {
observers_.RemoveObserver(observer);
}
virtual input_method::InputMethodDescriptors* GetActiveInputMethods() {
input_method::InputMethodDescriptors* result =
new input_method::InputMethodDescriptors;
for (size_t i = 0; i < active_input_method_ids_.size(); ++i) {
const std::string& input_method_id = active_input_method_ids_[i];
const input_method::InputMethodDescriptor* descriptor =
input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
result->push_back(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
if (result->empty()) {
LOG(WARNING) << "No active input methods found.";
result->push_back(input_method::GetFallbackInputMethodDescriptor());
}
return result;
}
virtual size_t GetNumActiveInputMethods() {
scoped_ptr<input_method::InputMethodDescriptors> input_methods(
GetActiveInputMethods());
return input_methods->size();
}
virtual input_method::InputMethodDescriptors* GetSupportedInputMethods() {
if (!initialized_successfully_) {
input_method::InputMethodDescriptors* result =
new input_method::InputMethodDescriptors;
result->push_back(input_method::GetFallbackInputMethodDescriptor());
return result;
}
return input_method::GetSupportedInputMethodDescriptors();
}
virtual void ChangeInputMethod(const std::string& input_method_id) {
tentative_current_input_method_id_ = input_method_id;
if (ibus_daemon_process_handle_ == base::kNullProcessHandle &&
input_method::IsKeyboardLayout(input_method_id)) {
ChangeCurrentInputMethodFromId(input_method_id);
} else {
StartInputMethodDaemon();
if (!ChangeInputMethodViaIBus(input_method_id)) {
VLOG(1) << "Failed to change the input method to " << input_method_id
<< " (deferring)";
}
}
}
virtual void SetImePropertyActivated(const std::string& key,
bool activated) {
if (!initialized_successfully_)
return;
DCHECK(!key.empty());
ibus_controller_->SetImePropertyActivated(key, activated);
}
virtual bool InputMethodIsActivated(const std::string& input_method_id) {
scoped_ptr<input_method::InputMethodDescriptors>
active_input_method_descriptors(
GetActiveInputMethods());
for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) {
if (active_input_method_descriptors->at(i).id == input_method_id) {
return true;
}
}
return false;
}
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
value.type == input_method::ImeConfigValue::kValueTypeStringList) {
active_input_method_ids_ = value.string_list_value;
}
MaybeStartInputMethodDaemon(section, config_name, value);
const ConfigKeyType key = std::make_pair(section, config_name);
current_config_values_[key] = value;
if (ime_connected_) {
pending_config_requests_[key] = value;
FlushImeConfig();
}
MaybeStopInputMethodDaemon(section, config_name, value);
MaybeChangeCurrentKeyboardLayout(section, config_name, value);
return pending_config_requests_.empty();
}
virtual input_method::InputMethodDescriptor previous_input_method() const {
if (previous_input_method_.id.empty()) {
return input_method::GetFallbackInputMethodDescriptor();
}
return previous_input_method_;
}
virtual input_method::InputMethodDescriptor current_input_method() const {
if (current_input_method_.id.empty()) {
return input_method::GetFallbackInputMethodDescriptor();
}
return current_input_method_;
}
virtual const input_method::ImePropertyList& current_ime_properties() const {
return current_ime_properties_;
}
virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return input_method::GetKeyboardOverlayId(input_method_id);
}
virtual void SendHandwritingStroke(
const input_method::HandwritingStroke& stroke) {
if (!initialized_successfully_)
return;
ibus_controller_->SendHandwritingStroke(stroke);
}
virtual void CancelHandwritingStrokes(int stroke_count) {
if (!initialized_successfully_)
return;
ibus_controller_->CancelHandwriting(stroke_count);
}
private:
bool ContainOnlyOneKeyboardLayout(
const input_method::ImeConfigValue& value) {
return (value.type == input_method::ImeConfigValue::kValueTypeStringList &&
value.string_list_value.size() == 1 &&
input_method::IsKeyboardLayout(
value.string_list_value[0]));
}
void MaybeStartInputMethodDaemon(const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
value.type == input_method::ImeConfigValue::kValueTypeStringList &&
!value.string_list_value.empty()) {
if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) {
return;
}
const bool just_started = StartInputMethodDaemon();
if (!just_started) {
return;
}
if (tentative_current_input_method_id_.empty()) {
tentative_current_input_method_id_ = current_input_method_.id;
}
if (std::find(value.string_list_value.begin(),
value.string_list_value.end(),
tentative_current_input_method_id_)
== value.string_list_value.end()) {
tentative_current_input_method_id_.clear();
}
}
}
void MaybeStopInputMethodDaemon(const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value) &&
enable_auto_ime_shutdown_) {
StopInputMethodDaemon();
}
}
void MaybeChangeCurrentKeyboardLayout(
const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value)) {
ChangeCurrentInputMethodFromId(value.string_list_value[0]);
}
}
bool ChangeInputMethodViaIBus(const std::string& input_method_id) {
if (!initialized_successfully_)
return false;
std::string input_method_id_to_switch = input_method_id;
if (!InputMethodIsActivated(input_method_id)) {
scoped_ptr<input_method::InputMethodDescriptors> input_methods(
GetActiveInputMethods());
DCHECK(!input_methods->empty());
if (!input_methods->empty()) {
input_method_id_to_switch = input_methods->at(0).id;
LOG(INFO) << "Can't change the current input method to "
<< input_method_id << " since the engine is not preloaded. "
<< "Switch to " << input_method_id_to_switch << " instead.";
}
}
if (ibus_controller_->ChangeInputMethod(input_method_id_to_switch)) {
return true;
}
LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch;
return false;
}
void FlushImeConfig() {
if (!initialized_successfully_)
return;
bool active_input_methods_are_changed = false;
InputMethodConfigRequests::iterator iter =
pending_config_requests_.begin();
while (iter != pending_config_requests_.end()) {
const std::string& section = iter->first.first;
const std::string& config_name = iter->first.second;
input_method::ImeConfigValue& value = iter->second;
if (config_name == language_prefs::kPreloadEnginesConfigName &&
!tentative_current_input_method_id_.empty()) {
std::vector<std::string>::iterator engine_iter = std::find(
value.string_list_value.begin(),
value.string_list_value.end(),
tentative_current_input_method_id_);
if (engine_iter != value.string_list_value.end()) {
std::rotate(value.string_list_value.begin(),
engine_iter, // this becomes the new first element
value.string_list_value.end());
} else {
LOG(WARNING) << tentative_current_input_method_id_
<< " is not in preload_engines: " << value.ToString();
}
tentative_current_input_method_id_.erase();
}
if (ibus_controller_->SetImeConfig(section, config_name, value)) {
if (config_name == language_prefs::kPreloadEnginesConfigName) {
active_input_methods_are_changed = true;
VLOG(1) << "Updated preload_engines: " << value.ToString();
}
pending_config_requests_.erase(iter++);
} else {
break;
}
}
if (active_input_methods_are_changed) {
const size_t num_active_input_methods = GetNumActiveInputMethods();
FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_,
ActiveInputMethodsChanged(this,
current_input_method_,
num_active_input_methods));
}
}
// IBusController override.
virtual void OnCurrentInputMethodChanged(
const input_method::InputMethodDescriptor& current_input_method) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
ChangeCurrentInputMethod(current_input_method);
}
// IBusController override.
virtual void OnRegisterImeProperties(
const input_method::ImePropertyList& prop_list) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
RegisterProperties(prop_list);
}
// IBusController override.
virtual void OnUpdateImeProperty(
const input_method::ImePropertyList& prop_list) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
UpdateProperty(prop_list);
}
// IBusController override.
virtual void OnConnectionChange(bool connected) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
ime_connected_ = connected;
if (connected) {
pending_config_requests_.clear();
pending_config_requests_.insert(
current_config_values_.begin(),
current_config_values_.end());
FlushImeConfig();
ChangeInputMethod(previous_input_method().id);
ChangeInputMethod(current_input_method().id);
}
}
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));
}
void ChangeCurrentInputMethodFromId(const std::string& input_method_id) {
const input_method::InputMethodDescriptor* descriptor =
input_method::GetInputMethodDescriptorFromId(
input_method_id);
if (descriptor) {
ChangeCurrentInputMethod(*descriptor);
} else {
LOG(ERROR) << "Descriptor is not found for: " << input_method_id;
}
}
void RegisterProperties(const input_method::ImePropertyList& prop_list) {
current_ime_properties_ = prop_list;
FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_,
PropertyListChanged(this,
current_ime_properties_));
}
bool StartInputMethodDaemon() {
should_launch_ime_ = true;
return MaybeLaunchInputMethodDaemon();
}
void UpdateProperty(const input_method::ImePropertyList& prop_list) {
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_,
PropertyListChanged(this,
current_ime_properties_));
}
bool LaunchInputMethodProcess(const std::string& command_line,
base::ProcessHandle* process_handle) {
std::vector<std::string> argv;
base::file_handle_mapping_vector fds_to_remap;
base::ProcessHandle handle = base::kNullProcessHandle;
base::SplitString(command_line, ' ', &argv);
const bool result = base::LaunchApp(argv,
fds_to_remap, // no remapping
false, // wait
&handle);
if (!result) {
LOG(ERROR) << "Could not launch: " << command_line;
return false;
}
const base::ProcessId pid = base::GetProcId(handle);
g_child_watch_add(pid,
reinterpret_cast<GChildWatchFunc>(OnImeShutdown),
this);
*process_handle = handle;
VLOG(1) << command_line << " (PID=" << pid << ") is started";
return true;
}
bool MaybeLaunchInputMethodDaemon() {
if (!initialized_successfully_)
return false;
if (!should_launch_ime_) {
return false;
}
#if !defined(TOUCH_UI)
if (!candidate_window_controller_.get()) {
candidate_window_controller_.reset(new CandidateWindowController);
if (!candidate_window_controller_->Init()) {
LOG(WARNING) << "Failed to initialize the candidate window controller";
}
}
#endif
if (ibus_daemon_process_handle_ != base::kNullProcessHandle) {
return false; // ibus-daemon is already running.
}
const std::string ibus_daemon_command_line =
StringPrintf("%s --panel=disable --cache=none --restart --replace",
kIBusDaemonPath);
if (!LaunchInputMethodProcess(
ibus_daemon_command_line, &ibus_daemon_process_handle_)) {
LOG(ERROR) << "Failed to launch " << ibus_daemon_command_line;
return false;
}
return true;
}
static void OnImeShutdown(GPid pid,
gint status,
InputMethodLibraryImpl* library) {
if (library->ibus_daemon_process_handle_ != base::kNullProcessHandle &&
base::GetProcId(library->ibus_daemon_process_handle_) == pid) {
library->ibus_daemon_process_handle_ = base::kNullProcessHandle;
}
library->MaybeLaunchInputMethodDaemon();
}
void StopInputMethodDaemon() {
if (!initialized_successfully_)
return;
should_launch_ime_ = false;
if (ibus_daemon_process_handle_ != base::kNullProcessHandle) {
const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_);
if (!ibus_controller_->StopInputMethodProcess()) {
LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to "
<< "PID " << pid;
base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */);
}
VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated";
ibus_daemon_process_handle_ = base::kNullProcessHandle;
}
}
void SetDeferImeStartup(bool defer) {
VLOG(1) << "Setting DeferImeStartup to " << defer;
defer_ime_startup_ = defer;
}
void SetEnableAutoImeShutdown(bool enable) {
enable_auto_ime_shutdown_ = enable;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type.value == NotificationType::APP_TERMINATING) {
notification_registrar_.RemoveAll();
StopInputMethodDaemon();
#if !defined(TOUCH_UI)
candidate_window_controller_.reset(NULL);
#endif
}
}
input_method::IBusController* ibus_controller_;
ObserverList<InputMethodLibrary::Observer> observers_;
input_method::InputMethodDescriptor previous_input_method_;
input_method::InputMethodDescriptor current_input_method_;
input_method::ImePropertyList current_ime_properties_;
typedef std::pair<std::string, std::string> ConfigKeyType;
typedef std::map<ConfigKeyType,
input_method::ImeConfigValue> InputMethodConfigRequests;
InputMethodConfigRequests pending_config_requests_;
InputMethodConfigRequests current_config_values_;
NotificationRegistrar notification_registrar_;
bool should_launch_ime_;
bool ime_connected_;
bool defer_ime_startup_;
bool enable_auto_ime_shutdown_;
std::string tentative_current_input_method_id_;
base::ProcessHandle ibus_daemon_process_handle_;
bool initialized_successfully_;
#if !defined(TOUCH_UI)
scoped_ptr<CandidateWindowController> candidate_window_controller_;
#endif
std::vector<std::string> active_input_method_ids_;
DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryImpl);
};
| 170,497 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void mark_screen_rdonly(struct mm_struct *mm)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
spinlock_t *ptl;
int i;
pgd = pgd_offset(mm, 0xA0000);
if (pgd_none_or_clear_bad(pgd))
goto out;
pud = pud_offset(pgd, 0xA0000);
if (pud_none_or_clear_bad(pud))
goto out;
pmd = pmd_offset(pud, 0xA0000);
split_huge_page_pmd(mm, pmd);
if (pmd_none_or_clear_bad(pmd))
goto out;
pte = pte_offset_map_lock(mm, pmd, 0xA0000, &ptl);
for (i = 0; i < 32; i++) {
if (pte_present(*pte))
set_pte(pte, pte_wrprotect(*pte));
pte++;
}
pte_unmap_unlock(pte, ptl);
out:
flush_tlb();
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264 | static void mark_screen_rdonly(struct mm_struct *mm)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
spinlock_t *ptl;
int i;
down_write(&mm->mmap_sem);
pgd = pgd_offset(mm, 0xA0000);
if (pgd_none_or_clear_bad(pgd))
goto out;
pud = pud_offset(pgd, 0xA0000);
if (pud_none_or_clear_bad(pud))
goto out;
pmd = pmd_offset(pud, 0xA0000);
split_huge_page_pmd(mm, pmd);
if (pmd_none_or_clear_bad(pmd))
goto out;
pte = pte_offset_map_lock(mm, pmd, 0xA0000, &ptl);
for (i = 0; i < 32; i++) {
if (pte_present(*pte))
set_pte(pte, pte_wrprotect(*pte));
pte++;
}
pte_unmap_unlock(pte, ptl);
out:
up_write(&mm->mmap_sem);
flush_tlb();
}
| 165,626 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseStartTag(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
const xmlChar *attname;
xmlChar *attvalue;
const xmlChar **atts = ctxt->atts;
int nbatts = 0;
int maxatts = ctxt->maxatts;
int i;
if (RAW != '<') return(NULL);
NEXT1;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStartTag: invalid element name\n");
return(NULL);
}
/*
* Now parse the attributes, it ends up with the ending
*
* (S Attribute)* S?
*/
SKIP_BLANKS;
GROW;
while ((RAW != '>') &&
((RAW != '/') || (NXT(1) != '>')) &&
(IS_BYTE_CHAR(RAW))) {
const xmlChar *q = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
attname = xmlParseAttribute(ctxt, &attvalue);
if ((attname != NULL) && (attvalue != NULL)) {
/*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same
* start-tag or empty-element tag.
*/
for (i = 0; i < nbatts;i += 2) {
if (xmlStrEqual(atts[i], attname)) {
xmlErrAttributeDup(ctxt, NULL, attname);
xmlFree(attvalue);
goto failed;
}
}
/*
* Add the pair to atts
*/
if (atts == NULL) {
maxatts = 22; /* allow for 10 attrs by default */
atts = (const xmlChar **)
xmlMalloc(maxatts * sizeof(xmlChar *));
if (atts == NULL) {
xmlErrMemory(ctxt, NULL);
if (attvalue != NULL)
xmlFree(attvalue);
goto failed;
}
ctxt->atts = atts;
ctxt->maxatts = maxatts;
} else if (nbatts + 4 > maxatts) {
const xmlChar **n;
maxatts *= 2;
n = (const xmlChar **) xmlRealloc((void *) atts,
maxatts * sizeof(const xmlChar *));
if (n == NULL) {
xmlErrMemory(ctxt, NULL);
if (attvalue != NULL)
xmlFree(attvalue);
goto failed;
}
atts = n;
ctxt->atts = atts;
ctxt->maxatts = maxatts;
}
atts[nbatts++] = attname;
atts[nbatts++] = attvalue;
atts[nbatts] = NULL;
atts[nbatts + 1] = NULL;
} else {
if (attvalue != NULL)
xmlFree(attvalue);
}
failed:
GROW
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
}
SKIP_BLANKS;
if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
(attname == NULL) && (attvalue == NULL)) {
xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseStartTag: problem parsing attributes\n");
break;
}
SHRINK;
GROW;
}
/*
* SAX: Start of Element !
*/
if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) &&
(!ctxt->disableSAX)) {
if (nbatts > 0)
ctxt->sax->startElement(ctxt->userData, name, atts);
else
ctxt->sax->startElement(ctxt->userData, name, NULL);
}
if (atts != NULL) {
/* Free only the content strings */
for (i = 1;i < nbatts;i+=2)
if (atts[i] != NULL)
xmlFree((xmlChar *) atts[i]);
}
return(name);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseStartTag(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
const xmlChar *attname;
xmlChar *attvalue;
const xmlChar **atts = ctxt->atts;
int nbatts = 0;
int maxatts = ctxt->maxatts;
int i;
if (RAW != '<') return(NULL);
NEXT1;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseStartTag: invalid element name\n");
return(NULL);
}
/*
* Now parse the attributes, it ends up with the ending
*
* (S Attribute)* S?
*/
SKIP_BLANKS;
GROW;
while (((RAW != '>') &&
((RAW != '/') || (NXT(1) != '>')) &&
(IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *q = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
attname = xmlParseAttribute(ctxt, &attvalue);
if ((attname != NULL) && (attvalue != NULL)) {
/*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same
* start-tag or empty-element tag.
*/
for (i = 0; i < nbatts;i += 2) {
if (xmlStrEqual(atts[i], attname)) {
xmlErrAttributeDup(ctxt, NULL, attname);
xmlFree(attvalue);
goto failed;
}
}
/*
* Add the pair to atts
*/
if (atts == NULL) {
maxatts = 22; /* allow for 10 attrs by default */
atts = (const xmlChar **)
xmlMalloc(maxatts * sizeof(xmlChar *));
if (atts == NULL) {
xmlErrMemory(ctxt, NULL);
if (attvalue != NULL)
xmlFree(attvalue);
goto failed;
}
ctxt->atts = atts;
ctxt->maxatts = maxatts;
} else if (nbatts + 4 > maxatts) {
const xmlChar **n;
maxatts *= 2;
n = (const xmlChar **) xmlRealloc((void *) atts,
maxatts * sizeof(const xmlChar *));
if (n == NULL) {
xmlErrMemory(ctxt, NULL);
if (attvalue != NULL)
xmlFree(attvalue);
goto failed;
}
atts = n;
ctxt->atts = atts;
ctxt->maxatts = maxatts;
}
atts[nbatts++] = attname;
atts[nbatts++] = attvalue;
atts[nbatts] = NULL;
atts[nbatts + 1] = NULL;
} else {
if (attvalue != NULL)
xmlFree(attvalue);
}
failed:
GROW
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
}
SKIP_BLANKS;
if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
(attname == NULL) && (attvalue == NULL)) {
xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseStartTag: problem parsing attributes\n");
break;
}
SHRINK;
GROW;
}
/*
* SAX: Start of Element !
*/
if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) &&
(!ctxt->disableSAX)) {
if (nbatts > 0)
ctxt->sax->startElement(ctxt->userData, name, atts);
else
ctxt->sax->startElement(ctxt->userData, name, NULL);
}
if (atts != NULL) {
/* Free only the content strings */
for (i = 1;i < nbatts;i+=2)
if (atts[i] != NULL)
xmlFree((xmlChar *) atts[i]);
}
return(name);
}
| 171,302 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void webkit_web_view_update_settings(WebKitWebView* webView)
{
WebKitWebViewPrivate* priv = webView->priv;
WebKitWebSettings* webSettings = priv->webSettings.get();
Settings* settings = core(webView)->settings();
gchar* defaultEncoding, *cursiveFontFamily, *defaultFontFamily, *fantasyFontFamily, *monospaceFontFamily, *sansSerifFontFamily, *serifFontFamily, *userStylesheetUri, *defaultSpellCheckingLanguages;
gboolean autoLoadImages, autoShrinkImages, printBackgrounds,
enableScripts, enablePlugins, enableDeveloperExtras, resizableTextAreas,
enablePrivateBrowsing, enableCaretBrowsing, enableHTML5Database, enableHTML5LocalStorage,
enableXSSAuditor, enableSpatialNavigation, enableFrameFlattening, javascriptCanOpenWindows,
javaScriptCanAccessClipboard, enableOfflineWebAppCache,
enableUniversalAccessFromFileURI, enableFileAccessFromFileURI,
enableDOMPaste, tabKeyCyclesThroughElements, enableWebGL,
enableSiteSpecificQuirks, usePageCache, enableJavaApplet,
enableHyperlinkAuditing, enableFullscreen, enableDNSPrefetching;
WebKitEditingBehavior editingBehavior;
g_object_get(webSettings,
"default-encoding", &defaultEncoding,
"cursive-font-family", &cursiveFontFamily,
"default-font-family", &defaultFontFamily,
"fantasy-font-family", &fantasyFontFamily,
"monospace-font-family", &monospaceFontFamily,
"sans-serif-font-family", &sansSerifFontFamily,
"serif-font-family", &serifFontFamily,
"auto-load-images", &autoLoadImages,
"auto-shrink-images", &autoShrinkImages,
"print-backgrounds", &printBackgrounds,
"enable-scripts", &enableScripts,
"enable-plugins", &enablePlugins,
"resizable-text-areas", &resizableTextAreas,
"user-stylesheet-uri", &userStylesheetUri,
"enable-developer-extras", &enableDeveloperExtras,
"enable-private-browsing", &enablePrivateBrowsing,
"enable-caret-browsing", &enableCaretBrowsing,
"enable-html5-database", &enableHTML5Database,
"enable-html5-local-storage", &enableHTML5LocalStorage,
"enable-xss-auditor", &enableXSSAuditor,
"enable-spatial-navigation", &enableSpatialNavigation,
"enable-frame-flattening", &enableFrameFlattening,
"javascript-can-open-windows-automatically", &javascriptCanOpenWindows,
"javascript-can-access-clipboard", &javaScriptCanAccessClipboard,
"enable-offline-web-application-cache", &enableOfflineWebAppCache,
"editing-behavior", &editingBehavior,
"enable-universal-access-from-file-uris", &enableUniversalAccessFromFileURI,
"enable-file-access-from-file-uris", &enableFileAccessFromFileURI,
"enable-dom-paste", &enableDOMPaste,
"tab-key-cycles-through-elements", &tabKeyCyclesThroughElements,
"enable-site-specific-quirks", &enableSiteSpecificQuirks,
"enable-page-cache", &usePageCache,
"enable-java-applet", &enableJavaApplet,
"enable-hyperlink-auditing", &enableHyperlinkAuditing,
"spell-checking-languages", &defaultSpellCheckingLanguages,
"enable-fullscreen", &enableFullscreen,
"enable-dns-prefetching", &enableDNSPrefetching,
"enable-webgl", &enableWebGL,
NULL);
settings->setDefaultTextEncodingName(defaultEncoding);
settings->setCursiveFontFamily(cursiveFontFamily);
settings->setStandardFontFamily(defaultFontFamily);
settings->setFantasyFontFamily(fantasyFontFamily);
settings->setFixedFontFamily(monospaceFontFamily);
settings->setSansSerifFontFamily(sansSerifFontFamily);
settings->setSerifFontFamily(serifFontFamily);
settings->setLoadsImagesAutomatically(autoLoadImages);
settings->setShrinksStandaloneImagesToFit(autoShrinkImages);
settings->setShouldPrintBackgrounds(printBackgrounds);
settings->setJavaScriptEnabled(enableScripts);
settings->setPluginsEnabled(enablePlugins);
settings->setTextAreasAreResizable(resizableTextAreas);
settings->setUserStyleSheetLocation(KURL(KURL(), userStylesheetUri));
settings->setDeveloperExtrasEnabled(enableDeveloperExtras);
settings->setPrivateBrowsingEnabled(enablePrivateBrowsing);
settings->setCaretBrowsingEnabled(enableCaretBrowsing);
#if ENABLE(DATABASE)
AbstractDatabase::setIsAvailable(enableHTML5Database);
#endif
settings->setLocalStorageEnabled(enableHTML5LocalStorage);
settings->setXSSAuditorEnabled(enableXSSAuditor);
settings->setSpatialNavigationEnabled(enableSpatialNavigation);
settings->setFrameFlatteningEnabled(enableFrameFlattening);
settings->setJavaScriptCanOpenWindowsAutomatically(javascriptCanOpenWindows);
settings->setJavaScriptCanAccessClipboard(javaScriptCanAccessClipboard);
settings->setOfflineWebApplicationCacheEnabled(enableOfflineWebAppCache);
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(editingBehavior));
settings->setAllowUniversalAccessFromFileURLs(enableUniversalAccessFromFileURI);
settings->setAllowFileAccessFromFileURLs(enableFileAccessFromFileURI);
settings->setDOMPasteAllowed(enableDOMPaste);
settings->setNeedsSiteSpecificQuirks(enableSiteSpecificQuirks);
settings->setUsesPageCache(usePageCache);
settings->setJavaEnabled(enableJavaApplet);
settings->setHyperlinkAuditingEnabled(enableHyperlinkAuditing);
settings->setDNSPrefetchingEnabled(enableDNSPrefetching);
#if ENABLE(FULLSCREEN_API)
settings->setFullScreenEnabled(enableFullscreen);
#endif
#if ENABLE(SPELLCHECK)
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(defaultSpellCheckingLanguages);
#endif
#if ENABLE(WEBGL)
settings->setWebGLEnabled(enableWebGL);
#endif
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(tabKeyCyclesThroughElements);
g_free(defaultEncoding);
g_free(cursiveFontFamily);
g_free(defaultFontFamily);
g_free(fantasyFontFamily);
g_free(monospaceFontFamily);
g_free(sansSerifFontFamily);
g_free(serifFontFamily);
g_free(userStylesheetUri);
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
}
Commit Message: 2011-06-02 Joone Hur <[email protected]>
Reviewed by Martin Robinson.
[GTK] Only load dictionaries if spell check is enabled
https://bugs.webkit.org/show_bug.cgi?id=32879
We don't need to call enchant if enable-spell-checking is false.
* webkit/webkitwebview.cpp:
(webkit_web_view_update_settings): Skip loading dictionaries when enable-spell-checking is false.
(webkit_web_view_settings_notify): Ditto.
git-svn-id: svn://svn.chromium.org/blink/trunk@87925 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void webkit_web_view_update_settings(WebKitWebView* webView)
{
WebKitWebViewPrivate* priv = webView->priv;
WebKitWebSettings* webSettings = priv->webSettings.get();
Settings* settings = core(webView)->settings();
gchar* defaultEncoding, *cursiveFontFamily, *defaultFontFamily, *fantasyFontFamily, *monospaceFontFamily, *sansSerifFontFamily, *serifFontFamily, *userStylesheetUri, *defaultSpellCheckingLanguages;
gboolean autoLoadImages, autoShrinkImages, printBackgrounds,
enableScripts, enablePlugins, enableDeveloperExtras, resizableTextAreas,
enablePrivateBrowsing, enableCaretBrowsing, enableHTML5Database, enableHTML5LocalStorage,
enableXSSAuditor, enableSpatialNavigation, enableFrameFlattening, javascriptCanOpenWindows,
javaScriptCanAccessClipboard, enableOfflineWebAppCache,
enableUniversalAccessFromFileURI, enableFileAccessFromFileURI,
enableDOMPaste, tabKeyCyclesThroughElements, enableWebGL,
enableSiteSpecificQuirks, usePageCache, enableJavaApplet,
enableHyperlinkAuditing, enableFullscreen, enableDNSPrefetching,
enableSpellChecking;
WebKitEditingBehavior editingBehavior;
g_object_get(webSettings,
"default-encoding", &defaultEncoding,
"cursive-font-family", &cursiveFontFamily,
"default-font-family", &defaultFontFamily,
"fantasy-font-family", &fantasyFontFamily,
"monospace-font-family", &monospaceFontFamily,
"sans-serif-font-family", &sansSerifFontFamily,
"serif-font-family", &serifFontFamily,
"auto-load-images", &autoLoadImages,
"auto-shrink-images", &autoShrinkImages,
"print-backgrounds", &printBackgrounds,
"enable-scripts", &enableScripts,
"enable-plugins", &enablePlugins,
"resizable-text-areas", &resizableTextAreas,
"user-stylesheet-uri", &userStylesheetUri,
"enable-developer-extras", &enableDeveloperExtras,
"enable-private-browsing", &enablePrivateBrowsing,
"enable-caret-browsing", &enableCaretBrowsing,
"enable-html5-database", &enableHTML5Database,
"enable-html5-local-storage", &enableHTML5LocalStorage,
"enable-xss-auditor", &enableXSSAuditor,
"enable-spatial-navigation", &enableSpatialNavigation,
"enable-frame-flattening", &enableFrameFlattening,
"javascript-can-open-windows-automatically", &javascriptCanOpenWindows,
"javascript-can-access-clipboard", &javaScriptCanAccessClipboard,
"enable-offline-web-application-cache", &enableOfflineWebAppCache,
"editing-behavior", &editingBehavior,
"enable-universal-access-from-file-uris", &enableUniversalAccessFromFileURI,
"enable-file-access-from-file-uris", &enableFileAccessFromFileURI,
"enable-dom-paste", &enableDOMPaste,
"tab-key-cycles-through-elements", &tabKeyCyclesThroughElements,
"enable-site-specific-quirks", &enableSiteSpecificQuirks,
"enable-page-cache", &usePageCache,
"enable-java-applet", &enableJavaApplet,
"enable-hyperlink-auditing", &enableHyperlinkAuditing,
"enable-spell-checking", &enableSpellChecking,
"spell-checking-languages", &defaultSpellCheckingLanguages,
"enable-fullscreen", &enableFullscreen,
"enable-dns-prefetching", &enableDNSPrefetching,
"enable-webgl", &enableWebGL,
NULL);
settings->setDefaultTextEncodingName(defaultEncoding);
settings->setCursiveFontFamily(cursiveFontFamily);
settings->setStandardFontFamily(defaultFontFamily);
settings->setFantasyFontFamily(fantasyFontFamily);
settings->setFixedFontFamily(monospaceFontFamily);
settings->setSansSerifFontFamily(sansSerifFontFamily);
settings->setSerifFontFamily(serifFontFamily);
settings->setLoadsImagesAutomatically(autoLoadImages);
settings->setShrinksStandaloneImagesToFit(autoShrinkImages);
settings->setShouldPrintBackgrounds(printBackgrounds);
settings->setJavaScriptEnabled(enableScripts);
settings->setPluginsEnabled(enablePlugins);
settings->setTextAreasAreResizable(resizableTextAreas);
settings->setUserStyleSheetLocation(KURL(KURL(), userStylesheetUri));
settings->setDeveloperExtrasEnabled(enableDeveloperExtras);
settings->setPrivateBrowsingEnabled(enablePrivateBrowsing);
settings->setCaretBrowsingEnabled(enableCaretBrowsing);
#if ENABLE(DATABASE)
AbstractDatabase::setIsAvailable(enableHTML5Database);
#endif
settings->setLocalStorageEnabled(enableHTML5LocalStorage);
settings->setXSSAuditorEnabled(enableXSSAuditor);
settings->setSpatialNavigationEnabled(enableSpatialNavigation);
settings->setFrameFlatteningEnabled(enableFrameFlattening);
settings->setJavaScriptCanOpenWindowsAutomatically(javascriptCanOpenWindows);
settings->setJavaScriptCanAccessClipboard(javaScriptCanAccessClipboard);
settings->setOfflineWebApplicationCacheEnabled(enableOfflineWebAppCache);
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(editingBehavior));
settings->setAllowUniversalAccessFromFileURLs(enableUniversalAccessFromFileURI);
settings->setAllowFileAccessFromFileURLs(enableFileAccessFromFileURI);
settings->setDOMPasteAllowed(enableDOMPaste);
settings->setNeedsSiteSpecificQuirks(enableSiteSpecificQuirks);
settings->setUsesPageCache(usePageCache);
settings->setJavaEnabled(enableJavaApplet);
settings->setHyperlinkAuditingEnabled(enableHyperlinkAuditing);
settings->setDNSPrefetchingEnabled(enableDNSPrefetching);
#if ENABLE(FULLSCREEN_API)
settings->setFullScreenEnabled(enableFullscreen);
#endif
#if ENABLE(SPELLCHECK)
if (enableSpellChecking) {
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(defaultSpellCheckingLanguages);
}
#endif
#if ENABLE(WEBGL)
settings->setWebGLEnabled(enableWebGL);
#endif
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(tabKeyCyclesThroughElements);
g_free(defaultEncoding);
g_free(cursiveFontFamily);
g_free(defaultFontFamily);
g_free(fantasyFontFamily);
g_free(monospaceFontFamily);
g_free(sansSerifFontFamily);
g_free(serifFontFamily);
g_free(userStylesheetUri);
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
}
| 170,450 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void lo_release(struct gendisk *disk, fmode_t mode)
{
struct loop_device *lo = disk->private_data;
int err;
if (atomic_dec_return(&lo->lo_refcnt))
return;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
/*
* In autoclear mode, stop the loop thread
* and remove configuration after last close.
*/
err = loop_clr_fd(lo);
if (!err)
return;
} else if (lo->lo_state == Lo_bound) {
/*
* Otherwise keep thread (if running) and config,
* but flush possible ongoing bios in thread.
*/
blk_mq_freeze_queue(lo->lo_queue);
blk_mq_unfreeze_queue(lo->lo_queue);
}
mutex_unlock(&lo->lo_ctl_mutex);
}
Commit Message: loop: fix concurrent lo_open/lo_release
范龙飞 reports that KASAN can report a use-after-free in __lock_acquire.
The reason is due to insufficient serialization in lo_release(), which
will continue to use the loop device even after it has decremented the
lo_refcnt to zero.
In the meantime, another process can come in, open the loop device
again as it is being shut down. Confusion ensues.
Reported-by: 范龙飞 <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416 | static void lo_release(struct gendisk *disk, fmode_t mode)
static void __lo_release(struct loop_device *lo)
{
int err;
if (atomic_dec_return(&lo->lo_refcnt))
return;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
/*
* In autoclear mode, stop the loop thread
* and remove configuration after last close.
*/
err = loop_clr_fd(lo);
if (!err)
return;
} else if (lo->lo_state == Lo_bound) {
/*
* Otherwise keep thread (if running) and config,
* but flush possible ongoing bios in thread.
*/
blk_mq_freeze_queue(lo->lo_queue);
blk_mq_unfreeze_queue(lo->lo_queue);
}
mutex_unlock(&lo->lo_ctl_mutex);
}
| 169,352 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: print_trans(netdissect_options *ndo,
const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf)
{
u_int bcc;
const char *f1, *f2, *f3, *f4;
const u_char *data, *param;
const u_char *w = words + 1;
int datalen, paramlen;
if (request) {
ND_TCHECK2(w[12 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 9 * 2);
param = buf + EXTRACT_LE_16BITS(w + 10 * 2);
datalen = EXTRACT_LE_16BITS(w + 11 * 2);
data = buf + EXTRACT_LE_16BITS(w + 12 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n";
f2 = "|Name=[S]\n";
f3 = "|Param ";
f4 = "|Data ";
} else {
ND_TCHECK2(w[7 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 3 * 2);
param = buf + EXTRACT_LE_16BITS(w + 4 * 2);
datalen = EXTRACT_LE_16BITS(w + 6 * 2);
data = buf + EXTRACT_LE_16BITS(w + 7 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n";
f2 = "|Unknown ";
f3 = "|Param ";
f4 = "|Data ";
}
smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf),
unicodestr);
ND_TCHECK2(*data1, 2);
bcc = EXTRACT_LE_16BITS(data1);
ND_PRINT((ndo, "smb_bcc=%u\n", bcc));
if (bcc > 0) {
smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr);
if (strcmp((const char *)(data1 + 2), "\\MAILSLOT\\BROWSE") == 0) {
print_browse(ndo, param, paramlen, data, datalen);
return;
}
if (strcmp((const char *)(data1 + 2), "\\PIPE\\LANMAN") == 0) {
print_ipc(ndo, param, paramlen, data, datalen);
return;
}
if (paramlen)
smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr);
if (datalen)
smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: (for 4.9.3) SMB: Add two missing bounds checks
CWE ID: CWE-125 | print_trans(netdissect_options *ndo,
const u_char *words, const u_char *data1, const u_char *buf, const u_char *maxbuf)
{
u_int bcc;
const char *f1, *f2, *f3, *f4;
const u_char *data, *param;
const u_char *w = words + 1;
int datalen, paramlen;
if (request) {
ND_TCHECK2(w[12 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 9 * 2);
param = buf + EXTRACT_LE_16BITS(w + 10 * 2);
datalen = EXTRACT_LE_16BITS(w + 11 * 2);
data = buf + EXTRACT_LE_16BITS(w + 12 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nMaxParmCnt=[d] \nMaxDataCnt=[d]\nMaxSCnt=[d] \nTransFlags=[w] \nRes1=[w] \nRes2=[w] \nRes3=[w]\nParamCnt=[d] \nParamOff=[d] \nDataCnt=[d] \nDataOff=[d] \nSUCnt=[d]\n";
f2 = "|Name=[S]\n";
f3 = "|Param ";
f4 = "|Data ";
} else {
ND_TCHECK2(w[7 * 2], 2);
paramlen = EXTRACT_LE_16BITS(w + 3 * 2);
param = buf + EXTRACT_LE_16BITS(w + 4 * 2);
datalen = EXTRACT_LE_16BITS(w + 6 * 2);
data = buf + EXTRACT_LE_16BITS(w + 7 * 2);
f1 = "TotParamCnt=[d] \nTotDataCnt=[d] \nRes1=[d]\nParamCnt=[d] \nParamOff=[d] \nRes2=[d] \nDataCnt=[d] \nDataOff=[d] \nRes3=[d]\nLsetup=[d]\n";
f2 = "|Unknown ";
f3 = "|Param ";
f4 = "|Data ";
}
smb_fdata(ndo, words + 1, f1, min(words + 1 + 2 * words[0], maxbuf),
unicodestr);
ND_TCHECK2(*data1, 2);
bcc = EXTRACT_LE_16BITS(data1);
ND_PRINT((ndo, "smb_bcc=%u\n", bcc));
if (bcc > 0) {
smb_fdata(ndo, data1 + 2, f2, maxbuf - (paramlen + datalen), unicodestr);
#define MAILSLOT_BROWSE_STR "\\MAILSLOT\\BROWSE"
ND_TCHECK2(*(data1 + 2), strlen(MAILSLOT_BROWSE_STR) + 1);
if (strcmp((const char *)(data1 + 2), MAILSLOT_BROWSE_STR) == 0) {
print_browse(ndo, param, paramlen, data, datalen);
return;
}
#undef MAILSLOT_BROWSE_STR
#define PIPE_LANMAN_STR "\\PIPE\\LANMAN"
ND_TCHECK2(*(data1 + 2), strlen(PIPE_LANMAN_STR) + 1);
if (strcmp((const char *)(data1 + 2), PIPE_LANMAN_STR) == 0) {
print_ipc(ndo, param, paramlen, data, datalen);
return;
}
#undef PIPE_LANMAN_STR
if (paramlen)
smb_fdata(ndo, param, f3, min(param + paramlen, maxbuf), unicodestr);
if (datalen)
smb_fdata(ndo, data, f4, min(data + datalen, maxbuf), unicodestr);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 169,815 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SYSCALL_DEFINE2(osf_getdomainname, char __user *, name, int, namelen)
{
unsigned len;
int i;
if (!access_ok(VERIFY_WRITE, name, namelen))
return -EFAULT;
len = namelen;
if (namelen > 32)
len = 32;
down_read(&uts_sem);
for (i = 0; i < len; ++i) {
__put_user(utsname()->domainname[i], name + i);
if (utsname()->domainname[i] == '\0')
break;
}
up_read(&uts_sem);
return 0;
}
Commit Message: alpha: fix several security issues
Fix several security issues in Alpha-specific syscalls. Untested, but
mostly trivial.
1. Signedness issue in osf_getdomainname allows copying out-of-bounds
kernel memory to userland.
2. Signedness issue in osf_sysinfo allows copying large amounts of
kernel memory to userland.
3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy
size, allowing copying large amounts of kernel memory to userland.
4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows
privilege escalation via writing return value of sys_wait4 to kernel
memory.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: Richard Henderson <[email protected]>
Cc: Ivan Kokshaysky <[email protected]>
Cc: Matt Turner <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | SYSCALL_DEFINE2(osf_getdomainname, char __user *, name, int, namelen)
{
unsigned len;
int i;
if (!access_ok(VERIFY_WRITE, name, namelen))
return -EFAULT;
len = namelen;
if (len > 32)
len = 32;
down_read(&uts_sem);
for (i = 0; i < len; ++i) {
__put_user(utsname()->domainname[i], name + i);
if (utsname()->domainname[i] == '\0')
break;
}
up_read(&uts_sem);
return 0;
}
| 165,867 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MaybeRestoreIBusConfig() {
if (!ibus_) {
return;
}
MaybeDestroyIBusConfig();
if (!ibus_config_) {
GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_);
if (!ibus_connection) {
LOG(INFO) << "Couldn't create an ibus config object since "
<< "IBus connection is not ready.";
return;
}
const gboolean disconnected
= g_dbus_connection_is_closed(ibus_connection);
if (disconnected) {
LOG(ERROR) << "Couldn't create an ibus config object since "
<< "IBus connection is closed.";
return;
}
ibus_config_ = ibus_config_new(ibus_connection,
NULL /* do not cancel the operation */,
NULL /* do not get error information */);
if (!ibus_config_) {
LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?";
return;
}
g_object_ref(ibus_config_);
LOG(INFO) << "ibus_config_ is ready.";
}
}
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 MaybeRestoreIBusConfig() {
if (!ibus_) {
return;
}
MaybeDestroyIBusConfig();
if (!ibus_config_) {
GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_);
if (!ibus_connection) {
VLOG(1) << "Couldn't create an ibus config object since "
<< "IBus connection is not ready.";
return;
}
const gboolean disconnected
= g_dbus_connection_is_closed(ibus_connection);
if (disconnected) {
LOG(ERROR) << "Couldn't create an ibus config object since "
<< "IBus connection is closed.";
return;
}
ibus_config_ = ibus_config_new(ibus_connection,
NULL /* do not cancel the operation */,
NULL /* do not get error information */);
if (!ibus_config_) {
LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?";
return;
}
g_object_ref(ibus_config_);
VLOG(1) << "ibus_config_ is ready.";
}
}
| 170,543 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,954 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_get_copyright(png_structp png_ptr)
{
PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
#ifdef PNG_STRING_COPYRIGHT
return PNG_STRING_COPYRIGHT
#else
#ifdef __STDC__
return ((png_charp) PNG_STRING_NEWLINE \
"libpng version 1.2.52 - November 20, 2014" PNG_STRING_NEWLINE \
"Copyright (c) 1998-2014 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
"Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
"Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
PNG_STRING_NEWLINE);
#else
return ((png_charp) "libpng version 1.2.52 - November 20, 2014\
Copyright (c) 1998-2014 Glenn Randers-Pehrson\
Copyright (c) 1996-1997 Andreas Dilger\
Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.");
#endif
#endif
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_get_copyright(png_structp png_ptr)
{
PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
#ifdef PNG_STRING_COPYRIGHT
return PNG_STRING_COPYRIGHT
#else
#ifdef __STDC__
return ((png_charp) PNG_STRING_NEWLINE \
"libpng version 1.2.54 - November 12, 2015" PNG_STRING_NEWLINE \
"Copyright (c) 1998-2015 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
"Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
"Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
PNG_STRING_NEWLINE);
#else
return ((png_charp) "libpng version 1.2.54 - November 12, 2015\
Copyright (c) 1998-2015 Glenn Randers-Pehrson\
Copyright (c) 1996-1997 Andreas Dilger\
Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.");
#endif
#endif
}
| 172,162 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct scm_fp_list *scm_fp_dup(struct scm_fp_list *fpl)
{
struct scm_fp_list *new_fpl;
int i;
if (!fpl)
return NULL;
new_fpl = kmemdup(fpl, offsetof(struct scm_fp_list, fp[fpl->count]),
GFP_KERNEL);
if (new_fpl) {
for (i = 0; i < fpl->count; i++)
get_file(fpl->fp[i]);
new_fpl->max = new_fpl->count;
}
return new_fpl;
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | struct scm_fp_list *scm_fp_dup(struct scm_fp_list *fpl)
{
struct scm_fp_list *new_fpl;
int i;
if (!fpl)
return NULL;
new_fpl = kmemdup(fpl, offsetof(struct scm_fp_list, fp[fpl->count]),
GFP_KERNEL);
if (new_fpl) {
for (i = 0; i < fpl->count; i++)
get_file(fpl->fp[i]);
new_fpl->max = new_fpl->count;
new_fpl->user = get_uid(fpl->user);
}
return new_fpl;
}
| 167,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void v9fs_device_unrealize_common(V9fsState *s, Error **errp)
{
g_free(s->ctx.fs_root);
g_free(s->tag);
}
Commit Message:
CWE ID: CWE-400 | void v9fs_device_unrealize_common(V9fsState *s, Error **errp)
{
g_free(s->tag);
g_free(s->ctx.fs_root);
}
| 164,896 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void flush_tlb_page(struct vm_area_struct *vma, unsigned long start)
{
struct mm_struct *mm = vma->vm_mm;
preempt_disable();
if (current->active_mm == mm) {
if (current->mm)
__flush_tlb_one(start);
else
leave_mm(smp_processor_id());
}
if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids)
flush_tlb_others(mm_cpumask(mm), mm, start, 0UL);
preempt_enable();
}
Commit Message: x86/mm: Add barriers and document switch_mm()-vs-flush synchronization
When switch_mm() activates a new PGD, it also sets a bit that
tells other CPUs that the PGD is in use so that TLB flush IPIs
will be sent. In order for that to work correctly, the bit
needs to be visible prior to loading the PGD and therefore
starting to fill the local TLB.
Document all the barriers that make this work correctly and add
a couple that were missing.
Signed-off-by: Andy Lutomirski <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Borislav Petkov <[email protected]>
Cc: Brian Gerst <[email protected]>
Cc: Dave Hansen <[email protected]>
Cc: Denys Vlasenko <[email protected]>
Cc: H. Peter Anvin <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: [email protected]
Cc: [email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-362 | void flush_tlb_page(struct vm_area_struct *vma, unsigned long start)
{
struct mm_struct *mm = vma->vm_mm;
preempt_disable();
if (current->active_mm == mm) {
if (current->mm) {
/*
* Implicit full barrier (INVLPG) that synchronizes
* with switch_mm.
*/
__flush_tlb_one(start);
} else {
leave_mm(smp_processor_id());
/* Synchronize with switch_mm. */
smp_mb();
}
}
if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids)
flush_tlb_others(mm_cpumask(mm), mm, start, 0UL);
preempt_enable();
}
| 167,441 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcScreenSaverUnsetAttributes(ClientPtr client)
{
#ifdef PANORAMIX
if (!noPanoramiXExtension) {
REQUEST(xScreenSaverUnsetAttributesReq);
PanoramiXRes *draw;
int rc, i;
rc = dixLookupResourceByClass((void **) &draw, stuff->drawable,
XRC_DRAWABLE, client, DixWriteAccess);
if (rc != Success)
for (i = PanoramiXNumScreens - 1; i > 0; i--) {
stuff->drawable = draw->info[i].id;
ScreenSaverUnsetAttributes(client);
}
stuff->drawable = draw->info[0].id;
}
#endif
return ScreenSaverUnsetAttributes(client);
}
Commit Message:
CWE ID: CWE-20 | ProcScreenSaverUnsetAttributes(ClientPtr client)
{
#ifdef PANORAMIX
if (!noPanoramiXExtension) {
REQUEST(xScreenSaverUnsetAttributesReq);
PanoramiXRes *draw;
int rc, i;
REQUEST_SIZE_MATCH(xScreenSaverUnsetAttributesReq);
rc = dixLookupResourceByClass((void **) &draw, stuff->drawable,
XRC_DRAWABLE, client, DixWriteAccess);
if (rc != Success)
for (i = PanoramiXNumScreens - 1; i > 0; i--) {
stuff->drawable = draw->info[i].id;
ScreenSaverUnsetAttributes(client);
}
stuff->drawable = draw->info[0].id;
}
#endif
return ScreenSaverUnsetAttributes(client);
}
| 165,433 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InspectorHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_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 <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void InspectorHandler::SetRenderer(RenderProcessHost* process_host,
void InspectorHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
}
| 172,748 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct mobj *alloc_ta_mem(size_t size)
{
#ifdef CFG_PAGED_USER_TA
return mobj_paged_alloc(size);
#else
struct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr);
if (mobj)
memset(mobj_get_va(mobj, 0), 0, size);
return mobj;
#endif
}
Commit Message: core: clear the entire TA area
Previously we cleared (memset to zero) the size corresponding to code
and data segments, however the allocation for the TA is made on the
granularity of the memory pool, meaning that we did not clear all memory
and because of that we could potentially leak code and data of a
previous loaded TA.
Fixes: OP-TEE-2018-0006: "Potential disclosure of previously loaded TA
code and data"
Signed-off-by: Joakim Bech <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Suggested-by: Jens Wiklander <[email protected]>
Reviewed-by: Jens Wiklander <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]>
CWE ID: CWE-189 | static struct mobj *alloc_ta_mem(size_t size)
{
#ifdef CFG_PAGED_USER_TA
return mobj_paged_alloc(size);
#else
struct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr);
if (mobj) {
size_t granularity = BIT(tee_mm_sec_ddr.shift);
/* Round up to allocation granularity size */
memset(mobj_get_va(mobj, 0), 0, ROUNDUP(size, granularity));
}
return mobj;
#endif
}
| 169,472 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[])
{
opj_dinfo_t* dinfo;
opj_event_mgr_t event_mgr; /* event manager */
int tnum;
unsigned int snum;
opj_mj2_t *movie;
mj2_tk_t *track;
mj2_sample_t *sample;
unsigned char* frame_codestream;
FILE *file, *outfile;
char outfilename[50];
mj2_dparameters_t parameters;
if (argc != 3) {
printf("Usage: %s mj2filename output_location\n", argv[0]);
printf("Example: %s foreman.mj2 output/foreman\n", argv[0]);
return 1;
}
file = fopen(argv[1], "rb");
if (!file) {
fprintf(stderr, "failed to open %s for reading\n", argv[1]);
return 1;
}
/*
configure the event callbacks (not required)
setting of each callback is optional
*/
memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
event_mgr.error_handler = error_callback;
event_mgr.warning_handler = warning_callback;
event_mgr.info_handler = info_callback;
/* get a MJ2 decompressor handle */
dinfo = mj2_create_decompress();
/* catch events using our callbacks and give a local context */
opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
/* setup the decoder decoding parameters using user parameters */
memset(¶meters, 0, sizeof(mj2_dparameters_t));
movie = (opj_mj2_t*) dinfo->mj2_handle;
mj2_setup_decoder(movie, ¶meters);
if (mj2_read_struct(file, movie)) { /* Creating the movie structure*/
return 1;
}
/* Decode first video track */
tnum = 0;
while (movie->tk[tnum].track_type != 0) {
tnum ++;
}
track = &movie->tk[tnum];
fprintf(stdout, "Extracting %d frames from file...\n", track->num_samples);
for (snum = 0; snum < track->num_samples; snum++) {
sample = &track->sample[snum];
frame_codestream = (unsigned char*) malloc(sample->sample_size -
8); /* Skipping JP2C marker*/
fseek(file, sample->offset + 8, SEEK_SET);
fread(frame_codestream, sample->sample_size - 8, 1,
file); /* Assuming that jp and ftyp markers size do*/
sprintf(outfilename, "%s_%05d.j2k", argv[2], snum);
outfile = fopen(outfilename, "wb");
if (!outfile) {
fprintf(stderr, "failed to open %s for writing\n", outfilename);
return 1;
}
fwrite(frame_codestream, sample->sample_size - 8, 1, outfile);
fclose(outfile);
free(frame_codestream);
}
fclose(file);
fprintf(stdout, "%d frames correctly extracted\n", snum);
/* free remaining structures */
if (dinfo) {
mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
}
return 0;
}
Commit Message: opj_mj2_extract: Check provided output prefix for length
This uses snprintf() with correct buffer length instead of sprintf(). This
prevents a buffer overflow when providing a long output prefix. Furthermore
the program exits with an error when the provided output prefix is too long.
Fixes #1088.
CWE ID: CWE-119 | int main(int argc, char *argv[])
{
opj_dinfo_t* dinfo;
opj_event_mgr_t event_mgr; /* event manager */
int tnum;
unsigned int snum;
opj_mj2_t *movie;
mj2_tk_t *track;
mj2_sample_t *sample;
unsigned char* frame_codestream;
FILE *file, *outfile;
char outfilename[50];
mj2_dparameters_t parameters;
if (argc != 3) {
printf("Usage: %s mj2filename output_location\n", argv[0]);
printf("Example: %s foreman.mj2 output/foreman\n", argv[0]);
return 1;
}
file = fopen(argv[1], "rb");
if (!file) {
fprintf(stderr, "failed to open %s for reading\n", argv[1]);
return 1;
}
/*
configure the event callbacks (not required)
setting of each callback is optional
*/
memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
event_mgr.error_handler = error_callback;
event_mgr.warning_handler = warning_callback;
event_mgr.info_handler = info_callback;
/* get a MJ2 decompressor handle */
dinfo = mj2_create_decompress();
/* catch events using our callbacks and give a local context */
opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
/* setup the decoder decoding parameters using user parameters */
memset(¶meters, 0, sizeof(mj2_dparameters_t));
movie = (opj_mj2_t*) dinfo->mj2_handle;
mj2_setup_decoder(movie, ¶meters);
if (mj2_read_struct(file, movie)) { /* Creating the movie structure*/
return 1;
}
/* Decode first video track */
tnum = 0;
while (movie->tk[tnum].track_type != 0) {
tnum ++;
}
track = &movie->tk[tnum];
fprintf(stdout, "Extracting %d frames from file...\n", track->num_samples);
for (snum = 0; snum < track->num_samples; snum++) {
sample = &track->sample[snum];
frame_codestream = (unsigned char*) malloc(sample->sample_size -
8); /* Skipping JP2C marker*/
fseek(file, sample->offset + 8, SEEK_SET);
fread(frame_codestream, sample->sample_size - 8, 1,
file); /* Assuming that jp and ftyp markers size do*/
int num = snprintf(outfilename, sizeof(outfilename), "%s_%05d.j2k", argv[2], snum);
if (num >= sizeof(outfilename)) {
fprintf(stderr, "maximum length of output prefix exceeded\n");
return 1;
}
outfile = fopen(outfilename, "wb");
if (!outfile) {
fprintf(stderr, "failed to open %s for writing\n", outfilename);
return 1;
}
fwrite(frame_codestream, sample->sample_size - 8, 1, outfile);
fclose(outfile);
free(frame_codestream);
}
fclose(file);
fprintf(stdout, "%d frames correctly extracted\n", snum);
/* free remaining structures */
if (dinfo) {
mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle);
}
return 0;
}
| 169,307 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[8] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, 8);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
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 | construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[EVP_MAX_IV_LENGTH] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, sizeof iv);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
| 169,053 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool CheckMov(const uint8* buffer, int buffer_size) {
RCHECK(buffer_size > 8);
int offset = 0;
while (offset + 8 < buffer_size) {
int atomsize = Read32(buffer + offset);
uint32 atomtype = Read32(buffer + offset + 4);
switch (atomtype) {
case TAG('f','t','y','p'):
case TAG('p','d','i','n'):
case TAG('m','o','o','v'):
case TAG('m','o','o','f'):
case TAG('m','f','r','a'):
case TAG('m','d','a','t'):
case TAG('f','r','e','e'):
case TAG('s','k','i','p'):
case TAG('m','e','t','a'):
case TAG('m','e','c','o'):
case TAG('s','t','y','p'):
case TAG('s','i','d','x'):
case TAG('s','s','i','x'):
case TAG('p','r','f','t'):
case TAG('b','l','o','c'):
break;
default:
return false;
}
if (atomsize == 1) {
if (offset + 16 > buffer_size)
break;
if (Read32(buffer + offset + 8) != 0)
break; // Offset is way past buffer size.
atomsize = Read32(buffer + offset + 12);
}
if (atomsize <= 0)
break; // Indicates the last atom or length too big.
offset += atomsize;
}
return true;
}
Commit Message: Add extra checks to avoid integer overflow.
BUG=425980
TEST=no crash with ASAN
Review URL: https://codereview.chromium.org/659743004
Cr-Commit-Position: refs/heads/master@{#301249}
CWE ID: CWE-189 | static bool CheckMov(const uint8* buffer, int buffer_size) {
RCHECK(buffer_size > 8);
int offset = 0;
while (offset + 8 < buffer_size) {
uint32 atomsize = Read32(buffer + offset);
uint32 atomtype = Read32(buffer + offset + 4);
switch (atomtype) {
case TAG('f','t','y','p'):
case TAG('p','d','i','n'):
case TAG('m','o','o','v'):
case TAG('m','o','o','f'):
case TAG('m','f','r','a'):
case TAG('m','d','a','t'):
case TAG('f','r','e','e'):
case TAG('s','k','i','p'):
case TAG('m','e','t','a'):
case TAG('m','e','c','o'):
case TAG('s','t','y','p'):
case TAG('s','i','d','x'):
case TAG('s','s','i','x'):
case TAG('p','r','f','t'):
case TAG('b','l','o','c'):
break;
default:
return false;
}
if (atomsize == 1) {
if (offset + 16 > buffer_size)
break;
if (Read32(buffer + offset + 8) != 0)
break; // Offset is way past buffer size.
atomsize = Read32(buffer + offset + 12);
}
if (atomsize == 0 || atomsize > static_cast<size_t>(buffer_size))
break; // Indicates the last atom or length too big.
offset += atomsize;
}
return true;
}
| 171,611 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int snd_timer_user_tselect(struct file *file,
struct snd_timer_select __user *_tselect)
{
struct snd_timer_user *tu;
struct snd_timer_select tselect;
char str[32];
int err = 0;
tu = file->private_data;
if (tu->timeri) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
}
if (copy_from_user(&tselect, _tselect, sizeof(tselect))) {
err = -EFAULT;
goto __err;
}
sprintf(str, "application %i", current->pid);
if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE)
tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid);
if (err < 0)
goto __err;
kfree(tu->queue);
tu->queue = NULL;
kfree(tu->tqueue);
tu->tqueue = NULL;
if (tu->tread) {
tu->tqueue = kmalloc(tu->queue_size * sizeof(struct snd_timer_tread),
GFP_KERNEL);
if (tu->tqueue == NULL)
err = -ENOMEM;
} else {
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL)
err = -ENOMEM;
}
if (err < 0) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
} else {
tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST;
tu->timeri->callback = tu->tread
? snd_timer_user_tinterrupt : snd_timer_user_interrupt;
tu->timeri->ccallback = snd_timer_user_ccallback;
tu->timeri->callback_data = (void *)tu;
tu->timeri->disconnect = snd_timer_user_disconnect;
}
__err:
return err;
}
Commit Message: ALSA: timer: Fix missing queue indices reset at SNDRV_TIMER_IOCTL_SELECT
snd_timer_user_tselect() reallocates the queue buffer dynamically, but
it forgot to reset its indices. Since the read may happen
concurrently with ioctl and snd_timer_user_tselect() allocates the
buffer via kmalloc(), this may lead to the leak of uninitialized
kernel-space data, as spotted via KMSAN:
BUG: KMSAN: use of unitialized memory in snd_timer_user_read+0x6c4/0xa10
CPU: 0 PID: 1037 Comm: probe Not tainted 4.11.0-rc5+ #2739
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
Call Trace:
__dump_stack lib/dump_stack.c:16
dump_stack+0x143/0x1b0 lib/dump_stack.c:52
kmsan_report+0x12a/0x180 mm/kmsan/kmsan.c:1007
kmsan_check_memory+0xc2/0x140 mm/kmsan/kmsan.c:1086
copy_to_user ./arch/x86/include/asm/uaccess.h:725
snd_timer_user_read+0x6c4/0xa10 sound/core/timer.c:2004
do_loop_readv_writev fs/read_write.c:716
__do_readv_writev+0x94c/0x1380 fs/read_write.c:864
do_readv_writev fs/read_write.c:894
vfs_readv fs/read_write.c:908
do_readv+0x52a/0x5d0 fs/read_write.c:934
SYSC_readv+0xb6/0xd0 fs/read_write.c:1021
SyS_readv+0x87/0xb0 fs/read_write.c:1018
This patch adds the missing reset of queue indices. Together with the
previous fix for the ioctl/read race, we cover the whole problem.
Reported-by: Alexander Potapenko <[email protected]>
Tested-by: Alexander Potapenko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-200 | static int snd_timer_user_tselect(struct file *file,
struct snd_timer_select __user *_tselect)
{
struct snd_timer_user *tu;
struct snd_timer_select tselect;
char str[32];
int err = 0;
tu = file->private_data;
if (tu->timeri) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
}
if (copy_from_user(&tselect, _tselect, sizeof(tselect))) {
err = -EFAULT;
goto __err;
}
sprintf(str, "application %i", current->pid);
if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE)
tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid);
if (err < 0)
goto __err;
tu->qhead = tu->qtail = tu->qused = 0;
kfree(tu->queue);
tu->queue = NULL;
kfree(tu->tqueue);
tu->tqueue = NULL;
if (tu->tread) {
tu->tqueue = kmalloc(tu->queue_size * sizeof(struct snd_timer_tread),
GFP_KERNEL);
if (tu->tqueue == NULL)
err = -ENOMEM;
} else {
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL)
err = -ENOMEM;
}
if (err < 0) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
} else {
tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST;
tu->timeri->callback = tu->tread
? snd_timer_user_tinterrupt : snd_timer_user_interrupt;
tu->timeri->ccallback = snd_timer_user_ccallback;
tu->timeri->callback_data = (void *)tu;
tu->timeri->disconnect = snd_timer_user_disconnect;
}
__err:
return err;
}
| 167,619 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcSendEvent(ClientPtr client)
{
WindowPtr pWin;
WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */
DeviceIntPtr dev = PickPointer(client);
DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD);
SpritePtr pSprite = dev->spriteInfo->sprite;
REQUEST(xSendEventReq);
REQUEST_SIZE_MATCH(xSendEventReq);
/* libXext and other extension libraries may set the bit indicating
* that this event came from a SendEvent request so remove it
* since otherwise the event type may fail the range checks
* and cause an invalid BadValue error to be returned.
*
* This is safe to do since we later add the SendEvent bit (0x80)
* back in once we send the event to the client */
stuff->event.u.u.type &= ~(SEND_EVENT_BIT);
/* The client's event type must be a core event type or one defined by an
extension. */
if (!((stuff->event.u.u.type > X_Reply &&
stuff->event.u.u.type < LASTEvent) ||
(stuff->event.u.u.type >= EXTENSION_EVENT_BASE &&
stuff->event.u.u.type < (unsigned) lastEvent))) {
client->errorValue = stuff->event.u.u.type;
return BadValue;
}
if (stuff->event.u.u.type == ClientMessage &&
stuff->event.u.u.detail != 8 &&
stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) {
}
if (stuff->destination == PointerWindow)
pWin = pSprite->win;
else if (stuff->destination == InputFocus) {
WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin;
if (inputFocus == NoneWin)
return Success;
/* If the input focus is PointerRootWin, send the event to where
the pointer is if possible, then perhaps propogate up to root. */
if (inputFocus == PointerRootWin)
inputFocus = GetCurrentRootWindow(dev);
if (IsParent(inputFocus, pSprite->win)) {
effectiveFocus = inputFocus;
pWin = pSprite->win;
}
else
effectiveFocus = pWin = inputFocus;
}
else
dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess);
if (!pWin)
return BadWindow;
if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) {
client->errorValue = stuff->propagate;
return BadValue;
}
stuff->event.u.u.type |= SEND_EVENT_BIT;
if (stuff->propagate) {
for (; pWin; pWin = pWin->parent) {
if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin,
&stuff->event, 1))
return Success;
if (DeliverEventsToWindow(dev, pWin,
&stuff->event, 1, stuff->eventMask,
NullGrab))
return Success;
if (pWin == effectiveFocus)
return Success;
stuff->eventMask &= ~wDontPropagateMask(pWin);
if (!stuff->eventMask)
break;
}
}
else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1))
DeliverEventsToWindow(dev, pWin, &stuff->event,
1, stuff->eventMask, NullGrab);
return Success;
}
Commit Message:
CWE ID: CWE-119 | ProcSendEvent(ClientPtr client)
{
WindowPtr pWin;
WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */
DeviceIntPtr dev = PickPointer(client);
DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD);
SpritePtr pSprite = dev->spriteInfo->sprite;
REQUEST(xSendEventReq);
REQUEST_SIZE_MATCH(xSendEventReq);
/* libXext and other extension libraries may set the bit indicating
* that this event came from a SendEvent request so remove it
* since otherwise the event type may fail the range checks
* and cause an invalid BadValue error to be returned.
*
* This is safe to do since we later add the SendEvent bit (0x80)
* back in once we send the event to the client */
stuff->event.u.u.type &= ~(SEND_EVENT_BIT);
/* The client's event type must be a core event type or one defined by an
extension. */
if (!((stuff->event.u.u.type > X_Reply &&
stuff->event.u.u.type < LASTEvent) ||
(stuff->event.u.u.type >= EXTENSION_EVENT_BASE &&
stuff->event.u.u.type < (unsigned) lastEvent))) {
client->errorValue = stuff->event.u.u.type;
return BadValue;
}
/* Generic events can have variable size, but SendEvent request holds
exactly 32B of event data. */
if (stuff->event.u.u.type == GenericEvent) {
client->errorValue = stuff->event.u.u.type;
return BadValue;
}
if (stuff->event.u.u.type == ClientMessage &&
stuff->event.u.u.detail != 8 &&
stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) {
}
if (stuff->destination == PointerWindow)
pWin = pSprite->win;
else if (stuff->destination == InputFocus) {
WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin;
if (inputFocus == NoneWin)
return Success;
/* If the input focus is PointerRootWin, send the event to where
the pointer is if possible, then perhaps propogate up to root. */
if (inputFocus == PointerRootWin)
inputFocus = GetCurrentRootWindow(dev);
if (IsParent(inputFocus, pSprite->win)) {
effectiveFocus = inputFocus;
pWin = pSprite->win;
}
else
effectiveFocus = pWin = inputFocus;
}
else
dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess);
if (!pWin)
return BadWindow;
if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) {
client->errorValue = stuff->propagate;
return BadValue;
}
stuff->event.u.u.type |= SEND_EVENT_BIT;
if (stuff->propagate) {
for (; pWin; pWin = pWin->parent) {
if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin,
&stuff->event, 1))
return Success;
if (DeliverEventsToWindow(dev, pWin,
&stuff->event, 1, stuff->eventMask,
NullGrab))
return Success;
if (pWin == effectiveFocus)
return Success;
stuff->eventMask &= ~wDontPropagateMask(pWin);
if (!stuff->eventMask)
break;
}
}
else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1))
DeliverEventsToWindow(dev, pWin, &stuff->event,
1, stuff->eventMask, NullGrab);
return Success;
}
| 164,764 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,212 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int32_t PepperFlashRendererHost::OnNavigate(
ppapi::host::HostMessageContext* host_context,
const ppapi::URLRequestInfoData& data,
const std::string& target,
bool from_user_action) {
content::PepperPluginInstance* plugin_instance =
host_->GetPluginInstance(pp_instance());
if (!plugin_instance)
return PP_ERROR_FAILED;
ppapi::proxy::HostDispatcher* host_dispatcher =
ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
host_dispatcher->set_allow_plugin_reentrancy();
base::WeakPtr<PepperFlashRendererHost> weak_ptr = weak_factory_.GetWeakPtr();
navigate_replies_.push_back(host_context->MakeReplyMessageContext());
plugin_instance->Navigate(data, target.c_str(), from_user_action);
if (weak_ptr.get()) {
SendReply(navigate_replies_.back(), IPC::Message());
navigate_replies_.pop_back();
}
return PP_OK_COMPLETIONPENDING;
}
Commit Message: PPB_Flash.Navigate(): Disallow certain HTTP request headers.
With this CL, PPB_Flash.Navigate() fails the operation with
PP_ERROR_NOACCESS if the request headers contain non-simple headers.
BUG=332023
TEST=None
Review URL: https://codereview.chromium.org/136393004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249114 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | int32_t PepperFlashRendererHost::OnNavigate(
ppapi::host::HostMessageContext* host_context,
const ppapi::URLRequestInfoData& data,
const std::string& target,
bool from_user_action) {
content::PepperPluginInstance* plugin_instance =
host_->GetPluginInstance(pp_instance());
if (!plugin_instance)
return PP_ERROR_FAILED;
std::map<std::string, FlashNavigateUsage>& rejected_headers =
g_rejected_headers.Get();
if (rejected_headers.empty()) {
for (size_t i = 0; i < arraysize(kRejectedHttpRequestHeaders); ++i)
rejected_headers[kRejectedHttpRequestHeaders[i]] =
static_cast<FlashNavigateUsage>(i);
}
net::HttpUtil::HeadersIterator header_iter(data.headers.begin(),
data.headers.end(),
"\n\r");
bool rejected = false;
while (header_iter.GetNext()) {
std::string lower_case_header_name = StringToLowerASCII(header_iter.name());
if (!IsSimpleHeader(lower_case_header_name, header_iter.values())) {
rejected = true;
std::map<std::string, FlashNavigateUsage>::const_iterator iter =
rejected_headers.find(lower_case_header_name);
FlashNavigateUsage usage = iter != rejected_headers.end() ?
iter->second : REJECT_OTHER_HEADERS;
RecordFlashNavigateUsage(usage);
}
}
RecordFlashNavigateUsage(TOTAL_NAVIGATE_REQUESTS);
if (rejected) {
RecordFlashNavigateUsage(TOTAL_REJECTED_NAVIGATE_REQUESTS);
return PP_ERROR_NOACCESS;
}
ppapi::proxy::HostDispatcher* host_dispatcher =
ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
host_dispatcher->set_allow_plugin_reentrancy();
base::WeakPtr<PepperFlashRendererHost> weak_ptr = weak_factory_.GetWeakPtr();
navigate_replies_.push_back(host_context->MakeReplyMessageContext());
plugin_instance->Navigate(data, target.c_str(), from_user_action);
if (weak_ptr.get()) {
SendReply(navigate_replies_.back(), IPC::Message());
navigate_replies_.pop_back();
}
return PP_OK_COMPLETIONPENDING;
}
| 171,709 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long ContentEncoding::ParseCompressionEntry(long long start, long long size,
IMkvReader* pReader,
ContentCompression* compression) {
assert(pReader);
assert(compression);
long long pos = start;
const long long stop = start + size;
bool valid = false;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x254) {
long long algo = UnserializeUInt(pReader, pos, size);
if (algo < 0)
return E_FILE_FORMAT_INVALID;
compression->algo = algo;
valid = true;
} else if (id == 0x255) {
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
compression->settings = buf;
compression->settings_len = buflen;
}
pos += size; // consume payload
assert(pos <= stop);
}
if (!valid)
return E_FILE_FORMAT_INVALID;
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 ContentEncoding::ParseCompressionEntry(long long start, long long size,
IMkvReader* pReader,
ContentCompression* compression) {
assert(pReader);
assert(compression);
long long pos = start;
const long long stop = start + size;
bool valid = false;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x254) {
long long algo = UnserializeUInt(pReader, pos, size);
if (algo < 0)
return E_FILE_FORMAT_INVALID;
compression->algo = algo;
valid = true;
} else if (id == 0x255) {
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
compression->settings = buf;
compression->settings_len = buflen;
}
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (!valid)
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,848 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ping()
{
CCMainThread::postTask(createMainThreadTask(this, &PingPongTestUsingTasks::pong));
hit = true;
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void ping()
{
m_mainThreadProxy->postTask(createMainThreadTask(this, &PingPongTestUsingTasks::pong));
hit = true;
}
| 170,298 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void InputDispatcher::enqueueDispatchEntryLocked(
const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
int32_t dispatchMode) {
int32_t inputTargetFlags = inputTarget->flags;
if (!(inputTargetFlags & dispatchMode)) {
return;
}
inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
inputTarget->scaleFactor);
switch (eventEntry->type) {
case EventEntry::TYPE_KEY: {
KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
dispatchEntry->resolvedAction = keyEntry->action;
dispatchEntry->resolvedFlags = keyEntry->flags;
if (!connection->inputState.trackKey(keyEntry,
dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
connection->getInputChannelName());
#endif
delete dispatchEntry;
return; // skip the inconsistent event
}
break;
}
case EventEntry::TYPE_MOTION: {
MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
} else {
dispatchEntry->resolvedAction = motionEntry->action;
}
if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
&& !connection->inputState.isHovering(
motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
connection->getInputChannelName());
#endif
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
}
dispatchEntry->resolvedFlags = motionEntry->flags;
if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
}
if (!connection->inputState.trackMotion(motionEntry,
dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
connection->getInputChannelName());
#endif
delete dispatchEntry;
return; // skip the inconsistent event
}
break;
}
}
if (dispatchEntry->hasForegroundTarget()) {
incrementPendingForegroundDispatchesLocked(eventEntry);
}
connection->outboundQueue.enqueueAtTail(dispatchEntry);
traceOutboundQueueLengthLocked(connection);
}
Commit Message: Add new MotionEvent flag for partially obscured windows.
Due to more complex window layouts resulting in lots of overlapping
windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to
only be set when the point at which the window was touched is
obscured. Unfortunately, this doesn't prevent tapjacking attacks that
overlay the dialog's text, making a potentially dangerous operation
seem innocuous. To avoid this on particularly sensitive dialogs,
introduce a new flag that really does tell you when your window is
being even partially overlapped.
We aren't exposing this as API since we plan on making the original
flag more robust. This is really a workaround for system dialogs
since we generally know their layout and screen position, and that
they're unlikely to be overlapped by other applications.
Bug: 26677796
Change-Id: I9e336afe90f262ba22015876769a9c510048fd47
CWE ID: CWE-264 | void InputDispatcher::enqueueDispatchEntryLocked(
const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
int32_t dispatchMode) {
int32_t inputTargetFlags = inputTarget->flags;
if (!(inputTargetFlags & dispatchMode)) {
return;
}
inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
inputTarget->scaleFactor);
switch (eventEntry->type) {
case EventEntry::TYPE_KEY: {
KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
dispatchEntry->resolvedAction = keyEntry->action;
dispatchEntry->resolvedFlags = keyEntry->flags;
if (!connection->inputState.trackKey(keyEntry,
dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
connection->getInputChannelName());
#endif
delete dispatchEntry;
return; // skip the inconsistent event
}
break;
}
case EventEntry::TYPE_MOTION: {
MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
} else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
} else {
dispatchEntry->resolvedAction = motionEntry->action;
}
if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
&& !connection->inputState.isHovering(
motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
connection->getInputChannelName());
#endif
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
}
dispatchEntry->resolvedFlags = motionEntry->flags;
if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
}
if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
}
if (!connection->inputState.trackMotion(motionEntry,
dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
#if DEBUG_DISPATCH_CYCLE
ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
connection->getInputChannelName());
#endif
delete dispatchEntry;
return; // skip the inconsistent event
}
break;
}
}
if (dispatchEntry->hasForegroundTarget()) {
incrementPendingForegroundDispatchesLocked(eventEntry);
}
connection->outboundQueue.enqueueAtTail(dispatchEntry);
traceOutboundQueueLengthLocked(connection);
}
| 174,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et;
struct extent_node *en;
struct extent_info ei;
if (!f2fs_may_extent_tree(inode)) {
/* drop largest extent */
if (i_ext && i_ext->len) {
i_ext->len = 0;
return true;
}
return false;
}
et = __grab_extent_tree(inode);
if (!i_ext || !i_ext->len)
return false;
get_extent_info(&ei, i_ext);
write_lock(&et->lock);
if (atomic_read(&et->node_cnt))
goto out;
en = __init_extent_tree(sbi, et, &ei);
if (en) {
spin_lock(&sbi->extent_lock);
list_add_tail(&en->list, &sbi->extent_list);
spin_unlock(&sbi->extent_lock);
}
out:
write_unlock(&et->lock);
return false;
}
Commit Message: f2fs: fix a bug caused by NULL extent tree
Thread A: Thread B:
-f2fs_remount
-sbi->mount_opt.opt = 0;
<--- -f2fs_iget
-do_read_inode
-f2fs_init_extent_tree
-F2FS_I(inode)->extent_tree is NULL
-default_options && parse_options
-remount return
<--- -f2fs_map_blocks
-f2fs_lookup_extent_tree
-f2fs_bug_on(sbi, !et);
The same problem with f2fs_new_inode.
Signed-off-by: Yunlei He <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: CWE-119 | bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext)
static bool __f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et;
struct extent_node *en;
struct extent_info ei;
if (!f2fs_may_extent_tree(inode)) {
/* drop largest extent */
if (i_ext && i_ext->len) {
i_ext->len = 0;
return true;
}
return false;
}
et = __grab_extent_tree(inode);
if (!i_ext || !i_ext->len)
return false;
get_extent_info(&ei, i_ext);
write_lock(&et->lock);
if (atomic_read(&et->node_cnt))
goto out;
en = __init_extent_tree(sbi, et, &ei);
if (en) {
spin_lock(&sbi->extent_lock);
list_add_tail(&en->list, &sbi->extent_list);
spin_unlock(&sbi->extent_lock);
}
out:
write_unlock(&et->lock);
return false;
}
| 169,416 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
pthread_mutex_lock(&slot_lock);
rfc_slot_t *slot = find_rfc_slot_by_id(user_id);
if (!slot)
goto out;
bool need_close = false;
if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
if (slot->f.connected) {
int size = 0;
if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size))
pthread_mutex_unlock(&slot_lock);
BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
} else {
LOG_ERROR("%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (flags & SOCK_THREAD_FD_WR) {
if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
LOG_ERROR("%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
int size = 0;
if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size)
cleanup_rfc_slot(slot);
}
out:;
pthread_mutex_unlock(&slot_lock);
}
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 btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
pthread_mutex_lock(&slot_lock);
rfc_slot_t *slot = find_rfc_slot_by_id(user_id);
if (!slot)
goto out;
bool need_close = false;
if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
if (slot->f.connected) {
int size = 0;
if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (TEMP_FAILURE_RETRY(ioctl(slot->fd, FIONREAD, &size)) == 0 && size)) {
BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
}
} else {
LOG_ERROR("%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (flags & SOCK_THREAD_FD_WR) {
if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
LOG_ERROR("%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
int size = 0;
if (need_close || TEMP_FAILURE_RETRY(ioctl(slot->fd, FIONREAD, &size)) != 0 || !size)
cleanup_rfc_slot(slot);
}
out:;
pthread_mutex_unlock(&slot_lock);
}
| 173,457 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void BooleanOrNullAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "booleanOrNullAttribute");
bool cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(info.GetIsolate(), v8_value, exception_state);
if (exception_state.HadException())
return;
bool is_null = IsUndefinedOrNull(v8_value);
impl->setBooleanOrNullAttribute(cpp_value, is_null);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID: | static void BooleanOrNullAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "booleanOrNullAttribute");
bool is_null = IsUndefinedOrNull(v8_value);
bool cpp_value = is_null ? bool() : NativeValueTraits<IDLBoolean>::NativeValue(info.GetIsolate(), v8_value, exception_state);
if (exception_state.HadException())
return;
impl->setBooleanOrNullAttribute(cpp_value, is_null);
}
| 172,304 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct page *follow_page_pte(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd, unsigned int flags,
struct dev_pagemap **pgmap)
{
struct mm_struct *mm = vma->vm_mm;
struct page *page;
spinlock_t *ptl;
pte_t *ptep, pte;
retry:
if (unlikely(pmd_bad(*pmd)))
return no_page_table(vma, flags);
ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
pte = *ptep;
if (!pte_present(pte)) {
swp_entry_t entry;
/*
* KSM's break_ksm() relies upon recognizing a ksm page
* even while it is being migrated, so for that case we
* need migration_entry_wait().
*/
if (likely(!(flags & FOLL_MIGRATION)))
goto no_page;
if (pte_none(pte))
goto no_page;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto no_page;
pte_unmap_unlock(ptep, ptl);
migration_entry_wait(mm, pmd, address);
goto retry;
}
if ((flags & FOLL_NUMA) && pte_protnone(pte))
goto no_page;
if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
pte_unmap_unlock(ptep, ptl);
return NULL;
}
page = vm_normal_page(vma, address, pte);
if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
/*
* Only return device mapping pages in the FOLL_GET case since
* they are only valid while holding the pgmap reference.
*/
*pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
if (*pgmap)
page = pte_page(pte);
else
goto no_page;
} else if (unlikely(!page)) {
if (flags & FOLL_DUMP) {
/* Avoid special (like zero) pages in core dumps */
page = ERR_PTR(-EFAULT);
goto out;
}
if (is_zero_pfn(pte_pfn(pte))) {
page = pte_page(pte);
} else {
int ret;
ret = follow_pfn_pte(vma, address, ptep, flags);
page = ERR_PTR(ret);
goto out;
}
}
if (flags & FOLL_SPLIT && PageTransCompound(page)) {
int ret;
get_page(page);
pte_unmap_unlock(ptep, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return ERR_PTR(ret);
goto retry;
}
if (flags & FOLL_GET)
get_page(page);
if (flags & FOLL_TOUCH) {
if ((flags & FOLL_WRITE) &&
!pte_dirty(pte) && !PageDirty(page))
set_page_dirty(page);
/*
* pte_mkyoung() would be more correct here, but atomic care
* is needed to avoid losing the dirty bit: it is easier to use
* mark_page_accessed().
*/
mark_page_accessed(page);
}
if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
/* Do not mlock pte-mapped THP */
if (PageTransCompound(page))
goto out;
/*
* The preliminary mapping check is mainly to avoid the
* pointless overhead of lock_page on the ZERO_PAGE
* which might bounce very badly if there is contention.
*
* If the page is already locked, we don't need to
* handle it now - vmscan will handle it later if and
* when it attempts to reclaim the page.
*/
if (page->mapping && trylock_page(page)) {
lru_add_drain(); /* push cached pages to LRU */
/*
* Because we lock page here, and migration is
* blocked by the pte's page reference, and we
* know the page is still mapped, we don't even
* need to check for file-cache page truncation.
*/
mlock_vma_page(page);
unlock_page(page);
}
}
out:
pte_unmap_unlock(ptep, ptl);
return page;
no_page:
pte_unmap_unlock(ptep, ptl);
if (!pte_none(pte))
return NULL;
return no_page_table(vma, flags);
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static struct page *follow_page_pte(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd, unsigned int flags,
struct dev_pagemap **pgmap)
{
struct mm_struct *mm = vma->vm_mm;
struct page *page;
spinlock_t *ptl;
pte_t *ptep, pte;
retry:
if (unlikely(pmd_bad(*pmd)))
return no_page_table(vma, flags);
ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
pte = *ptep;
if (!pte_present(pte)) {
swp_entry_t entry;
/*
* KSM's break_ksm() relies upon recognizing a ksm page
* even while it is being migrated, so for that case we
* need migration_entry_wait().
*/
if (likely(!(flags & FOLL_MIGRATION)))
goto no_page;
if (pte_none(pte))
goto no_page;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto no_page;
pte_unmap_unlock(ptep, ptl);
migration_entry_wait(mm, pmd, address);
goto retry;
}
if ((flags & FOLL_NUMA) && pte_protnone(pte))
goto no_page;
if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
pte_unmap_unlock(ptep, ptl);
return NULL;
}
page = vm_normal_page(vma, address, pte);
if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
/*
* Only return device mapping pages in the FOLL_GET case since
* they are only valid while holding the pgmap reference.
*/
*pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
if (*pgmap)
page = pte_page(pte);
else
goto no_page;
} else if (unlikely(!page)) {
if (flags & FOLL_DUMP) {
/* Avoid special (like zero) pages in core dumps */
page = ERR_PTR(-EFAULT);
goto out;
}
if (is_zero_pfn(pte_pfn(pte))) {
page = pte_page(pte);
} else {
int ret;
ret = follow_pfn_pte(vma, address, ptep, flags);
page = ERR_PTR(ret);
goto out;
}
}
if (flags & FOLL_SPLIT && PageTransCompound(page)) {
int ret;
get_page(page);
pte_unmap_unlock(ptep, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return ERR_PTR(ret);
goto retry;
}
if (flags & FOLL_GET) {
if (unlikely(!try_get_page(page))) {
page = ERR_PTR(-ENOMEM);
goto out;
}
}
if (flags & FOLL_TOUCH) {
if ((flags & FOLL_WRITE) &&
!pte_dirty(pte) && !PageDirty(page))
set_page_dirty(page);
/*
* pte_mkyoung() would be more correct here, but atomic care
* is needed to avoid losing the dirty bit: it is easier to use
* mark_page_accessed().
*/
mark_page_accessed(page);
}
if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
/* Do not mlock pte-mapped THP */
if (PageTransCompound(page))
goto out;
/*
* The preliminary mapping check is mainly to avoid the
* pointless overhead of lock_page on the ZERO_PAGE
* which might bounce very badly if there is contention.
*
* If the page is already locked, we don't need to
* handle it now - vmscan will handle it later if and
* when it attempts to reclaim the page.
*/
if (page->mapping && trylock_page(page)) {
lru_add_drain(); /* push cached pages to LRU */
/*
* Because we lock page here, and migration is
* blocked by the pte's page reference, and we
* know the page is still mapped, we don't even
* need to check for file-cache page truncation.
*/
mlock_vma_page(page);
unlock_page(page);
}
}
out:
pte_unmap_unlock(ptep, ptl);
return page;
no_page:
pte_unmap_unlock(ptep, ptl);
if (!pte_none(pte))
return NULL;
return no_page_table(vma, flags);
}
| 170,222 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestActiveDOMObjectPrototypeFunctionPostMessage(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestActiveDOMObject::s_info))
return throwVMTypeError(exec);
JSTestActiveDOMObject* castedThis = jsCast<JSTestActiveDOMObject*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestActiveDOMObject::s_info);
TestActiveDOMObject* impl = static_cast<TestActiveDOMObject*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
const String& message(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->postMessage(message);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestActiveDOMObjectPrototypeFunctionPostMessage(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestActiveDOMObject::s_info))
return throwVMTypeError(exec);
JSTestActiveDOMObject* castedThis = jsCast<JSTestActiveDOMObject*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestActiveDOMObject::s_info);
TestActiveDOMObject* impl = static_cast<TestActiveDOMObject*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
const String& message(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->postMessage(message);
return JSValue::encode(jsUndefined());
}
| 170,568 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int dev_get_valid_name(struct net *net,
struct net_device *dev,
const char *name)
{
BUG_ON(!net);
if (!dev_valid_name(name))
return -EINVAL;
if (strchr(name, '%'))
return dev_alloc_name_ns(net, dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
Commit Message: tun: call dev_get_valid_name() before register_netdevice()
register_netdevice() could fail early when we have an invalid
dev name, in which case ->ndo_uninit() is not called. For tun
device, this is a problem because a timer etc. are already
initialized and it expects ->ndo_uninit() to clean them up.
We could move these initializations into a ->ndo_init() so
that register_netdevice() knows better, however this is still
complicated due to the logic in tun_detach().
Therefore, I choose to just call dev_get_valid_name() before
register_netdevice(), which is quicker and much easier to audit.
And for this specific case, it is already enough.
Fixes: 96442e42429e ("tuntap: choose the txq based on rxq")
Reported-by: Dmitry Alexeev <[email protected]>
Cc: Jason Wang <[email protected]>
Cc: "Michael S. Tsirkin" <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | static int dev_get_valid_name(struct net *net,
int dev_get_valid_name(struct net *net, struct net_device *dev,
const char *name)
{
BUG_ON(!net);
if (!dev_valid_name(name))
return -EINVAL;
if (strchr(name, '%'))
return dev_alloc_name_ns(net, dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
| 169,855 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CreateFusionSensor(
std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm) {
auto callback =
base::Bind(&PlatformSensorFusionTest::PlatformSensorFusionCallback,
base::Unretained(this));
SensorType type = fusion_algorithm->fused_type();
PlatformSensorFusion::Create(provider_->GetMapping(type), provider_.get(),
std::move(fusion_algorithm), callback);
EXPECT_TRUE(platform_sensor_fusion_callback_called_);
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732 | void CreateFusionSensor(
std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm) {
auto callback =
base::Bind(&PlatformSensorFusionTest::PlatformSensorFusionCallback,
base::Unretained(this));
SensorType type = fusion_algorithm->fused_type();
PlatformSensorFusion::Create(provider_->GetSensorReadingBuffer(type),
provider_.get(), std::move(fusion_algorithm),
callback);
EXPECT_TRUE(platform_sensor_fusion_callback_called_);
}
| 172,832 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChildProcessSecurityPolicyImpl::CanCommitURL(int child_id,
const GURL& url) {
if (!url.is_valid())
return false; // Can't commit invalid URLs.
const std::string& scheme = url.scheme();
if (IsPseudoScheme(scheme))
return url == url::kAboutBlankURL || url == kAboutSrcDocURL;
if (url.SchemeIsBlob() || url.SchemeIsFileSystem()) {
if (IsMalformedBlobUrl(url))
return false;
url::Origin origin = url::Origin::Create(url);
return origin.unique() || CanCommitURL(child_id, GURL(origin.Serialize()));
}
{
base::AutoLock lock(lock_);
if (base::ContainsKey(schemes_okay_to_commit_in_any_process_, scheme))
return true;
SecurityStateMap::iterator state = security_state_.find(child_id);
if (state == security_state_.end())
return false;
return state->second->CanCommitURL(url);
}
}
Commit Message: Lock down blob/filesystem URL creation with a stronger CPSP::CanCommitURL()
ChildProcessSecurityPolicy::CanCommitURL() is a security check that's
supposed to tell whether a given renderer process is allowed to commit
a given URL. It is currently used to validate (1) blob and filesystem
URL creation, and (2) Origin headers. Currently, it has scheme-based
checks that disallow things like web renderers creating
blob/filesystem URLs in chrome-extension: origins, but it cannot stop
one web origin from creating those URLs for another origin.
This CL locks down its use for (1) to also consult
CanAccessDataForOrigin(). With site isolation, this will check origin
locks and ensure that foo.com cannot create blob/filesystem URLs for
other origins.
For now, this CL does not provide the same enforcements for (2),
Origin header validation, which has additional constraints that need
to be solved first (see https://crbug.com/515309).
Bug: 886976, 888001
Change-Id: I743ef05469e4000b2c0bee840022162600cc237f
Reviewed-on: https://chromium-review.googlesource.com/1235343
Commit-Queue: Alex Moshchuk <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#594914}
CWE ID: | bool ChildProcessSecurityPolicyImpl::CanCommitURL(int child_id,
const GURL& url,
bool check_origin_locks) {
if (!url.is_valid())
return false; // Can't commit invalid URLs.
const std::string& scheme = url.scheme();
if (IsPseudoScheme(scheme))
return url == url::kAboutBlankURL || url == kAboutSrcDocURL;
if (url.SchemeIsBlob() || url.SchemeIsFileSystem()) {
if (IsMalformedBlobUrl(url))
return false;
url::Origin origin = url::Origin::Create(url);
return origin.unique() ||
CanCommitURL(child_id, GURL(origin.Serialize()), check_origin_locks);
}
// With site isolation, a URL from a site may only be committed in a process
// dedicated to that site. This check will ensure that |url| can't commit if
// the process is locked to a different site. Note that this check is only
// effective for processes that are locked to a site, but even with strict
// site isolation, currently not all processes are locked (e.g., extensions
// or <webview> tags - see ShouldLockToOrigin()).
if (check_origin_locks && !CanAccessDataForOrigin(child_id, url))
return false;
{
base::AutoLock lock(lock_);
// TODO(creis, nick): https://crbug.com/515309: The line below does not
if (base::ContainsKey(schemes_okay_to_commit_in_any_process_, scheme))
return true;
SecurityStateMap::iterator state = security_state_.find(child_id);
if (state == security_state_.end())
return false;
return state->second->CanCommitURL(url);
}
}
| 172,610 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXLayoutObject::supportsARIADragging() const {
const AtomicString& grabbed = getAttribute(aria_grabbedAttr);
return equalIgnoringCase(grabbed, "true") ||
equalIgnoringCase(grabbed, "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 AXLayoutObject::supportsARIADragging() const {
const AtomicString& grabbed = getAttribute(aria_grabbedAttr);
return equalIgnoringASCIICase(grabbed, "true") ||
equalIgnoringASCIICase(grabbed, "false");
}
| 171,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: produce_output()
{
char *str;
FILE *mailer;
MyString subject,szTmp;
subject.sprintf("condor_preen results %s: %d old file%s found",
my_full_hostname(), BadFiles->number(),
(BadFiles->number() > 1)?"s":"");
if( MailFlag ) {
if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) {
EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value());
}
} else {
mailer = stdout;
}
szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value());
dprintf(D_ALWAYS, szTmp.Value());
if( MailFlag ) {
fprintf( mailer, "\n" );
fprintf( mailer, szTmp.Value());
}
for( BadFiles->rewind(); (str = BadFiles->next()); ) {
szTmp.sprintf(" %s\n", str);
dprintf(D_ALWAYS, szTmp.Value() );
fprintf( mailer, szTmp.Value() );
}
if( MailFlag ) {
const char *explanation = "\n\nWhat is condor_preen?\n\n"
"The condor_preen tool examines the directories belonging to Condor, and\n"
"removes extraneous files and directories which may be left over from Condor\n"
"processes which terminated abnormally either due to internal errors or a\n"
"system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n"
"directories as defined in the Condor configuration files. The condor_preen\n"
"tool is intended to be run as user root (or user condor) periodically as a\n"
"backup method to ensure reasonable file system cleanliness in the face of\n"
"errors. This is done automatically by default by the condor_master daemon.\n"
"It may also be explicitly invoked on an as needed basis.\n\n"
"See the Condor manual section on condor_preen for more details.\n";
fprintf( mailer, "%s\n", explanation );
email_close( mailer );
}
}
Commit Message:
CWE ID: CWE-134 | produce_output()
{
char *str;
FILE *mailer;
MyString subject,szTmp;
subject.sprintf("condor_preen results %s: %d old file%s found",
my_full_hostname(), BadFiles->number(),
(BadFiles->number() > 1)?"s":"");
if( MailFlag ) {
if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) {
EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value());
}
} else {
mailer = stdout;
}
szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value());
dprintf(D_ALWAYS, "%s", szTmp.Value());
if( MailFlag ) {
fprintf( mailer, "\n" );
fprintf( mailer, "%s", szTmp.Value());
}
for( BadFiles->rewind(); (str = BadFiles->next()); ) {
szTmp.sprintf(" %s\n", str);
dprintf(D_ALWAYS, "%s", szTmp.Value() );
fprintf( mailer, "%s", szTmp.Value() );
}
if( MailFlag ) {
const char *explanation = "\n\nWhat is condor_preen?\n\n"
"The condor_preen tool examines the directories belonging to Condor, and\n"
"removes extraneous files and directories which may be left over from Condor\n"
"processes which terminated abnormally either due to internal errors or a\n"
"system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n"
"directories as defined in the Condor configuration files. The condor_preen\n"
"tool is intended to be run as user root (or user condor) periodically as a\n"
"backup method to ensure reasonable file system cleanliness in the face of\n"
"errors. This is done automatically by default by the condor_master daemon.\n"
"It may also be explicitly invoked on an as needed basis.\n\n"
"See the Condor manual section on condor_preen for more details.\n";
fprintf( mailer, "%s\n", explanation );
email_close( mailer );
}
}
| 165,381 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->partitioned_frame = 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
Commit Message: avcodec/mpeg4videodec: Clear interlaced_dct for studio profile
Fixes: Out of array access
Fixes: 13090/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5408668986638336
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Reviewed-by: Kieran Kunhya <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->partitioned_frame = 0;
s->interlaced_dct = 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
| 170,232 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DictionaryValue* NigoriSpecificsToValue(
const sync_pb::NigoriSpecifics& proto) {
DictionaryValue* value = new DictionaryValue();
SET(encrypted, EncryptedDataToValue);
SET_BOOL(using_explicit_passphrase);
SET_BOOL(encrypt_bookmarks);
SET_BOOL(encrypt_preferences);
SET_BOOL(encrypt_autofill_profile);
SET_BOOL(encrypt_autofill);
SET_BOOL(encrypt_themes);
SET_BOOL(encrypt_typed_urls);
SET_BOOL(encrypt_extension_settings);
SET_BOOL(encrypt_extensions);
SET_BOOL(encrypt_sessions);
SET_BOOL(encrypt_app_settings);
SET_BOOL(encrypt_apps);
SET_BOOL(encrypt_search_engines);
SET_BOOL(sync_tabs);
SET_BOOL(encrypt_everything);
SET_REP(device_information, DeviceInformationToValue);
SET_BOOL(sync_tab_favicons);
return value;
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | DictionaryValue* NigoriSpecificsToValue(
const sync_pb::NigoriSpecifics& proto) {
DictionaryValue* value = new DictionaryValue();
SET(encrypted, EncryptedDataToValue);
SET_BOOL(using_explicit_passphrase);
SET_BOOL(encrypt_bookmarks);
SET_BOOL(encrypt_preferences);
SET_BOOL(encrypt_autofill_profile);
SET_BOOL(encrypt_autofill);
SET_BOOL(encrypt_themes);
SET_BOOL(encrypt_typed_urls);
SET_BOOL(encrypt_extension_settings);
SET_BOOL(encrypt_extensions);
SET_BOOL(encrypt_sessions);
SET_BOOL(encrypt_app_settings);
SET_BOOL(encrypt_apps);
SET_BOOL(encrypt_search_engines);
SET_BOOL(encrypt_everything);
SET_REP(device_information, DeviceInformationToValue);
SET_BOOL(sync_tab_favicons);
return value;
}
| 170,800 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int link_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, i = 0, nbuf;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
/*
* If we have iterated all input buffers or ran out of
* output room, break.
*/
if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
break;
ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
obuf = opipe->bufs + nbuf;
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
if (obuf->len > len)
obuf->len = len;
opipe->nrbufs++;
ret += obuf->len;
len -= obuf->len;
i++;
} while (len);
/*
* return EAGAIN if we have the potential of some data in the
* future, otherwise just return 0
*/
if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
ret = -EAGAIN;
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
return ret;
}
Commit Message: fs: prevent page refcount overflow in pipe_buf_get
Change pipe_buf_get() to return a bool indicating whether it succeeded
in raising the refcount of the page (if the thing in the pipe is a page).
This removes another mechanism for overflowing the page refcount. All
callers converted to handle a failure.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Matthew Wilcox <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416 | static int link_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, i = 0, nbuf;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
/*
* If we have iterated all input buffers or ran out of
* output room, break.
*/
if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
break;
ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
if (!pipe_buf_get(ipipe, ibuf)) {
if (ret == 0)
ret = -EFAULT;
break;
}
obuf = opipe->bufs + nbuf;
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
if (obuf->len > len)
obuf->len = len;
opipe->nrbufs++;
ret += obuf->len;
len -= obuf->len;
i++;
} while (len);
/*
* return EAGAIN if we have the potential of some data in the
* future, otherwise just return 0
*/
if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
ret = -EAGAIN;
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
return ret;
}
| 170,230 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PaymentRequest::Init(mojom::PaymentRequestClientPtr client,
std::vector<mojom::PaymentMethodDataPtr> method_data,
mojom::PaymentDetailsPtr details,
mojom::PaymentOptionsPtr options) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
client_ = std::move(client);
const GURL last_committed_url = delegate_->GetLastCommittedURL();
if (!OriginSecurityChecker::IsOriginSecure(last_committed_url)) {
LOG(ERROR) << "Not in a secure origin";
OnConnectionTerminated();
return;
}
bool allowed_origin =
OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) ||
OriginSecurityChecker::IsOriginLocalhostOrFile(last_committed_url);
if (!allowed_origin) {
LOG(ERROR) << "Only localhost, file://, and cryptographic scheme origins "
"allowed";
}
bool invalid_ssl =
OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) &&
!delegate_->IsSslCertificateValid();
if (invalid_ssl)
LOG(ERROR) << "SSL certificate is not valid";
if (!allowed_origin || invalid_ssl) {
return;
}
std::string error;
if (!ValidatePaymentDetails(ConvertPaymentDetails(details), &error)) {
LOG(ERROR) << error;
OnConnectionTerminated();
return;
}
if (!details->total) {
LOG(ERROR) << "Missing total";
OnConnectionTerminated();
return;
}
spec_ = std::make_unique<PaymentRequestSpec>(
std::move(options), std::move(details), std::move(method_data), this,
delegate_->GetApplicationLocale());
state_ = std::make_unique<PaymentRequestState>(
web_contents_, top_level_origin_, frame_origin_, spec_.get(), this,
delegate_->GetApplicationLocale(), delegate_->GetPersonalDataManager(),
delegate_.get(), &journey_logger_);
journey_logger_.SetRequestedInformation(
spec_->request_shipping(), spec_->request_payer_email(),
spec_->request_payer_phone(), spec_->request_payer_name());
GURL google_pay_url(kGooglePayMethodName);
GURL android_pay_url(kAndroidPayMethodName);
auto non_google_it =
std::find_if(spec_->url_payment_method_identifiers().begin(),
spec_->url_payment_method_identifiers().end(),
[google_pay_url, android_pay_url](const GURL& url) {
return url != google_pay_url && url != android_pay_url;
});
journey_logger_.SetRequestedPaymentMethodTypes(
/*requested_basic_card=*/!spec_->supported_card_networks().empty(),
/*requested_method_google=*/
base::ContainsValue(spec_->url_payment_method_identifiers(),
google_pay_url) ||
base::ContainsValue(spec_->url_payment_method_identifiers(),
android_pay_url),
/*requested_method_other=*/non_google_it !=
spec_->url_payment_method_identifiers().end());
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189 | void PaymentRequest::Init(mojom::PaymentRequestClientPtr client,
std::vector<mojom::PaymentMethodDataPtr> method_data,
mojom::PaymentDetailsPtr details,
mojom::PaymentOptionsPtr options) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (is_initialized_) {
log_.Error("Attempted initialization twice");
OnConnectionTerminated();
return;
}
is_initialized_ = true;
client_ = std::move(client);
const GURL last_committed_url = delegate_->GetLastCommittedURL();
if (!OriginSecurityChecker::IsOriginSecure(last_committed_url)) {
log_.Error("Not in a secure origin");
OnConnectionTerminated();
return;
}
bool allowed_origin =
OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) ||
OriginSecurityChecker::IsOriginLocalhostOrFile(last_committed_url);
if (!allowed_origin) {
log_.Error(
"Only localhost, file://, and cryptographic scheme origins allowed");
}
bool invalid_ssl =
OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) &&
!delegate_->IsSslCertificateValid();
if (invalid_ssl) {
log_.Error("SSL certificate is not valid.");
}
if (!allowed_origin || invalid_ssl) {
// Intentionally don't set |spec_| and |state_|, so the UI is never shown.
log_.Error(
"No UI will be shown. CanMakePayment will always return false. "
"Show will be rejected with NotSupportedError.");
return;
}
std::string error;
if (!ValidatePaymentDetails(ConvertPaymentDetails(details), &error)) {
log_.Error(error);
OnConnectionTerminated();
return;
}
if (!details->total) {
log_.Error("Missing total");
OnConnectionTerminated();
return;
}
spec_ = std::make_unique<PaymentRequestSpec>(
std::move(options), std::move(details), std::move(method_data), this,
delegate_->GetApplicationLocale());
state_ = std::make_unique<PaymentRequestState>(
web_contents_, top_level_origin_, frame_origin_, spec_.get(), this,
delegate_->GetApplicationLocale(), delegate_->GetPersonalDataManager(),
delegate_.get(), &journey_logger_);
journey_logger_.SetRequestedInformation(
spec_->request_shipping(), spec_->request_payer_email(),
spec_->request_payer_phone(), spec_->request_payer_name());
GURL google_pay_url(kGooglePayMethodName);
GURL android_pay_url(kAndroidPayMethodName);
auto non_google_it =
std::find_if(spec_->url_payment_method_identifiers().begin(),
spec_->url_payment_method_identifiers().end(),
[google_pay_url, android_pay_url](const GURL& url) {
return url != google_pay_url && url != android_pay_url;
});
journey_logger_.SetRequestedPaymentMethodTypes(
/*requested_basic_card=*/!spec_->supported_card_networks().empty(),
/*requested_method_google=*/
base::ContainsValue(spec_->url_payment_method_identifiers(),
google_pay_url) ||
base::ContainsValue(spec_->url_payment_method_identifiers(),
android_pay_url),
/*requested_method_other=*/non_google_it !=
spec_->url_payment_method_identifiers().end());
}
| 173,082 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport MagickBooleanType AnnotateImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
char
*p,
primitive[MagickPathExtent],
*text,
**textlist;
DrawInfo
*annotate,
*annotate_info;
GeometryInfo
geometry_info;
MagickBooleanType
status;
PointInfo
offset;
RectangleInfo
geometry;
register ssize_t
i;
TypeMetric
metrics;
size_t
height,
number_lines;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->text == (char *) NULL)
return(MagickFalse);
if (*draw_info->text == '\0')
return(MagickTrue);
annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
text=annotate->text;
annotate->text=(char *) NULL;
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
number_lines=1;
for (p=text; *p != '\0'; p++)
if (*p == '\n')
number_lines++;
textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist));
if (textlist == (char **) NULL)
return(MagickFalse);
p=text;
for (i=0; i < number_lines; i++)
{
char
*q;
textlist[i]=p;
for (q=p; *q != '\0'; q++)
if ((*q == '\r') || (*q == '\n'))
break;
if (*q == '\r')
{
*q='\0';
q++;
}
*q='\0';
p=q+1;
}
textlist[i]=(char *) NULL;
SetGeometry(image,&geometry);
SetGeometryInfo(&geometry_info);
if (annotate_info->geometry != (char *) NULL)
{
(void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
exception);
(void) ParseGeometry(annotate_info->geometry,&geometry_info);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics,exception);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+
annotate_info->affine.ry*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-
annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-
annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.alpha != TransparentAlpha)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MagickPathExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info,exception);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics,exception);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1589
CWE ID: CWE-399 | MagickExport MagickBooleanType AnnotateImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
char
*p,
primitive[MagickPathExtent],
*text,
**textlist;
DrawInfo
*annotate,
*annotate_info;
GeometryInfo
geometry_info;
MagickBooleanType
status;
PointInfo
offset;
RectangleInfo
geometry;
register ssize_t
i;
TypeMetric
metrics;
size_t
height,
number_lines;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->text == (char *) NULL)
return(MagickFalse);
if (*draw_info->text == '\0')
return(MagickTrue);
annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
text=annotate->text;
annotate->text=(char *) NULL;
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
number_lines=1;
for (p=text; *p != '\0'; p++)
if (*p == '\n')
number_lines++;
textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist));
if (textlist == (char **) NULL)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
return(MagickFalse);
}
p=text;
for (i=0; i < number_lines; i++)
{
char
*q;
textlist[i]=p;
for (q=p; *q != '\0'; q++)
if ((*q == '\r') || (*q == '\n'))
break;
if (*q == '\r')
{
*q='\0';
q++;
}
*q='\0';
p=q+1;
}
textlist[i]=(char *) NULL;
SetGeometry(image,&geometry);
SetGeometryInfo(&geometry_info);
if (annotate_info->geometry != (char *) NULL)
{
(void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
exception);
(void) ParseGeometry(annotate_info->geometry,&geometry_info);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(MagickFalse);
}
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics,exception);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+
annotate_info->affine.ry*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-
annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-
annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.alpha != TransparentAlpha)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MagickPathExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info,exception);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics,exception);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
}
| 169,600 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcXFixesSetCursorName(ClientPtr client)
{
CursorPtr pCursor;
char *tchar;
REQUEST(xXFixesSetCursorNameReq);
REQUEST(xXFixesSetCursorNameReq);
Atom atom;
REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq);
VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess);
tchar = (char *) &stuff[1];
atom = MakeAtom(tchar, stuff->nbytes, TRUE);
return BadAlloc;
pCursor->name = atom;
return Success;
}
Commit Message:
CWE ID: CWE-20 | ProcXFixesSetCursorName(ClientPtr client)
{
CursorPtr pCursor;
char *tchar;
REQUEST(xXFixesSetCursorNameReq);
REQUEST(xXFixesSetCursorNameReq);
Atom atom;
REQUEST_FIXED_SIZE(xXFixesSetCursorNameReq, stuff->nbytes);
VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess);
tchar = (char *) &stuff[1];
atom = MakeAtom(tchar, stuff->nbytes, TRUE);
return BadAlloc;
pCursor->name = atom;
return Success;
}
| 165,439 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Chapters::Display::Display()
{
}
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 | Chapters::Display::Display()
| 174,263 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct perf_event *event = file->private_data;
void (*func)(struct perf_event *);
u32 flags = arg;
switch (cmd) {
case PERF_EVENT_IOC_ENABLE:
func = perf_event_enable;
break;
case PERF_EVENT_IOC_DISABLE:
func = perf_event_disable;
break;
case PERF_EVENT_IOC_RESET:
func = perf_event_reset;
break;
case PERF_EVENT_IOC_REFRESH:
return perf_event_refresh(event, arg);
case PERF_EVENT_IOC_PERIOD:
return perf_event_period(event, (u64 __user *)arg);
case PERF_EVENT_IOC_ID:
{
u64 id = primary_event_id(event);
if (copy_to_user((void __user *)arg, &id, sizeof(id)))
return -EFAULT;
return 0;
}
case PERF_EVENT_IOC_SET_OUTPUT:
{
int ret;
if (arg != -1) {
struct perf_event *output_event;
struct fd output;
ret = perf_fget_light(arg, &output);
if (ret)
return ret;
output_event = output.file->private_data;
ret = perf_event_set_output(event, output_event);
fdput(output);
} else {
ret = perf_event_set_output(event, NULL);
}
return ret;
}
case PERF_EVENT_IOC_SET_FILTER:
return perf_event_set_filter(event, (void __user *)arg);
default:
return -ENOTTY;
}
if (flags & PERF_IOC_FLAG_GROUP)
perf_event_for_each(event, func);
else
perf_event_for_each_child(event, func);
return 0;
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
{
void (*func)(struct perf_event *);
u32 flags = arg;
switch (cmd) {
case PERF_EVENT_IOC_ENABLE:
func = _perf_event_enable;
break;
case PERF_EVENT_IOC_DISABLE:
func = _perf_event_disable;
break;
case PERF_EVENT_IOC_RESET:
func = _perf_event_reset;
break;
case PERF_EVENT_IOC_REFRESH:
return _perf_event_refresh(event, arg);
case PERF_EVENT_IOC_PERIOD:
return perf_event_period(event, (u64 __user *)arg);
case PERF_EVENT_IOC_ID:
{
u64 id = primary_event_id(event);
if (copy_to_user((void __user *)arg, &id, sizeof(id)))
return -EFAULT;
return 0;
}
case PERF_EVENT_IOC_SET_OUTPUT:
{
int ret;
if (arg != -1) {
struct perf_event *output_event;
struct fd output;
ret = perf_fget_light(arg, &output);
if (ret)
return ret;
output_event = output.file->private_data;
ret = perf_event_set_output(event, output_event);
fdput(output);
} else {
ret = perf_event_set_output(event, NULL);
}
return ret;
}
case PERF_EVENT_IOC_SET_FILTER:
return perf_event_set_filter(event, (void __user *)arg);
default:
return -ENOTTY;
}
if (flags & PERF_IOC_FLAG_GROUP)
perf_event_for_each(event, func);
else
perf_event_for_each_child(event, func);
return 0;
}
| 166,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: brcmf_cfg80211_start_ap(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_ap_settings *settings)
{
s32 ie_offset;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
const struct brcmf_tlv *ssid_ie;
const struct brcmf_tlv *country_ie;
struct brcmf_ssid_le ssid_le;
s32 err = -EPERM;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
struct brcmf_join_params join_params;
enum nl80211_iftype dev_role;
struct brcmf_fil_bss_enable_le bss_enable;
u16 chanspec = chandef_to_chanspec(&cfg->d11inf, &settings->chandef);
bool mbss;
int is_11d;
brcmf_dbg(TRACE, "ctrlchn=%d, center=%d, bw=%d, beacon_interval=%d, dtim_period=%d,\n",
settings->chandef.chan->hw_value,
settings->chandef.center_freq1, settings->chandef.width,
settings->beacon_interval, settings->dtim_period);
brcmf_dbg(TRACE, "ssid=%s(%zu), auth_type=%d, inactivity_timeout=%d\n",
settings->ssid, settings->ssid_len, settings->auth_type,
settings->inactivity_timeout);
dev_role = ifp->vif->wdev.iftype;
mbss = ifp->vif->mbss;
/* store current 11d setting */
brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_REGULATORY, &ifp->vif->is_11d);
country_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len,
WLAN_EID_COUNTRY);
is_11d = country_ie ? 1 : 0;
memset(&ssid_le, 0, sizeof(ssid_le));
if (settings->ssid == NULL || settings->ssid_len == 0) {
ie_offset = DOT11_MGMT_HDR_LEN + DOT11_BCN_PRB_FIXED_LEN;
ssid_ie = brcmf_parse_tlvs(
(u8 *)&settings->beacon.head[ie_offset],
settings->beacon.head_len - ie_offset,
WLAN_EID_SSID);
if (!ssid_ie)
return -EINVAL;
memcpy(ssid_le.SSID, ssid_ie->data, ssid_ie->len);
ssid_le.SSID_len = cpu_to_le32(ssid_ie->len);
brcmf_dbg(TRACE, "SSID is (%s) in Head\n", ssid_le.SSID);
} else {
memcpy(ssid_le.SSID, settings->ssid, settings->ssid_len);
ssid_le.SSID_len = cpu_to_le32((u32)settings->ssid_len);
}
if (!mbss) {
brcmf_set_mpc(ifp, 0);
brcmf_configure_arp_nd_offload(ifp, false);
}
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len, WLAN_EID_RSN);
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)settings->beacon.tail,
settings->beacon.tail_len);
if ((wpa_ie != NULL || rsn_ie != NULL)) {
brcmf_dbg(TRACE, "WPA(2) IE is found\n");
if (wpa_ie != NULL) {
/* WPA IE */
err = brcmf_configure_wpaie(ifp, wpa_ie, false);
if (err < 0)
goto exit;
} else {
struct brcmf_vs_tlv *tmp_ie;
tmp_ie = (struct brcmf_vs_tlv *)rsn_ie;
/* RSN IE */
err = brcmf_configure_wpaie(ifp, tmp_ie, true);
if (err < 0)
goto exit;
}
} else {
brcmf_dbg(TRACE, "No WPA(2) IEs found\n");
brcmf_configure_opensecurity(ifp);
}
brcmf_config_ap_mgmt_ie(ifp->vif, &settings->beacon);
/* Parameters shared by all radio interfaces */
if (!mbss) {
if (is_11d != ifp->vif->is_11d) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,
is_11d);
if (err < 0) {
brcmf_err("Regulatory Set Error, %d\n", err);
goto exit;
}
}
if (settings->beacon_interval) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD,
settings->beacon_interval);
if (err < 0) {
brcmf_err("Beacon Interval Set Error, %d\n",
err);
goto exit;
}
}
if (settings->dtim_period) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_DTIMPRD,
settings->dtim_period);
if (err < 0) {
brcmf_err("DTIM Interval Set Error, %d\n", err);
goto exit;
}
}
if ((dev_role == NL80211_IFTYPE_AP) &&
((ifp->ifidx == 0) ||
!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_RSDB))) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
if (err < 0) {
brcmf_err("BRCMF_C_DOWN error %d\n", err);
goto exit;
}
brcmf_fil_iovar_int_set(ifp, "apsta", 0);
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, 1);
if (err < 0) {
brcmf_err("SET INFRA error %d\n", err);
goto exit;
}
} else if (WARN_ON(is_11d != ifp->vif->is_11d)) {
/* Multiple-BSS should use same 11d configuration */
err = -EINVAL;
goto exit;
}
/* Interface specific setup */
if (dev_role == NL80211_IFTYPE_AP) {
if ((brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS)) && (!mbss))
brcmf_fil_iovar_int_set(ifp, "mbss", 1);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 1);
if (err < 0) {
brcmf_err("setting AP mode failed %d\n", err);
goto exit;
}
if (!mbss) {
/* Firmware 10.x requires setting channel after enabling
* AP and before bringing interface up.
*/
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
if (err < 0) {
brcmf_err("BRCMF_C_UP error (%d)\n", err);
goto exit;
}
/* On DOWN the firmware removes the WEP keys, reconfigure
* them if they were set.
*/
brcmf_cfg80211_reconfigure_wep(ifp);
memset(&join_params, 0, sizeof(join_params));
/* join parameters starts with ssid */
memcpy(&join_params.ssid_le, &ssid_le, sizeof(ssid_le));
/* create softap */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, sizeof(join_params));
if (err < 0) {
brcmf_err("SET SSID error (%d)\n", err);
goto exit;
}
if (settings->hidden_ssid) {
err = brcmf_fil_iovar_int_set(ifp, "closednet", 1);
if (err) {
brcmf_err("closednet error (%d)\n", err);
goto exit;
}
}
brcmf_dbg(TRACE, "AP mode configuration complete\n");
} else if (dev_role == NL80211_IFTYPE_P2P_GO) {
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
err = brcmf_fil_bsscfg_data_set(ifp, "ssid", &ssid_le,
sizeof(ssid_le));
if (err < 0) {
brcmf_err("setting ssid failed %d\n", err);
goto exit;
}
bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);
bss_enable.enable = cpu_to_le32(1);
err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable,
sizeof(bss_enable));
if (err < 0) {
brcmf_err("bss_enable config failed %d\n", err);
goto exit;
}
brcmf_dbg(TRACE, "GO mode configuration complete\n");
} else {
WARN_ON(1);
}
set_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);
brcmf_net_setcarrier(ifp, true);
exit:
if ((err) && (!mbss)) {
brcmf_set_mpc(ifp, 1);
brcmf_configure_arp_nd_offload(ifp, true);
}
return err;
}
Commit Message: brcmfmac: avoid potential stack overflow in brcmf_cfg80211_start_ap()
User-space can choose to omit NL80211_ATTR_SSID and only provide raw
IE TLV data. When doing so it can provide SSID IE with length exceeding
the allowed size. The driver further processes this IE copying it
into a local variable without checking the length. Hence stack can be
corrupted and used as exploit.
Cc: [email protected] # v4.7
Reported-by: Daxing Guo <[email protected]>
Reviewed-by: Hante Meuleman <[email protected]>
Reviewed-by: Pieter-Paul Giesberts <[email protected]>
Reviewed-by: Franky Lin <[email protected]>
Signed-off-by: Arend van Spriel <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>
CWE ID: CWE-119 | brcmf_cfg80211_start_ap(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_ap_settings *settings)
{
s32 ie_offset;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
const struct brcmf_tlv *ssid_ie;
const struct brcmf_tlv *country_ie;
struct brcmf_ssid_le ssid_le;
s32 err = -EPERM;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
struct brcmf_join_params join_params;
enum nl80211_iftype dev_role;
struct brcmf_fil_bss_enable_le bss_enable;
u16 chanspec = chandef_to_chanspec(&cfg->d11inf, &settings->chandef);
bool mbss;
int is_11d;
brcmf_dbg(TRACE, "ctrlchn=%d, center=%d, bw=%d, beacon_interval=%d, dtim_period=%d,\n",
settings->chandef.chan->hw_value,
settings->chandef.center_freq1, settings->chandef.width,
settings->beacon_interval, settings->dtim_period);
brcmf_dbg(TRACE, "ssid=%s(%zu), auth_type=%d, inactivity_timeout=%d\n",
settings->ssid, settings->ssid_len, settings->auth_type,
settings->inactivity_timeout);
dev_role = ifp->vif->wdev.iftype;
mbss = ifp->vif->mbss;
/* store current 11d setting */
brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_REGULATORY, &ifp->vif->is_11d);
country_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len,
WLAN_EID_COUNTRY);
is_11d = country_ie ? 1 : 0;
memset(&ssid_le, 0, sizeof(ssid_le));
if (settings->ssid == NULL || settings->ssid_len == 0) {
ie_offset = DOT11_MGMT_HDR_LEN + DOT11_BCN_PRB_FIXED_LEN;
ssid_ie = brcmf_parse_tlvs(
(u8 *)&settings->beacon.head[ie_offset],
settings->beacon.head_len - ie_offset,
WLAN_EID_SSID);
if (!ssid_ie || ssid_ie->len > IEEE80211_MAX_SSID_LEN)
return -EINVAL;
memcpy(ssid_le.SSID, ssid_ie->data, ssid_ie->len);
ssid_le.SSID_len = cpu_to_le32(ssid_ie->len);
brcmf_dbg(TRACE, "SSID is (%s) in Head\n", ssid_le.SSID);
} else {
memcpy(ssid_le.SSID, settings->ssid, settings->ssid_len);
ssid_le.SSID_len = cpu_to_le32((u32)settings->ssid_len);
}
if (!mbss) {
brcmf_set_mpc(ifp, 0);
brcmf_configure_arp_nd_offload(ifp, false);
}
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len, WLAN_EID_RSN);
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)settings->beacon.tail,
settings->beacon.tail_len);
if ((wpa_ie != NULL || rsn_ie != NULL)) {
brcmf_dbg(TRACE, "WPA(2) IE is found\n");
if (wpa_ie != NULL) {
/* WPA IE */
err = brcmf_configure_wpaie(ifp, wpa_ie, false);
if (err < 0)
goto exit;
} else {
struct brcmf_vs_tlv *tmp_ie;
tmp_ie = (struct brcmf_vs_tlv *)rsn_ie;
/* RSN IE */
err = brcmf_configure_wpaie(ifp, tmp_ie, true);
if (err < 0)
goto exit;
}
} else {
brcmf_dbg(TRACE, "No WPA(2) IEs found\n");
brcmf_configure_opensecurity(ifp);
}
brcmf_config_ap_mgmt_ie(ifp->vif, &settings->beacon);
/* Parameters shared by all radio interfaces */
if (!mbss) {
if (is_11d != ifp->vif->is_11d) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,
is_11d);
if (err < 0) {
brcmf_err("Regulatory Set Error, %d\n", err);
goto exit;
}
}
if (settings->beacon_interval) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD,
settings->beacon_interval);
if (err < 0) {
brcmf_err("Beacon Interval Set Error, %d\n",
err);
goto exit;
}
}
if (settings->dtim_period) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_DTIMPRD,
settings->dtim_period);
if (err < 0) {
brcmf_err("DTIM Interval Set Error, %d\n", err);
goto exit;
}
}
if ((dev_role == NL80211_IFTYPE_AP) &&
((ifp->ifidx == 0) ||
!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_RSDB))) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
if (err < 0) {
brcmf_err("BRCMF_C_DOWN error %d\n", err);
goto exit;
}
brcmf_fil_iovar_int_set(ifp, "apsta", 0);
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, 1);
if (err < 0) {
brcmf_err("SET INFRA error %d\n", err);
goto exit;
}
} else if (WARN_ON(is_11d != ifp->vif->is_11d)) {
/* Multiple-BSS should use same 11d configuration */
err = -EINVAL;
goto exit;
}
/* Interface specific setup */
if (dev_role == NL80211_IFTYPE_AP) {
if ((brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS)) && (!mbss))
brcmf_fil_iovar_int_set(ifp, "mbss", 1);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 1);
if (err < 0) {
brcmf_err("setting AP mode failed %d\n", err);
goto exit;
}
if (!mbss) {
/* Firmware 10.x requires setting channel after enabling
* AP and before bringing interface up.
*/
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
if (err < 0) {
brcmf_err("BRCMF_C_UP error (%d)\n", err);
goto exit;
}
/* On DOWN the firmware removes the WEP keys, reconfigure
* them if they were set.
*/
brcmf_cfg80211_reconfigure_wep(ifp);
memset(&join_params, 0, sizeof(join_params));
/* join parameters starts with ssid */
memcpy(&join_params.ssid_le, &ssid_le, sizeof(ssid_le));
/* create softap */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, sizeof(join_params));
if (err < 0) {
brcmf_err("SET SSID error (%d)\n", err);
goto exit;
}
if (settings->hidden_ssid) {
err = brcmf_fil_iovar_int_set(ifp, "closednet", 1);
if (err) {
brcmf_err("closednet error (%d)\n", err);
goto exit;
}
}
brcmf_dbg(TRACE, "AP mode configuration complete\n");
} else if (dev_role == NL80211_IFTYPE_P2P_GO) {
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
err = brcmf_fil_bsscfg_data_set(ifp, "ssid", &ssid_le,
sizeof(ssid_le));
if (err < 0) {
brcmf_err("setting ssid failed %d\n", err);
goto exit;
}
bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);
bss_enable.enable = cpu_to_le32(1);
err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable,
sizeof(bss_enable));
if (err < 0) {
brcmf_err("bss_enable config failed %d\n", err);
goto exit;
}
brcmf_dbg(TRACE, "GO mode configuration complete\n");
} else {
WARN_ON(1);
}
set_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);
brcmf_net_setcarrier(ifp, true);
exit:
if ((err) && (!mbss)) {
brcmf_set_mpc(ifp, 1);
brcmf_configure_arp_nd_offload(ifp, true);
}
return err;
}
| 166,908 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int treo_attach(struct usb_serial *serial)
{
struct usb_serial_port *swap_port;
/* Only do this endpoint hack for the Handspring devices with
* interrupt in endpoints, which for now are the Treo devices. */
if (!((le16_to_cpu(serial->dev->descriptor.idVendor)
== HANDSPRING_VENDOR_ID) ||
(le16_to_cpu(serial->dev->descriptor.idVendor)
== KYOCERA_VENDOR_ID)) ||
(serial->num_interrupt_in == 0))
return 0;
/*
* It appears that Treos and Kyoceras want to use the
* 1st bulk in endpoint to communicate with the 2nd bulk out endpoint,
* so let's swap the 1st and 2nd bulk in and interrupt endpoints.
* Note that swapping the bulk out endpoints would break lots of
* apps that want to communicate on the second port.
*/
#define COPY_PORT(dest, src) \
do { \
int i; \
\
for (i = 0; i < ARRAY_SIZE(src->read_urbs); ++i) { \
dest->read_urbs[i] = src->read_urbs[i]; \
dest->read_urbs[i]->context = dest; \
dest->bulk_in_buffers[i] = src->bulk_in_buffers[i]; \
} \
dest->read_urb = src->read_urb; \
dest->bulk_in_endpointAddress = src->bulk_in_endpointAddress;\
dest->bulk_in_buffer = src->bulk_in_buffer; \
dest->bulk_in_size = src->bulk_in_size; \
dest->interrupt_in_urb = src->interrupt_in_urb; \
dest->interrupt_in_urb->context = dest; \
dest->interrupt_in_endpointAddress = \
src->interrupt_in_endpointAddress;\
dest->interrupt_in_buffer = src->interrupt_in_buffer; \
} while (0);
swap_port = kmalloc(sizeof(*swap_port), GFP_KERNEL);
if (!swap_port)
return -ENOMEM;
COPY_PORT(swap_port, serial->port[0]);
COPY_PORT(serial->port[0], serial->port[1]);
COPY_PORT(serial->port[1], swap_port);
kfree(swap_port);
return 0;
}
Commit Message: USB: visor: fix null-deref at probe
Fix null-pointer dereference at probe should a (malicious) Treo device
lack the expected endpoints.
Specifically, the Treo port-setup hack was dereferencing the bulk-in and
interrupt-in urbs without first making sure they had been allocated by
core.
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: | static int treo_attach(struct usb_serial *serial)
{
struct usb_serial_port *swap_port;
/* Only do this endpoint hack for the Handspring devices with
* interrupt in endpoints, which for now are the Treo devices. */
if (!((le16_to_cpu(serial->dev->descriptor.idVendor)
== HANDSPRING_VENDOR_ID) ||
(le16_to_cpu(serial->dev->descriptor.idVendor)
== KYOCERA_VENDOR_ID)) ||
(serial->num_interrupt_in == 0))
return 0;
if (serial->num_bulk_in < 2 || serial->num_interrupt_in < 2) {
dev_err(&serial->interface->dev, "missing endpoints\n");
return -ENODEV;
}
/*
* It appears that Treos and Kyoceras want to use the
* 1st bulk in endpoint to communicate with the 2nd bulk out endpoint,
* so let's swap the 1st and 2nd bulk in and interrupt endpoints.
* Note that swapping the bulk out endpoints would break lots of
* apps that want to communicate on the second port.
*/
#define COPY_PORT(dest, src) \
do { \
int i; \
\
for (i = 0; i < ARRAY_SIZE(src->read_urbs); ++i) { \
dest->read_urbs[i] = src->read_urbs[i]; \
dest->read_urbs[i]->context = dest; \
dest->bulk_in_buffers[i] = src->bulk_in_buffers[i]; \
} \
dest->read_urb = src->read_urb; \
dest->bulk_in_endpointAddress = src->bulk_in_endpointAddress;\
dest->bulk_in_buffer = src->bulk_in_buffer; \
dest->bulk_in_size = src->bulk_in_size; \
dest->interrupt_in_urb = src->interrupt_in_urb; \
dest->interrupt_in_urb->context = dest; \
dest->interrupt_in_endpointAddress = \
src->interrupt_in_endpointAddress;\
dest->interrupt_in_buffer = src->interrupt_in_buffer; \
} while (0);
swap_port = kmalloc(sizeof(*swap_port), GFP_KERNEL);
if (!swap_port)
return -ENOMEM;
COPY_PORT(swap_port, serial->port[0]);
COPY_PORT(serial->port[0], serial->port[1]);
COPY_PORT(serial->port[1], swap_port);
kfree(swap_port);
return 0;
}
| 167,390 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const {
assert(m_count == 0);
if (m_preload_count >= cue_points_size) {
const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size;
CuePoint** const qq = new CuePoint* [n];
CuePoint** q = qq; // beginning of target
CuePoint** p = m_cue_points; // beginning of source
CuePoint** const pp = p + m_preload_count; // end of source
while (p != pp)
*q++ = *p++;
delete[] m_cue_points;
m_cue_points = qq;
cue_points_size = n;
}
CuePoint* const pCP = new CuePoint(m_preload_count, pos);
m_cue_points[m_preload_count++] = pCP;
}
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::PreloadCuePoint(long& cue_points_size, long long pos) const {
bool Cues::PreloadCuePoint(long& cue_points_size, long long pos) const {
if (m_count != 0)
return false;
if (m_preload_count >= cue_points_size) {
const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size;
CuePoint** const qq = new (std::nothrow) CuePoint*[n];
if (qq == NULL)
return false;
CuePoint** q = qq; // beginning of target
CuePoint** p = m_cue_points; // beginning of source
CuePoint** const pp = p + m_preload_count; // end of source
while (p != pp)
*q++ = *p++;
delete[] m_cue_points;
m_cue_points = qq;
cue_points_size = n;
}
CuePoint* const pCP = new (std::nothrow) CuePoint(m_preload_count, pos);
if (pCP == NULL)
return false;
m_cue_points[m_preload_count++] = pCP;
return true;
}
| 173,861 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void bpf_map_inc(struct bpf_map *map, bool uref)
{
atomic_inc(&map->refcnt);
if (uref)
atomic_inc(&map->usercnt);
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | void bpf_map_inc(struct bpf_map *map, bool uref)
/* prog's and map's refcnt limit */
#define BPF_MAX_REFCNT 32768
struct bpf_map *bpf_map_inc(struct bpf_map *map, bool uref)
{
if (atomic_inc_return(&map->refcnt) > BPF_MAX_REFCNT) {
atomic_dec(&map->refcnt);
return ERR_PTR(-EBUSY);
}
if (uref)
atomic_inc(&map->usercnt);
return map;
}
| 167,253 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fslib_copy_libs(const char *full_path) {
assert(full_path);
if (arg_debug || arg_debug_private_lib)
printf(" fslib_copy_libs %s\n", full_path);
if (access(full_path, R_OK)) {
if (arg_debug || arg_debug_private_lib)
printf("cannot find %s for private-lib, skipping...\n", full_path);
return;
}
unlink(RUN_LIB_FILE); // in case is there
create_empty_file_as_root(RUN_LIB_FILE, 0644);
if (chown(RUN_LIB_FILE, getuid(), getgid()))
errExit("chown");
if (arg_debug || arg_debug_private_lib)
printf(" running fldd %s\n", full_path);
sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE);
FILE *fp = fopen(RUN_LIB_FILE, "r");
if (!fp)
errExit("fopen");
char buf[MAXBUF];
while (fgets(buf, MAXBUF, fp)) {
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
fslib_duplicate(buf);
}
fclose(fp);
}
Commit Message: mount runtime seccomp files read-only (#2602)
avoid creating locations in the file system that are both writable and
executable (in this case for processes with euid of the user).
for the same reason also remove user owned libfiles
when it is not needed any more
CWE ID: CWE-284 | void fslib_copy_libs(const char *full_path) {
assert(full_path);
if (arg_debug || arg_debug_private_lib)
printf(" fslib_copy_libs %s\n", full_path);
if (access(full_path, R_OK)) {
if (arg_debug || arg_debug_private_lib)
printf("cannot find %s for private-lib, skipping...\n", full_path);
return;
}
unlink(RUN_LIB_FILE); // in case is there
create_empty_file_as_root(RUN_LIB_FILE, 0644);
if (chown(RUN_LIB_FILE, getuid(), getgid()))
errExit("chown");
if (arg_debug || arg_debug_private_lib)
printf(" running fldd %s\n", full_path);
sbox_run(SBOX_USER | SBOX_SECCOMP | SBOX_CAPS_NONE, 3, PATH_FLDD, full_path, RUN_LIB_FILE);
FILE *fp = fopen(RUN_LIB_FILE, "r");
if (!fp)
errExit("fopen");
char buf[MAXBUF];
while (fgets(buf, MAXBUF, fp)) {
char *ptr = strchr(buf, '\n');
if (ptr)
*ptr = '\0';
fslib_duplicate(buf);
}
fclose(fp);
unlink(RUN_LIB_FILE);
}
| 169,657 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr,
struct nfsd4_layoutget *lgp)
{
struct xdr_stream *xdr = &resp->xdr;
const struct nfsd4_layout_ops *ops =
nfsd4_layout_ops[lgp->lg_layout_type];
__be32 *p;
dprintk("%s: err %d\n", __func__, nfserr);
if (nfserr)
goto out;
nfserr = nfserr_resource;
p = xdr_reserve_space(xdr, 36 + sizeof(stateid_opaque_t));
if (!p)
goto out;
*p++ = cpu_to_be32(1); /* we always set return-on-close */
*p++ = cpu_to_be32(lgp->lg_sid.si_generation);
p = xdr_encode_opaque_fixed(p, &lgp->lg_sid.si_opaque,
sizeof(stateid_opaque_t));
*p++ = cpu_to_be32(1); /* we always return a single layout */
p = xdr_encode_hyper(p, lgp->lg_seg.offset);
p = xdr_encode_hyper(p, lgp->lg_seg.length);
*p++ = cpu_to_be32(lgp->lg_seg.iomode);
*p++ = cpu_to_be32(lgp->lg_layout_type);
nfserr = ops->encode_layoutget(xdr, lgp);
out:
kfree(lgp->lg_content);
return nfserr;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr,
struct nfsd4_layoutget *lgp)
{
struct xdr_stream *xdr = &resp->xdr;
const struct nfsd4_layout_ops *ops;
__be32 *p;
dprintk("%s: err %d\n", __func__, nfserr);
if (nfserr)
goto out;
nfserr = nfserr_resource;
p = xdr_reserve_space(xdr, 36 + sizeof(stateid_opaque_t));
if (!p)
goto out;
*p++ = cpu_to_be32(1); /* we always set return-on-close */
*p++ = cpu_to_be32(lgp->lg_sid.si_generation);
p = xdr_encode_opaque_fixed(p, &lgp->lg_sid.si_opaque,
sizeof(stateid_opaque_t));
*p++ = cpu_to_be32(1); /* we always return a single layout */
p = xdr_encode_hyper(p, lgp->lg_seg.offset);
p = xdr_encode_hyper(p, lgp->lg_seg.length);
*p++ = cpu_to_be32(lgp->lg_seg.iomode);
*p++ = cpu_to_be32(lgp->lg_layout_type);
ops = nfsd4_layout_ops[lgp->lg_layout_type];
nfserr = ops->encode_layoutget(xdr, lgp);
out:
kfree(lgp->lg_content);
return nfserr;
}
| 168,149 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuProcessHost::OnProcessCrashed(int exit_code) {
int process_crash_exit_code = exit_code;
base::debug::Alias(&process_crash_exit_code);
if (activity_flags_.IsFlagSet(
gpu::ActivityFlagsBase::FLAG_LOADING_PROGRAM_BINARY)) {
for (auto cache_key : client_id_to_shader_cache_) {
GetShaderCacheFactorySingleton()->ClearByClientId(
cache_key.first, base::Time(), base::Time::Max(), base::Bind([] {}));
}
}
SendOutstandingReplies(EstablishChannelStatus::GPU_HOST_INVALID);
RecordProcessCrash();
ChildProcessTerminationInfo info =
process_->GetTerminationInfo(true /* known_dead */);
GpuDataManagerImpl::GetInstance()->ProcessCrashed(info.status);
}
Commit Message: Fix GPU process fallback logic.
1. In GpuProcessHost::OnProcessCrashed() record the process crash first.
This means the GPU mode fallback will happen before a new GPU process
is started.
2. Don't call FallBackToNextGpuMode() if GPU process initialization
fails for an unsandboxed GPU process. The unsandboxed GPU is only
used for collect information and it's failure doesn't indicate a need
to change GPU modes.
Bug: 869419
Change-Id: I8bd0a03268f0ea8809f3df8458d4e6a92db9391f
Reviewed-on: https://chromium-review.googlesource.com/1157164
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: kylechar <[email protected]>
Cr-Commit-Position: refs/heads/master@{#579625}
CWE ID: | void GpuProcessHost::OnProcessCrashed(int exit_code) {
int process_crash_exit_code = exit_code;
base::debug::Alias(&process_crash_exit_code);
// Record crash before doing anything that could start a new GPU process.
RecordProcessCrash();
if (activity_flags_.IsFlagSet(
gpu::ActivityFlagsBase::FLAG_LOADING_PROGRAM_BINARY)) {
for (auto cache_key : client_id_to_shader_cache_) {
GetShaderCacheFactorySingleton()->ClearByClientId(
cache_key.first, base::Time(), base::Time::Max(), base::Bind([] {}));
}
}
SendOutstandingReplies(EstablishChannelStatus::GPU_HOST_INVALID);
ChildProcessTerminationInfo info =
process_->GetTerminationInfo(true /* known_dead */);
GpuDataManagerImpl::GetInstance()->ProcessCrashed(info.status);
}
| 172,242 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,
struct btrfs_path *path,
const char *name, int name_len)
{
struct btrfs_dir_item *dir_item;
unsigned long name_ptr;
u32 total_len;
u32 cur = 0;
u32 this_len;
struct extent_buffer *leaf;
leaf = path->nodes[0];
dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
if (verify_dir_item(root, leaf, dir_item))
return NULL;
total_len = btrfs_item_size_nr(leaf, path->slots[0]);
while (cur < total_len) {
this_len = sizeof(*dir_item) +
btrfs_dir_name_len(leaf, dir_item) +
btrfs_dir_data_len(leaf, dir_item);
name_ptr = (unsigned long)(dir_item + 1);
if (btrfs_dir_name_len(leaf, dir_item) == name_len &&
memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0)
return dir_item;
cur += this_len;
dir_item = (struct btrfs_dir_item *)((char *)dir_item +
this_len);
}
return NULL;
}
Commit Message: Btrfs: make xattr replace operations atomic
Replacing a xattr consists of doing a lookup for its existing value, delete
the current value from the respective leaf, release the search path and then
finally insert the new value. This leaves a time window where readers (getxattr,
listxattrs) won't see any value for the xattr. Xattrs are used to store ACLs,
so this has security implications.
This change also fixes 2 other existing issues which were:
*) Deleting the old xattr value without verifying first if the new xattr will
fit in the existing leaf item (in case multiple xattrs are packed in the
same item due to name hash collision);
*) Returning -EEXIST when the flag XATTR_CREATE is given and the xattr doesn't
exist but we have have an existing item that packs muliple xattrs with
the same name hash as the input xattr. In this case we should return ENOSPC.
A test case for xfstests follows soon.
Thanks to Alexandre Oliva for reporting the non-atomicity of the xattr replace
implementation.
Reported-by: Alexandre Oliva <[email protected]>
Signed-off-by: Filipe Manana <[email protected]>
Signed-off-by: Chris Mason <[email protected]>
CWE ID: CWE-362 | static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,
struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,
struct btrfs_path *path,
const char *name, int name_len)
{
struct btrfs_dir_item *dir_item;
unsigned long name_ptr;
u32 total_len;
u32 cur = 0;
u32 this_len;
struct extent_buffer *leaf;
leaf = path->nodes[0];
dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
if (verify_dir_item(root, leaf, dir_item))
return NULL;
total_len = btrfs_item_size_nr(leaf, path->slots[0]);
while (cur < total_len) {
this_len = sizeof(*dir_item) +
btrfs_dir_name_len(leaf, dir_item) +
btrfs_dir_data_len(leaf, dir_item);
name_ptr = (unsigned long)(dir_item + 1);
if (btrfs_dir_name_len(leaf, dir_item) == name_len &&
memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0)
return dir_item;
cur += this_len;
dir_item = (struct btrfs_dir_item *)((char *)dir_item +
this_len);
}
return NULL;
}
| 166,764 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: sg_start_req(Sg_request *srp, unsigned char *cmd)
{
int res;
struct request *rq;
Sg_fd *sfp = srp->parentfp;
sg_io_hdr_t *hp = &srp->header;
int dxfer_len = (int) hp->dxfer_len;
int dxfer_dir = hp->dxfer_direction;
unsigned int iov_count = hp->iovec_count;
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
struct rq_map_data *md, map_data;
int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ;
unsigned char *long_cmdp = NULL;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_start_req: dxfer_len=%d\n",
dxfer_len));
if (hp->cmd_len > BLK_MAX_CDB) {
long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL);
if (!long_cmdp)
return -ENOMEM;
}
/*
* NOTE
*
* With scsi-mq enabled, there are a fixed number of preallocated
* requests equal in number to shost->can_queue. If all of the
* preallocated requests are already in use, then using GFP_ATOMIC with
* blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL
* will cause blk_get_request() to sleep until an active command
* completes, freeing up a request. Neither option is ideal, but
* GFP_KERNEL is the better choice to prevent userspace from getting an
* unexpected EWOULDBLOCK.
*
* With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually
* does not sleep except under memory pressure.
*/
rq = blk_get_request(q, rw, GFP_KERNEL);
if (IS_ERR(rq)) {
kfree(long_cmdp);
return PTR_ERR(rq);
}
blk_rq_set_block_pc(rq);
if (hp->cmd_len > BLK_MAX_CDB)
rq->cmd = long_cmdp;
memcpy(rq->cmd, cmd, hp->cmd_len);
rq->cmd_len = hp->cmd_len;
srp->rq = rq;
rq->end_io_data = srp;
rq->sense = srp->sense_b;
rq->retries = SG_DEFAULT_RETRIES;
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
return 0;
if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&
dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&
!sfp->parentdp->device->host->unchecked_isa_dma &&
blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))
md = NULL;
else
md = &map_data;
if (md) {
if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen)
sg_link_reserve(sfp, srp, dxfer_len);
else {
res = sg_build_indirect(req_schp, sfp, dxfer_len);
if (res)
return res;
}
md->pages = req_schp->pages;
md->page_order = req_schp->page_order;
md->nr_entries = req_schp->k_use_sg;
md->offset = 0;
md->null_mapped = hp->dxferp ? 0 : 1;
if (dxfer_dir == SG_DXFER_TO_FROM_DEV)
md->from_user = 1;
else
md->from_user = 0;
}
if (unlikely(iov_count > MAX_UIOVEC))
return -EINVAL;
if (iov_count) {
int size = sizeof(struct iovec) * iov_count;
struct iovec *iov;
struct iov_iter i;
iov = memdup_user(hp->dxferp, size);
if (IS_ERR(iov))
return PTR_ERR(iov);
iov_iter_init(&i, rw, iov, iov_count,
min_t(size_t, hp->dxfer_len,
iov_length(iov, iov_count)));
res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC);
kfree(iov);
} else
res = blk_rq_map_user(q, rq, md, hp->dxferp,
hp->dxfer_len, GFP_ATOMIC);
if (!res) {
srp->bio = rq->bio;
if (!md) {
req_schp->dio_in_use = 1;
hp->info |= SG_INFO_DIRECT_IO;
}
}
return res;
}
Commit Message: sg_start_req(): use import_iovec()
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-189 | sg_start_req(Sg_request *srp, unsigned char *cmd)
{
int res;
struct request *rq;
Sg_fd *sfp = srp->parentfp;
sg_io_hdr_t *hp = &srp->header;
int dxfer_len = (int) hp->dxfer_len;
int dxfer_dir = hp->dxfer_direction;
unsigned int iov_count = hp->iovec_count;
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
struct rq_map_data *md, map_data;
int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ;
unsigned char *long_cmdp = NULL;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_start_req: dxfer_len=%d\n",
dxfer_len));
if (hp->cmd_len > BLK_MAX_CDB) {
long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL);
if (!long_cmdp)
return -ENOMEM;
}
/*
* NOTE
*
* With scsi-mq enabled, there are a fixed number of preallocated
* requests equal in number to shost->can_queue. If all of the
* preallocated requests are already in use, then using GFP_ATOMIC with
* blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL
* will cause blk_get_request() to sleep until an active command
* completes, freeing up a request. Neither option is ideal, but
* GFP_KERNEL is the better choice to prevent userspace from getting an
* unexpected EWOULDBLOCK.
*
* With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually
* does not sleep except under memory pressure.
*/
rq = blk_get_request(q, rw, GFP_KERNEL);
if (IS_ERR(rq)) {
kfree(long_cmdp);
return PTR_ERR(rq);
}
blk_rq_set_block_pc(rq);
if (hp->cmd_len > BLK_MAX_CDB)
rq->cmd = long_cmdp;
memcpy(rq->cmd, cmd, hp->cmd_len);
rq->cmd_len = hp->cmd_len;
srp->rq = rq;
rq->end_io_data = srp;
rq->sense = srp->sense_b;
rq->retries = SG_DEFAULT_RETRIES;
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
return 0;
if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&
dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&
!sfp->parentdp->device->host->unchecked_isa_dma &&
blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))
md = NULL;
else
md = &map_data;
if (md) {
if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen)
sg_link_reserve(sfp, srp, dxfer_len);
else {
res = sg_build_indirect(req_schp, sfp, dxfer_len);
if (res)
return res;
}
md->pages = req_schp->pages;
md->page_order = req_schp->page_order;
md->nr_entries = req_schp->k_use_sg;
md->offset = 0;
md->null_mapped = hp->dxferp ? 0 : 1;
if (dxfer_dir == SG_DXFER_TO_FROM_DEV)
md->from_user = 1;
else
md->from_user = 0;
}
if (iov_count) {
struct iovec *iov = NULL;
struct iov_iter i;
res = import_iovec(rw, hp->dxferp, iov_count, 0, &iov, &i);
if (res < 0)
return res;
iov_iter_truncate(&i, hp->dxfer_len);
res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC);
kfree(iov);
} else
res = blk_rq_map_user(q, rq, md, hp->dxferp,
hp->dxfer_len, GFP_ATOMIC);
if (!res) {
srp->bio = rq->bio;
if (!md) {
req_schp->dio_in_use = 1;
hp->info |= SG_INFO_DIRECT_IO;
}
}
return res;
}
| 169,924 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::ParseSimpleBlock(long long block_size, long long& pos,
long& len) {
const long long block_start = pos;
const long long block_stop = pos + block_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long track = ReadUInt(pReader, pos, len);
if (track < 0) // error
return static_cast<long>(track);
if (track == 0)
return E_FILE_FORMAT_INVALID;
#if 0
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return E_FILE_FORMAT_INVALID;
#endif
pos += len; // consume track number
if ((pos + 2) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 2) > avail) {
len = 2;
return E_BUFFER_NOT_FULL;
}
pos += 2; // consume timecode
if ((pos + 1) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
unsigned char flags;
status = pReader->Read(pos, 1, &flags);
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
status = CreateBlock(0x23, // simple block id
block_start, block_size,
0); // DiscardPadding
if (status != 0)
return status;
m_pos = block_stop;
return 0; // success
}
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 Cluster::ParseSimpleBlock(long long block_size, long long& pos,
long& len) {
const long long block_start = pos;
const long long block_stop = pos + block_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long track = ReadUInt(pReader, pos, len);
if (track < 0) // error
return static_cast<long>(track);
if (track == 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume track number
if ((pos + 2) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 2) > avail) {
len = 2;
return E_BUFFER_NOT_FULL;
}
pos += 2; // consume timecode
if ((pos + 1) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
unsigned char flags;
status = pReader->Read(pos, 1, &flags);
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
status = CreateBlock(0x23, // simple block id
block_start, block_size,
0); // DiscardPadding
if (status != 0)
return status;
m_pos = block_stop;
return 0; // success
}
| 173,858 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_module_get_algo_block_size)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir));
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_module_get_algo_block_size)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir));
}
| 167,099 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL)
{
ALOGV("constructor");
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != NULL) {
mMediaRecorder = service->createMediaRecorder(opPackageName);
}
if (mMediaRecorder != NULL) {
mCurrentState = MEDIA_RECORDER_IDLE;
}
doCleanUp();
}
Commit Message: Don't use sp<>&
because they may end up pointing to NULL after a NULL check was performed.
Bug: 28166152
Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe
CWE ID: CWE-476 | MediaRecorder::MediaRecorder(const String16& opPackageName) : mSurfaceMediaSource(NULL)
{
ALOGV("constructor");
const sp<IMediaPlayerService> service(getMediaPlayerService());
if (service != NULL) {
mMediaRecorder = service->createMediaRecorder(opPackageName);
}
if (mMediaRecorder != NULL) {
mCurrentState = MEDIA_RECORDER_IDLE;
}
doCleanUp();
}
| 173,540 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IndexedDBDispatcher::~IndexedDBDispatcher() {
g_idb_dispatcher_tls.Pointer()->Set(NULL);
}
Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created.
This could happen if there are IDB objects that survive the call to
didStopWorkerRunLoop.
BUG=121734
TEST=
Review URL: http://codereview.chromium.org/9999035
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | IndexedDBDispatcher::~IndexedDBDispatcher() {
g_idb_dispatcher_tls.Pointer()->Set(HAS_BEEN_DELETED);
}
| 171,040 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void sas_eh_defer_cmd(struct scsi_cmnd *cmd)
{
struct domain_device *dev = cmd_to_domain_dev(cmd);
struct sas_ha_struct *ha = dev->port->ha;
struct sas_task *task = TO_SAS_TASK(cmd);
if (!dev_is_sata(dev)) {
sas_eh_finish_cmd(cmd);
return;
}
/* report the timeout to libata */
sas_end_task(cmd, task);
list_move_tail(&cmd->eh_entry, &ha->eh_ata_q);
}
Commit Message: scsi: libsas: defer ata device eh commands to libata
When ata device doing EH, some commands still attached with tasks are
not passed to libata when abort failed or recover failed, so libata did
not handle these commands. After these commands done, sas task is freed,
but ata qc is not freed. This will cause ata qc leak and trigger a
warning like below:
WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037
ata_eh_finish+0xb4/0xcc
CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1
......
Call trace:
[<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc
[<ffff0000088b8420>] ata_do_eh+0xc4/0xd8
[<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c
[<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694
[<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80
[<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170
[<ffff0000080ebd70>] process_one_work+0x144/0x390
[<ffff0000080ec100>] worker_thread+0x144/0x418
[<ffff0000080f2c98>] kthread+0x10c/0x138
[<ffff0000080855dc>] ret_from_fork+0x10/0x18
If ata qc leaked too many, ata tag allocation will fail and io blocked
for ever.
As suggested by Dan Williams, defer ata device commands to libata and
merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle
ata qcs correctly after this.
Signed-off-by: Jason Yan <[email protected]>
CC: Xiaofei Tan <[email protected]>
CC: John Garry <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Dan Williams <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: | static void sas_eh_defer_cmd(struct scsi_cmnd *cmd)
| 169,260 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void cJSON_AddItemToArray( cJSON *array, cJSON *item )
{
cJSON *c = array->child;
if ( ! item )
return;
if ( ! c ) {
array->child = item;
} else {
while ( c && c->next )
c = c->next;
suffix_object( c, item );
}
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | void cJSON_AddItemToArray( cJSON *array, cJSON *item )
| 167,267 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
char addrbuf[64];
const int buffsize = sizeof (addrbuf) - 1;
memset (op, '\0', sizeof (RAnalOp));
op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->id = data[0];
r_strbuf_init (&op->esil);
switch (data[0]) {
case 0x02:
case 0x03:
case 0x04:
case 0x07:
case 0x0b:
case 0x0c:
case 0x0f:
case 0x12:
case 0x13:
case 0x14:
case 0x17:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1f:
case 0x22:
case 0x23:
case 0x27:
case 0x2b:
case 0x2f:
case 0x32:
case 0x33:
case 0x34:
case 0x37:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3f:
case 0x42:
case 0x43:
case 0x44:
case 0x47:
case 0x4b:
case 0x4f:
case 0x52:
case 0x53:
case 0x54:
case 0x57:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5f:
case 0x62:
case 0x63:
case 0x64:
case 0x67:
case 0x6b:
case 0x6f:
case 0x72:
case 0x73:
case 0x74:
case 0x77:
case 0x7a:
case 0x7b:
case 0x7c:
case 0x7f:
case 0x80:
case 0x82:
case 0x83:
case 0x87:
case 0x89:
case 0x8b:
case 0x8f:
case 0x92:
case 0x93:
case 0x97:
case 0x9b:
case 0x9c:
case 0x9e:
case 0x9f:
case 0xa3:
case 0xa7:
case 0xab:
case 0xaf:
case 0xb2:
case 0xb3:
case 0xb7:
case 0xbb:
case 0xbf:
case 0xc2:
case 0xc3:
case 0xc7:
case 0xcb:
case 0xcf:
case 0xd2:
case 0xd3:
case 0xd4:
case 0xd7:
case 0xda:
case 0xdb:
case 0xdc:
case 0xdf:
case 0xe2:
case 0xe3:
case 0xe7:
case 0xeb:
case 0xef:
case 0xf2:
case 0xf3:
case 0xf4:
case 0xf7:
case 0xfa:
case 0xfb:
case 0xfc:
case 0xff:
op->size = 1;
op->type = R_ANAL_OP_TYPE_ILL;
break;
case 0x00: // brk
op->cycles = 7;
op->type = R_ANAL_OP_TYPE_SWI;
op->size = 1;
r_strbuf_set (&op->esil, ",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=");
break;
case 0x78: // sei
case 0x58: // cli
case 0x38: // sec
case 0x18: // clc
case 0xf8: // sed
case 0xd8: // cld
case 0xb8: // clv
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_NOP;
_6502_anal_esil_flags (op, data[0]);
break;
case 0x24: // bit $ff
case 0x2c: // bit $ffff
op->type = R_ANAL_OP_TYPE_MOV;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
r_strbuf_setf (&op->esil, "a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,=",addrbuf, addrbuf, addrbuf);
break;
case 0x69: // adc #$ff
case 0x65: // adc $ff
case 0x75: // adc $ff,x
case 0x6d: // adc $ffff
case 0x7d: // adc $ffff,x
case 0x79: // adc $ffff,y
case 0x61: // adc ($ff,x)
case 0x71: // adc ($ff,y)
op->type = R_ANAL_OP_TYPE_ADD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x69) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=");
break;
case 0xe9: // sbc #$ff
case 0xe5: // sbc $ff
case 0xf5: // sbc $ff,x
case 0xed: // sbc $ffff
case 0xfd: // sbc $ffff,x
case 0xf9: // sbc $ffff,y
case 0xe1: // sbc ($ff,x)
case 0xf1: // sbc ($ff,y)
op->type = R_ANAL_OP_TYPE_SUB;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xe9) // immediate mode
r_strbuf_setf (&op->esil, "C,!,%s,+,a,-=", addrbuf);
else r_strbuf_setf (&op->esil, "C,!,%s,[1],+,a,-=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=,C,!=");
break;
case 0x09: // ora #$ff
case 0x05: // ora $ff
case 0x15: // ora $ff,x
case 0x0d: // ora $ffff
case 0x1d: // ora $ffff,x
case 0x19: // ora $ffff,y
case 0x01: // ora ($ff,x)
case 0x11: // ora ($ff),y
op->type = R_ANAL_OP_TYPE_OR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x09) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x29: // and #$ff
case 0x25: // and $ff
case 0x35: // and $ff,x
case 0x2d: // and $ffff
case 0x3d: // and $ffff,x
case 0x39: // and $ffff,y
case 0x21: // and ($ff,x)
case 0x31: // and ($ff),y
op->type = R_ANAL_OP_TYPE_AND;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x29) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,&=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,&=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x49: // eor #$ff
case 0x45: // eor $ff
case 0x55: // eor $ff,x
case 0x4d: // eor $ffff
case 0x5d: // eor $ffff,x
case 0x59: // eor $ffff,y
case 0x41: // eor ($ff,x)
case 0x51: // eor ($ff),y
op->type = R_ANAL_OP_TYPE_XOR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x49) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,^=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,^=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x0a: // asl a
case 0x06: // asl $ff
case 0x16: // asl $ff,x
case 0x0e: // asl $ffff
case 0x1e: // asl $ffff,x
op->type = R_ANAL_OP_TYPE_SHL;
if (data[0] == 0x0a) {
r_strbuf_set (&op->esil, "1,a,<<=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x4a: // lsr a
case 0x46: // lsr $ff
case 0x56: // lsr $ff,x
case 0x4e: // lsr $ffff
case 0x5e: // lsr $ffff,x
op->type = R_ANAL_OP_TYPE_SHR;
if (data[0] == 0x4a) {
r_strbuf_set (&op->esil, "1,a,&,C,=,1,a,>>=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x2a: // rol a
case 0x26: // rol $ff
case 0x36: // rol $ff,x
case 0x2e: // rol $ffff
case 0x3e: // rol $ffff,x
op->type = R_ANAL_OP_TYPE_ROL;
if (data[0] == 0x2a) {
r_strbuf_set (&op->esil, "1,a,<<,C,|,a,=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,C,|,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x6a: // ror a
case 0x66: // ror $ff
case 0x76: // ror $ff,x
case 0x6e: // ror $ffff
case 0x7e: // ror $ffff,x
op->type = R_ANAL_OP_TYPE_ROR;
if (data[0] == 0x6a) {
r_strbuf_set (&op->esil, "C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xe6: // inc $ff
case 0xf6: // inc $ff,x
case 0xee: // inc $ffff
case 0xfe: // inc $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,++=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xc6: // dec $ff
case 0xd6: // dec $ff,x
case 0xce: // dec $ffff
case 0xde: // dec $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,--=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xe8: // inx
case 0xc8: // iny
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "+");
break;
case 0xca: // dex
case 0x88: // dey
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "-");
break;
case 0xc9: // cmp #$ff
case 0xc5: // cmp $ff
case 0xd5: // cmp $ff,x
case 0xcd: // cmp $ffff
case 0xdd: // cmp $ffff,x
case 0xd9: // cmp $ffff,y
case 0xc1: // cmp ($ff,x)
case 0xd1: // cmp ($ff),y
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xc9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0xe0: // cpx #$ff
case 0xe4: // cpx $ff
case 0xec: // cpx $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xe0) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0xc0: // cpy #$ff
case 0xc4: // cpy $ff
case 0xcc: // cpy $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xc0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0x10: // bpl $ffff
case 0x30: // bmi $ffff
case 0x50: // bvc $ffff
case 0x70: // bvs $ffff
case 0x90: // bcc $ffff
case 0xb0: // bcs $ffff
case 0xd0: // bne $ffff
case 0xf0: // beq $ffff
op->cycles = 2;
op->failcycles = 3;
op->type = R_ANAL_OP_TYPE_CJMP;
if (data[1] <= 127)
op->jump = addr + data[1] + op->size;
else op->jump = addr - (256 - data[1]) + op->size;
op->fail = addr + op->size;
_6502_anal_esil_ccall (op, data[0]);
break;
case 0x20: // jsr $ffff
op->cycles = 6;
op->type = R_ANAL_OP_TYPE_CALL;
op->jump = data[1] | data[2] << 8;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 2;
r_strbuf_setf (&op->esil, "1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-=", op->jump);
break;
case 0x4c: // jmp $ffff
op->cycles = 3;
op->type = R_ANAL_OP_TYPE_JMP;
op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,pc,=", op->jump);
break;
case 0x6c: // jmp ($ffff)
op->cycles = 5;
op->type = R_ANAL_OP_TYPE_UJMP;
r_strbuf_setf (&op->esil, "0x%04x,[2],pc,=", data[1] | data[2] << 8);
break;
case 0x60: // rts
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -2;
r_strbuf_set (&op->esil, "0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=");
break;
case 0x40: // rti
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -3;
r_strbuf_set (&op->esil, "0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=");
break;
case 0xea: // nop
op->type = R_ANAL_OP_TYPE_NOP;
op->cycles = 2;
break;
case 0xa9: // lda #$ff
case 0xa5: // lda $ff
case 0xb5: // lda $ff,x
case 0xad: // lda $ffff
case 0xbd: // lda $ffff,x
case 0xb9: // lda $ffff,y
case 0xa1: // lda ($ff,x)
case 0xb1: // lda ($ff),y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xa9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xa2: // ldx #$ff
case 0xa6: // ldx $ff
case 0xb6: // ldx $ff,y
case 0xae: // ldx $ffff
case 0xbe: // ldx $ffff,y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
if (data[0] == 0xa2) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xa0: // ldy #$ff
case 0xa4: // ldy $ff
case 0xb4: // ldy $ff,x
case 0xac: // ldy $ffff
case 0xbc: // ldy $ffff,x
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
if (data[0] == 0xa0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x85: // sta $ff
case 0x95: // sta $ff,x
case 0x8d: // sta $ffff
case 0x9d: // sta $ffff,x
case 0x99: // sta $ffff,y
case 0x81: // sta ($ff,x)
case 0x91: // sta ($ff),y
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
r_strbuf_setf (&op->esil, "a,%s,=[1]", addrbuf);
break;
case 0x86: // stx $ff
case 0x96: // stx $ff,y
case 0x8e: // stx $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
r_strbuf_setf (&op->esil, "x,%s,=[1]", addrbuf);
break;
case 0x84: // sty $ff
case 0x94: // sty $ff,x
case 0x8c: // sty $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "y,%s,=[1]", addrbuf);
break;
case 0x08: // php
case 0x48: // pha
op->type = R_ANAL_OP_TYPE_PUSH;
op->cycles = 3;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 1;
_6502_anal_esil_push (op, data[0]);
break;
case 0x28: // plp
case 0x68: // plp
op->type = R_ANAL_OP_TYPE_POP;
op->cycles = 4;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -1;
_6502_anal_esil_pop (op, data[0]);
break;
case 0xaa: // tax
case 0x8a: // txa
case 0xa8: // tay
case 0x98: // tya
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
_6502_anal_esil_mov (op, data[0]);
break;
case 0x9a: // txs
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_SET;
_6502_anal_esil_mov (op, data[0]);
break;
case 0xba: // tsx
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_GET;
_6502_anal_esil_mov (op, data[0]);
break;
}
return op->size;
}
Commit Message: Fix #10294 - crash in r2_hoobr__6502_op
CWE ID: CWE-125 | static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
char addrbuf[64];
const int buffsize = sizeof (addrbuf) - 1;
memset (op, '\0', sizeof (RAnalOp));
op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->id = data[0];
r_strbuf_init (&op->esil);
switch (data[0]) {
case 0x02:
case 0x03:
case 0x04:
case 0x07:
case 0x0b:
case 0x0c:
case 0x0f:
case 0x12:
case 0x13:
case 0x14:
case 0x17:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1f:
case 0x22:
case 0x23:
case 0x27:
case 0x2b:
case 0x2f:
case 0x32:
case 0x33:
case 0x34:
case 0x37:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3f:
case 0x42:
case 0x43:
case 0x44:
case 0x47:
case 0x4b:
case 0x4f:
case 0x52:
case 0x53:
case 0x54:
case 0x57:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5f:
case 0x62:
case 0x63:
case 0x64:
case 0x67:
case 0x6b:
case 0x6f:
case 0x72:
case 0x73:
case 0x74:
case 0x77:
case 0x7a:
case 0x7b:
case 0x7c:
case 0x7f:
case 0x80:
case 0x82:
case 0x83:
case 0x87:
case 0x89:
case 0x8b:
case 0x8f:
case 0x92:
case 0x93:
case 0x97:
case 0x9b:
case 0x9c:
case 0x9e:
case 0x9f:
case 0xa3:
case 0xa7:
case 0xab:
case 0xaf:
case 0xb2:
case 0xb3:
case 0xb7:
case 0xbb:
case 0xbf:
case 0xc2:
case 0xc3:
case 0xc7:
case 0xcb:
case 0xcf:
case 0xd2:
case 0xd3:
case 0xd4:
case 0xd7:
case 0xda:
case 0xdb:
case 0xdc:
case 0xdf:
case 0xe2:
case 0xe3:
case 0xe7:
case 0xeb:
case 0xef:
case 0xf2:
case 0xf3:
case 0xf4:
case 0xf7:
case 0xfa:
case 0xfb:
case 0xfc:
case 0xff:
op->size = 1;
op->type = R_ANAL_OP_TYPE_ILL;
break;
case 0x00: // brk
op->cycles = 7;
op->type = R_ANAL_OP_TYPE_SWI;
op->size = 1;
r_strbuf_set (&op->esil, ",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=");
break;
case 0x78: // sei
case 0x58: // cli
case 0x38: // sec
case 0x18: // clc
case 0xf8: // sed
case 0xd8: // cld
case 0xb8: // clv
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_NOP;
_6502_anal_esil_flags (op, data[0]);
break;
case 0x24: // bit $ff
case 0x2c: // bit $ffff
op->type = R_ANAL_OP_TYPE_MOV;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
r_strbuf_setf (&op->esil, "a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,=",addrbuf, addrbuf, addrbuf);
break;
case 0x69: // adc #$ff
case 0x65: // adc $ff
case 0x75: // adc $ff,x
case 0x6d: // adc $ffff
case 0x7d: // adc $ffff,x
case 0x79: // adc $ffff,y
case 0x61: // adc ($ff,x)
case 0x71: // adc ($ff,y)
op->type = R_ANAL_OP_TYPE_ADD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x69) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=");
break;
case 0xe9: // sbc #$ff
case 0xe5: // sbc $ff
case 0xf5: // sbc $ff,x
case 0xed: // sbc $ffff
case 0xfd: // sbc $ffff,x
case 0xf9: // sbc $ffff,y
case 0xe1: // sbc ($ff,x)
case 0xf1: // sbc ($ff,y)
op->type = R_ANAL_OP_TYPE_SUB;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xe9) // immediate mode
r_strbuf_setf (&op->esil, "C,!,%s,+,a,-=", addrbuf);
else r_strbuf_setf (&op->esil, "C,!,%s,[1],+,a,-=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=,C,!=");
break;
case 0x09: // ora #$ff
case 0x05: // ora $ff
case 0x15: // ora $ff,x
case 0x0d: // ora $ffff
case 0x1d: // ora $ffff,x
case 0x19: // ora $ffff,y
case 0x01: // ora ($ff,x)
case 0x11: // ora ($ff),y
op->type = R_ANAL_OP_TYPE_OR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x09) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x29: // and #$ff
case 0x25: // and $ff
case 0x35: // and $ff,x
case 0x2d: // and $ffff
case 0x3d: // and $ffff,x
case 0x39: // and $ffff,y
case 0x21: // and ($ff,x)
case 0x31: // and ($ff),y
op->type = R_ANAL_OP_TYPE_AND;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x29) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,&=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,&=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x49: // eor #$ff
case 0x45: // eor $ff
case 0x55: // eor $ff,x
case 0x4d: // eor $ffff
case 0x5d: // eor $ffff,x
case 0x59: // eor $ffff,y
case 0x41: // eor ($ff,x)
case 0x51: // eor ($ff),y
op->type = R_ANAL_OP_TYPE_XOR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x49) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,^=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,^=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x0a: // asl a
case 0x06: // asl $ff
case 0x16: // asl $ff,x
case 0x0e: // asl $ffff
case 0x1e: // asl $ffff,x
op->type = R_ANAL_OP_TYPE_SHL;
if (data[0] == 0x0a) {
r_strbuf_set (&op->esil, "1,a,<<=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x4a: // lsr a
case 0x46: // lsr $ff
case 0x56: // lsr $ff,x
case 0x4e: // lsr $ffff
case 0x5e: // lsr $ffff,x
op->type = R_ANAL_OP_TYPE_SHR;
if (data[0] == 0x4a) {
r_strbuf_set (&op->esil, "1,a,&,C,=,1,a,>>=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x2a: // rol a
case 0x26: // rol $ff
case 0x36: // rol $ff,x
case 0x2e: // rol $ffff
case 0x3e: // rol $ffff,x
op->type = R_ANAL_OP_TYPE_ROL;
if (data[0] == 0x2a) {
r_strbuf_set (&op->esil, "1,a,<<,C,|,a,=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,C,|,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x6a: // ror a
case 0x66: // ror $ff
case 0x76: // ror $ff,x
case 0x6e: // ror $ffff
case 0x7e: // ror $ffff,x
op->type = R_ANAL_OP_TYPE_ROR;
if (data[0] == 0x6a) {
r_strbuf_set (&op->esil, "C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xe6: // inc $ff
case 0xf6: // inc $ff,x
case 0xee: // inc $ffff
case 0xfe: // inc $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,++=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xc6: // dec $ff
case 0xd6: // dec $ff,x
case 0xce: // dec $ffff
case 0xde: // dec $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,--=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xe8: // inx
case 0xc8: // iny
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "+");
break;
case 0xca: // dex
case 0x88: // dey
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "-");
break;
case 0xc9: // cmp #$ff
case 0xc5: // cmp $ff
case 0xd5: // cmp $ff,x
case 0xcd: // cmp $ffff
case 0xdd: // cmp $ffff,x
case 0xd9: // cmp $ffff,y
case 0xc1: // cmp ($ff,x)
case 0xd1: // cmp ($ff),y
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xc9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0xe0: // cpx #$ff
case 0xe4: // cpx $ff
case 0xec: // cpx $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xe0) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0xc0: // cpy #$ff
case 0xc4: // cpy $ff
case 0xcc: // cpy $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xc0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
case 0x10: // bpl $ffff
case 0x30: // bmi $ffff
case 0x50: // bvc $ffff
case 0x70: // bvs $ffff
case 0x90: // bcc $ffff
case 0xb0: // bcs $ffff
case 0xd0: // bne $ffff
case 0xf0: // beq $ffff
op->cycles = 2;
op->failcycles = 3;
op->type = R_ANAL_OP_TYPE_CJMP;
if (len > 1) {
if (data[1] <= 127) {
op->jump = addr + data[1] + op->size;
} else {
op->jump = addr - (256 - data[1]) + op->size;
}
} else {
op->jump = addr;
}
op->fail = addr + op->size;
_6502_anal_esil_ccall (op, data[0]);
break;
case 0x20: // jsr $ffff
op->cycles = 6;
op->type = R_ANAL_OP_TYPE_CALL;
op->jump = data[1] | data[2] << 8;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 2;
r_strbuf_setf (&op->esil, "1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-=", op->jump);
break;
case 0x4c: // jmp $ffff
op->cycles = 3;
op->type = R_ANAL_OP_TYPE_JMP;
op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,pc,=", op->jump);
break;
case 0x6c: // jmp ($ffff)
op->cycles = 5;
op->type = R_ANAL_OP_TYPE_UJMP;
r_strbuf_setf (&op->esil, "0x%04x,[2],pc,=", data[1] | data[2] << 8);
break;
case 0x60: // rts
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -2;
r_strbuf_set (&op->esil, "0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=");
break;
case 0x40: // rti
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -3;
r_strbuf_set (&op->esil, "0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=");
break;
case 0xea: // nop
op->type = R_ANAL_OP_TYPE_NOP;
op->cycles = 2;
break;
case 0xa9: // lda #$ff
case 0xa5: // lda $ff
case 0xb5: // lda $ff,x
case 0xad: // lda $ffff
case 0xbd: // lda $ffff,x
case 0xb9: // lda $ffff,y
case 0xa1: // lda ($ff,x)
case 0xb1: // lda ($ff),y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xa9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xa2: // ldx #$ff
case 0xa6: // ldx $ff
case 0xb6: // ldx $ff,y
case 0xae: // ldx $ffff
case 0xbe: // ldx $ffff,y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
if (data[0] == 0xa2) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0xa0: // ldy #$ff
case 0xa4: // ldy $ff
case 0xb4: // ldy $ff,x
case 0xac: // ldy $ffff
case 0xbc: // ldy $ffff,x
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
if (data[0] == 0xa0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
case 0x85: // sta $ff
case 0x95: // sta $ff,x
case 0x8d: // sta $ffff
case 0x9d: // sta $ffff,x
case 0x99: // sta $ffff,y
case 0x81: // sta ($ff,x)
case 0x91: // sta ($ff),y
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
r_strbuf_setf (&op->esil, "a,%s,=[1]", addrbuf);
break;
case 0x86: // stx $ff
case 0x96: // stx $ff,y
case 0x8e: // stx $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
r_strbuf_setf (&op->esil, "x,%s,=[1]", addrbuf);
break;
case 0x84: // sty $ff
case 0x94: // sty $ff,x
case 0x8c: // sty $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "y,%s,=[1]", addrbuf);
break;
case 0x08: // php
case 0x48: // pha
op->type = R_ANAL_OP_TYPE_PUSH;
op->cycles = 3;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 1;
_6502_anal_esil_push (op, data[0]);
break;
case 0x28: // plp
case 0x68: // plp
op->type = R_ANAL_OP_TYPE_POP;
op->cycles = 4;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -1;
_6502_anal_esil_pop (op, data[0]);
break;
case 0xaa: // tax
case 0x8a: // txa
case 0xa8: // tay
case 0x98: // tya
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
_6502_anal_esil_mov (op, data[0]);
break;
case 0x9a: // txs
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_SET;
_6502_anal_esil_mov (op, data[0]);
break;
case 0xba: // tsx
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_GET;
_6502_anal_esil_mov (op, data[0]);
break;
}
return op->size;
}
| 169,197 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GestureProviderAura::OnGestureEvent(
const GestureEventData& gesture) {
GestureEventDetails details = gesture.details;
if (gesture.type == ET_GESTURE_TAP) {
int tap_count = 1;
if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture))
tap_count = 1 + (previous_tap_->details.tap_count() % 3);
details.set_tap_count(tap_count);
if (!previous_tap_)
previous_tap_.reset(new GestureEventData(gesture));
else
*previous_tap_ = gesture;
previous_tap_->details = details;
} else if (gesture.type == ET_GESTURE_TAP_CANCEL) {
previous_tap_.reset();
}
scoped_ptr<ui::GestureEvent> event(
new ui::GestureEvent(gesture.type,
gesture.x,
gesture.y,
last_touch_event_flags_,
gesture.time - base::TimeTicks(),
details,
1 << gesture.motion_event_id));
if (!handling_event_) {
client_->OnGestureEvent(event.get());
} else {
pending_gestures_.push_back(event.release());
}
}
Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura.
BUG=379812
TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent
Review URL: https://codereview.chromium.org/309823002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GestureProviderAura::OnGestureEvent(
const GestureEventData& gesture) {
GestureEventDetails details = gesture.details;
if (gesture.type == ET_GESTURE_TAP) {
int tap_count = 1;
if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture))
tap_count = 1 + (previous_tap_->details.tap_count() % 3);
details.set_tap_count(tap_count);
if (!previous_tap_)
previous_tap_.reset(new GestureEventData(gesture));
else
*previous_tap_ = gesture;
previous_tap_->details = details;
} else if (gesture.type == ET_GESTURE_TAP_CANCEL) {
previous_tap_.reset();
}
scoped_ptr<ui::GestureEvent> event(
new ui::GestureEvent(gesture.type,
gesture.x,
gesture.y,
last_touch_event_flags_,
gesture.time - base::TimeTicks(),
details,
1 << gesture.motion_event_id));
ui::LatencyInfo* gesture_latency = event->latency();
gesture_latency->CopyLatencyFrom(
last_touch_event_latency_info_,
ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT);
gesture_latency->CopyLatencyFrom(
last_touch_event_latency_info_,
ui::INPUT_EVENT_LATENCY_UI_COMPONENT);
gesture_latency->CopyLatencyFrom(
last_touch_event_latency_info_,
ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT);
if (!handling_event_) {
client_->OnGestureEvent(event.get());
} else {
pending_gestures_.push_back(event.release());
}
}
| 171,204 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TypingCommand::insertText(Document& document,
const String& text,
Options options,
TextCompositionType composition,
const bool isIncrementalInsertion) {
LocalFrame* frame = document.frame();
DCHECK(frame);
if (!text.isEmpty())
document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
insertText(document, text,
frame->selection().computeVisibleSelectionInDOMTreeDeprecated(),
options, composition, isIncrementalInsertion);
}
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368}
CWE ID: | void TypingCommand::insertText(Document& document,
const String& text,
Options options,
TextCompositionType composition,
const bool isIncrementalInsertion) {
LocalFrame* frame = document.frame();
DCHECK(frame);
if (!text.isEmpty())
document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
insertText(document, text, frame->selection().selectionInDOMTree(), options,
composition, isIncrementalInsertion);
}
| 172,031 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct blkcipher_walk walk;
struct crypto_blkcipher *tfm = desc->tfm;
struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm);
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, 64);
salsa20_ivsetup(ctx, walk.iv);
if (likely(walk.nbytes == nbytes))
{
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr, nbytes);
return blkcipher_walk_done(desc, &walk, 0);
}
while (walk.nbytes >= 64) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr,
walk.nbytes - (walk.nbytes % 64));
err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64);
}
if (walk.nbytes) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr, walk.nbytes);
err = blkcipher_walk_done(desc, &walk, 0);
}
return err;
}
Commit Message: crypto: salsa20 - fix blkcipher_walk API usage
When asked to encrypt or decrypt 0 bytes, both the generic and x86
implementations of Salsa20 crash in blkcipher_walk_done(), either when
doing 'kfree(walk->buffer)' or 'free_page((unsigned long)walk->page)',
because walk->buffer and walk->page have not been initialized.
The bug is that Salsa20 is calling blkcipher_walk_done() even when
nothing is in 'walk.nbytes'. But blkcipher_walk_done() is only meant to
be called when a nonzero number of bytes have been provided.
The broken code is part of an optimization that tries to make only one
call to salsa20_encrypt_bytes() to process inputs that are not evenly
divisible by 64 bytes. To fix the bug, just remove this "optimization"
and use the blkcipher_walk API the same way all the other users do.
Reproducer:
#include <linux/if_alg.h>
#include <sys/socket.h>
#include <unistd.h>
int main()
{
int algfd, reqfd;
struct sockaddr_alg addr = {
.salg_type = "skcipher",
.salg_name = "salsa20",
};
char key[16] = { 0 };
algfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
bind(algfd, (void *)&addr, sizeof(addr));
reqfd = accept(algfd, 0, 0);
setsockopt(algfd, SOL_ALG, ALG_SET_KEY, key, sizeof(key));
read(reqfd, key, sizeof(key));
}
Reported-by: syzbot <[email protected]>
Fixes: eb6f13eb9f81 ("[CRYPTO] salsa20_generic: Fix multi-page processing")
Cc: <[email protected]> # v2.6.25+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-20 | static int encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct blkcipher_walk walk;
struct crypto_blkcipher *tfm = desc->tfm;
struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm);
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, 64);
salsa20_ivsetup(ctx, walk.iv);
while (walk.nbytes >= 64) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr,
walk.nbytes - (walk.nbytes % 64));
err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64);
}
if (walk.nbytes) {
salsa20_encrypt_bytes(ctx, walk.dst.virt.addr,
walk.src.virt.addr, walk.nbytes);
err = blkcipher_walk_done(desc, &walk, 0);
}
return err;
}
| 167,652 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintMsg_Print_Params::Reset() {
page_size = gfx::Size();
content_size = gfx::Size();
printable_area = gfx::Rect();
margin_top = 0;
margin_left = 0;
dpi = 0;
min_shrink = 0;
max_shrink = 0;
desired_dpi = 0;
document_cookie = 0;
selection_only = false;
supports_alpha_blend = false;
preview_ui_addr = std::string();
preview_request_id = 0;
is_first_request = false;
print_scaling_option = WebKit::WebPrintScalingOptionSourceSize;
print_to_pdf = false;
display_header_footer = false;
date = string16();
title = string16();
url = string16();
}
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 PrintMsg_Print_Params::Reset() {
page_size = gfx::Size();
content_size = gfx::Size();
printable_area = gfx::Rect();
margin_top = 0;
margin_left = 0;
dpi = 0;
min_shrink = 0;
max_shrink = 0;
desired_dpi = 0;
document_cookie = 0;
selection_only = false;
supports_alpha_blend = false;
preview_ui_id = -1;
preview_request_id = 0;
is_first_request = false;
print_scaling_option = WebKit::WebPrintScalingOptionSourceSize;
print_to_pdf = false;
display_header_footer = false;
date = string16();
title = string16();
url = string16();
}
| 170,846 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool __skb_flow_dissect(const struct sk_buff *skb,
struct flow_dissector *flow_dissector,
void *target_container,
void *data, __be16 proto, int nhoff, int hlen)
{
struct flow_dissector_key_control *key_control;
struct flow_dissector_key_basic *key_basic;
struct flow_dissector_key_addrs *key_addrs;
struct flow_dissector_key_ports *key_ports;
struct flow_dissector_key_tags *key_tags;
struct flow_dissector_key_keyid *key_keyid;
u8 ip_proto = 0;
if (!data) {
data = skb->data;
proto = skb->protocol;
nhoff = skb_network_offset(skb);
hlen = skb_headlen(skb);
}
/* It is ensured by skb_flow_dissector_init() that control key will
* be always present.
*/
key_control = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_CONTROL,
target_container);
/* It is ensured by skb_flow_dissector_init() that basic key will
* be always present.
*/
key_basic = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_BASIC,
target_container);
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
struct ethhdr *eth = eth_hdr(skb);
struct flow_dissector_key_eth_addrs *key_eth_addrs;
key_eth_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_ETH_ADDRS,
target_container);
memcpy(key_eth_addrs, ð->h_dest, sizeof(*key_eth_addrs));
}
again:
switch (proto) {
case htons(ETH_P_IP): {
const struct iphdr *iph;
struct iphdr _iph;
ip:
iph = __skb_header_pointer(skb, nhoff, sizeof(_iph), data, hlen, &_iph);
if (!iph || iph->ihl < 5)
return false;
nhoff += iph->ihl * 4;
ip_proto = iph->protocol;
if (ip_is_fragment(iph))
ip_proto = 0;
if (!skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_IPV4_ADDRS))
break;
key_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_IPV4_ADDRS, target_container);
memcpy(&key_addrs->v4addrs, &iph->saddr,
sizeof(key_addrs->v4addrs));
key_control->addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
break;
}
case htons(ETH_P_IPV6): {
const struct ipv6hdr *iph;
struct ipv6hdr _iph;
__be32 flow_label;
ipv6:
iph = __skb_header_pointer(skb, nhoff, sizeof(_iph), data, hlen, &_iph);
if (!iph)
return false;
ip_proto = iph->nexthdr;
nhoff += sizeof(struct ipv6hdr);
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_IPV6_ADDRS)) {
struct flow_dissector_key_ipv6_addrs *key_ipv6_addrs;
key_ipv6_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_IPV6_ADDRS,
target_container);
memcpy(key_ipv6_addrs, &iph->saddr, sizeof(*key_ipv6_addrs));
key_control->addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
}
flow_label = ip6_flowlabel(iph);
if (flow_label) {
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_FLOW_LABEL)) {
key_tags = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_FLOW_LABEL,
target_container);
key_tags->flow_label = ntohl(flow_label);
}
}
break;
}
case htons(ETH_P_8021AD):
case htons(ETH_P_8021Q): {
const struct vlan_hdr *vlan;
struct vlan_hdr _vlan;
vlan = __skb_header_pointer(skb, nhoff, sizeof(_vlan), data, hlen, &_vlan);
if (!vlan)
return false;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_VLANID)) {
key_tags = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_VLANID,
target_container);
key_tags->vlan_id = skb_vlan_tag_get_id(skb);
}
proto = vlan->h_vlan_encapsulated_proto;
nhoff += sizeof(*vlan);
goto again;
}
case htons(ETH_P_PPP_SES): {
struct {
struct pppoe_hdr hdr;
__be16 proto;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
return false;
proto = hdr->proto;
nhoff += PPPOE_SES_HLEN;
switch (proto) {
case htons(PPP_IP):
goto ip;
case htons(PPP_IPV6):
goto ipv6;
default:
return false;
}
}
case htons(ETH_P_TIPC): {
struct {
__be32 pre[3];
__be32 srcnode;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
return false;
key_basic->n_proto = proto;
key_control->thoff = (u16)nhoff;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_TIPC_ADDRS)) {
key_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_TIPC_ADDRS,
target_container);
key_addrs->tipcaddrs.srcnode = hdr->srcnode;
key_control->addr_type = FLOW_DISSECTOR_KEY_TIPC_ADDRS;
}
return true;
}
case htons(ETH_P_MPLS_UC):
case htons(ETH_P_MPLS_MC): {
struct mpls_label *hdr, _hdr[2];
mpls:
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data,
hlen, &_hdr);
if (!hdr)
return false;
if ((ntohl(hdr[0].entry) & MPLS_LS_LABEL_MASK) >>
MPLS_LS_LABEL_SHIFT == MPLS_LABEL_ENTROPY) {
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_MPLS_ENTROPY)) {
key_keyid = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_MPLS_ENTROPY,
target_container);
key_keyid->keyid = hdr[1].entry &
htonl(MPLS_LS_LABEL_MASK);
}
key_basic->n_proto = proto;
key_basic->ip_proto = ip_proto;
key_control->thoff = (u16)nhoff;
return true;
}
return true;
}
case htons(ETH_P_FCOE):
key_control->thoff = (u16)(nhoff + FCOE_HEADER_LEN);
/* fall through */
default:
return false;
}
ip_proto_again:
switch (ip_proto) {
case IPPROTO_GRE: {
struct gre_hdr {
__be16 flags;
__be16 proto;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
return false;
/*
* Only look inside GRE if version zero and no
* routing
*/
if (hdr->flags & (GRE_VERSION | GRE_ROUTING))
break;
proto = hdr->proto;
nhoff += 4;
if (hdr->flags & GRE_CSUM)
nhoff += 4;
if (hdr->flags & GRE_KEY) {
const __be32 *keyid;
__be32 _keyid;
keyid = __skb_header_pointer(skb, nhoff, sizeof(_keyid),
data, hlen, &_keyid);
if (!keyid)
return false;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_GRE_KEYID)) {
key_keyid = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_GRE_KEYID,
target_container);
key_keyid->keyid = *keyid;
}
nhoff += 4;
}
if (hdr->flags & GRE_SEQ)
nhoff += 4;
if (proto == htons(ETH_P_TEB)) {
const struct ethhdr *eth;
struct ethhdr _eth;
eth = __skb_header_pointer(skb, nhoff,
sizeof(_eth),
data, hlen, &_eth);
if (!eth)
return false;
proto = eth->h_proto;
nhoff += sizeof(*eth);
}
goto again;
}
case NEXTHDR_HOP:
case NEXTHDR_ROUTING:
case NEXTHDR_DEST: {
u8 _opthdr[2], *opthdr;
if (proto != htons(ETH_P_IPV6))
break;
opthdr = __skb_header_pointer(skb, nhoff, sizeof(_opthdr),
data, hlen, &_opthdr);
if (!opthdr)
return false;
ip_proto = opthdr[0];
nhoff += (opthdr[1] + 1) << 3;
goto ip_proto_again;
}
case IPPROTO_IPIP:
proto = htons(ETH_P_IP);
goto ip;
case IPPROTO_IPV6:
proto = htons(ETH_P_IPV6);
goto ipv6;
case IPPROTO_MPLS:
proto = htons(ETH_P_MPLS_UC);
goto mpls;
default:
break;
}
key_basic->n_proto = proto;
key_basic->ip_proto = ip_proto;
key_control->thoff = (u16)nhoff;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_PORTS)) {
key_ports = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_PORTS,
target_container);
key_ports->ports = __skb_flow_get_ports(skb, nhoff, ip_proto,
data, hlen);
}
return true;
}
Commit Message: flow_dissector: Jump to exit code in __skb_flow_dissect
Instead of returning immediately (on a parsing failure for instance) we
jump to cleanup code. This always sets protocol values in key_control
(even on a failure there is still valid information in the key_tags that
was set before the problem was hit).
Signed-off-by: Tom Herbert <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | bool __skb_flow_dissect(const struct sk_buff *skb,
struct flow_dissector *flow_dissector,
void *target_container,
void *data, __be16 proto, int nhoff, int hlen)
{
struct flow_dissector_key_control *key_control;
struct flow_dissector_key_basic *key_basic;
struct flow_dissector_key_addrs *key_addrs;
struct flow_dissector_key_ports *key_ports;
struct flow_dissector_key_tags *key_tags;
struct flow_dissector_key_keyid *key_keyid;
u8 ip_proto = 0;
bool ret = false;
if (!data) {
data = skb->data;
proto = skb->protocol;
nhoff = skb_network_offset(skb);
hlen = skb_headlen(skb);
}
/* It is ensured by skb_flow_dissector_init() that control key will
* be always present.
*/
key_control = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_CONTROL,
target_container);
/* It is ensured by skb_flow_dissector_init() that basic key will
* be always present.
*/
key_basic = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_BASIC,
target_container);
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
struct ethhdr *eth = eth_hdr(skb);
struct flow_dissector_key_eth_addrs *key_eth_addrs;
key_eth_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_ETH_ADDRS,
target_container);
memcpy(key_eth_addrs, ð->h_dest, sizeof(*key_eth_addrs));
}
again:
switch (proto) {
case htons(ETH_P_IP): {
const struct iphdr *iph;
struct iphdr _iph;
ip:
iph = __skb_header_pointer(skb, nhoff, sizeof(_iph), data, hlen, &_iph);
if (!iph || iph->ihl < 5)
goto out_bad;
nhoff += iph->ihl * 4;
ip_proto = iph->protocol;
if (ip_is_fragment(iph))
ip_proto = 0;
if (!skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_IPV4_ADDRS))
break;
key_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_IPV4_ADDRS, target_container);
memcpy(&key_addrs->v4addrs, &iph->saddr,
sizeof(key_addrs->v4addrs));
key_control->addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
break;
}
case htons(ETH_P_IPV6): {
const struct ipv6hdr *iph;
struct ipv6hdr _iph;
__be32 flow_label;
ipv6:
iph = __skb_header_pointer(skb, nhoff, sizeof(_iph), data, hlen, &_iph);
if (!iph)
goto out_bad;
ip_proto = iph->nexthdr;
nhoff += sizeof(struct ipv6hdr);
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_IPV6_ADDRS)) {
struct flow_dissector_key_ipv6_addrs *key_ipv6_addrs;
key_ipv6_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_IPV6_ADDRS,
target_container);
memcpy(key_ipv6_addrs, &iph->saddr, sizeof(*key_ipv6_addrs));
key_control->addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
}
flow_label = ip6_flowlabel(iph);
if (flow_label) {
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_FLOW_LABEL)) {
key_tags = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_FLOW_LABEL,
target_container);
key_tags->flow_label = ntohl(flow_label);
}
}
break;
}
case htons(ETH_P_8021AD):
case htons(ETH_P_8021Q): {
const struct vlan_hdr *vlan;
struct vlan_hdr _vlan;
vlan = __skb_header_pointer(skb, nhoff, sizeof(_vlan), data, hlen, &_vlan);
if (!vlan)
goto out_bad;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_VLANID)) {
key_tags = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_VLANID,
target_container);
key_tags->vlan_id = skb_vlan_tag_get_id(skb);
}
proto = vlan->h_vlan_encapsulated_proto;
nhoff += sizeof(*vlan);
goto again;
}
case htons(ETH_P_PPP_SES): {
struct {
struct pppoe_hdr hdr;
__be16 proto;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
goto out_bad;
proto = hdr->proto;
nhoff += PPPOE_SES_HLEN;
switch (proto) {
case htons(PPP_IP):
goto ip;
case htons(PPP_IPV6):
goto ipv6;
default:
goto out_bad;
}
}
case htons(ETH_P_TIPC): {
struct {
__be32 pre[3];
__be32 srcnode;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
goto out_bad;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_TIPC_ADDRS)) {
key_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_TIPC_ADDRS,
target_container);
key_addrs->tipcaddrs.srcnode = hdr->srcnode;
key_control->addr_type = FLOW_DISSECTOR_KEY_TIPC_ADDRS;
}
goto out_good;
}
case htons(ETH_P_MPLS_UC):
case htons(ETH_P_MPLS_MC): {
struct mpls_label *hdr, _hdr[2];
mpls:
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data,
hlen, &_hdr);
if (!hdr)
goto out_bad;
if ((ntohl(hdr[0].entry) & MPLS_LS_LABEL_MASK) >>
MPLS_LS_LABEL_SHIFT == MPLS_LABEL_ENTROPY) {
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_MPLS_ENTROPY)) {
key_keyid = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_MPLS_ENTROPY,
target_container);
key_keyid->keyid = hdr[1].entry &
htonl(MPLS_LS_LABEL_MASK);
}
goto out_good;
}
goto out_good;
}
case htons(ETH_P_FCOE):
key_control->thoff = (u16)(nhoff + FCOE_HEADER_LEN);
/* fall through */
default:
goto out_bad;
}
ip_proto_again:
switch (ip_proto) {
case IPPROTO_GRE: {
struct gre_hdr {
__be16 flags;
__be16 proto;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
goto out_bad;
/*
* Only look inside GRE if version zero and no
* routing
*/
if (hdr->flags & (GRE_VERSION | GRE_ROUTING))
break;
proto = hdr->proto;
nhoff += 4;
if (hdr->flags & GRE_CSUM)
nhoff += 4;
if (hdr->flags & GRE_KEY) {
const __be32 *keyid;
__be32 _keyid;
keyid = __skb_header_pointer(skb, nhoff, sizeof(_keyid),
data, hlen, &_keyid);
if (!keyid)
goto out_bad;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_GRE_KEYID)) {
key_keyid = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_GRE_KEYID,
target_container);
key_keyid->keyid = *keyid;
}
nhoff += 4;
}
if (hdr->flags & GRE_SEQ)
nhoff += 4;
if (proto == htons(ETH_P_TEB)) {
const struct ethhdr *eth;
struct ethhdr _eth;
eth = __skb_header_pointer(skb, nhoff,
sizeof(_eth),
data, hlen, &_eth);
if (!eth)
goto out_bad;
proto = eth->h_proto;
nhoff += sizeof(*eth);
}
goto again;
}
case NEXTHDR_HOP:
case NEXTHDR_ROUTING:
case NEXTHDR_DEST: {
u8 _opthdr[2], *opthdr;
if (proto != htons(ETH_P_IPV6))
break;
opthdr = __skb_header_pointer(skb, nhoff, sizeof(_opthdr),
data, hlen, &_opthdr);
if (!opthdr)
goto out_bad;
ip_proto = opthdr[0];
nhoff += (opthdr[1] + 1) << 3;
goto ip_proto_again;
}
case IPPROTO_IPIP:
proto = htons(ETH_P_IP);
goto ip;
case IPPROTO_IPV6:
proto = htons(ETH_P_IPV6);
goto ipv6;
case IPPROTO_MPLS:
proto = htons(ETH_P_MPLS_UC);
goto mpls;
default:
break;
}
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_PORTS)) {
key_ports = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_PORTS,
target_container);
key_ports->ports = __skb_flow_get_ports(skb, nhoff, ip_proto,
data, hlen);
}
out_good:
ret = true;
out_bad:
key_basic->n_proto = proto;
key_basic->ip_proto = ip_proto;
key_control->thoff = (u16)nhoff;
return ret;
}
| 167,785 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::MaybeLocal<v8::Array> V8Debugger::internalProperties(v8::Local<v8::Context> context, v8::Local<v8::Value> value)
{
v8::Local<v8::Array> properties;
if (!v8::Debug::GetInternalProperties(m_isolate, value).ToLocal(&properties))
return v8::MaybeLocal<v8::Array>();
if (value->IsFunction()) {
v8::Local<v8::Function> function = value.As<v8::Function>();
v8::Local<v8::Value> location = functionLocation(context, function);
if (location->IsObject()) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[FunctionLocation]]"));
properties->Set(properties->Length(), location);
}
if (function->IsGeneratorFunction()) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[IsGenerator]]"));
properties->Set(properties->Length(), v8::True(m_isolate));
}
}
if (!enabled())
return properties;
if (value->IsMap() || value->IsWeakMap() || value->IsSet() || value->IsWeakSet() || value->IsSetIterator() || value->IsMapIterator()) {
v8::Local<v8::Value> entries = collectionEntries(context, v8::Local<v8::Object>::Cast(value));
if (entries->IsArray()) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Entries]]"));
properties->Set(properties->Length(), entries);
}
}
if (value->IsGeneratorObject()) {
v8::Local<v8::Value> location = generatorObjectLocation(v8::Local<v8::Object>::Cast(value));
if (location->IsObject()) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[GeneratorLocation]]"));
properties->Set(properties->Length(), location);
}
}
if (value->IsFunction()) {
v8::Local<v8::Function> function = value.As<v8::Function>();
v8::Local<v8::Value> boundFunction = function->GetBoundFunction();
v8::Local<v8::Value> scopes;
if (boundFunction->IsUndefined() && functionScopes(function).ToLocal(&scopes)) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Scopes]]"));
properties->Set(properties->Length(), scopes);
}
}
return properties;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79 | v8::MaybeLocal<v8::Array> V8Debugger::internalProperties(v8::Local<v8::Context> context, v8::Local<v8::Value> value)
{
v8::Local<v8::Array> properties;
if (!v8::Debug::GetInternalProperties(m_isolate, value).ToLocal(&properties))
return v8::MaybeLocal<v8::Array>();
if (value->IsFunction()) {
v8::Local<v8::Function> function = value.As<v8::Function>();
v8::Local<v8::Value> location = functionLocation(context, function);
if (location->IsObject()) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[FunctionLocation]]"));
properties->Set(properties->Length(), location);
}
if (function->IsGeneratorFunction()) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[IsGenerator]]"));
properties->Set(properties->Length(), v8::True(m_isolate));
}
}
if (!enabled())
return properties;
if (value->IsMap() || value->IsWeakMap() || value->IsSet() || value->IsWeakSet() || value->IsSetIterator() || value->IsMapIterator()) {
v8::Local<v8::Value> entries = collectionEntries(context, v8::Local<v8::Object>::Cast(value));
if (entries->IsArray()) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Entries]]"));
properties->Set(properties->Length(), entries);
}
}
if (value->IsGeneratorObject()) {
v8::Local<v8::Value> location = generatorObjectLocation(context, v8::Local<v8::Object>::Cast(value));
if (location->IsObject()) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[GeneratorLocation]]"));
properties->Set(properties->Length(), location);
}
}
if (value->IsFunction()) {
v8::Local<v8::Function> function = value.As<v8::Function>();
v8::Local<v8::Value> boundFunction = function->GetBoundFunction();
v8::Local<v8::Value> scopes;
if (boundFunction->IsUndefined() && functionScopes(context, function).ToLocal(&scopes)) {
properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Scopes]]"));
properties->Set(properties->Length(), scopes);
}
}
return properties;
}
| 172,068 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)
{
ioapic->rtc_status.pending_eoi = 0;
bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS);
}
Commit Message: KVM: x86: fix out-of-bounds accesses of rtc_eoi map
KVM was using arrays of size KVM_MAX_VCPUS with vcpu_id, but ID can be
bigger that the maximal number of VCPUs, resulting in out-of-bounds
access.
Found by syzkaller:
BUG: KASAN: slab-out-of-bounds in __apic_accept_irq+0xb33/0xb50 at addr [...]
Write of size 1 by task a.out/27101
CPU: 1 PID: 27101 Comm: a.out Not tainted 4.9.0-rc5+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
[...]
Call Trace:
[...] __apic_accept_irq+0xb33/0xb50 arch/x86/kvm/lapic.c:905
[...] kvm_apic_set_irq+0x10e/0x180 arch/x86/kvm/lapic.c:495
[...] kvm_irq_delivery_to_apic+0x732/0xc10 arch/x86/kvm/irq_comm.c:86
[...] ioapic_service+0x41d/0x760 arch/x86/kvm/ioapic.c:360
[...] ioapic_set_irq+0x275/0x6c0 arch/x86/kvm/ioapic.c:222
[...] kvm_ioapic_inject_all arch/x86/kvm/ioapic.c:235
[...] kvm_set_ioapic+0x223/0x310 arch/x86/kvm/ioapic.c:670
[...] kvm_vm_ioctl_set_irqchip arch/x86/kvm/x86.c:3668
[...] kvm_arch_vm_ioctl+0x1a08/0x23c0 arch/x86/kvm/x86.c:3999
[...] kvm_vm_ioctl+0x1fa/0x1a70 arch/x86/kvm/../../../virt/kvm/kvm_main.c:3099
Reported-by: Dmitry Vyukov <[email protected]>
Cc: [email protected]
Fixes: af1bae5497b9 ("KVM: x86: bump KVM_MAX_VCPU_ID to 1023")
Reviewed-by: Paolo Bonzini <[email protected]>
Reviewed-by: David Hildenbrand <[email protected]>
Signed-off-by: Radim Krčmář <[email protected]>
CWE ID: CWE-125 | static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)
{
ioapic->rtc_status.pending_eoi = 0;
bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPU_ID);
}
| 166,847 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint16 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
Commit Message: * tools/tiffcp.c: fix read of undefined variable in case of missing
required tags. Found on test case of MSVR 35100.
* tools/tiffcrop.c: fix read of undefined buffer in
readContigStripsIntoBuffer() due to uint16 overflow. Probably not a
security issue but I can be wrong. Reported as MSVR 35100 by Axel
Souchet from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-190 | static int readContigStripsIntoBuffer (TIFF* in, uint8* buf)
{
uint8* bufp = buf;
int32 bytes_read = 0;
uint32 strip, nstrips = TIFFNumberOfStrips(in);
uint32 stripsize = TIFFStripSize(in);
uint32 rows = 0;
uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
tsize_t scanline_size = TIFFScanlineSize(in);
if (scanline_size == 0) {
TIFFError("", "TIFF scanline size is zero!");
return 0;
}
for (strip = 0; strip < nstrips; strip++) {
bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1);
rows = bytes_read / scanline_size;
if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize))
TIFFError("", "Strip %d: read %lu bytes, strip size %lu",
(int)strip + 1, (unsigned long) bytes_read,
(unsigned long)stripsize);
if (bytes_read < 0 && !ignore) {
TIFFError("", "Error reading strip %lu after %lu rows",
(unsigned long) strip, (unsigned long)rows);
return 0;
}
bufp += bytes_read;
}
return 1;
} /* end readContigStripsIntoBuffer */
| 166,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int jas_seq2d_output(jas_matrix_t *matrix, FILE *out)
{
#define MAXLINELEN 80
int i;
int j;
jas_seqent_t x;
char buf[MAXLINELEN + 1];
char sbuf[MAXLINELEN + 1];
int n;
fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix),
jas_seq2d_ystart(matrix));
fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix),
jas_matrix_numrows(matrix));
buf[0] = '\0';
for (i = 0; i < jas_matrix_numrows(matrix); ++i) {
for (j = 0; j < jas_matrix_numcols(matrix); ++j) {
x = jas_matrix_get(matrix, i, j);
sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "",
JAS_CAST(long, x));
n = JAS_CAST(int, strlen(buf));
if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
strcat(buf, sbuf);
if (j == jas_matrix_numcols(matrix) - 1) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
}
}
fputs(buf, out);
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | int jas_seq2d_output(jas_matrix_t *matrix, FILE *out)
{
#define MAXLINELEN 80
jas_matind_t i;
jas_matind_t j;
jas_seqent_t x;
char buf[MAXLINELEN + 1];
char sbuf[MAXLINELEN + 1];
int n;
fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix),
jas_seq2d_ystart(matrix));
fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix),
jas_matrix_numrows(matrix));
buf[0] = '\0';
for (i = 0; i < jas_matrix_numrows(matrix); ++i) {
for (j = 0; j < jas_matrix_numcols(matrix); ++j) {
x = jas_matrix_get(matrix, i, j);
sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "",
JAS_CAST(long, x));
n = JAS_CAST(int, strlen(buf));
if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
strcat(buf, sbuf);
if (j == jas_matrix_numcols(matrix) - 1) {
fputs(buf, out);
fputs("\n", out);
buf[0] = '\0';
}
}
}
fputs(buf, out);
return 0;
}
| 168,711 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: intuit_diff_type (bool need_header, mode_t *p_file_type)
{
file_offset this_line = 0;
file_offset first_command_line = -1;
char first_ed_command_letter = 0;
lin fcl_line = 0; /* Pacify 'gcc -W'. */
bool this_is_a_command = false;
bool stars_this_line = false;
bool extended_headers = false;
enum nametype i;
struct stat st[3];
int stat_errno[3];
int version_controlled[3];
enum diff retval;
mode_t file_type;
for (i = OLD; i <= INDEX; i++)
if (p_name[i]) {
free (p_name[i]);
p_name[i] = 0;
}
for (i = 0; i < ARRAY_SIZE (invalid_names); i++)
invalid_names[i] = NULL;
for (i = OLD; i <= NEW; i++)
if (p_timestr[i])
{
free(p_timestr[i]);
p_timestr[i] = 0;
}
for (i = OLD; i <= NEW; i++)
if (p_sha1[i])
{
free (p_sha1[i]);
p_sha1[i] = 0;
}
p_git_diff = false;
for (i = OLD; i <= NEW; i++)
{
p_mode[i] = 0;
p_copy[i] = false;
p_rename[i] = false;
}
/* Ed and normal format patches don't have filename headers. */
if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF)
need_header = false;
version_controlled[OLD] = -1;
version_controlled[NEW] = -1;
version_controlled[INDEX] = -1;
p_rfc934_nesting = 0;
p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1;
p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0;
Fseek (pfp, p_base, SEEK_SET);
p_input_line = p_bline - 1;
for (;;) {
char *s;
char *t;
file_offset previous_line = this_line;
bool last_line_was_command = this_is_a_command;
bool stars_last_line = stars_this_line;
size_t indent = 0;
char ed_command_letter;
bool strip_trailing_cr;
size_t chars_read;
this_line = file_tell (pfp);
chars_read = pget_line (0, 0, false, false);
if (chars_read == (size_t) -1)
xalloc_die ();
if (! chars_read) {
if (first_ed_command_letter) {
/* nothing but deletes!? */
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
else {
p_start = this_line;
p_sline = p_input_line;
if (extended_headers)
{
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
return NO_DIFF;
}
}
strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r';
for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
if (*s == '\t')
indent = (indent + 8) & ~7;
else
indent++;
}
if (ISDIGIT (*s))
{
for (t = s + 1; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
if (*t == 'd' || *t == 'c' || *t == 'a')
{
for (t++; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
for (; *t == ' ' || *t == '\t'; t++)
/* do nothing */ ;
if (*t == '\r')
t++;
this_is_a_command = (*t == '\n');
}
}
if (! need_header
&& first_command_line < 0
&& ((ed_command_letter = get_ed_command_letter (s))
|| this_is_a_command)) {
first_command_line = this_line;
first_ed_command_letter = ed_command_letter;
fcl_line = p_input_line;
p_indent = indent; /* assume this for now */
p_strip_trailing_cr = strip_trailing_cr;
}
if (!stars_last_line && strnEQ(s, "*** ", 4))
{
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
}
else if (strnEQ(s, "+++ ", 4))
{
/* Swap with NEW below. */
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Index:", 6))
{
fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Prereq:", 7))
{
for (t = s + 7; ISSPACE ((unsigned char) *t); t++)
/* do nothing */ ;
revision = t;
for (t = revision; *t; t++)
if (ISSPACE ((unsigned char) *t))
{
char const *u;
for (u = t + 1; ISSPACE ((unsigned char) *u); u++)
/* do nothing */ ;
if (*u)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("Prereq: with multiple words at line %s of patch\n",
format_linenum (numbuf, this_line));
}
break;
}
if (t == revision)
revision = 0;
else {
char oldc = *t;
*t = '\0';
revision = xstrdup (revision);
*t = oldc;
}
}
else if (strnEQ (s, "diff --git ", 11))
{
char const *u;
if (extended_headers)
{
p_start = this_line;
p_sline = p_input_line;
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u))
&& ISSPACE ((unsigned char) *u)
&& (p_name[NEW] = parse_name (u, strippath, &u))
&& (u = skip_spaces (u), ! *u)))
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
p_git_diff = true;
}
else if (p_git_diff && strnEQ (s, "index ", 6))
{
char const *u, *v;
if ((u = skip_hex_digits (s + 6))
&& u[0] == '.' && u[1] == '.'
&& (v = skip_hex_digits (u + 2))
&& (! *v || ISSPACE ((unsigned char) *v)))
{
get_sha1(&p_sha1[OLD], s + 6, u);
get_sha1(&p_sha1[NEW], u + 2, v);
p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]);
p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]);
if (*(v = skip_spaces (v)))
p_mode[OLD] = p_mode[NEW] = fetchmode (v);
extended_headers = true;
}
}
else if (p_git_diff && strnEQ (s, "old mode ", 9))
{
p_mode[OLD] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new mode ", 9))
{
p_mode[NEW] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "deleted file mode ", 18))
{
p_mode[OLD] = fetchmode (s + 18);
p_says_nonexistent[NEW] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new file mode ", 14))
{
p_mode[NEW] = fetchmode (s + 14);
p_says_nonexistent[OLD] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename from ", 12))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename to ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy from ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy to ", 8))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "GIT binary patch", 16))
{
p_start = this_line;
p_sline = p_input_line;
retval = GIT_BINARY_DIFF;
goto scan_exit;
}
else
{
for (t = s; t[0] == '-' && t[1] == ' '; t += 2)
/* do nothing */ ;
if (strnEQ(t, "--- ", 4))
{
struct timespec timestamp;
timestamp.tv_sec = -1;
fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW],
×tamp);
need_header = false;
if (timestamp.tv_sec != -1)
{
p_timestamp[NEW] = timestamp;
p_rfc934_nesting = (t - s) >> 1;
}
p_strip_trailing_cr = strip_trailing_cr;
}
}
if (need_header)
continue;
if ((diff_type == NO_DIFF || diff_type == ED_DIFF) &&
first_command_line >= 0 &&
strEQ(s, ".\n") ) {
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == UNI_DIFF)
&& strnEQ(s, "@@ -", 4)) {
/* 'p_name', 'p_timestr', and 'p_timestamp' are backwards;
swap them. */
struct timespec ti = p_timestamp[OLD];
p_timestamp[OLD] = p_timestamp[NEW];
p_timestamp[NEW] = ti;
t = p_name[OLD];
p_name[OLD] = p_name[NEW];
p_name[NEW] = t;
t = p_timestr[OLD];
p_timestr[OLD] = p_timestr[NEW];
p_timestr[NEW] = t;
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
while (*s != ' ' && *s != '\n')
s++;
while (*s == ' ')
s++;
if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2]))
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
p_indent = indent;
p_start = this_line;
p_sline = p_input_line;
retval = UNI_DIFF;
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for unified diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
stars_this_line = strnEQ(s, "********", 8);
if ((diff_type == NO_DIFF
|| diff_type == CONTEXT_DIFF
|| diff_type == NEW_CONTEXT_DIFF)
&& stars_last_line && strnEQ (s, "*** ", 4)) {
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
/* if this is a new context diff the character just before */
/* the newline is a '*'. */
while (*s != '\n')
s++;
p_indent = indent;
p_strip_trailing_cr = strip_trailing_cr;
p_start = previous_line;
p_sline = p_input_line - 1;
retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
{
/* Scan the first hunk to see whether the file contents
appear to have been deleted. */
file_offset saved_p_base = p_base;
lin saved_p_bline = p_bline;
Fseek (pfp, previous_line, SEEK_SET);
p_input_line -= 2;
if (another_hunk (retval, false)
&& ! p_repl_lines && p_newfirst == 1)
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
next_intuit_at (saved_p_base, saved_p_bline);
}
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for context diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) &&
last_line_was_command &&
(strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) {
p_start = previous_line;
p_sline = p_input_line - 1;
p_indent = indent;
retval = NORMAL_DIFF;
goto scan_exit;
}
}
scan_exit:
/* The old, new, or old and new file types may be defined. When both
file types are defined, make sure they are the same, or else assume
we do not know the file type. */
file_type = p_mode[OLD] & S_IFMT;
if (file_type)
{
mode_t new_file_type = p_mode[NEW] & S_IFMT;
if (new_file_type && file_type != new_file_type)
file_type = 0;
}
else
{
file_type = p_mode[NEW] & S_IFMT;
if (! file_type)
file_type = S_IFREG;
}
*p_file_type = file_type;
/* To intuit 'inname', the name of the file to patch,
use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599
(with some modifications if posixly_correct is zero):
- Take the old and new names from the context header if present,
and take the index name from the 'Index:' line if present and
if either the old and new names are both absent
or posixly_correct is nonzero.
Consider the file names to be in the order (old, new, index).
- If some named files exist, use the first one if posixly_correct
is nonzero, the best one otherwise.
- If patch_get is nonzero, and no named files exist,
but an RCS or SCCS master file exists,
use the first named file with an RCS or SCCS master.
- If no named files exist, no RCS or SCCS master was found,
some names are given, posixly_correct is zero,
and the patch appears to create a file, then use the best name
requiring the creation of the fewest directories.
- Otherwise, report failure by setting 'inname' to 0;
this causes our invoker to ask the user for a file name. */
i = NONE;
if (!inname)
{
enum nametype i0 = NONE;
if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX])
{
free (p_name[INDEX]);
p_name[INDEX] = 0;
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0)
{
/* It's the same name as before; reuse stat results. */
stat_errno[i] = stat_errno[i0];
if (! stat_errno[i])
st[i] = st[i0];
}
else
{
stat_errno[i] = stat_file (p_name[i], &st[i]);
if (! stat_errno[i])
{
if (lookup_file_id (&st[i]) == DELETE_LATER)
stat_errno[i] = ENOENT;
else if (posixly_correct && name_is_valid (p_name[i]))
break;
}
}
i0 = i;
}
if (! posixly_correct)
{
/* The best of all existing files. */
i = best_name (p_name, stat_errno);
if (i == NONE && patch_get)
{
enum nametype nope = NONE;
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
char const *cs;
char *getbuf;
char *diffbuf;
bool readonly = (outfile
&& strcmp (outfile, p_name[i]) != 0);
if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0)
{
cs = (version_controller
(p_name[i], readonly, (struct stat *) 0,
&getbuf, &diffbuf));
version_controlled[i] = !! cs;
if (cs)
{
if (version_get (p_name[i], cs, false, readonly,
getbuf, &st[i]))
stat_errno[i] = 0;
else
version_controlled[i] = 0;
free (getbuf);
free (diffbuf);
if (! stat_errno[i])
break;
}
}
nope = i;
}
}
if (i0 != NONE
&& (i == NONE || (st[i].st_mode & S_IFMT) == file_type)
&& maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE,
i == NONE || st[i].st_size == 0)
&& i == NONE)
i = i0;
if (i == NONE && p_says_nonexistent[reverse])
{
int newdirs[3];
int newdirs_min = INT_MAX;
int distance_from_minimum[3];
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
newdirs[i] = (prefix_components (p_name[i], false)
- prefix_components (p_name[i], true));
if (newdirs[i] < newdirs_min)
newdirs_min = newdirs[i];
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
distance_from_minimum[i] = newdirs[i] - newdirs_min;
/* The best of the filenames which create the fewest directories. */
i = best_name (p_name, distance_from_minimum);
}
}
}
if (i == NONE)
{
if (inname)
inname = xstrdup (p_name[i]);
inerrno = stat_errno[i];
invc = version_controlled[i];
instat = st[i];
}
return retval;
}
Commit Message:
CWE ID: CWE-22 | intuit_diff_type (bool need_header, mode_t *p_file_type)
{
file_offset this_line = 0;
file_offset first_command_line = -1;
char first_ed_command_letter = 0;
lin fcl_line = 0; /* Pacify 'gcc -W'. */
bool this_is_a_command = false;
bool stars_this_line = false;
bool extended_headers = false;
enum nametype i;
struct stat st[3];
int stat_errno[3];
int version_controlled[3];
enum diff retval;
mode_t file_type;
for (i = OLD; i <= INDEX; i++)
if (p_name[i]) {
free (p_name[i]);
p_name[i] = 0;
}
for (i = 0; i < ARRAY_SIZE (invalid_names); i++)
invalid_names[i] = NULL;
for (i = OLD; i <= NEW; i++)
if (p_timestr[i])
{
free(p_timestr[i]);
p_timestr[i] = 0;
}
for (i = OLD; i <= NEW; i++)
if (p_sha1[i])
{
free (p_sha1[i]);
p_sha1[i] = 0;
}
p_git_diff = false;
for (i = OLD; i <= NEW; i++)
{
p_mode[i] = 0;
p_copy[i] = false;
p_rename[i] = false;
}
/* Ed and normal format patches don't have filename headers. */
if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF)
need_header = false;
version_controlled[OLD] = -1;
version_controlled[NEW] = -1;
version_controlled[INDEX] = -1;
p_rfc934_nesting = 0;
p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1;
p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0;
Fseek (pfp, p_base, SEEK_SET);
p_input_line = p_bline - 1;
for (;;) {
char *s;
char *t;
file_offset previous_line = this_line;
bool last_line_was_command = this_is_a_command;
bool stars_last_line = stars_this_line;
size_t indent = 0;
char ed_command_letter;
bool strip_trailing_cr;
size_t chars_read;
this_line = file_tell (pfp);
chars_read = pget_line (0, 0, false, false);
if (chars_read == (size_t) -1)
xalloc_die ();
if (! chars_read) {
if (first_ed_command_letter) {
/* nothing but deletes!? */
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
else {
p_start = this_line;
p_sline = p_input_line;
if (extended_headers)
{
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
return NO_DIFF;
}
}
strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r';
for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
if (*s == '\t')
indent = (indent + 8) & ~7;
else
indent++;
}
if (ISDIGIT (*s))
{
for (t = s + 1; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
if (*t == 'd' || *t == 'c' || *t == 'a')
{
for (t++; ISDIGIT (*t) || *t == ','; t++)
/* do nothing */ ;
for (; *t == ' ' || *t == '\t'; t++)
/* do nothing */ ;
if (*t == '\r')
t++;
this_is_a_command = (*t == '\n');
}
}
if (! need_header
&& first_command_line < 0
&& ((ed_command_letter = get_ed_command_letter (s))
|| this_is_a_command)) {
first_command_line = this_line;
first_ed_command_letter = ed_command_letter;
fcl_line = p_input_line;
p_indent = indent; /* assume this for now */
p_strip_trailing_cr = strip_trailing_cr;
}
if (!stars_last_line && strnEQ(s, "*** ", 4))
{
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
}
else if (strnEQ(s, "+++ ", 4))
{
/* Swap with NEW below. */
fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD],
&p_timestamp[OLD]);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Index:", 6))
{
fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL);
need_header = false;
p_strip_trailing_cr = strip_trailing_cr;
}
else if (strnEQ(s, "Prereq:", 7))
{
for (t = s + 7; ISSPACE ((unsigned char) *t); t++)
/* do nothing */ ;
revision = t;
for (t = revision; *t; t++)
if (ISSPACE ((unsigned char) *t))
{
char const *u;
for (u = t + 1; ISSPACE ((unsigned char) *u); u++)
/* do nothing */ ;
if (*u)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("Prereq: with multiple words at line %s of patch\n",
format_linenum (numbuf, this_line));
}
break;
}
if (t == revision)
revision = 0;
else {
char oldc = *t;
*t = '\0';
revision = xstrdup (revision);
*t = oldc;
}
}
else if (strnEQ (s, "diff --git ", 11))
{
char const *u;
if (extended_headers)
{
p_start = this_line;
p_sline = p_input_line;
/* Patch contains no hunks; any diff type will do. */
retval = UNI_DIFF;
goto scan_exit;
}
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u))
&& ISSPACE ((unsigned char) *u)
&& (p_name[NEW] = parse_name (u, strippath, &u))
&& (u = skip_spaces (u), ! *u)))
for (i = OLD; i <= NEW; i++)
{
free (p_name[i]);
p_name[i] = 0;
}
p_git_diff = true;
}
else if (p_git_diff && strnEQ (s, "index ", 6))
{
char const *u, *v;
if ((u = skip_hex_digits (s + 6))
&& u[0] == '.' && u[1] == '.'
&& (v = skip_hex_digits (u + 2))
&& (! *v || ISSPACE ((unsigned char) *v)))
{
get_sha1(&p_sha1[OLD], s + 6, u);
get_sha1(&p_sha1[NEW], u + 2, v);
p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]);
p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]);
if (*(v = skip_spaces (v)))
p_mode[OLD] = p_mode[NEW] = fetchmode (v);
extended_headers = true;
}
}
else if (p_git_diff && strnEQ (s, "old mode ", 9))
{
p_mode[OLD] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new mode ", 9))
{
p_mode[NEW] = fetchmode (s + 9);
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "deleted file mode ", 18))
{
p_mode[OLD] = fetchmode (s + 18);
p_says_nonexistent[NEW] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "new file mode ", 14))
{
p_mode[NEW] = fetchmode (s + 14);
p_says_nonexistent[OLD] = 2;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename from ", 12))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "rename to ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_rename[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy from ", 10))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[OLD] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "copy to ", 8))
{
/* Git leaves out the prefix in the file name in this header,
so we can only ignore the file name. */
p_copy[NEW] = true;
extended_headers = true;
}
else if (p_git_diff && strnEQ (s, "GIT binary patch", 16))
{
p_start = this_line;
p_sline = p_input_line;
retval = GIT_BINARY_DIFF;
goto scan_exit;
}
else
{
for (t = s; t[0] == '-' && t[1] == ' '; t += 2)
/* do nothing */ ;
if (strnEQ(t, "--- ", 4))
{
struct timespec timestamp;
timestamp.tv_sec = -1;
fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW],
×tamp);
need_header = false;
if (timestamp.tv_sec != -1)
{
p_timestamp[NEW] = timestamp;
p_rfc934_nesting = (t - s) >> 1;
}
p_strip_trailing_cr = strip_trailing_cr;
}
}
if (need_header)
continue;
if ((diff_type == NO_DIFF || diff_type == ED_DIFF) &&
first_command_line >= 0 &&
strEQ(s, ".\n") ) {
p_start = first_command_line;
p_sline = fcl_line;
retval = ED_DIFF;
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == UNI_DIFF)
&& strnEQ(s, "@@ -", 4)) {
/* 'p_name', 'p_timestr', and 'p_timestamp' are backwards;
swap them. */
struct timespec ti = p_timestamp[OLD];
p_timestamp[OLD] = p_timestamp[NEW];
p_timestamp[NEW] = ti;
t = p_name[OLD];
p_name[OLD] = p_name[NEW];
p_name[NEW] = t;
t = p_timestr[OLD];
p_timestr[OLD] = p_timestr[NEW];
p_timestr[NEW] = t;
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
while (*s != ' ' && *s != '\n')
s++;
while (*s == ' ')
s++;
if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2]))
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
p_indent = indent;
p_start = this_line;
p_sline = p_input_line;
retval = UNI_DIFF;
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for unified diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
stars_this_line = strnEQ(s, "********", 8);
if ((diff_type == NO_DIFF
|| diff_type == CONTEXT_DIFF
|| diff_type == NEW_CONTEXT_DIFF)
&& stars_last_line && strnEQ (s, "*** ", 4)) {
s += 4;
if (s[0] == '0' && !ISDIGIT (s[1]))
p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec;
/* if this is a new context diff the character just before */
/* the newline is a '*'. */
while (*s != '\n')
s++;
p_indent = indent;
p_strip_trailing_cr = strip_trailing_cr;
p_start = previous_line;
p_sline = p_input_line - 1;
retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
{
/* Scan the first hunk to see whether the file contents
appear to have been deleted. */
file_offset saved_p_base = p_base;
lin saved_p_bline = p_bline;
Fseek (pfp, previous_line, SEEK_SET);
p_input_line -= 2;
if (another_hunk (retval, false)
&& ! p_repl_lines && p_newfirst == 1)
p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec;
next_intuit_at (saved_p_base, saved_p_bline);
}
if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec)
&& (p_name[NEW] || ! p_timestamp[NEW].tv_sec))
&& ! p_name[INDEX] && need_header)
{
char numbuf[LINENUM_LENGTH_BOUND + 1];
say ("missing header for context diff at line %s of patch\n",
format_linenum (numbuf, p_sline));
}
goto scan_exit;
}
if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) &&
last_line_was_command &&
(strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) {
p_start = previous_line;
p_sline = p_input_line - 1;
p_indent = indent;
retval = NORMAL_DIFF;
goto scan_exit;
}
}
scan_exit:
/* The old, new, or old and new file types may be defined. When both
file types are defined, make sure they are the same, or else assume
we do not know the file type. */
file_type = p_mode[OLD] & S_IFMT;
if (file_type)
{
mode_t new_file_type = p_mode[NEW] & S_IFMT;
if (new_file_type && file_type != new_file_type)
file_type = 0;
}
else
{
file_type = p_mode[NEW] & S_IFMT;
if (! file_type)
file_type = S_IFREG;
}
*p_file_type = file_type;
/* To intuit 'inname', the name of the file to patch,
use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599
(with some modifications if posixly_correct is zero):
- Take the old and new names from the context header if present,
and take the index name from the 'Index:' line if present and
if either the old and new names are both absent
or posixly_correct is nonzero.
Consider the file names to be in the order (old, new, index).
- If some named files exist, use the first one if posixly_correct
is nonzero, the best one otherwise.
- If patch_get is nonzero, and no named files exist,
but an RCS or SCCS master file exists,
use the first named file with an RCS or SCCS master.
- If no named files exist, no RCS or SCCS master was found,
some names are given, posixly_correct is zero,
and the patch appears to create a file, then use the best name
requiring the creation of the fewest directories.
- Otherwise, report failure by setting 'inname' to 0;
this causes our invoker to ask the user for a file name. */
i = NONE;
if (!inname)
{
enum nametype i0 = NONE;
if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX])
{
free (p_name[INDEX]);
p_name[INDEX] = 0;
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0)
{
/* It's the same name as before; reuse stat results. */
stat_errno[i] = stat_errno[i0];
if (! stat_errno[i])
st[i] = st[i0];
}
else
{
stat_errno[i] = stat_file (p_name[i], &st[i]);
if (! stat_errno[i])
{
if (lookup_file_id (&st[i]) == DELETE_LATER)
stat_errno[i] = ENOENT;
else if (posixly_correct && name_is_valid (p_name[i]))
break;
}
}
i0 = i;
}
if (! posixly_correct)
{
/* The best of all existing files. */
i = best_name (p_name, stat_errno);
if (i == NONE && patch_get)
{
enum nametype nope = NONE;
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
char const *cs;
char *getbuf;
char *diffbuf;
bool readonly = (outfile
&& strcmp (outfile, p_name[i]) != 0);
if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0)
{
cs = (version_controller
(p_name[i], readonly, (struct stat *) 0,
&getbuf, &diffbuf));
version_controlled[i] = !! cs;
if (cs)
{
if (version_get (p_name[i], cs, false, readonly,
getbuf, &st[i]))
stat_errno[i] = 0;
else
version_controlled[i] = 0;
free (getbuf);
free (diffbuf);
if (! stat_errno[i])
break;
}
}
nope = i;
}
}
if (i0 != NONE
&& (i == NONE || (st[i].st_mode & S_IFMT) == file_type)
&& maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE,
i == NONE || st[i].st_size == 0)
&& i == NONE)
i = i0;
if (i == NONE && p_says_nonexistent[reverse])
{
int newdirs[3];
int newdirs_min = INT_MAX;
int distance_from_minimum[3];
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
{
newdirs[i] = (prefix_components (p_name[i], false)
- prefix_components (p_name[i], true));
if (newdirs[i] < newdirs_min)
newdirs_min = newdirs[i];
}
for (i = OLD; i <= INDEX; i++)
if (p_name[i])
distance_from_minimum[i] = newdirs[i] - newdirs_min;
/* The best of the filenames which create the fewest directories. */
i = best_name (p_name, distance_from_minimum);
}
}
}
if ((pch_rename () || pch_copy ())
&& ! inname
&& ! ((i == OLD || i == NEW) &&
p_name[! reverse] &&
name_is_valid (p_name[! reverse])))
{
say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy");
skip_rest_of_patch = true;
}
if (i == NONE)
{
if (inname)
inname = xstrdup (p_name[i]);
inerrno = stat_errno[i];
invc = version_controlled[i];
instat = st[i];
}
return retval;
}
| 165,397 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeOSSendHandwritingStroke(InputMethodStatusConnection* connection,
const HandwritingStroke& stroke) {
g_return_if_fail(connection);
connection->SendHandwritingStroke(stroke);
}
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 ChromeOSSendHandwritingStroke(InputMethodStatusConnection* connection,
virtual void SendHandwritingStroke(const HandwritingStroke& stroke) {
}
virtual void CancelHandwriting(int n_strokes) {
}
};
IBusController* IBusController::Create() {
#if defined(HAVE_IBUS)
return IBusControllerImpl::GetInstance();
#else
return new IBusControllerStubImpl;
#endif
}
| 170,525 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface(ExecState* exec)
{
JSTestSerializedScriptValueInterfaceConstructor* castedThis = jsCast<JSTestSerializedScriptValueInterfaceConstructor*>(exec->callee());
if (exec->argumentCount() < 2)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
const String& hello(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
RefPtr<SerializedScriptValue> data(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
Array* transferList(toArray(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
RefPtr<TestSerializedScriptValueInterface> object = TestSerializedScriptValueInterface::create(hello, data, transferList);
return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get())));
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface(ExecState* exec)
{
JSTestSerializedScriptValueInterfaceConstructor* castedThis = jsCast<JSTestSerializedScriptValueInterfaceConstructor*>(exec->callee());
if (exec->argumentCount() < 2)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
const String& hello(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
RefPtr<SerializedScriptValue> data(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
Array* transferList(toArray(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
RefPtr<TestSerializedScriptValueInterface> object = TestSerializedScriptValueInterface::create(hello, data, transferList);
return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get())));
}
| 170,611 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebRunnerContentBrowserClient::CreateBrowserMainParts(
const content::MainFunctionParams& parameters) {
DCHECK(context_channel_);
return new WebRunnerBrowserMainParts(std::move(context_channel_));
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | WebRunnerContentBrowserClient::CreateBrowserMainParts(
const content::MainFunctionParams& parameters) {
DCHECK(context_channel_);
main_parts_ = new WebRunnerBrowserMainParts(std::move(context_channel_));
return main_parts_;
}
| 172,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const service_manager::Manifest& GetChromeContentBrowserOverlayManifest() {
static base::NoDestructor<service_manager::Manifest> manifest {
service_manager::ManifestBuilder()
.ExposeCapability("gpu",
service_manager::Manifest::InterfaceList<
metrics::mojom::CallStackProfileCollector>())
.ExposeCapability("renderer",
service_manager::Manifest::InterfaceList<
chrome::mojom::AvailableOfflineContentProvider,
chrome::mojom::CacheStatsRecorder,
chrome::mojom::NetBenchmarking,
data_reduction_proxy::mojom::DataReductionProxy,
metrics::mojom::CallStackProfileCollector,
#if defined(OS_WIN)
mojom::ModuleEventSink,
#endif
rappor::mojom::RapporRecorder,
safe_browsing::mojom::SafeBrowsing>())
.RequireCapability("ash", "system_ui")
.RequireCapability("ash", "test")
.RequireCapability("ash", "display")
.RequireCapability("assistant", "assistant")
.RequireCapability("assistant_audio_decoder", "assistant:audio_decoder")
.RequireCapability("chrome", "input_device_controller")
.RequireCapability("chrome_printing", "converter")
.RequireCapability("cups_ipp_parser", "ipp_parser")
.RequireCapability("device", "device:fingerprint")
.RequireCapability("device", "device:geolocation_config")
.RequireCapability("device", "device:geolocation_control")
.RequireCapability("device", "device:ip_geolocator")
.RequireCapability("ime", "input_engine")
.RequireCapability("mirroring", "mirroring")
.RequireCapability("nacl_broker", "browser")
.RequireCapability("nacl_loader", "browser")
.RequireCapability("noop", "noop")
.RequireCapability("patch", "patch_file")
.RequireCapability("preferences", "pref_client")
.RequireCapability("preferences", "pref_control")
.RequireCapability("profile_import", "import")
.RequireCapability("removable_storage_writer",
"removable_storage_writer")
.RequireCapability("secure_channel", "secure_channel")
.RequireCapability("ui", "ime_registrar")
.RequireCapability("ui", "input_device_controller")
.RequireCapability("ui", "window_manager")
.RequireCapability("unzip", "unzip_file")
.RequireCapability("util_win", "util_win")
.RequireCapability("xr_device_service", "xr_device_provider")
.RequireCapability("xr_device_service", "xr_device_test_hook")
#if defined(OS_CHROMEOS)
.RequireCapability("multidevice_setup", "multidevice_setup")
#endif
.ExposeInterfaceFilterCapability_Deprecated(
"navigation:frame", "renderer",
service_manager::Manifest::InterfaceList<
autofill::mojom::AutofillDriver,
autofill::mojom::PasswordManagerDriver,
chrome::mojom::OfflinePageAutoFetcher,
#if defined(OS_CHROMEOS)
chromeos_camera::mojom::CameraAppHelper,
chromeos::cellular_setup::mojom::CellularSetup,
chromeos::crostini_installer::mojom::PageHandlerFactory,
chromeos::crostini_upgrader::mojom::PageHandlerFactory,
chromeos::ime::mojom::InputEngineManager,
chromeos::machine_learning::mojom::PageHandler,
chromeos::media_perception::mojom::MediaPerception,
chromeos::multidevice_setup::mojom::MultiDeviceSetup,
chromeos::multidevice_setup::mojom::PrivilegedHostDeviceSetter,
chromeos::network_config::mojom::CrosNetworkConfig,
cros::mojom::CameraAppDeviceProvider,
#endif
contextual_search::mojom::ContextualSearchJsApiService,
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::KeepAlive,
#endif
media::mojom::MediaEngagementScoreDetailsProvider,
media_router::mojom::MediaRouter,
page_load_metrics::mojom::PageLoadMetrics,
translate::mojom::ContentTranslateDriver,
downloads::mojom::PageHandlerFactory,
feed_internals::mojom::PageHandler,
new_tab_page::mojom::PageHandlerFactory,
#if defined(OS_ANDROID)
explore_sites_internals::mojom::PageHandler,
#else
app_management::mojom::PageHandlerFactory,
#endif
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
defined(OS_CHROMEOS)
discards::mojom::DetailsProvider, discards::mojom::GraphDump,
#endif
#if defined(OS_CHROMEOS)
add_supervision::mojom::AddSupervisionHandler,
#endif
mojom::BluetoothInternalsHandler,
mojom::InterventionsInternalsPageHandler,
mojom::OmniboxPageHandler, mojom::ResetPasswordHandler,
mojom::SiteEngagementDetailsProvider,
mojom::UsbInternalsPageHandler,
snippets_internals::mojom::PageHandlerFactory>())
.PackageService(prefs::GetManifest())
#if defined(OS_CHROMEOS)
.PackageService(chromeos::multidevice_setup::GetManifest())
#endif // defined(OS_CHROMEOS)
.Build()
};
return *manifest;
}
Commit Message: Revert "Creates a WebUI-based Crostini Upgrader"
This reverts commit 29c8bb394dd8b8c03e006efb39ec77fc42f96900.
Reason for revert:
Findit (https://goo.gl/kROfz5) identified CL at revision 717476 as the
culprit for failures in the build cycles as shown on:
https://analysis.chromium.org/waterfall/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyRAsSDVdmU3VzcGVjdGVkQ0wiMWNocm9taXVtLzI5YzhiYjM5NGRkOGI4YzAzZTAwNmVmYjM5ZWM3N2ZjNDJmOTY5MDAM
Sample Failed Build: https://ci.chromium.org/b/8896211200981346592
Sample Failed Step: compile
Original change's description:
> Creates a WebUI-based Crostini Upgrader
>
> The UI is behind the new crostini-webui-upgrader flag
> (currently disabled by default)
>
> The main areas for review are
>
> calamity@:
> html/js - chrome/browser/chromeos/crostini_upgrader/
> mojo and webui glue classes - chrome/browser/ui/webui/crostini_upgrader/
>
> davidmunro@
> crostini business logic - chrome/browser/chromeos/crostini/
>
> In this CL, the optional container backup stage is stubbed, and will be
> in a subsequent CL.
>
> A suite of unit/browser tests are also currently lacking. I intend them for
> follow-up CLs.
>
>
> Bug: 930901
> Change-Id: Ic52c5242e6c57232ffa6be5d6af65aaff5e8f4ff
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1900520
> Commit-Queue: Nicholas Verne <[email protected]>
> Reviewed-by: Sam McNally <[email protected]>
> Reviewed-by: calamity <[email protected]>
> Reviewed-by: Ken Rockot <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#717476}
Change-Id: I704f549216a7d1dc21942fbf6cf4ab9a1d600380
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 930901
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1928159
Cr-Commit-Position: refs/heads/master@{#717481}
CWE ID: CWE-20 | const service_manager::Manifest& GetChromeContentBrowserOverlayManifest() {
static base::NoDestructor<service_manager::Manifest> manifest {
service_manager::ManifestBuilder()
.ExposeCapability("gpu",
service_manager::Manifest::InterfaceList<
metrics::mojom::CallStackProfileCollector>())
.ExposeCapability("renderer",
service_manager::Manifest::InterfaceList<
chrome::mojom::AvailableOfflineContentProvider,
chrome::mojom::CacheStatsRecorder,
chrome::mojom::NetBenchmarking,
data_reduction_proxy::mojom::DataReductionProxy,
metrics::mojom::CallStackProfileCollector,
#if defined(OS_WIN)
mojom::ModuleEventSink,
#endif
rappor::mojom::RapporRecorder,
safe_browsing::mojom::SafeBrowsing>())
.RequireCapability("ash", "system_ui")
.RequireCapability("ash", "test")
.RequireCapability("ash", "display")
.RequireCapability("assistant", "assistant")
.RequireCapability("assistant_audio_decoder", "assistant:audio_decoder")
.RequireCapability("chrome", "input_device_controller")
.RequireCapability("chrome_printing", "converter")
.RequireCapability("cups_ipp_parser", "ipp_parser")
.RequireCapability("device", "device:fingerprint")
.RequireCapability("device", "device:geolocation_config")
.RequireCapability("device", "device:geolocation_control")
.RequireCapability("device", "device:ip_geolocator")
.RequireCapability("ime", "input_engine")
.RequireCapability("mirroring", "mirroring")
.RequireCapability("nacl_broker", "browser")
.RequireCapability("nacl_loader", "browser")
.RequireCapability("noop", "noop")
.RequireCapability("patch", "patch_file")
.RequireCapability("preferences", "pref_client")
.RequireCapability("preferences", "pref_control")
.RequireCapability("profile_import", "import")
.RequireCapability("removable_storage_writer",
"removable_storage_writer")
.RequireCapability("secure_channel", "secure_channel")
.RequireCapability("ui", "ime_registrar")
.RequireCapability("ui", "input_device_controller")
.RequireCapability("ui", "window_manager")
.RequireCapability("unzip", "unzip_file")
.RequireCapability("util_win", "util_win")
.RequireCapability("xr_device_service", "xr_device_provider")
.RequireCapability("xr_device_service", "xr_device_test_hook")
#if defined(OS_CHROMEOS)
.RequireCapability("multidevice_setup", "multidevice_setup")
#endif
.ExposeInterfaceFilterCapability_Deprecated(
"navigation:frame", "renderer",
service_manager::Manifest::InterfaceList<
autofill::mojom::AutofillDriver,
autofill::mojom::PasswordManagerDriver,
chrome::mojom::OfflinePageAutoFetcher,
#if defined(OS_CHROMEOS)
chromeos_camera::mojom::CameraAppHelper,
chromeos::cellular_setup::mojom::CellularSetup,
chromeos::crostini_installer::mojom::PageHandlerFactory,
chromeos::ime::mojom::InputEngineManager,
chromeos::machine_learning::mojom::PageHandler,
chromeos::media_perception::mojom::MediaPerception,
chromeos::multidevice_setup::mojom::MultiDeviceSetup,
chromeos::multidevice_setup::mojom::PrivilegedHostDeviceSetter,
chromeos::network_config::mojom::CrosNetworkConfig,
cros::mojom::CameraAppDeviceProvider,
#endif
contextual_search::mojom::ContextualSearchJsApiService,
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::KeepAlive,
#endif
media::mojom::MediaEngagementScoreDetailsProvider,
media_router::mojom::MediaRouter,
page_load_metrics::mojom::PageLoadMetrics,
translate::mojom::ContentTranslateDriver,
downloads::mojom::PageHandlerFactory,
feed_internals::mojom::PageHandler,
new_tab_page::mojom::PageHandlerFactory,
#if defined(OS_ANDROID)
explore_sites_internals::mojom::PageHandler,
#else
app_management::mojom::PageHandlerFactory,
#endif
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
defined(OS_CHROMEOS)
discards::mojom::DetailsProvider, discards::mojom::GraphDump,
#endif
#if defined(OS_CHROMEOS)
add_supervision::mojom::AddSupervisionHandler,
#endif
mojom::BluetoothInternalsHandler,
mojom::InterventionsInternalsPageHandler,
mojom::OmniboxPageHandler, mojom::ResetPasswordHandler,
mojom::SiteEngagementDetailsProvider,
mojom::UsbInternalsPageHandler,
snippets_internals::mojom::PageHandlerFactory>())
.PackageService(prefs::GetManifest())
#if defined(OS_CHROMEOS)
.PackageService(chromeos::multidevice_setup::GetManifest())
#endif // defined(OS_CHROMEOS)
.Build()
};
return *manifest;
}
| 172,350 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gss_accept_sec_context (minor_status,
context_handle,
verifier_cred_handle,
input_token_buffer,
input_chan_bindings,
src_name,
mech_type,
output_token,
ret_flags,
time_rec,
d_cred)
OM_uint32 * minor_status;
gss_ctx_id_t * context_handle;
gss_cred_id_t verifier_cred_handle;
gss_buffer_t input_token_buffer;
gss_channel_bindings_t input_chan_bindings;
gss_name_t * src_name;
gss_OID * mech_type;
gss_buffer_t output_token;
OM_uint32 * ret_flags;
OM_uint32 * time_rec;
gss_cred_id_t * d_cred;
{
OM_uint32 status, temp_status, temp_minor_status;
OM_uint32 temp_ret_flags = 0;
gss_union_ctx_id_t union_ctx_id = NULL;
gss_cred_id_t input_cred_handle = GSS_C_NO_CREDENTIAL;
gss_cred_id_t tmp_d_cred = GSS_C_NO_CREDENTIAL;
gss_name_t internal_name = GSS_C_NO_NAME;
gss_name_t tmp_src_name = GSS_C_NO_NAME;
gss_OID_desc token_mech_type_desc;
gss_OID token_mech_type = &token_mech_type_desc;
gss_OID actual_mech = GSS_C_NO_OID;
gss_OID selected_mech = GSS_C_NO_OID;
gss_OID public_mech;
gss_mechanism mech = NULL;
gss_union_cred_t uc;
int i;
status = val_acc_sec_ctx_args(minor_status,
context_handle,
verifier_cred_handle,
input_token_buffer,
input_chan_bindings,
src_name,
mech_type,
output_token,
ret_flags,
time_rec,
d_cred);
if (status != GSS_S_COMPLETE)
return (status);
/*
* if context_handle is GSS_C_NO_CONTEXT, allocate a union context
* descriptor to hold the mech type information as well as the
* underlying mechanism context handle. Otherwise, cast the
* value of *context_handle to the union context variable.
*/
if(*context_handle == GSS_C_NO_CONTEXT) {
if (input_token_buffer == GSS_C_NO_BUFFER)
return (GSS_S_CALL_INACCESSIBLE_READ);
/* Get the token mech type */
status = gssint_get_mech_type(token_mech_type, input_token_buffer);
if (status)
return status;
/*
* An interposer calling back into the mechglue can't pass in a special
* mech, so we have to recognize it using verifier_cred_handle. Use
* the mechanism for which we have matching creds, if available.
*/
if (verifier_cred_handle != GSS_C_NO_CREDENTIAL) {
uc = (gss_union_cred_t)verifier_cred_handle;
for (i = 0; i < uc->count; i++) {
public_mech = gssint_get_public_oid(&uc->mechs_array[i]);
if (public_mech && g_OID_equal(token_mech_type, public_mech)) {
selected_mech = &uc->mechs_array[i];
break;
}
}
}
if (selected_mech == GSS_C_NO_OID) {
status = gssint_select_mech_type(minor_status, token_mech_type,
&selected_mech);
if (status)
return status;
}
} else {
union_ctx_id = (gss_union_ctx_id_t)*context_handle;
selected_mech = union_ctx_id->mech_type;
}
/* Now create a new context if we didn't get one. */
if (*context_handle == GSS_C_NO_CONTEXT) {
status = GSS_S_FAILURE;
union_ctx_id = (gss_union_ctx_id_t)
malloc(sizeof(gss_union_ctx_id_desc));
if (!union_ctx_id)
return (GSS_S_FAILURE);
union_ctx_id->loopback = union_ctx_id;
union_ctx_id->internal_ctx_id = GSS_C_NO_CONTEXT;
status = generic_gss_copy_oid(&temp_minor_status, selected_mech,
&union_ctx_id->mech_type);
if (status != GSS_S_COMPLETE) {
free(union_ctx_id);
return (status);
}
/* set the new context handle to caller's data */
*context_handle = (gss_ctx_id_t)union_ctx_id;
}
/*
* get the appropriate cred handle from the union cred struct.
*/
if (verifier_cred_handle != GSS_C_NO_CREDENTIAL) {
input_cred_handle =
gssint_get_mechanism_cred((gss_union_cred_t)verifier_cred_handle,
selected_mech);
if (input_cred_handle == GSS_C_NO_CREDENTIAL) {
/* verifier credential specified but no acceptor credential found */
status = GSS_S_NO_CRED;
goto error_out;
}
} else if (!allow_mech_by_default(selected_mech)) {
status = GSS_S_NO_CRED;
goto error_out;
}
/*
* now select the approprate underlying mechanism routine and
* call it.
*/
mech = gssint_get_mechanism(selected_mech);
if (mech && mech->gss_accept_sec_context) {
status = mech->gss_accept_sec_context(minor_status,
&union_ctx_id->internal_ctx_id,
input_cred_handle,
input_token_buffer,
input_chan_bindings,
src_name ? &internal_name : NULL,
&actual_mech,
output_token,
&temp_ret_flags,
time_rec,
d_cred ? &tmp_d_cred : NULL);
/* If there's more work to do, keep going... */
if (status == GSS_S_CONTINUE_NEEDED)
return GSS_S_CONTINUE_NEEDED;
/* if the call failed, return with failure */
if (status != GSS_S_COMPLETE) {
map_error(minor_status, mech);
goto error_out;
}
/*
* if src_name is non-NULL,
* convert internal_name into a union name equivalent
* First call the mechanism specific display_name()
* then call gss_import_name() to create
* the union name struct cast to src_name
*/
if (src_name != NULL) {
if (internal_name != GSS_C_NO_NAME) {
/* consumes internal_name regardless of success */
temp_status = gssint_convert_name_to_union_name(
&temp_minor_status, mech,
internal_name, &tmp_src_name);
if (temp_status != GSS_S_COMPLETE) {
status = temp_status;
*minor_status = temp_minor_status;
map_error(minor_status, mech);
if (output_token->length)
(void) gss_release_buffer(&temp_minor_status,
output_token);
goto error_out;
}
*src_name = tmp_src_name;
} else
*src_name = GSS_C_NO_NAME;
}
#define g_OID_prefix_equal(o1, o2) \
(((o1)->length >= (o2)->length) && \
(memcmp((o1)->elements, (o2)->elements, (o2)->length) == 0))
/* Ensure we're returning correct creds format */
if ((temp_ret_flags & GSS_C_DELEG_FLAG) &&
tmp_d_cred != GSS_C_NO_CREDENTIAL) {
public_mech = gssint_get_public_oid(selected_mech);
if (actual_mech != GSS_C_NO_OID &&
public_mech != GSS_C_NO_OID &&
!g_OID_prefix_equal(actual_mech, public_mech)) {
*d_cred = tmp_d_cred; /* unwrapped pseudo-mech */
} else {
gss_union_cred_t d_u_cred = NULL;
d_u_cred = malloc(sizeof (gss_union_cred_desc));
if (d_u_cred == NULL) {
status = GSS_S_FAILURE;
goto error_out;
}
(void) memset(d_u_cred, 0, sizeof (gss_union_cred_desc));
d_u_cred->count = 1;
status = generic_gss_copy_oid(&temp_minor_status,
selected_mech,
&d_u_cred->mechs_array);
if (status != GSS_S_COMPLETE) {
free(d_u_cred);
goto error_out;
}
d_u_cred->cred_array = malloc(sizeof(gss_cred_id_t));
if (d_u_cred->cred_array != NULL) {
d_u_cred->cred_array[0] = tmp_d_cred;
} else {
free(d_u_cred);
status = GSS_S_FAILURE;
goto error_out;
}
d_u_cred->loopback = d_u_cred;
*d_cred = (gss_cred_id_t)d_u_cred;
}
}
if (mech_type != NULL)
*mech_type = gssint_get_public_oid(actual_mech);
if (ret_flags != NULL)
*ret_flags = temp_ret_flags;
return (status);
} else {
status = GSS_S_BAD_MECH;
}
error_out:
if (union_ctx_id) {
if (union_ctx_id->mech_type) {
if (union_ctx_id->mech_type->elements)
free(union_ctx_id->mech_type->elements);
free(union_ctx_id->mech_type);
}
if (union_ctx_id->internal_ctx_id && mech &&
mech->gss_delete_sec_context) {
mech->gss_delete_sec_context(&temp_minor_status,
&union_ctx_id->internal_ctx_id,
GSS_C_NO_BUFFER);
}
free(union_ctx_id);
*context_handle = GSS_C_NO_CONTEXT;
}
if (src_name)
*src_name = GSS_C_NO_NAME;
if (tmp_src_name != GSS_C_NO_NAME)
(void) gss_release_buffer(&temp_minor_status,
(gss_buffer_t)tmp_src_name);
return (status);
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415 | gss_accept_sec_context (minor_status,
context_handle,
verifier_cred_handle,
input_token_buffer,
input_chan_bindings,
src_name,
mech_type,
output_token,
ret_flags,
time_rec,
d_cred)
OM_uint32 * minor_status;
gss_ctx_id_t * context_handle;
gss_cred_id_t verifier_cred_handle;
gss_buffer_t input_token_buffer;
gss_channel_bindings_t input_chan_bindings;
gss_name_t * src_name;
gss_OID * mech_type;
gss_buffer_t output_token;
OM_uint32 * ret_flags;
OM_uint32 * time_rec;
gss_cred_id_t * d_cred;
{
OM_uint32 status, temp_status, temp_minor_status;
OM_uint32 temp_ret_flags = 0;
gss_union_ctx_id_t union_ctx_id = NULL;
gss_cred_id_t input_cred_handle = GSS_C_NO_CREDENTIAL;
gss_cred_id_t tmp_d_cred = GSS_C_NO_CREDENTIAL;
gss_name_t internal_name = GSS_C_NO_NAME;
gss_name_t tmp_src_name = GSS_C_NO_NAME;
gss_OID_desc token_mech_type_desc;
gss_OID token_mech_type = &token_mech_type_desc;
gss_OID actual_mech = GSS_C_NO_OID;
gss_OID selected_mech = GSS_C_NO_OID;
gss_OID public_mech;
gss_mechanism mech = NULL;
gss_union_cred_t uc;
int i;
status = val_acc_sec_ctx_args(minor_status,
context_handle,
verifier_cred_handle,
input_token_buffer,
input_chan_bindings,
src_name,
mech_type,
output_token,
ret_flags,
time_rec,
d_cred);
if (status != GSS_S_COMPLETE)
return (status);
/*
* if context_handle is GSS_C_NO_CONTEXT, allocate a union context
* descriptor to hold the mech type information as well as the
* underlying mechanism context handle. Otherwise, cast the
* value of *context_handle to the union context variable.
*/
if(*context_handle == GSS_C_NO_CONTEXT) {
if (input_token_buffer == GSS_C_NO_BUFFER)
return (GSS_S_CALL_INACCESSIBLE_READ);
/* Get the token mech type */
status = gssint_get_mech_type(token_mech_type, input_token_buffer);
if (status)
return status;
/*
* An interposer calling back into the mechglue can't pass in a special
* mech, so we have to recognize it using verifier_cred_handle. Use
* the mechanism for which we have matching creds, if available.
*/
if (verifier_cred_handle != GSS_C_NO_CREDENTIAL) {
uc = (gss_union_cred_t)verifier_cred_handle;
for (i = 0; i < uc->count; i++) {
public_mech = gssint_get_public_oid(&uc->mechs_array[i]);
if (public_mech && g_OID_equal(token_mech_type, public_mech)) {
selected_mech = &uc->mechs_array[i];
break;
}
}
}
if (selected_mech == GSS_C_NO_OID) {
status = gssint_select_mech_type(minor_status, token_mech_type,
&selected_mech);
if (status)
return status;
}
} else {
union_ctx_id = (gss_union_ctx_id_t)*context_handle;
selected_mech = union_ctx_id->mech_type;
if (union_ctx_id->internal_ctx_id == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
}
/* Now create a new context if we didn't get one. */
if (*context_handle == GSS_C_NO_CONTEXT) {
status = GSS_S_FAILURE;
union_ctx_id = (gss_union_ctx_id_t)
malloc(sizeof(gss_union_ctx_id_desc));
if (!union_ctx_id)
return (GSS_S_FAILURE);
union_ctx_id->loopback = union_ctx_id;
union_ctx_id->internal_ctx_id = GSS_C_NO_CONTEXT;
status = generic_gss_copy_oid(&temp_minor_status, selected_mech,
&union_ctx_id->mech_type);
if (status != GSS_S_COMPLETE) {
free(union_ctx_id);
return (status);
}
}
/*
* get the appropriate cred handle from the union cred struct.
*/
if (verifier_cred_handle != GSS_C_NO_CREDENTIAL) {
input_cred_handle =
gssint_get_mechanism_cred((gss_union_cred_t)verifier_cred_handle,
selected_mech);
if (input_cred_handle == GSS_C_NO_CREDENTIAL) {
/* verifier credential specified but no acceptor credential found */
status = GSS_S_NO_CRED;
goto error_out;
}
} else if (!allow_mech_by_default(selected_mech)) {
status = GSS_S_NO_CRED;
goto error_out;
}
/*
* now select the approprate underlying mechanism routine and
* call it.
*/
mech = gssint_get_mechanism(selected_mech);
if (mech && mech->gss_accept_sec_context) {
status = mech->gss_accept_sec_context(minor_status,
&union_ctx_id->internal_ctx_id,
input_cred_handle,
input_token_buffer,
input_chan_bindings,
src_name ? &internal_name : NULL,
&actual_mech,
output_token,
&temp_ret_flags,
time_rec,
d_cred ? &tmp_d_cred : NULL);
/* If there's more work to do, keep going... */
if (status == GSS_S_CONTINUE_NEEDED) {
*context_handle = (gss_ctx_id_t)union_ctx_id;
return GSS_S_CONTINUE_NEEDED;
}
/* if the call failed, return with failure */
if (status != GSS_S_COMPLETE) {
map_error(minor_status, mech);
goto error_out;
}
/*
* if src_name is non-NULL,
* convert internal_name into a union name equivalent
* First call the mechanism specific display_name()
* then call gss_import_name() to create
* the union name struct cast to src_name
*/
if (src_name != NULL) {
if (internal_name != GSS_C_NO_NAME) {
/* consumes internal_name regardless of success */
temp_status = gssint_convert_name_to_union_name(
&temp_minor_status, mech,
internal_name, &tmp_src_name);
if (temp_status != GSS_S_COMPLETE) {
status = temp_status;
*minor_status = temp_minor_status;
map_error(minor_status, mech);
if (output_token->length)
(void) gss_release_buffer(&temp_minor_status,
output_token);
goto error_out;
}
*src_name = tmp_src_name;
} else
*src_name = GSS_C_NO_NAME;
}
#define g_OID_prefix_equal(o1, o2) \
(((o1)->length >= (o2)->length) && \
(memcmp((o1)->elements, (o2)->elements, (o2)->length) == 0))
/* Ensure we're returning correct creds format */
if ((temp_ret_flags & GSS_C_DELEG_FLAG) &&
tmp_d_cred != GSS_C_NO_CREDENTIAL) {
public_mech = gssint_get_public_oid(selected_mech);
if (actual_mech != GSS_C_NO_OID &&
public_mech != GSS_C_NO_OID &&
!g_OID_prefix_equal(actual_mech, public_mech)) {
*d_cred = tmp_d_cred; /* unwrapped pseudo-mech */
} else {
gss_union_cred_t d_u_cred = NULL;
d_u_cred = malloc(sizeof (gss_union_cred_desc));
if (d_u_cred == NULL) {
status = GSS_S_FAILURE;
goto error_out;
}
(void) memset(d_u_cred, 0, sizeof (gss_union_cred_desc));
d_u_cred->count = 1;
status = generic_gss_copy_oid(&temp_minor_status,
selected_mech,
&d_u_cred->mechs_array);
if (status != GSS_S_COMPLETE) {
free(d_u_cred);
goto error_out;
}
d_u_cred->cred_array = malloc(sizeof(gss_cred_id_t));
if (d_u_cred->cred_array != NULL) {
d_u_cred->cred_array[0] = tmp_d_cred;
} else {
free(d_u_cred);
status = GSS_S_FAILURE;
goto error_out;
}
d_u_cred->loopback = d_u_cred;
*d_cred = (gss_cred_id_t)d_u_cred;
}
}
if (mech_type != NULL)
*mech_type = gssint_get_public_oid(actual_mech);
if (ret_flags != NULL)
*ret_flags = temp_ret_flags;
*context_handle = (gss_ctx_id_t)union_ctx_id;
return GSS_S_COMPLETE;
} else {
status = GSS_S_BAD_MECH;
}
error_out:
/*
* RFC 2744 5.1 requires that we not create a context on a failed first
* call to accept, and recommends that on a failed subsequent call we
* make the caller responsible for calling gss_delete_sec_context.
* Even if the mech deleted its context, keep the union context around
* for the caller to delete.
*/
if (union_ctx_id && *context_handle == GSS_C_NO_CONTEXT) {
if (union_ctx_id->mech_type) {
if (union_ctx_id->mech_type->elements)
free(union_ctx_id->mech_type->elements);
free(union_ctx_id->mech_type);
}
if (union_ctx_id->internal_ctx_id && mech &&
mech->gss_delete_sec_context) {
mech->gss_delete_sec_context(&temp_minor_status,
&union_ctx_id->internal_ctx_id,
GSS_C_NO_BUFFER);
}
free(union_ctx_id);
}
if (src_name)
*src_name = GSS_C_NO_NAME;
if (tmp_src_name != GSS_C_NO_NAME)
(void) gss_release_buffer(&temp_minor_status,
(gss_buffer_t)tmp_src_name);
return (status);
}
| 168,011 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp)
{
struct net *net = sock_net(asoc->base.sk);
union sctp_addr addr;
int i;
__u16 sat;
int retval = 1;
sctp_scope_t scope;
time_t stale;
struct sctp_af *af;
union sctp_addr_param *addr_param;
struct sctp_transport *t;
struct sctp_endpoint *ep = asoc->ep;
/* We maintain all INIT parameters in network byte order all the
* time. This allows us to not worry about whether the parameters
* came from a fresh INIT, and INIT ACK, or were stored in a cookie.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 != asoc->base.sk->sk_family)
break;
goto do_addr_param;
case SCTP_PARAM_IPV4_ADDRESS:
/* v4 addresses are not allowed on v6-only socket */
if (ipv6_only_sock(asoc->base.sk))
break;
do_addr_param:
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0);
scope = sctp_scope(peer_addr);
if (sctp_in_scope(net, &addr, scope))
if (!sctp_assoc_add_peer(asoc, &addr, gfp, SCTP_UNCONFIRMED))
return 0;
break;
case SCTP_PARAM_COOKIE_PRESERVATIVE:
if (!net->sctp.cookie_preserve_enable)
break;
stale = ntohl(param.life->lifespan_increment);
/* Suggested Cookie Life span increment's unit is msec,
* (1/1000sec).
*/
asoc->cookie_life = ktime_add_ms(asoc->cookie_life, stale);
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
pr_debug("%s: unimplemented SCTP_HOST_NAME_ADDRESS\n", __func__);
break;
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
/* Turn off the default values first so we'll know which
* ones are really set by the peer.
*/
asoc->peer.ipv4_address = 0;
asoc->peer.ipv6_address = 0;
/* Assume that peer supports the address family
* by which it sends a packet.
*/
if (peer_addr->sa.sa_family == AF_INET6)
asoc->peer.ipv6_address = 1;
else if (peer_addr->sa.sa_family == AF_INET)
asoc->peer.ipv4_address = 1;
/* Cycle through address types; avoid divide by 0. */
sat = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
if (sat)
sat /= sizeof(__u16);
for (i = 0; i < sat; ++i) {
switch (param.sat->types[i]) {
case SCTP_PARAM_IPV4_ADDRESS:
asoc->peer.ipv4_address = 1;
break;
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 == asoc->base.sk->sk_family)
asoc->peer.ipv6_address = 1;
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
asoc->peer.hostname_address = 1;
break;
default: /* Just ignore anything else. */
break;
}
}
break;
case SCTP_PARAM_STATE_COOKIE:
asoc->peer.cookie_len =
ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
asoc->peer.cookie = param.cookie->body;
break;
case SCTP_PARAM_HEARTBEAT_INFO:
/* Would be odd to receive, but it causes no problems. */
break;
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
/* Rejected during verify stage. */
break;
case SCTP_PARAM_ECN_CAPABLE:
asoc->peer.ecn_capable = 1;
break;
case SCTP_PARAM_ADAPTATION_LAYER_IND:
asoc->peer.adaptation_ind = ntohl(param.aind->adaptation_ind);
break;
case SCTP_PARAM_SET_PRIMARY:
if (!net->sctp.addip_enable)
goto fall_through;
addr_param = param.v + sizeof(sctp_addip_param_t);
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, addr_param,
htons(asoc->peer.port), 0);
/* if the address is invalid, we can't process it.
* XXX: see spec for what to do.
*/
if (!af->addr_valid(&addr, NULL, NULL))
break;
t = sctp_assoc_lookup_paddr(asoc, &addr);
if (!t)
break;
sctp_assoc_set_primary(asoc, t);
break;
case SCTP_PARAM_SUPPORTED_EXT:
sctp_process_ext_param(asoc, param);
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (net->sctp.prsctp_enable) {
asoc->peer.prsctp_capable = 1;
break;
}
/* Fall Through */
goto fall_through;
case SCTP_PARAM_RANDOM:
if (!ep->auth_enable)
goto fall_through;
/* Save peer's random parameter */
asoc->peer.peer_random = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_random) {
retval = 0;
break;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!ep->auth_enable)
goto fall_through;
/* Save peer's HMAC list */
asoc->peer.peer_hmacs = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_hmacs) {
retval = 0;
break;
}
/* Set the default HMAC the peer requested*/
sctp_auth_asoc_set_default_hmac(asoc, param.hmac_algo);
break;
case SCTP_PARAM_CHUNKS:
if (!ep->auth_enable)
goto fall_through;
asoc->peer.peer_chunks = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_chunks)
retval = 0;
break;
fall_through:
default:
/* Any unrecognized parameters should have been caught
* and handled by sctp_verify_param() which should be
* called prior to this routine. Simply log the error
* here.
*/
pr_debug("%s: ignoring param:%d for association:%p.\n",
__func__, ntohs(param.p->type), asoc);
break;
}
return retval;
}
Commit Message: net: sctp: fix NULL pointer dereference in af->from_addr_param on malformed packet
An SCTP server doing ASCONF will panic on malformed INIT ping-of-death
in the form of:
------------ INIT[PARAM: SET_PRIMARY_IP] ------------>
While the INIT chunk parameter verification dissects through many things
in order to detect malformed input, it misses to actually check parameters
inside of parameters. E.g. RFC5061, section 4.2.4 proposes a 'set primary
IP address' parameter in ASCONF, which has as a subparameter an address
parameter.
So an attacker may send a parameter type other than SCTP_PARAM_IPV4_ADDRESS
or SCTP_PARAM_IPV6_ADDRESS, param_type2af() will subsequently return 0
and thus sctp_get_af_specific() returns NULL, too, which we then happily
dereference unconditionally through af->from_addr_param().
The trace for the log:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000078
IP: [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp]
PGD 0
Oops: 0000 [#1] SMP
[...]
Pid: 0, comm: swapper Not tainted 2.6.32-504.el6.x86_64 #1 Bochs Bochs
RIP: 0010:[<ffffffffa01e9c62>] [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp]
[...]
Call Trace:
<IRQ>
[<ffffffffa01f2add>] ? sctp_bind_addr_copy+0x5d/0xe0 [sctp]
[<ffffffffa01e1fcb>] sctp_sf_do_5_1B_init+0x21b/0x340 [sctp]
[<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp]
[<ffffffffa01e5c09>] ? sctp_endpoint_lookup_assoc+0xc9/0xf0 [sctp]
[<ffffffffa01e61f6>] sctp_endpoint_bh_rcv+0x116/0x230 [sctp]
[<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp]
[<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp]
[<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]
[<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[...]
A minimal way to address this is to check for NULL as we do on all
other such occasions where we know sctp_get_af_specific() could
possibly return with NULL.
Fixes: d6de3097592b ("[SCTP]: Add the handling of "Set Primary IP Address" parameter to INIT")
Signed-off-by: Daniel Borkmann <[email protected]>
Cc: Vlad Yasevich <[email protected]>
Acked-by: Neil Horman <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp)
{
struct net *net = sock_net(asoc->base.sk);
union sctp_addr addr;
int i;
__u16 sat;
int retval = 1;
sctp_scope_t scope;
time_t stale;
struct sctp_af *af;
union sctp_addr_param *addr_param;
struct sctp_transport *t;
struct sctp_endpoint *ep = asoc->ep;
/* We maintain all INIT parameters in network byte order all the
* time. This allows us to not worry about whether the parameters
* came from a fresh INIT, and INIT ACK, or were stored in a cookie.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 != asoc->base.sk->sk_family)
break;
goto do_addr_param;
case SCTP_PARAM_IPV4_ADDRESS:
/* v4 addresses are not allowed on v6-only socket */
if (ipv6_only_sock(asoc->base.sk))
break;
do_addr_param:
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0);
scope = sctp_scope(peer_addr);
if (sctp_in_scope(net, &addr, scope))
if (!sctp_assoc_add_peer(asoc, &addr, gfp, SCTP_UNCONFIRMED))
return 0;
break;
case SCTP_PARAM_COOKIE_PRESERVATIVE:
if (!net->sctp.cookie_preserve_enable)
break;
stale = ntohl(param.life->lifespan_increment);
/* Suggested Cookie Life span increment's unit is msec,
* (1/1000sec).
*/
asoc->cookie_life = ktime_add_ms(asoc->cookie_life, stale);
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
pr_debug("%s: unimplemented SCTP_HOST_NAME_ADDRESS\n", __func__);
break;
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
/* Turn off the default values first so we'll know which
* ones are really set by the peer.
*/
asoc->peer.ipv4_address = 0;
asoc->peer.ipv6_address = 0;
/* Assume that peer supports the address family
* by which it sends a packet.
*/
if (peer_addr->sa.sa_family == AF_INET6)
asoc->peer.ipv6_address = 1;
else if (peer_addr->sa.sa_family == AF_INET)
asoc->peer.ipv4_address = 1;
/* Cycle through address types; avoid divide by 0. */
sat = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
if (sat)
sat /= sizeof(__u16);
for (i = 0; i < sat; ++i) {
switch (param.sat->types[i]) {
case SCTP_PARAM_IPV4_ADDRESS:
asoc->peer.ipv4_address = 1;
break;
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 == asoc->base.sk->sk_family)
asoc->peer.ipv6_address = 1;
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
asoc->peer.hostname_address = 1;
break;
default: /* Just ignore anything else. */
break;
}
}
break;
case SCTP_PARAM_STATE_COOKIE:
asoc->peer.cookie_len =
ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
asoc->peer.cookie = param.cookie->body;
break;
case SCTP_PARAM_HEARTBEAT_INFO:
/* Would be odd to receive, but it causes no problems. */
break;
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
/* Rejected during verify stage. */
break;
case SCTP_PARAM_ECN_CAPABLE:
asoc->peer.ecn_capable = 1;
break;
case SCTP_PARAM_ADAPTATION_LAYER_IND:
asoc->peer.adaptation_ind = ntohl(param.aind->adaptation_ind);
break;
case SCTP_PARAM_SET_PRIMARY:
if (!net->sctp.addip_enable)
goto fall_through;
addr_param = param.v + sizeof(sctp_addip_param_t);
af = sctp_get_af_specific(param_type2af(param.p->type));
if (af == NULL)
break;
af->from_addr_param(&addr, addr_param,
htons(asoc->peer.port), 0);
/* if the address is invalid, we can't process it.
* XXX: see spec for what to do.
*/
if (!af->addr_valid(&addr, NULL, NULL))
break;
t = sctp_assoc_lookup_paddr(asoc, &addr);
if (!t)
break;
sctp_assoc_set_primary(asoc, t);
break;
case SCTP_PARAM_SUPPORTED_EXT:
sctp_process_ext_param(asoc, param);
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (net->sctp.prsctp_enable) {
asoc->peer.prsctp_capable = 1;
break;
}
/* Fall Through */
goto fall_through;
case SCTP_PARAM_RANDOM:
if (!ep->auth_enable)
goto fall_through;
/* Save peer's random parameter */
asoc->peer.peer_random = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_random) {
retval = 0;
break;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!ep->auth_enable)
goto fall_through;
/* Save peer's HMAC list */
asoc->peer.peer_hmacs = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_hmacs) {
retval = 0;
break;
}
/* Set the default HMAC the peer requested*/
sctp_auth_asoc_set_default_hmac(asoc, param.hmac_algo);
break;
case SCTP_PARAM_CHUNKS:
if (!ep->auth_enable)
goto fall_through;
asoc->peer.peer_chunks = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_chunks)
retval = 0;
break;
fall_through:
default:
/* Any unrecognized parameters should have been caught
* and handled by sctp_verify_param() which should be
* called prior to this routine. Simply log the error
* here.
*/
pr_debug("%s: ignoring param:%d for association:%p.\n",
__func__, ntohs(param.p->type), asoc);
break;
}
return retval;
}
| 166,253 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Object> object)
{
if (!enabled()) {
NOTREACHED();
return v8::Null(m_isolate);
}
v8::Local<v8::Value> argv[] = { object };
v8::Local<v8::Value> location = callDebuggerMethod("getGeneratorObjectLocation", 1, argv).ToLocalChecked();
if (!location->IsObject())
return v8::Null(m_isolate);
v8::Local<v8::Context> context = m_debuggerContext.Get(m_isolate);
if (!markAsInternal(context, v8::Local<v8::Object>::Cast(location), V8InternalValueType::kLocation))
return v8::Null(m_isolate);
return location;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79 | v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Object> object)
v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Context> context, v8::Local<v8::Object> object)
{
if (!enabled()) {
NOTREACHED();
return v8::Null(m_isolate);
}
v8::Local<v8::Value> argv[] = { object };
v8::Local<v8::Value> location = callDebuggerMethod("getGeneratorObjectLocation", 1, argv).ToLocalChecked();
v8::Local<v8::Value> copied;
if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, location).ToLocal(&copied) || !copied->IsObject())
return v8::Null(m_isolate);
if (!markAsInternal(context, v8::Local<v8::Object>::Cast(copied), V8InternalValueType::kLocation))
return v8::Null(m_isolate);
return copied;
}
| 172,067 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual ~InputMethodLibraryImpl() {
}
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 | virtual ~InputMethodLibraryImpl() {
ibus_controller_->RemoveObserver(this);
}
| 170,516 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.