prompt
stringlengths 799
20.4k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GestureProviderAura::OnTouchEventAck(bool event_consumed) {
DCHECK(pending_gestures_.empty());
DCHECK(!handling_event_);
base::AutoReset<bool> handling_event(&handling_event_, true);
filtered_gesture_provider_.OnTouchEventAck(event_consumed);
}
CWE ID:
Target: 1
Example 2:
Code: int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
#ifdef CONFIG_X86_64
regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
#endif
regs->rip = kvm_rip_read(vcpu);
regs->rflags = kvm_get_rflags(vcpu);
return 0;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ChromeWebContentsDelegateAndroid::AddNewContents(
WebContents* source,
WebContents* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_rect,
bool user_gesture,
bool* was_blocked) {
DCHECK_NE(disposition, SAVE_TO_DISK);
DCHECK_NE(disposition, CURRENT_TAB);
TabHelpers::AttachTabHelpers(new_contents);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = GetJavaDelegate(env);
AddWebContentsResult add_result =
ADD_WEB_CONTENTS_RESULT_STOP_LOAD_AND_DELETE;
if (!obj.is_null()) {
ScopedJavaLocalRef<jobject> jsource;
if (source)
jsource = source->GetJavaWebContents();
ScopedJavaLocalRef<jobject> jnew_contents;
if (new_contents)
jnew_contents = new_contents->GetJavaWebContents();
add_result = static_cast<AddWebContentsResult>(
Java_ChromeWebContentsDelegateAndroid_addNewContents(
env,
obj.obj(),
jsource.obj(),
jnew_contents.obj(),
static_cast<jint>(disposition),
NULL,
user_gesture));
}
if (was_blocked)
*was_blocked = !(add_result == ADD_WEB_CONTENTS_RESULT_PROCEED);
if (add_result == ADD_WEB_CONTENTS_RESULT_STOP_LOAD_AND_DELETE)
delete new_contents;
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: path_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
PATH *path;
int isopen;
char *s;
int npts;
int size;
int depth = 0;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
s = str;
while (isspace((unsigned char) *s))
s++;
/* skip single leading paren */
if ((*s == LDELIM) && (strrchr(s, LDELIM) == s))
{
s++;
depth++;
}
size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * npts;
path = (PATH *) palloc(size);
SET_VARSIZE(path, size);
path->npts = npts;
if ((!path_decode(TRUE, npts, s, &isopen, &s, &(path->p[0])))
&& (!((depth == 0) && (*s == '\0'))) && !((depth >= 1) && (*s == RDELIM)))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type path: \"%s\"", str)));
path->closed = (!isopen);
/* prevent instability in unused pad bytes */
path->dummy = 0;
PG_RETURN_PATH_P(path);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: PHP_METHOD(Phar, setMetadata)
{
char *error;
zval *metadata;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &metadata) == FAILURE) {
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->metadata) {
zval_ptr_dtor(&phar_obj->arc.archive->metadata);
phar_obj->arc.archive->metadata = NULL;
}
MAKE_STD_ZVAL(phar_obj->arc.archive->metadata);
ZVAL_ZVAL(phar_obj->arc.archive->metadata, metadata, 1, 0);
phar_obj->arc.archive->is_modified = 1;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IHEVCD_ERROR_T ihevcd_parse_coding_unit_intra(codec_t *ps_codec,
WORD32 x0,
WORD32 y0,
WORD32 log2_cb_size)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
sps_t *ps_sps;
cab_ctxt_t *ps_cabac = &ps_codec->s_parse.s_cabac;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 pcm_flag;
WORD32 value;
WORD32 cb_size = 1 << log2_cb_size;
WORD32 part_mode = ps_codec->s_parse.s_cu.i4_part_mode;
tu_t *ps_tu = ps_codec->s_parse.ps_tu;
pu_t *ps_pu = ps_codec->s_parse.ps_pu;
WORD32 ctb_x_base;
WORD32 ctb_y_base;
ps_sps = ps_codec->s_parse.ps_sps;
ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size;
ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size;
memset(ps_pu, 0, sizeof(pu_t));
ps_pu->b1_intra_flag = 1;
ps_pu->b4_wd = (cb_size >> 2) - 1;
ps_pu->b4_ht = (cb_size >> 2) - 1;
ps_pu->b4_pos_x = (x0 - ctb_x_base) >> 2;
ps_pu->b4_pos_y = (y0 - ctb_y_base) >> 2;
pcm_flag = 0;
if((PART_2Nx2N == part_mode) && (ps_sps->i1_pcm_enabled_flag)
&& (log2_cb_size
>= ps_sps->i1_log2_min_pcm_coding_block_size)
&& (log2_cb_size
<= (ps_sps->i1_log2_min_pcm_coding_block_size + ps_sps->i1_log2_diff_max_min_pcm_coding_block_size)))
{
TRACE_CABAC_CTXT("pcm_flag", ps_cabac->u4_range, 0);
pcm_flag = ihevcd_cabac_decode_terminate(ps_cabac, ps_bitstrm);
AEV_TRACE("pcm_flag", pcm_flag, ps_cabac->u4_range);
}
ps_codec->s_parse.i4_cu_pcm_flag = pcm_flag;
if(pcm_flag)
{
UWORD8 *pu1_luma_intra_pred_mode_top, *pu1_luma_intra_pred_mode_left;
WORD32 i, num_pred_blocks;
if(ps_codec->s_parse.s_bitstrm.u4_bit_ofst % 8)
{
TRACE_CABAC_CTXT("pcm_alignment_zero_bit", ps_cabac->u4_range, 0);
ihevcd_bits_flush_to_byte_boundary(&ps_codec->s_parse.s_bitstrm);
AEV_TRACE("pcm_alignment_zero_bit", 0, ps_cabac->u4_range);
}
ihevcd_parse_pcm_sample(ps_codec, x0, y0, log2_cb_size);
ihevcd_cabac_reset(&ps_codec->s_parse.s_cabac,
&ps_codec->s_parse.s_bitstrm);
ps_tu = ps_codec->s_parse.ps_tu;
ps_tu->b1_cb_cbf = 1;
ps_tu->b1_cr_cbf = 1;
ps_tu->b1_y_cbf = 1;
ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2);
ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2);
ps_tu->b1_transquant_bypass = 1;
ps_tu->b3_size = (log2_cb_size - 2);
ps_tu->b7_qp = ps_codec->s_parse.u4_qp;
ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE;
ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE;
/* Set the first TU in CU flag */
{
if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) &&
(ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2))
{
ps_tu->b1_first_tu_in_cu = 1;
}
else
{
ps_tu->b1_first_tu_in_cu = 0;
}
}
/* Update the intra pred mode for PCM to INTRA_DC(default mode) */
pu1_luma_intra_pred_mode_top = ps_codec->s_parse.pu1_luma_intra_pred_mode_top
+ (ps_codec->s_parse.s_cu.i4_pos_x * 2);
pu1_luma_intra_pred_mode_left = ps_codec->s_parse.pu1_luma_intra_pred_mode_left
+ (ps_codec->s_parse.s_cu.i4_pos_y * 2);
num_pred_blocks = 1; /* Because PCM part mode will be 2Nx2N */
ps_codec->s_func_selector.ihevc_memset_fptr(pu1_luma_intra_pred_mode_left, INTRA_DC, (cb_size / num_pred_blocks) / MIN_PU_SIZE);
ps_codec->s_func_selector.ihevc_memset_fptr(pu1_luma_intra_pred_mode_top, INTRA_DC, (cb_size / num_pred_blocks) / MIN_PU_SIZE);
/* Set no_loop_filter appropriately */
if(1 == ps_sps->i1_pcm_loop_filter_disable_flag)
{
UWORD8 *pu1_pic_no_loop_filter_flag;
WORD32 numbytes_row;
UWORD32 u4_mask;
pu1_pic_no_loop_filter_flag = ps_codec->s_parse.pu1_pic_no_loop_filter_flag;
numbytes_row = (ps_sps->i2_pic_width_in_luma_samples + 63) / 64;
pu1_pic_no_loop_filter_flag += (y0 / 8) * numbytes_row;
pu1_pic_no_loop_filter_flag += (x0 / 64);
/* Generate (cb_size / 8) number of 1s */
/* i.e (log2_cb_size - 2) number of 1s */
u4_mask = LSB_ONES((cb_size >> 3));
for(i = 0; i < (cb_size / 8); i++)
{
*pu1_pic_no_loop_filter_flag |= (u4_mask << (((x0) / 8) % 8));
pu1_pic_no_loop_filter_flag += numbytes_row;
}
}
/* Increment ps_tu and tu_idx */
ps_codec->s_parse.ps_tu++;
ps_codec->s_parse.s_cu.i4_tu_cnt++;
ps_codec->s_parse.i4_pic_tu_idx++;
}
else
{
WORD32 cnt = 0;
WORD32 i;
WORD32 part_cnt;
part_cnt = (part_mode == PART_NxN) ? 4 : 1;
for(i = 0; i < part_cnt; i++)
{
TRACE_CABAC_CTXT("prev_intra_pred_luma_flag", ps_cabac->u4_range, IHEVC_CAB_INTRA_LUMA_PRED_FLAG);
value = ihevcd_cabac_decode_bin(ps_cabac,
ps_bitstrm,
IHEVC_CAB_INTRA_LUMA_PRED_FLAG);
ps_codec->s_parse.s_cu.ai4_prev_intra_luma_pred_flag[i] =
value;
AEV_TRACE("prev_intra_pred_luma_flag", value, ps_cabac->u4_range);
}
for(i = 0; i < part_cnt; i++)
{
if(ps_codec->s_parse.s_cu.ai4_prev_intra_luma_pred_flag[cnt])
{
value = ihevcd_cabac_decode_bypass_bins_tunary(ps_cabac, ps_bitstrm, 2);
AEV_TRACE("mpm_idx", value, ps_cabac->u4_range);
ps_codec->s_parse.s_cu.ai4_mpm_idx[cnt] = value;
}
else
{
value = ihevcd_cabac_decode_bypass_bins(ps_cabac, ps_bitstrm, 5);
AEV_TRACE("rem_intra_luma_pred_mode", value,
ps_cabac->u4_range);
ps_codec->s_parse.s_cu.ai4_rem_intra_luma_pred_mode[cnt] =
value;
}
cnt++;
}
TRACE_CABAC_CTXT("intra_chroma_pred_mode", ps_cabac->u4_range, IHEVC_CAB_CHROMA_PRED_MODE);
value = ihevcd_cabac_decode_bin(ps_cabac,
ps_bitstrm,
IHEVC_CAB_CHROMA_PRED_MODE);
ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx = 4;
if(value)
{
ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx =
ihevcd_cabac_decode_bypass_bins(ps_cabac,
ps_bitstrm, 2);
}
AEV_TRACE("intra_chroma_pred_mode",
ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx,
ps_cabac->u4_range);
ihevcd_intra_pred_mode_prediction(ps_codec, log2_cb_size, x0, y0);
}
STATS_UPDATE_PU_SIZE(ps_pu);
/* Increment PU pointer */
ps_codec->s_parse.ps_pu++;
ps_codec->s_parse.i4_pic_pu_idx++;
return ret;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: sequential_row(standard_display *dp, png_structp pp, png_infop pi,
PNG_CONST int iImage, PNG_CONST int iDisplay)
{
PNG_CONST int npasses = dp->npasses;
PNG_CONST int do_interlace = dp->do_interlace &&
dp->interlace_type == PNG_INTERLACE_ADAM7;
PNG_CONST png_uint_32 height = standard_height(pp, dp->id);
PNG_CONST png_uint_32 width = standard_width(pp, dp->id);
PNG_CONST png_store* ps = dp->ps;
int pass;
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
png_uint_32 wPass = PNG_PASS_COLS(width, pass);
for (y=0; y<height; ++y)
{
if (do_interlace)
{
/* wPass may be zero or this row may not be in this pass.
* png_read_row must not be called in either case.
*/
if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
{
/* Read the row into a pair of temporary buffers, then do the
* merge here into the output rows.
*/
png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
/* The following aids (to some extent) error detection - we can
* see where png_read_row wrote. Use opposite values in row and
* display to make this easier. Don't use 0xff (which is used in
* the image write code to fill unused bits) or 0 (which is a
* likely value to overwrite unused bits with).
*/
memset(row, 0xc5, sizeof row);
memset(display, 0x5c, sizeof display);
png_read_row(pp, row, display);
if (iImage >= 0)
deinterlace_row(store_image_row(ps, pp, iImage, y), row,
dp->pixel_size, dp->w, pass);
if (iDisplay >= 0)
deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
dp->pixel_size, dp->w, pass);
}
}
else
png_read_row(pp,
iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
}
}
/* And finish the read operation (only really necessary if the caller wants
* to find additional data in png_info from chunks after the last IDAT.)
*/
png_read_end(pp, pi);
}
CWE ID:
Target: 1
Example 2:
Code: static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
struct bpf_reg_state *dst_reg,
enum bpf_reg_type type,
bool range_right_open)
{
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *reg;
u16 new_range;
int i, j;
if (dst_reg->off < 0 ||
(dst_reg->off == 0 && range_right_open))
/* This doesn't give us any range */
return;
if (dst_reg->umax_value > MAX_PACKET_OFF ||
dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
/* Risk of overflow. For instance, ptr + (1<<63) may be less
* than pkt_end, but that's because it's also less than pkt.
*/
return;
new_range = dst_reg->off;
if (range_right_open)
new_range--;
/* Examples for register markings:
*
* pkt_data in dst register:
*
* r2 = r3;
* r2 += 8;
* if (r2 > pkt_end) goto <handle exception>
* <access okay>
*
* r2 = r3;
* r2 += 8;
* if (r2 < pkt_end) goto <access okay>
* <handle exception>
*
* Where:
* r2 == dst_reg, pkt_end == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* pkt_data in src register:
*
* r2 = r3;
* r2 += 8;
* if (pkt_end >= r2) goto <access okay>
* <handle exception>
*
* r2 = r3;
* r2 += 8;
* if (pkt_end <= r2) goto <handle exception>
* <access okay>
*
* Where:
* pkt_end == dst_reg, r2 == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
* or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
* and [r3, r3 + 8-1) respectively is safe to access depending on
* the check.
*/
/* If our ids match, then we must have the same max_value. And we
* don't care about the other reg's fixed offset, since if it's too big
* the range won't allow anything.
* dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
*/
for (i = 0; i < MAX_BPF_REG; i++)
if (regs[i].type == type && regs[i].id == dst_reg->id)
/* keep the maximum range already checked */
regs[i].range = max(regs[i].range, new_range);
for (j = 0; j <= vstate->curframe; j++) {
state = vstate->frame[j];
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg->type == type && reg->id == dst_reg->id)
reg->range = max(reg->range, new_range);
}
}
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static zval *xml_call_handler(xml_parser *parser, zval *handler, zend_function *function_ptr, int argc, zval **argv)
{
int i;
TSRMLS_FETCH();
if (parser && handler && !EG(exception)) {
zval ***args;
zval *retval;
int result;
zend_fcall_info fci;
args = safe_emalloc(sizeof(zval **), argc, 0);
for (i = 0; i < argc; i++) {
args[i] = &argv[i];
}
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
fci.function_name = handler;
fci.symbol_table = NULL;
fci.object_ptr = parser->object;
fci.retval_ptr_ptr = &retval;
fci.param_count = argc;
fci.params = args;
fci.no_separation = 0;
/*fci.function_handler_cache = &function_ptr;*/
result = zend_call_function(&fci, NULL TSRMLS_CC);
if (result == FAILURE) {
zval **method;
zval **obj;
if (Z_TYPE_P(handler) == IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(handler));
} else if (zend_hash_index_find(Z_ARRVAL_P(handler), 0, (void **) &obj) == SUCCESS &&
zend_hash_index_find(Z_ARRVAL_P(handler), 1, (void **) &method) == SUCCESS &&
Z_TYPE_PP(obj) == IS_OBJECT &&
Z_TYPE_PP(method) == IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s::%s()", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method));
} else
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler");
}
for (i = 0; i < argc; i++) {
zval_ptr_dtor(args[i]);
}
efree(args);
if (result == FAILURE) {
return NULL;
} else {
return EG(exception) ? NULL : retval;
}
} else {
for (i = 0; i < argc; i++) {
zval_ptr_dtor(&argv[i]);
}
return NULL;
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static EAS_RESULT PushcdlStack (EAS_U32 *pStack, EAS_INT *pStackPtr, EAS_U32 value)
{
/* stack overflow, return an error */
if (*pStackPtr >= CDL_STACK_SIZE)
return EAS_ERROR_FILE_FORMAT;
/* push the value onto the stack */
*pStackPtr = *pStackPtr + 1;
pStack[*pStackPtr] = value;
return EAS_SUCCESS;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ProfileSyncService::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bt_status_t btif_storage_add_bonded_device(bt_bdaddr_t *remote_bd_addr,
LINK_KEY link_key,
uint8_t key_type,
uint8_t pin_length)
{
bdstr_t bdstr;
bdaddr_to_string(remote_bd_addr, bdstr, sizeof(bdstr));
int ret = btif_config_set_int(bdstr, "LinkKeyType", (int)key_type);
ret &= btif_config_set_int(bdstr, "PinLength", (int)pin_length);
ret &= btif_config_set_bin(bdstr, "LinkKey", link_key, sizeof(LINK_KEY));
/* write bonded info immediately */
btif_config_flush();
return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: dotraplinkage void notrace do_int3(struct pt_regs *regs, long error_code)
{
#ifdef CONFIG_DYNAMIC_FTRACE
/*
* ftrace must be first, everything else may cause a recursive crash.
* See note by declaration of modifying_ftrace_code in ftrace.c
*/
if (unlikely(atomic_read(&modifying_ftrace_code)) &&
ftrace_int3_handler(regs))
return;
#endif
if (poke_int3_handler(regs))
return;
ist_enter(regs);
RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
#ifdef CONFIG_KGDB_LOW_LEVEL_TRAP
if (kgdb_ll_trap(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
goto exit;
#endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */
#ifdef CONFIG_KPROBES
if (kprobe_int3_handler(regs))
goto exit;
#endif
if (notify_die(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
goto exit;
/*
* Let others (NMI) know that the debug stack is in use
* as we may switch to the interrupt stack.
*/
debug_stack_usage_inc();
cond_local_irq_enable(regs);
do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, error_code, NULL);
cond_local_irq_disable(regs);
debug_stack_usage_dec();
exit:
ist_exit(regs);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: bool GetHeaders(base::DictionaryValue* params, std::string* headers) {
if (!params)
return false;
base::ListValue* header_list;
if (!params->GetList("headers", &header_list))
return false;
std::string double_quote_headers;
base::JSONWriter::Write(header_list, &double_quote_headers);
base::ReplaceChars(double_quote_headers, "\"", "'", headers);
return true;
}
CWE ID: CWE-19
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx)
{
const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8;
if (avctx->lowres==1) {
c->idct_put = ff_jref_idct4_put;
c->idct_add = ff_jref_idct4_add;
c->idct = ff_j_rev_dct4;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==2) {
c->idct_put = ff_jref_idct2_put;
c->idct_add = ff_jref_idct2_add;
c->idct = ff_j_rev_dct2;
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->lowres==3) {
c->idct_put = ff_jref_idct1_put;
c->idct_add = ff_jref_idct1_add;
c->idct = ff_j_rev_dct1;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) {
/* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT
However, it only uses idct_put */
if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO)
c->idct_put = ff_simple_idct_put_int32_10bit;
else {
c->idct_put = ff_simple_idct_put_int16_10bit;
c->idct_add = ff_simple_idct_add_int16_10bit;
c->idct = ff_simple_idct_int16_10bit;
}
c->perm_type = FF_IDCT_PERM_NONE;
} else if (avctx->bits_per_raw_sample == 12) {
c->idct_put = ff_simple_idct_put_int16_12bit;
c->idct_add = ff_simple_idct_add_int16_12bit;
c->idct = ff_simple_idct_int16_12bit;
c->perm_type = FF_IDCT_PERM_NONE;
} else {
if (avctx->idct_algo == FF_IDCT_INT) {
c->idct_put = ff_jref_idct_put;
c->idct_add = ff_jref_idct_add;
c->idct = ff_j_rev_dct;
c->perm_type = FF_IDCT_PERM_LIBMPEG2;
#if CONFIG_FAANIDCT
} else if (avctx->idct_algo == FF_IDCT_FAAN) {
c->idct_put = ff_faanidct_put;
c->idct_add = ff_faanidct_add;
c->idct = ff_faanidct;
c->perm_type = FF_IDCT_PERM_NONE;
#endif /* CONFIG_FAANIDCT */
} else { // accurate/default
/* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */
c->idct_put = ff_simple_idct_put_int16_8bit;
c->idct_add = ff_simple_idct_add_int16_8bit;
c->idct = ff_simple_idct_int16_8bit;
c->perm_type = FF_IDCT_PERM_NONE;
}
}
}
c->put_pixels_clamped = ff_put_pixels_clamped_c;
c->put_signed_pixels_clamped = put_signed_pixels_clamped_c;
c->add_pixels_clamped = ff_add_pixels_clamped_c;
if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID)
ff_xvid_idct_init(c, avctx);
if (ARCH_AARCH64)
ff_idctdsp_init_aarch64(c, avctx, high_bit_depth);
if (ARCH_ALPHA)
ff_idctdsp_init_alpha(c, avctx, high_bit_depth);
if (ARCH_ARM)
ff_idctdsp_init_arm(c, avctx, high_bit_depth);
if (ARCH_PPC)
ff_idctdsp_init_ppc(c, avctx, high_bit_depth);
if (ARCH_X86)
ff_idctdsp_init_x86(c, avctx, high_bit_depth);
if (ARCH_MIPS)
ff_idctdsp_init_mips(c, avctx, high_bit_depth);
ff_init_scantable_permutation(c->idct_permutation,
c->perm_type);
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int cp2112_gpio_get_all(struct gpio_chip *chip)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
unsigned long flags;
int ret;
spin_lock_irqsave(&dev->lock, flags);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_GET, buf,
CP2112_GPIO_GET_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_GET_LENGTH) {
hid_err(hdev, "error requesting GPIO values: %d\n", ret);
ret = ret < 0 ? ret : -EIO;
goto exit;
}
ret = buf[1];
exit:
spin_unlock_irqrestore(&dev->lock, flags);
return ret;
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: void UserSelectionScreen::AttemptEasyUnlock(const AccountId& account_id) {
EasyUnlockService* service = GetEasyUnlockServiceForUser(account_id);
if (!service)
return;
service->AttemptAuth(account_id);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Add(int original_content_length, int received_content_length) {
AddInt64ToListPref(
kNumDaysInHistory - 1, original_content_length, original_update_.Get());
AddInt64ToListPref(
kNumDaysInHistory - 1, received_content_length, received_update_.Get());
}
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DefragVlanTest(void)
{
Packet *p1 = NULL, *p2 = NULL, *r = NULL;
int ret = 0;
DefragInit();
p1 = BuildTestPacket(1, 0, 1, 'A', 8);
if (p1 == NULL)
goto end;
p2 = BuildTestPacket(1, 1, 0, 'B', 8);
if (p2 == NULL)
goto end;
/* With no VLAN IDs set, packets should re-assemble. */
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL)
goto end;
SCFree(r);
/* With mismatched VLANs, packets should not re-assemble. */
p1->vlan_id[0] = 1;
p2->vlan_id[0] = 2;
if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL)
goto end;
if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL)
goto end;
/* Pass. */
ret = 1;
end:
if (p1 != NULL)
SCFree(p1);
if (p2 != NULL)
SCFree(p2);
DefragDestroy();
return ret;
}
CWE ID: CWE-358
Target: 1
Example 2:
Code: static void get_tr_index(void *data, struct trace_array **ptr,
unsigned int *pindex)
{
*pindex = *(unsigned char *)data;
*ptr = container_of(data - *pindex, struct trace_array,
trace_flags_index);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long Chapters::Edition::ParseAtom(
IMkvReader* pReader,
long long pos,
long long size)
{
if (!ExpandAtomsArray())
return -1;
Atom& a = m_atoms[m_atoms_count++];
a.Init();
return a.Parse(pReader, pos, size);
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck(
const KURL& current_src) {
DCHECK(IsMainThread());
return Context()->GetSecurityOrigin() &&
Context()->GetSecurityOrigin()->CanRequest(current_src);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: gro_result_t napi_gro_frags(struct napi_struct *napi)
{
struct sk_buff *skb = napi_frags_skb(napi);
if (!skb)
return GRO_DROP;
trace_napi_gro_frags_entry(skb);
return napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
}
CWE ID: CWE-400
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static __inline__ int scm_check_creds(struct ucred *creds)
{
const struct cred *cred = current_cred();
kuid_t uid = make_kuid(cred->user_ns, creds->uid);
kgid_t gid = make_kgid(cred->user_ns, creds->gid);
if (!uid_valid(uid) || !gid_valid(gid))
return -EINVAL;
if ((creds->pid == task_tgid_vnr(current) ||
ns_capable(current->nsproxy->pid_ns->user_ns, CAP_SYS_ADMIN)) &&
((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) ||
uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) &&
((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) ||
gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) {
return 0;
}
return -EPERM;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderViewImpl::DidFocus() {
WebFrame* main_frame = webview() ? webview()->MainFrame() : nullptr;
bool is_processing_user_gesture =
WebUserGestureIndicator::IsProcessingUserGesture(
main_frame && main_frame->IsWebLocalFrame()
? main_frame->ToWebLocalFrame()
: nullptr);
if (is_processing_user_gesture &&
!RenderThreadImpl::current()->layout_test_mode()) {
Send(new ViewHostMsg_Focus(GetRoutingID()));
}
}
CWE ID:
Target: 1
Example 2:
Code: static PHP_METHOD(PDOStatement, setAttribute)
{
long attr;
zval *value = NULL;
PHP_STMT_GET_OBJ;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lz!", &attr, &value)) {
RETURN_FALSE;
}
if (!stmt->methods->set_attribute) {
goto fail;
}
PDO_STMT_CLEAR_ERR();
if (stmt->methods->set_attribute(stmt, attr, value TSRMLS_CC)) {
RETURN_TRUE;
}
fail:
if (!stmt->methods->set_attribute) {
pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "This driver doesn't support setting attributes" TSRMLS_CC);
} else {
PDO_HANDLE_STMT_ERR();
}
RETURN_FALSE;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ip6t_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ip6t_entry *e, **jumpstack;
unsigned int stackidx, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
stackidx = 0;
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.hotdrop = false;
acpar.state = state;
WARN_ON(!(table->valid_hooks & (1 << hook)));
local_bh_disable();
addend = xt_write_recseq_begin();
private = READ_ONCE(table->private); /* Address dependency. */
cpu = smp_processor_id();
table_base = private->entries;
jumpstack = (struct ip6t_entry **)private->jumpstack[cpu];
/* Switch to alternate jumpstack if we're being invoked via TEE.
* TEE issues XT_CONTINUE verdict on original skb so we must not
* clobber the jumpstack.
*
* For recursion via REJECT or SYNPROXY the stack will be clobbered
* but it is no problem since absolute verdict is issued by these.
*/
if (static_key_false(&xt_tee_enabled))
jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated);
e = get_entry(table_base, private->hook_entry[hook]);
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
struct xt_counters *counter;
WARN_ON(!e);
acpar.thoff = 0;
if (!ip6_packet_match(skb, indev, outdev, &e->ipv6,
&acpar.thoff, &acpar.fragoff, &acpar.hotdrop)) {
no_match:
e = ip6t_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, skb->len, 1);
t = ip6t_get_target_c(e);
WARN_ON(!t->u.kernel.target);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(state->net, skb, hook, state->in,
state->out, table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0)
e = get_entry(table_base,
private->underflow[hook]);
else
e = ip6t_next_entry(jumpstack[--stackidx]);
continue;
}
if (table_base + v != ip6t_next_entry(e) &&
!(e->ipv6.flags & IP6T_F_GOTO)) {
jumpstack[stackidx++] = e;
}
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE)
e = ip6t_next_entry(e);
else
/* Verdict */
break;
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void svc_rdma_xdr_encode_reply_array(struct rpcrdma_write_array *ary,
int chunks)
{
ary->wc_discrim = xdr_one;
ary->wc_nchunks = cpu_to_be32(chunks);
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: static int gdGuessBackgroundColorFromCorners(gdImagePtr im, int *color)
{
const int tl = gdImageGetPixel(im, 0, 0);
const int tr = gdImageGetPixel(im, gdImageSX(im) - 1, 0);
const int bl = gdImageGetPixel(im, 0, gdImageSY(im) -1);
const int br = gdImageGetPixel(im, gdImageSX(im) - 1, gdImageSY(im) -1);
if (tr == bl && tr == br) {
*color = tr;
return 3;
} else if (tl == bl && tl == br) {
*color = tl;
return 3;
} else if (tl == tr && tl == br) {
*color = tl;
return 3;
} else if (tl == tr && tl == bl) {
*color = tl;
return 3;
} else if (tl == tr || tl == bl || tl == br) {
*color = tl;
return 2;
} else if (tr == bl) {
*color = tr;
return 2;
} else if (br == bl) {
*color = bl;
return 2;
} else {
register int r,b,g,a;
r = (int)(0.5f + (gdImageRed(im, tl) + gdImageRed(im, tr) + gdImageRed(im, bl) + gdImageRed(im, br)) / 4);
g = (int)(0.5f + (gdImageGreen(im, tl) + gdImageGreen(im, tr) + gdImageGreen(im, bl) + gdImageGreen(im, br)) / 4);
b = (int)(0.5f + (gdImageBlue(im, tl) + gdImageBlue(im, tr) + gdImageBlue(im, bl) + gdImageBlue(im, br)) / 4);
a = (int)(0.5f + (gdImageAlpha(im, tl) + gdImageAlpha(im, tr) + gdImageAlpha(im, bl) + gdImageAlpha(im, br)) / 4);
*color = gdImageColorClosestAlpha(im, r, g, b, a);
return 0;
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const Vector<IconURL>& Document::iconURLs(int iconTypesMask)
{
m_iconURLs.clear();
if (!head() || !(head()->children()))
return m_iconURLs;
RefPtr<HTMLCollection> children = head()->children();
unsigned int length = children->length();
for (unsigned int i = 0; i < length; ++i) {
Node* child = children->item(i);
if (!child->hasTagName(linkTag))
continue;
HTMLLinkElement* linkElement = toHTMLLinkElement(child);
if (!(linkElement->iconType() & iconTypesMask))
continue;
if (linkElement->href().isEmpty())
continue;
IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
m_iconURLs.prepend(newURL);
}
return m_iconURLs;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void unset_active_map(const vpx_codec_enc_cfg_t *cfg,
vpx_codec_ctx_t *codec) {
vpx_active_map_t map = {0};
map.rows = (cfg->g_h + 15) / 16;
map.cols = (cfg->g_w + 15) / 16;
map.active_map = NULL;
if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map))
die_codec(codec, "Failed to set active map");
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderFrameHostImpl::ExecuteJavaScriptForTests(
const base::string16& javascript,
JavaScriptResultCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
const bool has_user_gesture = false;
GetNavigationControl()->JavaScriptExecuteRequestForTests(
javascript, has_user_gesture, std::move(callback));
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BufferMeta(const sp<GraphicBuffer> &graphicBuffer)
: mGraphicBuffer(graphicBuffer),
mIsBackup(false) {
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE omx_video::allocate_input_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned i = 0;
DEBUG_PRINT_HIGH("allocate_input_buffer()::");
if (bytes != m_sInPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]",
(unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_inp_mem_ptr) {
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual);
m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \
calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual);
if (m_inp_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr");
return OMX_ErrorInsufficientResources;
}
DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr);
m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual);
if (m_pInput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual);
if (m_pInput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
m_pInput_pmem[i].fd = -1;
#ifdef USE_ION
m_pInput_ion[i].ion_device_fd =-1;
m_pInput_ion[i].fd_ion_data.fd =-1;
m_pInput_ion[i].ion_alloc_data.handle = 0;
#endif
}
}
for (i=0; i< m_sInPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_inp_bm_count,i)) {
break;
}
}
if (i < m_sInPortDef.nBufferCountActual) {
*bufferHdr = (m_inp_mem_ptr + i);
(*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE);
(*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION;
(*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize;
(*bufferHdr)->pAppPrivate = appData;
(*bufferHdr)->nInputPortIndex = PORT_INDEX_IN;
(*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i];
#ifdef USE_ION
#ifdef _MSM8974_
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,0);
#else
m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize,
&m_pInput_ion[i].ion_alloc_data,
&m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pInput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd;
#else
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pInput_pmem[i].fd == 0) {
m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pInput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pInput_pmem[i].size = m_sInPortDef.nBufferSize;
m_pInput_pmem[i].offset = 0;
m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pInput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pInput_pmem[i].fd,0);
if (m_pInput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno);
close(m_pInput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pInput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
} else {
m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
(*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*);
}
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer;
DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer);
BITMASK_SET(&m_inp_bm_count,i);
if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call"
"for index [%d]", i);
eRet = OMX_ErrorInsufficientResources;
}
return eRet;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: e1000e_set_fcrtl(E1000ECore *core, int index, uint32_t val)
{
core->mac[FCRTL] = val & 0x8000FFF8;
}
CWE ID: CWE-835
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
size_t len, loff_t *ptr)
{
struct ffs_data *ffs = file->private_data;
char *data = NULL;
size_t n;
int ret;
ENTER();
/* Fast check if setup was canceled */
if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
return -EIDRM;
/* Acquire mutex */
ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
if (unlikely(ret < 0))
return ret;
/* Check state */
if (ffs->state != FFS_ACTIVE) {
ret = -EBADFD;
goto done_mutex;
}
/*
* We're called from user space, we can use _irq rather then
* _irqsave
*/
spin_lock_irq(&ffs->ev.waitq.lock);
switch (ffs_setup_state_clear_cancelled(ffs)) {
case FFS_SETUP_CANCELLED:
ret = -EIDRM;
break;
case FFS_NO_SETUP:
n = len / sizeof(struct usb_functionfs_event);
if (unlikely(!n)) {
ret = -EINVAL;
break;
}
if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
ret = -EAGAIN;
break;
}
if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
ffs->ev.count)) {
ret = -EINTR;
break;
}
return __ffs_ep0_read_events(ffs, buf,
min(n, (size_t)ffs->ev.count));
case FFS_SETUP_PENDING:
if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
spin_unlock_irq(&ffs->ev.waitq.lock);
ret = __ffs_ep0_stall(ffs);
goto done_mutex;
}
len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
spin_unlock_irq(&ffs->ev.waitq.lock);
if (likely(len)) {
data = kmalloc(len, GFP_KERNEL);
if (unlikely(!data)) {
ret = -ENOMEM;
goto done_mutex;
}
}
spin_lock_irq(&ffs->ev.waitq.lock);
/* See ffs_ep0_write() */
if (ffs_setup_state_clear_cancelled(ffs) ==
FFS_SETUP_CANCELLED) {
ret = -EIDRM;
break;
}
/* unlocks spinlock */
ret = __ffs_ep0_queue_wait(ffs, data, len);
if (likely(ret > 0) && unlikely(copy_to_user(buf, data, len)))
ret = -EFAULT;
goto done_mutex;
default:
ret = -EBADFD;
break;
}
spin_unlock_irq(&ffs->ev.waitq.lock);
done_mutex:
mutex_unlock(&ffs->mutex);
kfree(data);
return ret;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceNew(
const GpuHostMsg_AcceleratedSurfaceNew_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
view->AcceleratedSurfaceNew(
params.width, params.height, params.surface_handle);
}
CWE ID:
Target: 1
Example 2:
Code: void ResourceFetcher::UpdateAllImageResourcePriorities() {
TRACE_EVENT0(
"blink",
"ResourceLoadPriorityOptimizer::updateAllImageResourcePriorities");
for (Resource* resource : document_resources_) {
if (!resource || resource->GetType() != Resource::kImage ||
!resource->IsLoading())
continue;
ResourcePriority resource_priority = resource->PriorityFromObservers();
ResourceLoadPriority resource_load_priority =
ComputeLoadPriority(Resource::kImage, resource->GetResourceRequest(),
resource_priority.visibility);
if (resource_load_priority == resource->GetResourceRequest().Priority())
continue;
resource->DidChangePriority(resource_load_priority,
resource_priority.intra_priority_value);
network_instrumentation::ResourcePrioritySet(resource->Identifier(),
resource_load_priority);
Context().DispatchDidChangeResourcePriority(
resource->Identifier(), resource_load_priority,
resource_priority.intra_priority_value);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int InputHandler::selectionPosition(bool start) const
{
if (!m_currentFocusElement->document() || !m_currentFocusElement->document()->frame())
return 0;
if (HTMLTextFormControlElement* controlElement = DOMSupport::toTextControlElement(m_currentFocusElement.get()))
return start ? controlElement->selectionStart() : controlElement->selectionEnd();
FrameSelection caretSelection;
caretSelection.setSelection(m_currentFocusElement->document()->frame()->selection()->selection());
RefPtr<Range> rangeSelection = caretSelection.selection().toNormalizedRange();
if (!rangeSelection)
return 0;
int selectionPointInNode = start ? rangeSelection->startOffset() : rangeSelection->endOffset();
Node* containerNode = start ? rangeSelection->startContainer() : rangeSelection->endContainer();
ExceptionCode ec;
RefPtr<Range> rangeForNode = rangeOfContents(m_currentFocusElement.get());
rangeForNode->setEnd(containerNode, selectionPointInNode, ec);
ASSERT(!ec);
return TextIterator::rangeLength(rangeForNode.get());
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DesktopSessionWin::OnChannelConnected() {
DCHECK(main_task_runner_->BelongsToCurrentThread());
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void resched_curr(struct rq *rq)
{
struct task_struct *curr = rq->curr;
int cpu;
lockdep_assert_held(&rq->lock);
if (test_tsk_need_resched(curr))
return;
cpu = cpu_of(rq);
if (cpu == smp_processor_id()) {
set_tsk_need_resched(curr);
set_preempt_need_resched();
return;
}
if (set_nr_and_not_polling(curr))
smp_send_reschedule(cpu);
else
trace_sched_wake_idle_without_ipi(cpu);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int mainloop(CLIENT *client) {
struct nbd_request request;
struct nbd_reply reply;
gboolean go_on=TRUE;
#ifdef DODBG
int i = 0;
#endif
negotiate(client->net, client, NULL);
DEBUG("Entering request loop!\n");
reply.magic = htonl(NBD_REPLY_MAGIC);
reply.error = 0;
while (go_on) {
char buf[BUFSIZE];
size_t len;
#ifdef DODBG
i++;
printf("%d: ", i);
#endif
readit(client->net, &request, sizeof(request));
request.from = ntohll(request.from);
request.type = ntohl(request.type);
if (request.type==NBD_CMD_DISC) {
msg2(LOG_INFO, "Disconnect request received.");
if (client->server->flags & F_COPYONWRITE) {
if (client->difmap) g_free(client->difmap) ;
close(client->difffile);
unlink(client->difffilename);
free(client->difffilename);
}
go_on=FALSE;
continue;
}
len = ntohl(request.len);
if (request.magic != htonl(NBD_REQUEST_MAGIC))
err("Not enough magic.");
if (len > BUFSIZE + sizeof(struct nbd_reply))
err("Request too big!");
#ifdef DODBG
printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" :
"READ", (unsigned long long)request.from,
(unsigned long long)request.from / 512, len);
#endif
memcpy(reply.handle, request.handle, sizeof(reply.handle));
if ((request.from + len) > (OFFT_MAX)) {
DEBUG("[Number too large!]");
ERROR(client, reply, EINVAL);
continue;
}
if (((ssize_t)((off_t)request.from + len) > client->exportsize)) {
DEBUG("[RANGE!]");
ERROR(client, reply, EINVAL);
continue;
}
if (request.type==NBD_CMD_WRITE) {
DEBUG("wr: net->buf, ");
readit(client->net, buf, len);
DEBUG("buf->exp, ");
if ((client->server->flags & F_READONLY) ||
(client->server->flags & F_AUTOREADONLY)) {
DEBUG("[WRITE to READONLY!]");
ERROR(client, reply, EPERM);
continue;
}
if (expwrite(request.from, buf, len, client)) {
DEBUG("Write failed: %m" );
ERROR(client, reply, errno);
continue;
}
SEND(client->net, reply);
DEBUG("OK!\n");
continue;
}
/* READ */
DEBUG("exp->buf, ");
if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) {
DEBUG("Read failed: %m");
ERROR(client, reply, errno);
continue;
}
DEBUG("buf->net, ");
memcpy(buf, &reply, sizeof(struct nbd_reply));
writeit(client->net, buf, len + sizeof(struct nbd_reply));
DEBUG("OK!\n");
}
return 0;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: gstd_accept(int fd, char **display_creds, char **export_name, char **mech)
{
gss_name_t client;
gss_OID mech_oid;
struct gstd_tok *tok;
gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
gss_buffer_desc in, out;
OM_uint32 maj, min;
int ret;
*display_creds = NULL;
*export_name = NULL;
out.length = 0;
in.length = 0;
read_packet(fd, &in, 60000, 1);
again:
while ((ret = read_packet(fd, &in, 60000, 0)) == -2)
;
if (ret < 1)
return NULL;
maj = gss_accept_sec_context(&min, &ctx, GSS_C_NO_CREDENTIAL,
&in, GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out, NULL,
NULL, NULL);
if (out.length && write_packet(fd, &out)) {
gss_release_buffer(&min, &out);
return NULL;
}
GSTD_GSS_ERROR(maj, min, NULL, "gss_accept_sec_context");
if (maj & GSS_S_CONTINUE_NEEDED)
goto again;
*display_creds = gstd_get_display_name(client);
*export_name = gstd_get_export_name(client);
*mech = gstd_get_mech(mech_oid);
gss_release_name(&min, &client);
SETUP_GSTD_TOK(tok, ctx, fd, "gstd_accept");
return tok;
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: v8::Persistent<v8::FunctionTemplate> V8TestEventTarget::GetTemplate()
{
V8BindingPerIsolateData* data = V8BindingPerIsolateData::current();
V8BindingPerIsolateData::TemplateMap::iterator result = data->templateMap().find(&info);
if (result != data->templateMap().end())
return result->second;
v8::HandleScope handleScope;
v8::Persistent<v8::FunctionTemplate> templ =
ConfigureV8TestEventTargetTemplate(GetRawTemplate());
data->templateMap().add(&info, templ);
return templ;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PushMessagingServiceImpl::PushMessagingServiceImpl(Profile* profile)
: profile_(profile),
push_subscription_count_(0),
pending_push_subscription_count_(0),
notification_manager_(profile),
push_messaging_service_observer_(PushMessagingServiceObserver::Create()),
weak_factory_(this) {
DCHECK(profile);
HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this);
registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
content::NotificationService::AllSources());
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int on_http_message_complete(http_parser* parser)
{
struct clt_info *info = parser->data;
ws_svr *svr = ws_svr_from_ses(info->ses);
info->request->version_major = parser->http_major;
info->request->version_minor = parser->http_minor;
info->request->method = parser->method;
dict_entry *entry;
dict_iterator *iter = dict_get_iterator(info->request->headers);
while ((entry = dict_next(iter)) != NULL) {
log_trace("Header: %s: %s", (char *)entry->key, (char *)entry->val);
}
dict_release_iterator(iter);
if (info->request->method != HTTP_GET)
goto error;
if (http_request_get_header(info->request, "Host") == NULL)
goto error;
double version = info->request->version_major + info->request->version_minor * 0.1;
if (version < 1.1)
goto error;
const char *upgrade = http_request_get_header(info->request, "Upgrade");
if (upgrade == NULL || strcasecmp(upgrade, "websocket") != 0)
goto error;
const char *connection = http_request_get_header(info->request, "Connection");
if (connection == NULL)
goto error;
else {
bool found_upgrade = false;
int count;
sds *tokens = sdssplitlen(connection, strlen(connection), ",", 1, &count);
if (tokens == NULL)
goto error;
for (int i = 0; i < count; i++) {
sds token = tokens[i];
sdstrim(token, " ");
if (strcasecmp(token, "Upgrade") == 0) {
found_upgrade = true;
break;
}
}
sdsfreesplitres(tokens, count);
if (!found_upgrade)
goto error;
}
const char *ws_version = http_request_get_header(info->request, "Sec-WebSocket-Version");
if (ws_version == NULL || strcmp(ws_version, "13") != 0)
goto error;
const char *ws_key = http_request_get_header(info->request, "Sec-WebSocket-Key");
if (ws_key == NULL)
goto error;
const char *protocol_list = http_request_get_header(info->request, "Sec-WebSocket-Protocol");
if (protocol_list && !is_good_protocol(protocol_list, svr->protocol))
goto error;
if (strlen(svr->origin) > 0) {
const char *origin = http_request_get_header(info->request, "Origin");
if (origin == NULL || !is_good_origin(origin, svr->origin))
goto error;
}
if (svr->type.on_privdata_alloc) {
info->privdata = svr->type.on_privdata_alloc(svr);
if (info->privdata == NULL)
goto error;
}
info->upgrade = true;
info->remote = sdsnew(http_get_remote_ip(info->ses, info->request));
info->url = sdsnew(info->request->url);
if (svr->type.on_upgrade) {
svr->type.on_upgrade(info->ses, info->remote);
}
if (protocol_list) {
send_hand_shake_reply(info->ses, svr->protocol, ws_key);
} else {
send_hand_shake_reply(info->ses, NULL, ws_key);
}
return 0;
error:
ws_svr_close_clt(ws_svr_from_ses(info->ses), info->ses);
return -1;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static AVRational find_fps(AVFormatContext *s, AVStream *st)
{
AVRational rate = st->avg_frame_rate;
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
rate = av_inv_q(st->codec->time_base);
if (av_timecode_check_frame_rate(rate) < 0) {
av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
rate = st->avg_frame_rate;
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
return rate;
}
CWE ID: CWE-369
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nfs41_sequence_handle_errors(struct rpc_task *task, struct nfs_client *clp)
{
switch(task->tk_status) {
case -NFS4ERR_DELAY:
rpc_delay(task, NFS4_POLL_RETRY_MAX);
return -EAGAIN;
default:
nfs4_schedule_lease_recovery(clp);
}
return 0;
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int LE_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
LoudnessEnhancerContext * pContext = (LoudnessEnhancerContext *)self;
int retsize;
if (pContext == NULL || pContext->mState == LOUDNESS_ENHANCER_STATE_UNINITIALIZED) {
return -EINVAL;
}
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = LE_init(pContext);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = LE_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL ||
*replySize != sizeof(effect_config_t)) {
return -EINVAL;
}
LE_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
LE_reset(pContext);
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pContext->mState != LOUDNESS_ENHANCER_STATE_INITIALIZED) {
return -ENOSYS;
}
pContext->mState = LOUDNESS_ENHANCER_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pContext->mState != LOUDNESS_ENHANCER_STATE_ACTIVE) {
return -ENOSYS;
}
pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_GET_PARAM: {
if (pCmdData == NULL ||
cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t)) ||
pReplyData == NULL ||
*replySize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t))) {
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(uint32_t));
effect_param_t *p = (effect_param_t *)pReplyData;
p->status = 0;
*replySize = sizeof(effect_param_t) + sizeof(uint32_t);
if (p->psize != sizeof(uint32_t)) {
p->status = -EINVAL;
break;
}
switch (*(uint32_t *)p->data) {
case LOUDNESS_ENHANCER_PARAM_TARGET_GAIN_MB:
ALOGV("get target gain(mB) = %d", pContext->mTargetGainmB);
*((int32_t *)p->data + 1) = pContext->mTargetGainmB;
p->vsize = sizeof(int32_t);
*replySize += sizeof(int32_t);
break;
default:
p->status = -EINVAL;
}
} break;
case EFFECT_CMD_SET_PARAM: {
if (pCmdData == NULL ||
cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t)) ||
pReplyData == NULL || *replySize != sizeof(int32_t)) {
return -EINVAL;
}
*(int32_t *)pReplyData = 0;
effect_param_t *p = (effect_param_t *)pCmdData;
if (p->psize != sizeof(uint32_t) || p->vsize != sizeof(uint32_t)) {
*(int32_t *)pReplyData = -EINVAL;
break;
}
switch (*(uint32_t *)p->data) {
case LOUDNESS_ENHANCER_PARAM_TARGET_GAIN_MB:
pContext->mTargetGainmB = *((int32_t *)p->data + 1);
ALOGV("set target gain(mB) = %d", pContext->mTargetGainmB);
LE_reset(pContext); // apply parameter update
break;
default:
*(int32_t *)pReplyData = -EINVAL;
}
} break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_VOLUME:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGW("LE_command invalid command %d",cmdCode);
return -EINVAL;
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void *xt_match_seq_start(struct seq_file *seq, loff_t *pos)
{
return xt_mttg_seq_start(seq, pos, false);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void ehci_port_write(void *ptr, hwaddr addr,
uint64_t val, unsigned size)
{
EHCIState *s = ptr;
int port = addr >> 2;
uint32_t *portsc = &s->portsc[port];
uint32_t old = *portsc;
USBDevice *dev = s->ports[port].dev;
trace_usb_ehci_portsc_write(addr + s->portscbase, addr >> 2, val);
/* Clear rwc bits */
*portsc &= ~(val & PORTSC_RWC_MASK);
/* The guest may clear, but not set the PED bit */
*portsc &= val | ~PORTSC_PED;
/* POWNER is masked out by RO_MASK as it is RO when we've no companion */
handle_port_owner_write(s, port, val);
/* And finally apply RO_MASK */
val &= PORTSC_RO_MASK;
if ((val & PORTSC_PRESET) && !(*portsc & PORTSC_PRESET)) {
trace_usb_ehci_port_reset(port, 1);
}
if (!(val & PORTSC_PRESET) &&(*portsc & PORTSC_PRESET)) {
trace_usb_ehci_port_reset(port, 0);
if (dev && dev->attached) {
usb_port_reset(&s->ports[port]);
*portsc &= ~PORTSC_CSC;
}
/*
* Table 2.16 Set the enable bit(and enable bit change) to indicate
* to SW that this port has a high speed device attached
*/
if (dev && dev->attached && (dev->speedmask & USB_SPEED_MASK_HIGH)) {
val |= PORTSC_PED;
}
}
if ((val & PORTSC_SUSPEND) && !(*portsc & PORTSC_SUSPEND)) {
trace_usb_ehci_port_suspend(port);
}
if (!(val & PORTSC_FPRES) && (*portsc & PORTSC_FPRES)) {
trace_usb_ehci_port_resume(port);
val &= ~PORTSC_SUSPEND;
}
*portsc &= ~PORTSC_RO_MASK;
*portsc |= val;
trace_usb_ehci_portsc_change(addr + s->portscbase, addr >> 2, *portsc, old);
}
CWE ID: CWE-772
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
{
if (x + 1 > 10)
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"%s",
"x is bigger than 9");
return FALSE;
}
return x + 1;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static UINT dvcman_close_channel_iface(IWTSVirtualChannel* pChannel)
{
DVCMAN_CHANNEL* channel = (DVCMAN_CHANNEL*) pChannel;
if (!channel)
return CHANNEL_RC_BAD_CHANNEL;
WLog_DBG(TAG, "close_channel_iface: id=%"PRIu32"", channel->channel_id);
return CHANNEL_RC_OK;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int do_insn_ioctl(struct comedi_device *dev,
struct comedi_insn __user *arg, void *file)
{
struct comedi_insn insn;
unsigned int *data = NULL;
int ret = 0;
data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
if (!data) {
ret = -ENOMEM;
goto error;
}
if (copy_from_user(&insn, arg, sizeof(struct comedi_insn))) {
ret = -EFAULT;
goto error;
}
/* This is where the behavior of insn and insnlist deviate. */
if (insn.n > MAX_SAMPLES)
insn.n = MAX_SAMPLES;
if (insn.insn & INSN_MASK_WRITE) {
if (copy_from_user(data,
insn.data,
insn.n * sizeof(unsigned int))) {
ret = -EFAULT;
goto error;
}
}
ret = parse_insn(dev, &insn, data, file);
if (ret < 0)
goto error;
if (insn.insn & INSN_MASK_READ) {
if (copy_to_user(insn.data,
data,
insn.n * sizeof(unsigned int))) {
ret = -EFAULT;
goto error;
}
}
ret = insn.n;
error:
kfree(data);
return ret;
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
{
struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
if (addr) {
addr->family = AF_TIPC;
addr->addrtype = TIPC_ADDR_ID;
addr->addr.id.ref = msg_origport(msg);
addr->addr.id.node = msg_orignode(msg);
addr->addr.name.domain = 0; /* could leave uninitialized */
addr->scope = 0; /* could leave uninitialized */
m->msg_namelen = sizeof(struct sockaddr_tipc);
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: get_array_end(void *state)
{
GetState *_state = (GetState *) state;
int lex_level = _state->lex->lex_level;
if (lex_level == 0 && _state->npath == 0)
{
/* Special case: return the entire array */
char *start = _state->result_start;
int len = _state->lex->prev_token_terminator - start;
_state->tresult = cstring_to_text_with_len(start, len);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void *Sys_LoadDll(const char *name, qboolean useSystemLib)
{
void *dllhandle;
if(useSystemLib)
Com_Printf("Trying to load \"%s\"...\n", name);
if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))
{
const char *topDir;
char libPath[MAX_OSPATH];
topDir = Sys_BinaryPath();
if(!*topDir)
topDir = ".";
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name);
if(!(dllhandle = Sys_LoadLibrary(libPath)))
{
const char *basePath = Cvar_VariableString("fs_basepath");
if(!basePath || !*basePath)
basePath = ".";
if(FS_FilenameCompare(topDir, basePath))
{
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name);
dllhandle = Sys_LoadLibrary(libPath);
}
if(!dllhandle)
Com_Printf("Loading \"%s\" failed\n", name);
}
}
return dllhandle;
}
CWE ID: CWE-269
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int hns_rcb_get_ring_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return HNS_RING_STATIC_REG_NUM;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebContentsImpl::OnCreditCardInputShownOnHttp() {
controller_.ssl_manager()->DidShowCreditCardInputOnHttp();
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::string TestFlashMessageLoop::TestBasics() {
message_loop_ = new pp::flash::MessageLoop(instance_);
pp::CompletionCallback callback = callback_factory_.NewCallback(
&TestFlashMessageLoop::QuitMessageLoopTask);
pp::Module::Get()->core()->CallOnMainThread(0, callback);
int32_t result = message_loop_->Run();
ASSERT_TRUE(message_loop_);
delete message_loop_;
message_loop_ = NULL;
ASSERT_EQ(PP_OK, result);
PASS();
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: jbig2_find_changing_element(const byte *line, int x, int w)
{
int a, b;
if (line == 0)
return w;
if (x == -1) {
a = 0;
x = 0;
} else {
}
while (x < w) {
b = getbit(line, x);
if (a != b)
break;
x++;
}
return x;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: file_replace(struct magic_set *ms, const char *pat, const char *rep)
{
file_regex_t rx;
int rc, rv = -1;
rc = file_regcomp(&rx, pat, REG_EXTENDED);
if (rc) {
file_regerror(&rx, rc, ms);
} else {
regmatch_t rm;
int nm = 0;
while (file_regexec(&rx, ms->o.buf, 1, &rm, 0) == 0) {
ms->o.buf[rm.rm_so] = '\0';
if (file_printf(ms, "%s%s", rep,
rm.rm_eo != 0 ? ms->o.buf + rm.rm_eo : "") == -1)
goto out;
nm++;
}
rv = nm;
}
out:
file_regfree(&rx);
return rv;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool DelegatedFrameHost::TransformPointToLocalCoordSpace(
const gfx::Point& point,
const viz::SurfaceId& original_surface,
gfx::Point* transformed_point) {
viz::SurfaceId surface_id(frame_sink_id_, local_surface_id_);
if (!surface_id.is_valid())
return false;
*transformed_point = point;
if (original_surface == surface_id)
return true;
viz::SurfaceHittest hittest(nullptr,
GetFrameSinkManager()->surface_manager());
return hittest.TransformPointToTargetSurface(original_surface, surface_id,
transformed_point);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: my_object_stringify (MyObject *obj, GValue *value, char **ret, GError **error)
{
GValue valstr = {0, };
g_value_init (&valstr, G_TYPE_STRING);
if (!g_value_transform (value, &valstr))
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"couldn't transform value");
return FALSE;
}
*ret = g_value_dup_string (&valstr);
g_value_unset (&valstr);
return TRUE;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: iperf_send(struct iperf_test *test, fd_set *write_setP)
{
register int multisend, r, streams_active;
register struct iperf_stream *sp;
struct timeval now;
/* Can we do multisend mode? */
if (test->settings->burst != 0)
multisend = test->settings->burst;
else if (test->settings->rate == 0)
multisend = test->multisend;
else
multisend = 1; /* nope */
for (; multisend > 0; --multisend) {
if (test->settings->rate != 0 && test->settings->burst == 0)
gettimeofday(&now, NULL);
streams_active = 0;
SLIST_FOREACH(sp, &test->streams, streams) {
if (sp->green_light &&
(write_setP == NULL || FD_ISSET(sp->socket, write_setP))) {
if ((r = sp->snd(sp)) < 0) {
if (r == NET_SOFTERROR)
break;
i_errno = IESTREAMWRITE;
return r;
}
streams_active = 1;
test->bytes_sent += r;
++test->blocks_sent;
if (test->settings->rate != 0 && test->settings->burst == 0)
iperf_check_throttle(sp, &now);
if (multisend > 1 && test->settings->bytes != 0 && test->bytes_sent >= test->settings->bytes)
break;
if (multisend > 1 && test->settings->blocks != 0 && test->blocks_sent >= test->settings->blocks)
break;
}
}
if (!streams_active)
break;
}
if (test->settings->burst != 0) {
gettimeofday(&now, NULL);
SLIST_FOREACH(sp, &test->streams, streams)
iperf_check_throttle(sp, &now);
}
if (write_setP != NULL)
SLIST_FOREACH(sp, &test->streams, streams)
if (FD_ISSET(sp->socket, write_setP))
FD_CLR(sp->socket, write_setP);
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Ins_GETVARIATION( TT_ExecContext exc,
FT_Long* args )
{
FT_UInt num_axes = exc->face->blend->num_axis;
FT_Fixed* coords = exc->face->blend->normalizedcoords;
FT_UInt i;
if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) )
{
exc->error = FT_THROW( Stack_Overflow );
return;
}
for ( i = 0; i < num_axes; i++ )
args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PresentationConnectionProxy::DidChangeState(
content::PresentationConnectionState state) {
if (state == content::PRESENTATION_CONNECTION_STATE_CONNECTED) {
source_connection_->didChangeState(
blink::WebPresentationConnectionState::Connected);
} else if (state == content::PRESENTATION_CONNECTION_STATE_CLOSED) {
source_connection_->didChangeState(
blink::WebPresentationConnectionState::Closed);
} else {
NOTREACHED();
}
}
CWE ID:
Target: 1
Example 2:
Code: bool SafeSock :: init_MD(CONDOR_MD_MODE /* mode */, KeyInfo * key, const char * keyId)
{
bool inited = true;
if (mdChecker_) {
delete mdChecker_;
mdChecker_ = 0;
}
if (key) {
mdChecker_ = new Condor_MD_MAC(key);
}
if (_longMsg) {
inited = _longMsg->verifyMD(mdChecker_);
}
else {
inited = _shortMsg.verifyMD(mdChecker_);
}
if( !_outMsg.init_MD(keyId) ) {
inited = false;
}
return inited;
}
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct dentry *debugfs_rename(struct dentry *old_dir, struct dentry *old_dentry,
struct dentry *new_dir, const char *new_name)
{
int error;
struct dentry *dentry = NULL, *trap;
const char *old_name;
trap = lock_rename(new_dir, old_dir);
/* Source or destination directories don't exist? */
if (d_really_is_negative(old_dir) || d_really_is_negative(new_dir))
goto exit;
/* Source does not exist, cyclic rename, or mountpoint? */
if (d_really_is_negative(old_dentry) || old_dentry == trap ||
d_mountpoint(old_dentry))
goto exit;
dentry = lookup_one_len(new_name, new_dir, strlen(new_name));
/* Lookup failed, cyclic rename or target exists? */
if (IS_ERR(dentry) || dentry == trap || d_really_is_positive(dentry))
goto exit;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
error = simple_rename(d_inode(old_dir), old_dentry, d_inode(new_dir),
dentry, 0);
if (error) {
fsnotify_oldname_free(old_name);
goto exit;
}
d_move(old_dentry, dentry);
fsnotify_move(d_inode(old_dir), d_inode(new_dir), old_name,
d_is_dir(old_dentry),
NULL, old_dentry);
fsnotify_oldname_free(old_name);
unlock_rename(new_dir, old_dir);
dput(dentry);
return old_dentry;
exit:
if (dentry && !IS_ERR(dentry))
dput(dentry);
unlock_rename(new_dir, old_dir);
return NULL;
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent,
uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto,
PacketQueue *pq)
{
int ret;
SCEnter();
/* get us a packet */
Packet *p = PacketGetFromQueueOrAlloc();
if (unlikely(p == NULL)) {
SCReturnPtr(NULL, "Packet");
}
/* copy packet and set lenght, proto */
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
p->datalink = DLT_RAW;
p->tenant_id = parent->tenant_id;
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p),
GET_PKT_LEN(p), pq, proto);
if (unlikely(ret != TM_ECODE_OK)) {
/* Not a tunnel packet, just a pseudo packet */
p->root = NULL;
UNSET_TUNNEL_PKT(p);
TmqhOutputPacketpool(tv, p);
SCReturnPtr(NULL, "Packet");
}
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
/* disable payload (not packet) inspection on the parent, as the payload
* is the packet we will now run through the system separately. We do
* check it against the ip/port/other header checks though */
DecodeSetNoPayloadInspectionFlag(parent);
SCReturnPtr(p, "Packet");
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: decode_OFPAT_RAW10_ENQUEUE(const struct ofp10_action_enqueue *oae,
enum ofp_version ofp_version OVS_UNUSED,
struct ofpbuf *out)
{
struct ofpact_enqueue *enqueue;
enqueue = ofpact_put_ENQUEUE(out);
enqueue->port = u16_to_ofp(ntohs(oae->port));
enqueue->queue = ntohl(oae->queue_id);
if (ofp_to_u16(enqueue->port) >= ofp_to_u16(OFPP_MAX)
&& enqueue->port != OFPP_IN_PORT
&& enqueue->port != OFPP_LOCAL) {
return OFPERR_OFPBAC_BAD_OUT_PORT;
}
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: inline uint32_t web_client_api_request_v1_data_options(char *o) {
uint32_t ret = 0x00000000;
char *tok;
while(o && *o && (tok = mystrsep(&o, ", |"))) {
if(!*tok) continue;
uint32_t hash = simple_hash(tok);
int i;
for(i = 0; api_v1_data_options[i].name ; i++) {
if (unlikely(hash == api_v1_data_options[i].hash && !strcmp(tok, api_v1_data_options[i].name))) {
ret |= api_v1_data_options[i].value;
break;
}
}
}
return ret;
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
if (n <= 0) return(n); /* error or non-blocking io */
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
*p == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
CWE ID:
Target: 1
Example 2:
Code: const void* ComputePackAlignmentAddress(
GLint x, GLint y, GLsizei width, const void* address) const {
GLint unpadded_row_size = ComputeImageDataSize(width, 1);
GLint two_rows_size = ComputeImageDataSize(width, 2);
GLsizei padded_row_size = two_rows_size - unpadded_row_size;
GLint offset = y * padded_row_size + x * bytes_per_pixel_;
return static_cast<const int8*>(address) + offset;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SubpelVarianceTest<SubpelVarianceFunctionType>::RefTest() {
for (int x = 0; x < 16; ++x) {
for (int y = 0; y < 16; ++y) {
for (int j = 0; j < block_size_; j++) {
src_[j] = rnd.Rand8();
}
for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) {
ref_[j] = rnd.Rand8();
}
unsigned int sse1, sse2;
unsigned int var1;
REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y,
src_, width_, &sse1));
const unsigned int var2 = subpel_variance_ref(ref_, src_, log2width_,
log2height_, x, y, &sse2);
EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y;
EXPECT_EQ(var1, var2) << "at position " << x << ", " << y;
}
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RunExtremalCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int max_error = 0;
int total_error = 0;
const int count_test_block = 100000;
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < 64; ++j) {
src[j] = rnd.Rand8() % 2 ? 255 : 0;
dst[j] = src[j] > 0 ? 0 : 255;
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(
RunFwdTxfm(test_input_block, test_temp_block, pitch_));
REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < 64; ++j) {
const int diff = dst[j] - src[j];
const int error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
EXPECT_GE(1, max_error)
<< "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has"
<< "an individual roundtrip error > 1";
EXPECT_GE(count_test_block/5, total_error)
<< "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has average"
<< " roundtrip error > 1/5 per block";
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static FxInfo **AcquireFxThreadSet(const Image *image,const char *expression,
ExceptionInfo *exception)
{
char
*fx_expression;
FxInfo
**fx_info;
double
alpha;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
fx_info=(FxInfo **) AcquireQuantumMemory(number_threads,sizeof(*fx_info));
if (fx_info == (FxInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return((FxInfo **) NULL);
}
(void) ResetMagickMemory(fx_info,0,number_threads*sizeof(*fx_info));
if (*expression != '@')
fx_expression=ConstantString(expression);
else
fx_expression=FileToString(expression+1,~0UL,exception);
for (i=0; i < (ssize_t) number_threads; i++)
{
MagickBooleanType
status;
fx_info[i]=AcquireFxInfo(image,fx_expression,exception);
if (fx_info[i] == (FxInfo *) NULL)
break;
status=FxPreprocessExpression(fx_info[i],&alpha,exception);
if (status == MagickFalse)
break;
}
fx_expression=DestroyString(fx_expression);
if (i < (ssize_t) number_threads)
fx_info=DestroyFxThreadSet(fx_info);
return(fx_info);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long len)
{
return jas_stream_copy(out, in, len);
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int mutt_b64_decode(char *out, const char *in)
{
int len = 0;
unsigned char digit4;
do
{
const unsigned char digit1 = in[0];
if ((digit1 > 127) || (base64val(digit1) == BAD))
return -1;
const unsigned char digit2 = in[1];
if ((digit2 > 127) || (base64val(digit2) == BAD))
return -1;
const unsigned char digit3 = in[2];
if ((digit3 > 127) || ((digit3 != '=') && (base64val(digit3) == BAD)))
return -1;
digit4 = in[3];
if ((digit4 > 127) || ((digit4 != '=') && (base64val(digit4) == BAD)))
return -1;
in += 4;
/* digits are already sanity-checked */
*out++ = (base64val(digit1) << 2) | (base64val(digit2) >> 4);
len++;
if (digit3 != '=')
{
*out++ = ((base64val(digit2) << 4) & 0xf0) | (base64val(digit3) >> 2);
len++;
if (digit4 != '=')
{
*out++ = ((base64val(digit3) << 6) & 0xc0) | base64val(digit4);
len++;
}
}
} while (*in && digit4 != '=');
return len;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
(u64)off + size > reg->range) {
verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
off, size, regno, reg->id, reg->off, reg->range);
return -EACCES;
}
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: kgdb_remove_hw_break(unsigned long addr, int len, enum kgdb_bptype bptype)
{
int i;
for (i = 0; i < HBP_NUM; i++)
if (breakinfo[i].addr == addr && breakinfo[i].enabled)
break;
if (i == HBP_NUM)
return -1;
if (hw_break_release_slot(i)) {
printk(KERN_ERR "Cannot remove hw breakpoint at %lx\n", addr);
return -1;
}
breakinfo[i].enabled = 0;
return 0;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void traverse_for_entities(
const char *old,
size_t oldlen,
char *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
size_t *retlen,
int all,
int flags,
const entity_ht *inv_map,
enum entity_charset charset)
{
const char *p,
*lim;
char *q;
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
lim = old + oldlen; /* terminator address */
assert(*lim == '\0');
for (p = old, q = ret; p < lim;) {
unsigned code, code2 = 0;
const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
/* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
* ASCII range byte can be part of a multi-byte sequence.
* However, they start at 0x40, therefore if we find a 0x26 byte,
* we're sure it represents the '&' character. */
/* assumes there are no single-char entities */
if (p[0] != '&' || (p + 3 >= lim)) {
*(q++) = *(p++);
continue;
}
/* now p[3] is surely valid and is no terminator */
/* numerical entity */
if (p[1] == '#') {
next = &p[2];
if (process_numeric_entity(&next, &code) == FAILURE)
goto invalid_code;
/* If we're in htmlspecialchars_decode, we're only decoding entities
* that represent &, <, >, " and '. Is this one of them? */
if (!all && (code > 63U ||
stage3_table_be_apos_00000[code].data.ent.entity == NULL))
goto invalid_code;
/* are we allowed to decode this entity in this document type?
* HTML 5 is the only that has a character that cannot be used in
* a numeric entity but is allowed literally (U+000D). The
* unoptimized version would be ... || !numeric_entity_is_allowed(code) */
if (!unicode_cp_is_allowed(code, doctype) ||
(doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
goto invalid_code;
} else {
const char *start;
size_t ent_len;
next = &p[1];
start = next;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto invalid_code;
if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
code = (unsigned) '\'';
} else {
goto invalid_code;
}
}
}
assert(*next == ';');
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
/* && code2 == '\0' always true for current maps */)
goto invalid_code;
/* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
* the call is needed to ensure the codepoint <= U+00FF) */
if (charset != cs_utf_8) {
/* replace unicode code point */
if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
goto invalid_code; /* not representable in target charset */
}
q += write_octet_sequence(q, charset, code);
if (code2) {
q += write_octet_sequence(q, charset, code2);
}
/* jump over the valid entity; may go beyond size of buffer; np */
p = next + 1;
continue;
invalid_code:
for (; p < next; p++) {
*(q++) = *p;
}
}
*q = '\0';
*retlen = (size_t)(q - ret);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: PassRefPtr<NodeList> Document::getItems(const String& typeNames)
{
String localTypeNames = typeNames.isNull() ? MicroDataItemList::undefinedItemType() : typeNames;
return ensureRareData()->ensureNodeLists()->addCacheWithName<MicroDataItemList>(this, MicroDataItemListType, localTypeNames);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void OPENSSL_fork_child(void)
{
rand_fork();
}
CWE ID: CWE-330
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking)
{
int k, at_head;
Sg_device *sdp = sfp->parentdp;
sg_io_hdr_t *hp = &srp->header;
srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */
hp->status = 0;
hp->masked_status = 0;
hp->msg_status = 0;
hp->info = 0;
hp->host_status = 0;
hp->driver_status = 0;
hp->resid = 0;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n",
(int) cmnd[0], (int) hp->cmd_len));
k = sg_start_req(srp, cmnd);
if (k) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
"sg_common_write: start_req err=%d\n", k));
sg_finish_rem_req(srp);
return k; /* probably out of space --> ENOMEM */
}
if (atomic_read(&sdp->detaching)) {
if (srp->bio)
blk_end_request_all(srp->rq, -EIO);
sg_finish_rem_req(srp);
return -ENODEV;
}
hp->duration = jiffies_to_msecs(jiffies);
if (hp->interface_id != '\0' && /* v3 (or later) interface */
(SG_FLAG_Q_AT_TAIL & hp->flags))
at_head = 0;
else
at_head = 1;
srp->rq->timeout = timeout;
kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */
blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
srp->rq, at_head, sg_rq_end_io);
return 0;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: static int read_file(const char *path, char *buf, size_t size,
struct file_info *d)
{
size_t linelen = 0, total_len = 0, rv = 0;
char *line = NULL;
char *cache = d->buf;
size_t cache_size = d->buflen;
FILE *f = fopen(path, "r");
if (!f)
return 0;
while (getline(&line, &linelen, f) != -1) {
size_t l = snprintf(cache, cache_size, "%s", line);
if (l < 0) {
perror("Error writing to cache");
rv = 0;
goto err;
}
if (l >= cache_size) {
fprintf(stderr, "Internal error: truncated write to cache\n");
rv = 0;
goto err;
}
if (l < cache_size) {
cache += l;
cache_size -= l;
total_len += l;
} else {
cache += cache_size;
total_len += cache_size;
cache_size = 0;
break;
}
}
d->size = total_len;
if (total_len > size ) total_len = size;
/* read from off 0 */
memcpy(buf, d->buf, total_len);
rv = total_len;
err:
fclose(f);
free(line);
return rv;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void get_cqs(enum ib_qp_type qp_type,
struct ib_cq *ib_send_cq, struct ib_cq *ib_recv_cq,
struct mlx5_ib_cq **send_cq, struct mlx5_ib_cq **recv_cq)
{
switch (qp_type) {
case IB_QPT_XRC_TGT:
*send_cq = NULL;
*recv_cq = NULL;
break;
case MLX5_IB_QPT_REG_UMR:
case IB_QPT_XRC_INI:
*send_cq = ib_send_cq ? to_mcq(ib_send_cq) : NULL;
*recv_cq = NULL;
break;
case IB_QPT_SMI:
case MLX5_IB_QPT_HW_GSI:
case IB_QPT_RC:
case IB_QPT_UC:
case IB_QPT_UD:
case IB_QPT_RAW_IPV6:
case IB_QPT_RAW_ETHERTYPE:
case IB_QPT_RAW_PACKET:
*send_cq = ib_send_cq ? to_mcq(ib_send_cq) : NULL;
*recv_cq = ib_recv_cq ? to_mcq(ib_recv_cq) : NULL;
break;
case IB_QPT_MAX:
default:
*send_cq = NULL;
*recv_cq = NULL;
break;
}
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: updateDevice(const struct header * headers, time_t t)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist; */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
/*printf("found! %d\n", (int)(t - p->t));*/
syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
p->t = t;
/* update Location ! */
if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l)
{
struct device * tmp;
tmp = realloc(p, sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l);
if(!tmp) /* allocation error */
{
syslog(LOG_ERR, "updateDevice() : memory allocation error");
free(p);
return 0;
}
p = tmp;
*pp = p;
}
memcpy(p->data + p->headers[0].l + p->headers[1].l,
headers[2].p, headers[2].l);
/* TODO : check p->headers[HEADER_LOCATION].l */
return 0;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_INFO, "new device discovered : %.*s",
headers[HEADER_USN].l, headers[HEADER_USN].p);
/* add */
{
char * pc;
int i;
p = malloc( sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l );
if(!p) {
syslog(LOG_ERR, "updateDevice(): cannot allocate memory");
return -1;
}
p->next = devlist;
p->t = t;
pc = p->data;
for(i = 0; i < 3; i++)
{
p->headers[i].p = pc;
p->headers[i].l = headers[i].l;
memcpy(pc, headers[i].p, headers[i].l);
pc += headers[i].l;
}
devlist = p;
sendNotifications(NOTIF_NEW, p, NULL);
}
return 1;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int rfcomm_sock_accept(struct socket *sock, struct socket *newsock, int flags)
{
DECLARE_WAITQUEUE(wait, current);
struct sock *sk = sock->sk, *nsk;
long timeo;
int err = 0;
lock_sock(sk);
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
BT_DBG("sk %p timeo %ld", sk, timeo);
/* Wait for an incoming connection. (wake-one). */
add_wait_queue_exclusive(sk_sleep(sk), &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (sk->sk_state != BT_LISTEN) {
err = -EBADFD;
break;
}
nsk = bt_accept_dequeue(sk, newsock);
if (nsk)
break;
if (!timeo) {
err = -EAGAIN;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
if (err)
goto done;
newsock->state = SS_CONNECTED;
BT_DBG("new socket %p", nsk);
done:
release_sock(sk);
return err;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static js_Ast *funexp(js_State *J)
{
js_Ast *a, *b, *c;
a = identifieropt(J);
jsP_expect(J, '(');
b = parameters(J);
jsP_expect(J, ')');
c = funbody(J);
return EXP3(FUN, a, b, c);
}
CWE ID: CWE-674
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: EncodedJSValue JSC_HOST_CALL jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestSerializedScriptValueInterface::s_info))
return throwVMTypeError(exec);
JSTestSerializedScriptValueInterface* castedThis = jsCast<JSTestSerializedScriptValueInterface*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestSerializedScriptValueInterface::s_info);
TestSerializedScriptValueInterface* impl = static_cast<TestSerializedScriptValueInterface*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
RefPtr<SerializedScriptValue> data(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
size_t argsCount = exec->argumentCount();
if (argsCount <= 1) {
impl->acceptTransferList(data);
return JSValue::encode(jsUndefined());
}
Array* transferList(toArray(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->acceptTransferList(data, transferList);
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: GDataEntry* FindEntryByResourceId(const std::string& resource_id) {
GDataEntry* entry = NULL;
file_system_->FindEntryByResourceIdSync(
resource_id, base::Bind(&ReadOnlyFindEntryCallback, &entry));
return entry;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int main(int argc, char **argv)
{
int i, n_valid, do_write, do_scrub;
char *c, *dname, *name;
DIR *dir;
FILE *fp;
pdf_t *pdf;
pdf_flag_t flags;
if (argc < 2)
usage();
/* Args */
do_write = do_scrub = flags = 0;
name = NULL;
for (i=1; i<argc; i++)
{
if (strncmp(argv[i], "-w", 2) == 0)
do_write = 1;
else if (strncmp(argv[i], "-i", 2) == 0)
flags |= PDF_FLAG_DISP_CREATOR;
else if (strncmp(argv[i], "-q", 2) == 0)
flags |= PDF_FLAG_QUIET;
else if (strncmp(argv[i], "-s", 2) == 0)
do_scrub = 1;
else if (argv[i][0] != '-')
name = argv[i];
else if (argv[i][0] == '-')
usage();
}
if (!name)
usage();
if (!(fp = fopen(name, "r")))
{
ERR("Could not open file '%s'\n", argv[1]);
return -1;
}
else if (!pdf_is_pdf(fp))
{
ERR("'%s' specified is not a valid PDF\n", name);
fclose(fp);
return -1;
}
/* Load PDF */
if (!(pdf = init_pdf(fp, name)))
{
fclose(fp);
return -1;
}
/* Count valid xrefs */
for (i=0, n_valid=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
++n_valid;
/* Bail if we only have 1 valid */
if (n_valid < 2)
{
if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR)))
printf("%s: There is only one version of this PDF\n", pdf->name);
if (do_write)
{
fclose(fp);
pdf_delete(pdf);
return 0;
}
}
dname = NULL;
if (do_write)
{
/* Create directory to place the various versions in */
if ((c = strrchr(name, '/')))
name = c + 1;
if ((c = strrchr(name, '.')))
*c = '\0';
dname = malloc(strlen(name) + 16);
sprintf(dname, "%s-versions", name);
if (!(dir = opendir(dname)))
mkdir(dname, S_IRWXU);
else
{
ERR("This directory already exists, PDF version extraction will "
"not occur.\n");
fclose(fp);
closedir(dir);
free(dname);
pdf_delete(pdf);
return -1;
}
/* Write the pdf as a pervious version */
for (i=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
write_version(fp, name, dname, &pdf->xrefs[i]);
}
/* Generate a per-object summary */
pdf_summarize(fp, pdf, dname, flags);
/* Have we been summoned to scrub history from this PDF */
if (do_scrub)
scrub_document(fp, pdf);
/* Display extra information */
if (flags & PDF_FLAG_DISP_CREATOR)
display_creator(fp, pdf);
fclose(fp);
free(dname);
pdf_delete(pdf);
return 0;
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int _nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred, struct nfs4_state **res)
{
struct nfs4_state_owner *sp;
struct nfs4_state *state = NULL;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *opendata;
int status;
/* Protect against reboot recovery conflicts */
status = -ENOMEM;
if (!(sp = nfs4_get_state_owner(server, cred))) {
dprintk("nfs4_do_open: nfs4_get_state_owner failed!\n");
goto out_err;
}
status = nfs4_recover_expired_lease(server);
if (status != 0)
goto err_put_state_owner;
if (path->dentry->d_inode != NULL)
nfs4_return_incompatible_delegation(path->dentry->d_inode, flags & (FMODE_READ|FMODE_WRITE));
status = -ENOMEM;
opendata = nfs4_opendata_alloc(path, sp, flags, sattr);
if (opendata == NULL)
goto err_put_state_owner;
if (path->dentry->d_inode != NULL)
opendata->state = nfs4_get_open_state(path->dentry->d_inode, sp);
status = _nfs4_proc_open(opendata);
if (status != 0)
goto err_opendata_put;
if (opendata->o_arg.open_flags & O_EXCL)
nfs4_exclusive_attrset(opendata, sattr);
state = nfs4_opendata_to_nfs4_state(opendata);
status = PTR_ERR(state);
if (IS_ERR(state))
goto err_opendata_put;
nfs4_opendata_put(opendata);
nfs4_put_state_owner(sp);
*res = state;
return 0;
err_opendata_put:
nfs4_opendata_put(opendata);
err_put_state_owner:
nfs4_put_state_owner(sp);
out_err:
*res = NULL;
return status;
}
CWE ID:
Target: 1
Example 2:
Code: static void vapic_realize(DeviceState *dev, Error **errp)
{
SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
VAPICROMState *s = VAPIC(dev);
memory_region_init_io(&s->io, OBJECT(s), &vapic_ops, s, "kvmvapic", 2);
sysbus_add_io(sbd, VAPIC_IO_PORT, &s->io);
sysbus_init_ioports(sbd, VAPIC_IO_PORT, 2);
option_rom[nb_option_roms].name = "kvmvapic.bin";
option_rom[nb_option_roms].bootindex = -1;
nb_option_roms++;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ContentSuggestionsNotifierService::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterIntegerPref(
prefs::kContentSuggestionsConsecutiveIgnoredPrefName, 0);
registry->RegisterStringPref(kNotificationIDWithinCategory, std::string());
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: usage(const char *prog)
{
/* ANSI C-90 limits strings to 509 characters, so use a string array: */
size_t i;
static const char *usage_string[] = {
" Tests, optimizes and optionally fixes the zlib header in PNG files.",
" Optionally, when fixing, strips ancilliary chunks from the file.",
0,
"OPTIONS",
" OPERATION",
" By default files are just checked for readability with a summary of the",
" of zlib issues founds for each compressed chunk and the IDAT stream in",
" the file.",
" --optimize (-o):",
" Find the smallest deflate window size for the compressed data.",
" --strip=[none|crc|unsafe|unused|transform|color|all]:",
" none (default): Retain all chunks.",
" crc: Remove chunks with a bad CRC.",
" unsafe: Remove chunks that may be unsafe to retain if the image data",
" is modified. This is set automatically if --max is given but",
" may be cancelled by a later --strip=none.",
" unused: Remove chunks not used by libpng when decoding an image.",
" This retains any chunks that might be used by libpng image",
" transformations.",
" transform: unused+bKGD.",
" color: transform+iCCP and cHRM.",
" all: color+gAMA and sRGB.",
" Only ancillary chunks are ever removed. In addition the tRNS and sBIT",
" chunks are never removed as they affect exact interpretation of the",
" image pixel values. The following known chunks are treated specially",
" by the above options:",
" gAMA, sRGB [all]: These specify the gamma encoding used for the pixel",
" values.",
" cHRM, iCCP [color]: These specify how colors are encoded. iCCP also",
" specifies the exact encoding of a pixel value however in practice",
" most programs will ignore it.",
" bKGD [transform]: This is used by libpng transforms."
" --max=<number>:",
" Use IDAT chunks sized <number>. If no number is given the the IDAT",
" chunks will be the maximum size permitted; 2^31-1 bytes. If the option",
" is omitted the original chunk sizes will not be changed. When the",
" option is given --strip=unsafe is set automatically, this may be",
" cancelled if you know that all unknown unsafe-to-copy chunks really are",
" safe to copy across an IDAT size change. This is true of all chunks",
" that have ever been formally proposed as PNG extensions.",
" MESSAGES",
" By default the program only outputs summaries for each file.",
" --quiet (-q):",
" Do not output the summaries except for files which cannot be read. With",
" two --quiets these are not output either.",
" --errors (-e):",
" Output errors from libpng and the program (except too-far-back).",
" --warnings (-w):",
" Output warnings from libpng.",
" OUTPUT",
" By default nothing is written.",
" --out=<file>:",
" Write the optimized/corrected version of the next PNG to <file>. This",
" overrides the following two options",
" --suffix=<suffix>:",
" Set --out=<name><suffix> for all following files unless overridden on",
" a per-file basis by explicit --out.",
" --prefix=<prefix>:",
" Set --out=<prefix><name> for all the following files unless overridden",
" on a per-file basis by explicit --out.",
" These two options can be used together to produce a suffix and prefix.",
" INTERNAL OPTIONS",
#if 0 /*NYI*/
#ifdef PNG_MAXIMUM_INFLATE_WINDOW
" --test:",
" Test the PNG_MAXIMUM_INFLATE_WINDOW option. Setting this disables",
" output as this would produce a broken file.",
#endif
#endif
0,
"EXIT CODES",
" *** SUBJECT TO CHANGE ***",
" The program exit code is value in the range 0..127 holding a bit mask of",
" the following codes. Notice that the results for each file are combined",
" together - check one file at a time to get a meaningful error code!",
" 0x01: The zlib too-far-back error existed in at least one chunk.",
" 0x02: At least once chunk had a CRC error.",
" 0x04: A chunk length was incorrect.",
" 0x08: The file was truncated.",
" Errors less than 16 are potentially recoverable, for a single file if the",
" exit code is less than 16 the file could be read (with corrections if a",
" non-zero code is returned).",
" 0x10: The file could not be read, even with corrections.",
" 0x20: The output file could not be written.",
" 0x40: An unexpected, potentially internal, error occured.",
" If the command line arguments are incorrect the program exits with exit",
" 255. Some older operating systems only support 7-bit exit codes, on those",
" systems it is suggested that this program is first tested by supplying",
" invalid arguments.",
0,
"DESCRIPTION",
" " PROGRAM_NAME ":",
" checks each PNG file on the command line for errors. By default errors are",
" not output and the program just returns an exit code and prints a summary.",
" With the --quiet (-q) option the summaries are suppressed too and the",
" program only outputs unexpected errors (internal errors and file open",
" errors).",
" Various known problems in PNG files are fixed while the file is being read",
" The exit code says what problems were fixed. In particular the zlib error:",
0,
" \"invalid distance too far back\"",
0,
" caused by an incorrect optimization of a zlib stream is fixed in any",
" compressed chunk in which it is encountered. An integrity problem of the",
" PNG stream caused by a bug in libpng which wrote an incorrect chunk length",
" is also fixed. Chunk CRC errors are automatically fixed up.",
0,
" Setting one of the \"OUTPUT\" options causes the possibly modified file to",
" be written to a new file.",
0,
" Notice that some PNG files with the zlib optimization problem can still be",
" read by libpng under some circumstances. This program will still detect",
" and, if requested, correct the error.",
0,
" The program will reliably process all files on the command line unless",
" either an invalid argument causes the usage message (this message) to be",
" produced or the program crashes.",
0,
" The summary lines describe issues encountered with the zlib compressed",
" stream of a chunk. They have the following format, which is SUBJECT TO",
" CHANGE in the future:",
0,
" chunk reason comp-level p1 p2 p3 p4 file",
0,
" p1 through p4 vary according to the 'reason'. There are always 8 space",
" separated fields. Reasons specific formats are:",
0,
" chunk ERR status code read-errno write-errno message file",
" chunk SKP comp-level file-bits zlib-rc compressed message file",
" chunk ??? comp-level file-bits ok-bits compressed uncompress file",
0,
" The various fields are",
0,
"$1 chunk: The chunk type of a chunk in the file or 'HEAD' if a problem",
" is reported by libpng at the start of the IDAT stream.",
"$2 reason: One of:",
" CHK: A zlib header checksum was detected and fixed.",
" TFB: The zlib too far back error was detected and fixed.",
" OK : No errors were detected in the zlib stream and optimization",
" was not requested, or was not possible.",
" OPT: The zlib stream window bits value could be improved (and was).",
" SKP: The chunk was skipped because of a zlib issue (zlib-rc) with",
" explanation 'message'",
" ERR: The read of the file was aborted. The parameters explain why.",
"$3 status: For 'ERR' the accumulate status code from 'EXIT CODES' above.",
" This is printed as a 2 digit hexadecimal value",
" comp-level: The recorded compression level (FLEVEL) of a zlib stream",
" expressed as a string {supfast,stdfast,default,maximum}",
"$4 code: The file exit code; where stop was called, as a fairly terse",
" string {warning,libpng,zlib,invalid,read,write,unexpected}.",
" file-bits: The zlib window bits recorded in the file.",
"$5 read-errno: A system errno value from a read translated by strerror(3).",
" zlib-rc: A zlib return code as a string (see zlib.h).",
" ok-bits: The smallest zlib window bits value that works.",
"$6 write-errno:A system errno value from a write translated by strerror(3).",
" compressed: The count of compressed bytes in the zlib stream, when the",
" reason is 'SKP'; this is a count of the bytes read from the",
" stream when the fatal error was encountered.",
"$7 message: An error message (spaces replaced by _, as in all parameters),",
" uncompress: The count of bytes from uncompressing the zlib stream; this",
" may not be the same as the number of bytes in the image.",
"$8 file: The name of the file (this may contain spaces).",
};
fprintf(stderr, "Usage: %s {[options] png-file}\n", prog);
for (i=0; i < (sizeof usage_string)/(sizeof usage_string[0]); ++i)
{
if (usage_string[i] != 0)
fputs(usage_string[i], stderr);
fputc('\n', stderr);
}
exit(255);
}
CWE ID:
Target: 1
Example 2:
Code: static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
{
int tileno, compno;
for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
if (s->tile[tileno].comp) {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = s->tile[tileno].comp + compno;
Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
ff_jpeg2000_cleanup(comp, codsty);
}
av_freep(&s->tile[tileno].comp);
}
}
av_freep(&s->tile);
s->numXtiles = s->numYtiles = 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: INST_HANDLER (sbrx) { // SBRC Rr, b
int b = buf[0] & 0x7;
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4);
RAnalOp next_op;
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBRC => branch if cleared
: "!,!,"); // SBRS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void RequestDeviceAuthorizationWithBadOrigin(const std::string& device_id) {
int session_id = 0;
host_->OnRequestDeviceAuthorization(kStreamId, kRenderFrameId, session_id,
device_id,
url::Origin(GURL(kBadSecurityOrigin)));
SyncWithAudioThread();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void InspectorHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ResourcePrefetchPredictor::PredictPreconnectOrigins(
const GURL& url,
PreconnectPrediction* prediction) const {
DCHECK(!prediction || prediction->requests.empty());
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (initialization_state_ != INITIALIZED)
return false;
url::Origin url_origin = url::Origin::Create(url);
url::Origin redirect_origin;
bool has_any_prediction = GetRedirectEndpointsForPreconnect(
url_origin, *host_redirect_data_, prediction);
if (!GetRedirectOrigin(url_origin, *host_redirect_data_, &redirect_origin)) {
return has_any_prediction;
}
OriginData data;
if (!origin_data_->TryGetData(redirect_origin.host(), &data)) {
return has_any_prediction;
}
if (prediction) {
prediction->host = redirect_origin.host();
prediction->is_redirected = (redirect_origin != url_origin);
}
net::NetworkIsolationKey network_isolation_key(redirect_origin,
redirect_origin);
for (const OriginStat& origin : data.origins()) {
float confidence = static_cast<float>(origin.number_of_hits()) /
(origin.number_of_hits() + origin.number_of_misses());
if (confidence < kMinOriginConfidenceToTriggerPreresolve)
continue;
has_any_prediction = true;
if (prediction) {
if (confidence > kMinOriginConfidenceToTriggerPreconnect) {
prediction->requests.emplace_back(GURL(origin.origin()), 1,
network_isolation_key);
} else {
prediction->requests.emplace_back(GURL(origin.origin()), 0,
network_isolation_key);
}
}
}
return has_any_prediction;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void QuotaThreadTask::RunOnTargetThread() {
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void smp_send_app_cback(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
tSMP_EVT_DATA cb_data;
tSMP_STATUS callback_rc;
SMP_TRACE_DEBUG("%s p_cb->cb_evt=%d", __func__, p_cb->cb_evt);
if (p_cb->p_callback && p_cb->cb_evt != 0) {
switch (p_cb->cb_evt) {
case SMP_IO_CAP_REQ_EVT:
cb_data.io_req.auth_req = p_cb->peer_auth_req;
cb_data.io_req.oob_data = SMP_OOB_NONE;
cb_data.io_req.io_cap = SMP_DEFAULT_IO_CAPS;
cb_data.io_req.max_key_size = SMP_MAX_ENC_KEY_SIZE;
cb_data.io_req.init_keys = p_cb->local_i_key;
cb_data.io_req.resp_keys = p_cb->local_r_key;
SMP_TRACE_WARNING("io_cap = %d", cb_data.io_req.io_cap);
break;
case SMP_NC_REQ_EVT:
cb_data.passkey = p_data->passkey;
break;
case SMP_SC_OOB_REQ_EVT:
cb_data.req_oob_type = p_data->req_oob_type;
break;
case SMP_SC_LOC_OOB_DATA_UP_EVT:
cb_data.loc_oob_data = p_cb->sc_oob_data.loc_oob_data;
break;
case SMP_BR_KEYS_REQ_EVT:
cb_data.io_req.auth_req = 0;
cb_data.io_req.oob_data = SMP_OOB_NONE;
cb_data.io_req.io_cap = 0;
cb_data.io_req.max_key_size = SMP_MAX_ENC_KEY_SIZE;
cb_data.io_req.init_keys = SMP_BR_SEC_DEFAULT_KEY;
cb_data.io_req.resp_keys = SMP_BR_SEC_DEFAULT_KEY;
break;
default:
break;
}
callback_rc =
(*p_cb->p_callback)(p_cb->cb_evt, p_cb->pairing_bda, &cb_data);
SMP_TRACE_DEBUG("%s: callback_rc=%d p_cb->cb_evt=%d", __func__,
callback_rc, p_cb->cb_evt);
if (callback_rc == SMP_SUCCESS) {
switch (p_cb->cb_evt) {
case SMP_IO_CAP_REQ_EVT:
p_cb->loc_auth_req = cb_data.io_req.auth_req;
p_cb->local_io_capability = cb_data.io_req.io_cap;
p_cb->loc_oob_flag = cb_data.io_req.oob_data;
p_cb->loc_enc_size = cb_data.io_req.max_key_size;
p_cb->local_i_key = cb_data.io_req.init_keys;
p_cb->local_r_key = cb_data.io_req.resp_keys;
if (!(p_cb->loc_auth_req & SMP_AUTH_BOND)) {
SMP_TRACE_WARNING("Non bonding: No keys will be exchanged");
p_cb->local_i_key = 0;
p_cb->local_r_key = 0;
}
SMP_TRACE_WARNING(
"rcvd auth_req: 0x%02x, io_cap: %d "
"loc_oob_flag: %d loc_enc_size: %d, "
"local_i_key: 0x%02x, local_r_key: 0x%02x",
p_cb->loc_auth_req, p_cb->local_io_capability, p_cb->loc_oob_flag,
p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key);
p_cb->secure_connections_only_mode_required =
(btm_cb.security_mode == BTM_SEC_MODE_SC) ? true : false;
/* just for PTS, force SC bit */
if (p_cb->secure_connections_only_mode_required) {
p_cb->loc_auth_req |= SMP_SC_SUPPORT_BIT;
}
if (!p_cb->secure_connections_only_mode_required &&
(!(p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT) ||
lmp_version_below(p_cb->pairing_bda, HCI_PROTO_VERSION_4_2) ||
interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS,
(const RawAddress*)&p_cb->pairing_bda))) {
p_cb->loc_auth_req &= ~SMP_SC_SUPPORT_BIT;
p_cb->loc_auth_req &= ~SMP_KP_SUPPORT_BIT;
p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK;
p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK;
}
if (lmp_version_below(p_cb->pairing_bda, HCI_PROTO_VERSION_5_0)) {
p_cb->loc_auth_req &= ~SMP_H7_SUPPORT_BIT;
}
SMP_TRACE_WARNING(
"set auth_req: 0x%02x, local_i_key: 0x%02x, local_r_key: 0x%02x",
p_cb->loc_auth_req, p_cb->local_i_key, p_cb->local_r_key);
smp_sm_event(p_cb, SMP_IO_RSP_EVT, NULL);
break;
case SMP_BR_KEYS_REQ_EVT:
p_cb->loc_enc_size = cb_data.io_req.max_key_size;
p_cb->local_i_key = cb_data.io_req.init_keys;
p_cb->local_r_key = cb_data.io_req.resp_keys;
p_cb->loc_auth_req |= SMP_H7_SUPPORT_BIT;
p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK;
p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK;
SMP_TRACE_WARNING(
"for SMP over BR max_key_size: 0x%02x, local_i_key: 0x%02x, "
"local_r_key: 0x%02x, p_cb->loc_auth_req: 0x%02x",
p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key,
p_cb->loc_auth_req);
smp_br_state_machine_event(p_cb, SMP_BR_KEYS_RSP_EVT, NULL);
break;
}
}
}
if (!p_cb->cb_evt && p_cb->discard_sec_req) {
p_cb->discard_sec_req = false;
smp_sm_event(p_cb, SMP_DISCARD_SEC_REQ_EVT, NULL);
}
SMP_TRACE_DEBUG("%s: return", __func__);
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void jas_matrix_asr(jas_matrix_t *matrix, int n)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
assert(n >= 0);
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = jas_seqent_asr(*data, n);
}
}
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int _nfs4_proc_rename(struct inode *old_dir, struct qstr *old_name,
struct inode *new_dir, struct qstr *new_name)
{
struct nfs_server *server = NFS_SERVER(old_dir);
struct nfs4_rename_arg arg = {
.old_dir = NFS_FH(old_dir),
.new_dir = NFS_FH(new_dir),
.old_name = old_name,
.new_name = new_name,
.bitmask = server->attr_bitmask,
};
struct nfs_fattr old_fattr, new_fattr;
struct nfs4_rename_res res = {
.server = server,
.old_fattr = &old_fattr,
.new_fattr = &new_fattr,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_RENAME],
.rpc_argp = &arg,
.rpc_resp = &res,
};
int status;
nfs_fattr_init(res.old_fattr);
nfs_fattr_init(res.new_fattr);
status = rpc_call_sync(server->client, &msg, 0);
if (!status) {
update_changeattr(old_dir, &res.old_cinfo);
nfs_post_op_update_inode(old_dir, res.old_fattr);
update_changeattr(new_dir, &res.new_cinfo);
nfs_post_op_update_inode(new_dir, res.new_fattr);
}
return status;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
/* now throw away the key memory */
if (key->type->destroy)
key->type->destroy(key);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct mem_size_stats *mss = walk->private;
struct vm_area_struct *vma = mss->vma;
pte_t *pte;
spinlock_t *ptl;
spin_lock(&walk->mm->page_table_lock);
if (pmd_trans_huge(*pmd)) {
if (pmd_trans_splitting(*pmd)) {
spin_unlock(&walk->mm->page_table_lock);
wait_split_huge_page(vma->anon_vma, pmd);
} else {
smaps_pte_entry(*(pte_t *)pmd, addr,
HPAGE_PMD_SIZE, walk);
spin_unlock(&walk->mm->page_table_lock);
mss->anonymous_thp += HPAGE_PMD_SIZE;
return 0;
}
} else {
spin_unlock(&walk->mm->page_table_lock);
}
/*
* The mmap_sem held all the way back in m_start() is what
* keeps khugepaged out of here and from collapsing things
* in here.
*/
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE)
smaps_pte_entry(*pte, addr, PAGE_SIZE, walk);
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool LearnMoreInfoBar::LinkClicked(WindowOpenDisposition disposition) {
OpenURLParams params(
learn_more_url_, Referrer(), disposition, content::PAGE_TRANSITION_LINK,
false);
owner()->web_contents()->OpenURL(params);
return false;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: M_bool M_fs_path_ishidden(const char *path, M_fs_info_t *info)
{
M_list_str_t *path_parts;
size_t len;
M_bool ret = M_FALSE;
(void)info;
if (path == NULL || *path == '\0') {
return M_FALSE;
}
/* Hidden. Check if the first character of the last part of the path. Either the file or directory name itself
* starts with a '.'. */
path_parts = M_fs_path_componentize_path(path, M_FS_SYSTEM_UNIX);
len = M_list_str_len(path_parts);
if (len > 0) {
if (*M_list_str_at(path_parts, len-1) == '.') {
ret = M_TRUE;
}
}
M_list_str_destroy(path_parts);
return ret;
}
CWE ID: CWE-732
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_,
unsigned char*& buf, size_t& buflen) {
assert(pReader);
assert(pos >= 0);
long long total, available;
long status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
if (status < 0)
return false;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
if ((unsigned long)id != id_)
return false;
pos += len; // consume id
const long long size_ = ReadUInt(pReader, pos, len);
assert(size_ >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
pos += len; // consume length of size of payload
assert((pos + size_) <= available);
const long buflen_ = static_cast<long>(size_);
buf = new (std::nothrow) unsigned char[buflen_];
assert(buf); // TODO
status = pReader->Read(pos, buflen_, buf);
assert(status == 0); // TODO
buflen = buflen_;
pos += size_; // consume size of payload
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: LayoutObject* LayoutBlockFlow::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
{
LayoutMultiColumnFlowThread* flowThread = multiColumnFlowThread();
if (!flowThread)
return nullptr;
setLogicalTopForChild(*flowThread, borderBefore() + paddingBefore());
flowThread->layoutColumns(relayoutChildren, layoutScope);
determineLogicalLeftPositionForChild(*flowThread);
return flowThread;
}
CWE ID: CWE-22
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LinkChangeSerializerMarkupAccumulator::appendElement(StringBuilder& result, Element& element, Namespaces* namespaces)
{
if (element.hasTagName(HTMLNames::htmlTag)) {
result.append('\n');
MarkupFormatter::appendComment(result, String::format(" saved from url=(%04d)%s ",
static_cast<int>(document().url().string().utf8().length()),
document().url().string().utf8().data()));
result.append('\n');
}
if (element.hasTagName(HTMLNames::baseTag)) {
result.appendLiteral("<base href=\".\"");
if (!document().baseTarget().isEmpty()) {
result.appendLiteral(" target=\"");
MarkupFormatter::appendAttributeValue(result, document().baseTarget(), document().isHTMLDocument());
result.append('"');
}
if (document().isXHTMLDocument())
result.appendLiteral(" />");
else
result.appendLiteral(">");
} else {
SerializerMarkupAccumulator::appendElement(result, element, namespaces);
}
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void RenderFrameImpl::SetHasReceivedUserGesture() {
Send(new FrameHostMsg_SetHasReceivedUserGesture(routing_id_));
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void ath_tx_send_normal(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid, struct sk_buff *skb)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ath_frame_info *fi = get_frame_info(skb);
struct list_head bf_head;
struct ath_buf *bf = fi->bf;
INIT_LIST_HEAD(&bf_head);
list_add_tail(&bf->list, &bf_head);
bf->bf_state.bf_type = 0;
if (tid && (tx_info->flags & IEEE80211_TX_CTL_AMPDU)) {
bf->bf_state.bf_type = BUF_AMPDU;
ath_tx_addto_baw(sc, tid, bf);
}
bf->bf_next = NULL;
bf->bf_lastbf = bf;
ath_tx_fill_desc(sc, bf, txq, fi->framelen);
ath_tx_txqaddbuf(sc, txq, &bf_head, false);
TX_STAT_INC(txq->axq_qnum, queued);
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
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()
CWE ID: CWE-190
Target: 1
Example 2:
Code: void ChromeDownloadManagerDelegate::SubstituteGDataDownloadPathCallback(
int32 download_id,
bool should_prompt,
bool is_forced_path,
content::DownloadDangerType danger_type,
const FilePath& suggested_path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DownloadItem* download =
download_manager_->GetActiveDownloadItem(download_id);
if (!download)
return;
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&ChromeDownloadManagerDelegate::CheckIfSuggestedPathExists,
this, download->GetId(), suggested_path, should_prompt,
is_forced_path, danger_type,
download_prefs_->download_path()));
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Node* HTMLSelectElement::namedItem(const AtomicString& name)
{
return options()->namedItem(name);
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret;
unsigned long __user *datap = (unsigned long __user *) data;
switch (request) {
case PTRACE_PEEKUSR:
ret = ptrace_read_user(child, addr, datap);
break;
case PTRACE_POKEUSR:
ret = ptrace_write_user(child, addr, data);
break;
case PTRACE_GETREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_SETREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_GETFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
case PTRACE_SETFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
#ifdef CONFIG_IWMMXT
case PTRACE_GETWMMXREGS:
ret = ptrace_getwmmxregs(child, datap);
break;
case PTRACE_SETWMMXREGS:
ret = ptrace_setwmmxregs(child, datap);
break;
#endif
case PTRACE_GET_THREAD_AREA:
ret = put_user(task_thread_info(child)->tp_value,
datap);
break;
case PTRACE_SET_SYSCALL:
task_thread_info(child)->syscall = data;
ret = 0;
break;
#ifdef CONFIG_CRUNCH
case PTRACE_GETCRUNCHREGS:
ret = ptrace_getcrunchregs(child, datap);
break;
case PTRACE_SETCRUNCHREGS:
ret = ptrace_setcrunchregs(child, datap);
break;
#endif
#ifdef CONFIG_VFP
case PTRACE_GETVFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
case PTRACE_SETVFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
#endif
#ifdef CONFIG_HAVE_HW_BREAKPOINT
case PTRACE_GETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_gethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
case PTRACE_SETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_sethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
#endif
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int udf_parse_options(char *options, struct udf_options *uopt,
bool remount)
{
char *p;
int option;
uopt->novrs = 0;
uopt->partition = 0xFFFF;
uopt->session = 0xFFFFFFFF;
uopt->lastblock = 0;
uopt->anchor = 0;
uopt->volume = 0xFFFFFFFF;
uopt->rootdir = 0xFFFFFFFF;
uopt->fileset = 0xFFFFFFFF;
uopt->nls_map = NULL;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
substring_t args[MAX_OPT_ARGS];
int token;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_novrs:
uopt->novrs = 1;
break;
case Opt_bs:
if (match_int(&args[0], &option))
return 0;
uopt->blocksize = option;
uopt->flags |= (1 << UDF_FLAG_BLOCKSIZE_SET);
break;
case Opt_unhide:
uopt->flags |= (1 << UDF_FLAG_UNHIDE);
break;
case Opt_undelete:
uopt->flags |= (1 << UDF_FLAG_UNDELETE);
break;
case Opt_noadinicb:
uopt->flags &= ~(1 << UDF_FLAG_USE_AD_IN_ICB);
break;
case Opt_adinicb:
uopt->flags |= (1 << UDF_FLAG_USE_AD_IN_ICB);
break;
case Opt_shortad:
uopt->flags |= (1 << UDF_FLAG_USE_SHORT_AD);
break;
case Opt_longad:
uopt->flags &= ~(1 << UDF_FLAG_USE_SHORT_AD);
break;
case Opt_gid:
if (match_int(args, &option))
return 0;
uopt->gid = option;
uopt->flags |= (1 << UDF_FLAG_GID_SET);
break;
case Opt_uid:
if (match_int(args, &option))
return 0;
uopt->uid = option;
uopt->flags |= (1 << UDF_FLAG_UID_SET);
break;
case Opt_umask:
if (match_octal(args, &option))
return 0;
uopt->umask = option;
break;
case Opt_nostrict:
uopt->flags &= ~(1 << UDF_FLAG_STRICT);
break;
case Opt_session:
if (match_int(args, &option))
return 0;
uopt->session = option;
if (!remount)
uopt->flags |= (1 << UDF_FLAG_SESSION_SET);
break;
case Opt_lastblock:
if (match_int(args, &option))
return 0;
uopt->lastblock = option;
if (!remount)
uopt->flags |= (1 << UDF_FLAG_LASTBLOCK_SET);
break;
case Opt_anchor:
if (match_int(args, &option))
return 0;
uopt->anchor = option;
break;
case Opt_volume:
if (match_int(args, &option))
return 0;
uopt->volume = option;
break;
case Opt_partition:
if (match_int(args, &option))
return 0;
uopt->partition = option;
break;
case Opt_fileset:
if (match_int(args, &option))
return 0;
uopt->fileset = option;
break;
case Opt_rootdir:
if (match_int(args, &option))
return 0;
uopt->rootdir = option;
break;
case Opt_utf8:
uopt->flags |= (1 << UDF_FLAG_UTF8);
break;
#ifdef CONFIG_UDF_NLS
case Opt_iocharset:
uopt->nls_map = load_nls(args[0].from);
uopt->flags |= (1 << UDF_FLAG_NLS_MAP);
break;
#endif
case Opt_uignore:
uopt->flags |= (1 << UDF_FLAG_UID_IGNORE);
break;
case Opt_uforget:
uopt->flags |= (1 << UDF_FLAG_UID_FORGET);
break;
case Opt_gignore:
uopt->flags |= (1 << UDF_FLAG_GID_IGNORE);
break;
case Opt_gforget:
uopt->flags |= (1 << UDF_FLAG_GID_FORGET);
break;
case Opt_fmode:
if (match_octal(args, &option))
return 0;
uopt->fmode = option & 0777;
break;
case Opt_dmode:
if (match_octal(args, &option))
return 0;
uopt->dmode = option & 0777;
break;
default:
pr_err("bad mount option \"%s\" or missing value\n", p);
return 0;
}
}
return 1;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cmsBool Type_MLU_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsMLU* mlu =(cmsMLU*) Ptr;
cmsUInt32Number HeaderSize;
cmsUInt32Number Len, Offset;
cmsUInt32Number i;
if (Ptr == NULL) {
if (!_cmsWriteUInt32Number(io, 0)) return FALSE;
if (!_cmsWriteUInt32Number(io, 12)) return FALSE;
return TRUE;
}
if (!_cmsWriteUInt32Number(io, mlu ->UsedEntries)) return FALSE;
if (!_cmsWriteUInt32Number(io, 12)) return FALSE;
HeaderSize = 12 * mlu ->UsedEntries + sizeof(_cmsTagBase);
for (i=0; i < mlu ->UsedEntries; i++) {
Len = mlu ->Entries[i].Len;
Offset = mlu ->Entries[i].StrW;
Len = (Len * sizeof(cmsUInt16Number)) / sizeof(wchar_t);
Offset = (Offset * sizeof(cmsUInt16Number)) / sizeof(wchar_t) + HeaderSize + 8;
if (!_cmsWriteUInt16Number(io, mlu ->Entries[i].Language)) return FALSE;
if (!_cmsWriteUInt16Number(io, mlu ->Entries[i].Country)) return FALSE;
if (!_cmsWriteUInt32Number(io, Len)) return FALSE;
if (!_cmsWriteUInt32Number(io, Offset)) return FALSE;
}
if (!_cmsWriteWCharArray(io, mlu ->PoolUsed / sizeof(wchar_t), (wchar_t*) mlu ->MemPool)) return FALSE;
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply)
{
uint8_t buf[NBD_REPLY_SIZE];
uint32_t magic;
ssize_t ret;
ret = read_sync(ioc, buf, sizeof(buf));
if (ret < 0) {
return ret;
}
if (ret != sizeof(buf)) {
LOG("read failed");
return -EINVAL;
}
/* Reply
[ 0 .. 3] magic (NBD_REPLY_MAGIC)
[ 4 .. 7] error (0 == no error)
[ 7 .. 15] handle
*/
magic = ldl_be_p(buf);
reply->error = ldl_be_p(buf + 4);
reply->handle = ldq_be_p(buf + 8);
reply->error = nbd_errno_to_system_errno(reply->error);
if (reply->error == ESHUTDOWN) {
/* This works even on mingw which lacks a native ESHUTDOWN */
LOG("server shutting down");
return -EINVAL;
}
TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32
", handle = %" PRIu64" }",
magic, reply->error, reply->handle);
if (magic != NBD_REPLY_MAGIC) {
LOG("invalid magic (got 0x%" PRIx32 ")", magic);
return -EINVAL;
}
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int udf_create(struct inode *dir, struct dentry *dentry, umode_t mode,
struct nameidata *nd)
{
struct udf_fileident_bh fibh;
struct inode *inode;
struct fileIdentDesc cfi, *fi;
int err;
struct udf_inode_info *iinfo;
inode = udf_new_inode(dir, mode, &err);
if (!inode) {
return err;
}
iinfo = UDF_I(inode);
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)
inode->i_data.a_ops = &udf_adinicb_aops;
else
inode->i_data.a_ops = &udf_aops;
inode->i_op = &udf_file_inode_operations;
inode->i_fop = &udf_file_operations;
mark_inode_dirty(inode);
fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err);
if (!fi) {
inode_dec_link_count(inode);
iput(inode);
return err;
}
cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize);
cfi.icb.extLocation = cpu_to_lelb(iinfo->i_location);
*(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse =
cpu_to_le32(iinfo->i_unique & 0x00000000FFFFFFFFUL);
udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL);
if (UDF_I(dir)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)
mark_inode_dirty(dir);
if (fibh.sbh != fibh.ebh)
brelse(fibh.ebh);
brelse(fibh.sbh);
d_instantiate(dentry, inode);
return 0;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterStringPref(prefs::kAuthSchemes,
"basic,digest,ntlm,negotiate,"
"spdyproxy");
registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
std::string());
registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
registry->RegisterStringPref(prefs::kSpdyProxyAuthOrigin, std::string());
registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
registry->RegisterInt64Pref(prefs::kHttpReceivedContentLength, 0);
registry->RegisterInt64Pref(prefs::kHttpOriginalContentLength, 0);
#if defined(OS_ANDROID) || defined(OS_IOS)
registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength);
registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength);
registry->RegisterListPref(
prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled);
registry->RegisterListPref(
prefs::kDailyContentLengthWithDataReductionProxyEnabled);
registry->RegisterListPref(
prefs::kDailyOriginalContentLengthViaDataReductionProxy);
registry->RegisterListPref(
prefs::kDailyContentLengthViaDataReductionProxy);
registry->RegisterInt64Pref(prefs::kDailyHttpContentLengthLastUpdateDate, 0L);
#endif
registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
}
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t FLACParser::init()
{
mDecoder = FLAC__stream_decoder_new();
if (mDecoder == NULL) {
ALOGE("new failed");
return NO_INIT;
}
FLAC__stream_decoder_set_md5_checking(mDecoder, false);
FLAC__stream_decoder_set_metadata_ignore_all(mDecoder);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_STREAMINFO);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_PICTURE);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
FLAC__StreamDecoderInitStatus initStatus;
initStatus = FLAC__stream_decoder_init_stream(
mDecoder,
read_callback, seek_callback, tell_callback,
length_callback, eof_callback, write_callback,
metadata_callback, error_callback, (void *) this);
if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
ALOGE("init_stream failed %d", initStatus);
return NO_INIT;
}
if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) {
ALOGE("end_of_metadata failed");
return NO_INIT;
}
if (mStreamInfoValid) {
if (getChannels() == 0 || getChannels() > 8) {
ALOGE("unsupported channel count %u", getChannels());
return NO_INIT;
}
switch (getBitsPerSample()) {
case 8:
case 16:
case 24:
break;
default:
ALOGE("unsupported bits per sample %u", getBitsPerSample());
return NO_INIT;
}
switch (getSampleRate()) {
case 8000:
case 11025:
case 12000:
case 16000:
case 22050:
case 24000:
case 32000:
case 44100:
case 48000:
case 88200:
case 96000:
break;
default:
ALOGE("unsupported sample rate %u", getSampleRate());
return NO_INIT;
}
static const struct {
unsigned mChannels;
unsigned mBitsPerSample;
void (*mCopy)(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels);
} table[] = {
{ 1, 8, copyMono8 },
{ 2, 8, copyStereo8 },
{ 8, 8, copyMultiCh8 },
{ 1, 16, copyMono16 },
{ 2, 16, copyStereo16 },
{ 8, 16, copyMultiCh16 },
{ 1, 24, copyMono24 },
{ 2, 24, copyStereo24 },
{ 8, 24, copyMultiCh24 },
};
for (unsigned i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
if (table[i].mChannels >= getChannels() &&
table[i].mBitsPerSample == getBitsPerSample()) {
mCopy = table[i].mCopy;
break;
}
}
if (mTrackMetadata != 0) {
mTrackMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
mTrackMetadata->setInt32(kKeyChannelCount, getChannels());
mTrackMetadata->setInt32(kKeySampleRate, getSampleRate());
mTrackMetadata->setInt32(kKeyPcmEncoding, kAudioEncodingPcm16bit);
mTrackMetadata->setInt64(kKeyDuration,
(getTotalSamples() * 1000000LL) / getSampleRate());
}
} else {
ALOGE("missing STREAMINFO");
return NO_INIT;
}
if (mFileMetadata != 0) {
mFileMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
}
return OK;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: WebContents* WebContentsImpl::GetAsWebContents() {
return this;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: views::Label* GetLabelView(WindowSelectorItem* window) {
return window->label_view_;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
int hdrlen;
uint16_t fc;
uint8_t seq;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4] %x", caplen));
return caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(fc);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[fc & 0x7]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
if (hdrlen == -1) {
ND_PRINT((ndo,"invalid! "));
return caplen;
}
if (!ndo->ndo_vflag) {
p+= hdrlen;
caplen -= hdrlen;
} else {
uint16_t panid = 0;
switch ((fc >> 10) & 0x3) {
case 0x00:
ND_PRINT((ndo,"none "));
break;
case 0x01:
ND_PRINT((ndo,"reserved destination addressing mode"));
return 0;
case 0x02:
panid = EXTRACT_LE_16BITS(p);
p += 2;
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
break;
case 0x03:
panid = EXTRACT_LE_16BITS(p);
p += 2;
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
break;
}
ND_PRINT((ndo,"< "));
switch ((fc >> 14) & 0x3) {
case 0x00:
ND_PRINT((ndo,"none "));
break;
case 0x01:
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case 0x02:
if (!(fc & (1 << 6))) {
panid = EXTRACT_LE_16BITS(p);
p += 2;
}
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
break;
case 0x03:
if (!(fc & (1 << 6))) {
panid = EXTRACT_LE_16BITS(p);
p += 2;
}
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
break;
}
caplen -= hdrlen;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return 0;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void Compositor::OnFrameTokenChanged(uint32_t frame_token) {
NOTREACHED();
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void backup_mb_border(uint8_t *top_border, uint8_t *src_y,
uint8_t *src_cb, uint8_t *src_cr,
ptrdiff_t linesize, ptrdiff_t uvlinesize, int simple)
{
AV_COPY128(top_border, src_y + 15 * linesize);
if (!simple) {
AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
}
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size,
png_bytep output, png_size_t output_size)
{
png_size_t count = 0;
png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */
png_ptr->zstream.avail_in = size;
while (1)
{
int ret, avail;
/* Reset the output buffer each time round - we empty it
* after every inflate call.
*/
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = png_ptr->zbuf_size;
ret = inflate(&png_ptr->zstream, Z_NO_FLUSH);
avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out;
/* First copy/count any new output - but only if we didn't
* get an error code.
*/
if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0)
{
if (output != 0 && output_size > count)
{
int copy = output_size - count;
if (avail < copy) copy = avail;
png_memcpy(output + count, png_ptr->zbuf, copy);
}
count += avail;
}
if (ret == Z_OK)
continue;
/* Termination conditions - always reset the zstream, it
* must be left in inflateInit state.
*/
png_ptr->zstream.avail_in = 0;
inflateReset(&png_ptr->zstream);
if (ret == Z_STREAM_END)
return count; /* NOTE: may be zero. */
/* Now handle the error codes - the API always returns 0
* and the error message is dumped into the uncompressed
* buffer if available.
*/
{
PNG_CONST char *msg;
if (png_ptr->zstream.msg != 0)
msg = png_ptr->zstream.msg;
else
{
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
char umsg[52];
switch (ret)
{
case Z_BUF_ERROR:
msg = "Buffer error in compressed datastream in %s chunk";
break;
case Z_DATA_ERROR:
msg = "Data error in compressed datastream in %s chunk";
break;
default:
msg = "Incomplete compressed datastream in %s chunk";
break;
}
png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name);
msg = umsg;
#else
msg = "Damaged compressed datastream in chunk other than IDAT";
#endif
}
png_warning(png_ptr, msg);
}
/* 0 means an error - notice that this code simple ignores
* zero length compressed chunks as a result.
*/
return 0;
}
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int mrc;
int mrt, qqi;
u_int nsrcs;
register u_int i;
/* Minimum len is 28 */
if (len < 28) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[0]);
mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]);
if (mrc < 32768) {
mrt = mrc;
} else {
mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3);
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," [max resp delay=%d]", mrt));
}
ND_TCHECK2(bp[8], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[8])));
if (ndo->ndo_vflag) {
ND_TCHECK(bp[25]);
if (bp[24] & 0x08) {
ND_PRINT((ndo," sflag"));
}
if (bp[24] & 0x07) {
ND_PRINT((ndo," robustness=%d", bp[24] & 0x07));
}
if (bp[25] < 128) {
qqi = bp[25];
} else {
qqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3);
}
ND_PRINT((ndo," qqi=%d", qqi));
}
ND_TCHECK2(bp[26], 2);
nsrcs = EXTRACT_16BITS(&bp[26]);
if (nsrcs > 0) {
if (len < 28 + nsrcs * sizeof(struct in6_addr))
ND_PRINT((ndo," [invalid number of sources]"));
else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo," {"));
for (i = 0; i < nsrcs; i++) {
ND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
} else
ND_PRINT((ndo,", %d source(s)", nsrcs));
}
ND_PRINT((ndo,"]"));
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: authentic_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data;
struct sc_apdu apdu;
unsigned char pin_data[SC_MAX_APDU_BUFFER_SIZE];
size_t offs;
int rv;
rv = authentic_pin_get_policy(card, data);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
memset(prv_data->pins_sha1[data->pin_reference], 0, sizeof(prv_data->pins_sha1[0]));
if (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) {
if (!(card->reader->capabilities & SC_READER_CAP_PIN_PAD))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN pad not supported");
rv = authentic_pin_change_pinpad(card, data->pin_reference, tries_left);
sc_log(ctx, "authentic_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
if (card->max_send_size && (data->pin1.len + data->pin2.len > (int)card->max_send_size))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_PIN_LENGTH, "APDU transmit failed");
memset(pin_data, data->pin1.pad_char, sizeof(pin_data));
offs = 0;
if (data->pin1.data && data->pin1.len) {
memcpy(pin_data, data->pin1.data, data->pin1.len);
offs += data->pin1.pad_length;
}
if (data->pin2.data && data->pin2.len)
memcpy(pin_data + offs, data->pin2.data, data->pin2.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, offs ? 0x00 : 0x01, data->pin_reference);
apdu.data = pin_data;
apdu.datalen = offs + data->pin1.pad_length;
apdu.lc = offs + data->pin1.pad_length;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(ctx, rv);
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi;
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
if (!EXT4_SB(inode->i_sb)->s_journal)
return 0;
mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
if (list_empty(&ei->i_orphan))
goto out;
ino_next = NEXT_ORPHAN(inode);
prev = ei->i_orphan.prev;
sbi = EXT4_SB(inode->i_sb);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (!handle)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_err;
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out_brelse;
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err)
goto out_brelse;
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
out:
mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: fbCombineInU (CARD32 *dest, const CARD32 *src, int width)
{
int i;
for (i = 0; i < width; ++i) {
CARD32 s = READ(src + i);
CARD32 a = Alpha(READ(dest + i));
FbByteMul(s, a);
WRITE(dest + i, s);
}
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cmsPipeline* DefaultICCintents(cmsContext ContextID,
cmsUInt32Number nProfiles,
cmsUInt32Number TheIntents[],
cmsHPROFILE hProfiles[],
cmsBool BPC[],
cmsFloat64Number AdaptationStates[],
cmsUInt32Number dwFlags)
{
cmsPipeline* Lut = NULL;
cmsPipeline* Result;
cmsHPROFILE hProfile;
cmsMAT3 m;
cmsVEC3 off;
cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut, CurrentColorSpace;
cmsProfileClassSignature ClassSig;
cmsUInt32Number i, Intent;
if (nProfiles == 0) return NULL;
Result = cmsPipelineAlloc(ContextID, 0, 0);
if (Result == NULL) return NULL;
CurrentColorSpace = cmsGetColorSpace(hProfiles[0]);
for (i=0; i < nProfiles; i++) {
cmsBool lIsDeviceLink, lIsInput;
hProfile = hProfiles[i];
ClassSig = cmsGetDeviceClass(hProfile);
lIsDeviceLink = (ClassSig == cmsSigLinkClass || ClassSig == cmsSigAbstractClass );
if ((i == 0) && !lIsDeviceLink) {
lIsInput = TRUE;
}
else {
lIsInput = (CurrentColorSpace != cmsSigXYZData) &&
(CurrentColorSpace != cmsSigLabData);
}
Intent = TheIntents[i];
if (lIsInput || lIsDeviceLink) {
ColorSpaceIn = cmsGetColorSpace(hProfile);
ColorSpaceOut = cmsGetPCS(hProfile);
}
else {
ColorSpaceIn = cmsGetPCS(hProfile);
ColorSpaceOut = cmsGetColorSpace(hProfile);
}
if (!ColorSpaceIsCompatible(ColorSpaceIn, CurrentColorSpace)) {
cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "ColorSpace mismatch");
goto Error;
}
if (lIsDeviceLink || ((ClassSig == cmsSigNamedColorClass) && (nProfiles == 1))) {
Lut = _cmsReadDevicelinkLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
if (ClassSig == cmsSigAbstractClass && i > 0) {
if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
}
else {
_cmsMAT3identity(&m);
_cmsVEC3init(&off, 0, 0, 0);
}
if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
}
else {
if (lIsInput) {
Lut = _cmsReadInputLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
}
else {
Lut = _cmsReadOutputLUT(hProfile, Intent);
if (Lut == NULL) goto Error;
if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
}
}
if (!cmsPipelineCat(Result, Lut))
goto Error;
cmsPipelineFree(Lut);
CurrentColorSpace = ColorSpaceOut;
}
return Result;
Error:
cmsPipelineFree(Lut);
if (Result != NULL) cmsPipelineFree(Result);
return NULL;
cmsUNUSED_PARAMETER(dwFlags);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ExtensionTtsPlatformImplWin::Speak(
const std::string& src_utterance,
const std::string& language,
const std::string& gender,
double rate,
double pitch,
double volume) {
std::wstring utterance = UTF8ToUTF16(src_utterance);
if (!speech_synthesizer_)
return false;
if (rate >= 0.0) {
speech_synthesizer_->SetRate(static_cast<int32>(rate * 20 - 10));
}
if (pitch >= 0.0) {
std::wstring pitch_value =
base::IntToString16(static_cast<int>(pitch * 20 - 10));
utterance = L"<pitch absmiddle=\"" + pitch_value + L"\">" +
utterance + L"</pitch>";
}
if (volume >= 0.0) {
speech_synthesizer_->SetVolume(static_cast<uint16>(volume * 100));
}
if (paused_) {
speech_synthesizer_->Resume();
paused_ = false;
}
speech_synthesizer_->Speak(
utterance.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static MagickBooleanType GetICCProperty(const Image *image,const char *property,
ExceptionInfo *exception)
{
const StringInfo
*profile;
magick_unreferenced(property);
profile=GetImageProfile(image,"icc");
if (profile == (StringInfo *) NULL)
profile=GetImageProfile(image,"icm");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
if (GetStringInfoLength(profile) < 128)
return(MagickFalse); /* minimum ICC profile length */
#if defined(MAGICKCORE_LCMS_DELEGATE)
{
cmsHPROFILE
icc_profile;
icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile),
(cmsUInt32Number) GetStringInfoLength(profile));
if (icc_profile != (cmsHPROFILE *) NULL)
{
#if defined(LCMS_VERSION) && (LCMS_VERSION < 2000)
const char
*name;
name=cmsTakeProductName(icc_profile);
if (name != (const char *) NULL)
(void) SetImageProperty((Image *) image,"icc:name",name,exception);
#else
char
info[MagickPathExtent];
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:description",info,
exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoManufacturer,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:manufacturer",info,
exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoModel,"en","US",info,
MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:model",info,exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoCopyright,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:copyright",info,exception);
#endif
(void) cmsCloseProfile(icc_profile);
}
}
#endif
return(MagickTrue);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: create_signature(krb5_context context,
const heim_oid *eContentType,
krb5_data *eContent,
struct krb5_pk_identity *id,
hx509_peer_info peer,
krb5_data *sd_data)
{
int ret, flags = 0;
if (id->cert == NULL)
flags |= HX509_CMS_SIGNATURE_NO_SIGNER;
ret = hx509_cms_create_signed_1(context->hx509ctx,
flags,
eContentType,
eContent->data,
eContent->length,
NULL,
id->cert,
peer,
NULL,
id->certs,
sd_data);
if (ret) {
pk_copy_error(context, context->hx509ctx, ret,
"Create CMS signedData");
return ret;
}
return 0;
}
CWE ID: CWE-320
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void *arm_coherent_dma_alloc(struct device *dev, size_t size,
dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs)
{
pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
void *memory;
if (dma_alloc_from_coherent(dev, size, handle, &memory))
return memory;
return __dma_alloc(dev, size, handle, gfp, prot, true,
__builtin_return_address(0));
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: mac80211_hwsim_beacon(struct hrtimer *timer)
{
struct mac80211_hwsim_data *data =
container_of(timer, struct mac80211_hwsim_data,
beacon_timer.timer);
struct ieee80211_hw *hw = data->hw;
u64 bcn_int = data->beacon_int;
ktime_t next_bcn;
if (!data->started)
goto out;
ieee80211_iterate_active_interfaces_atomic(
hw, IEEE80211_IFACE_ITER_NORMAL,
mac80211_hwsim_beacon_tx, data);
/* beacon at new TBTT + beacon interval */
if (data->bcn_delta) {
bcn_int -= data->bcn_delta;
data->bcn_delta = 0;
}
next_bcn = ktime_add(hrtimer_get_expires(timer),
ns_to_ktime(bcn_int * 1000));
tasklet_hrtimer_start(&data->beacon_timer, next_bcn, HRTIMER_MODE_ABS);
out:
return HRTIMER_NORESTART;
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PageHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
if (host_ == frame_host)
return;
RenderWidgetHostImpl* widget_host =
host_ ? host_->GetRenderWidgetHost() : nullptr;
if (widget_host) {
registrar_.Remove(
this,
content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
content::Source<RenderWidgetHost>(widget_host));
}
host_ = frame_host;
widget_host = host_ ? host_->GetRenderWidgetHost() : nullptr;
if (widget_host) {
registrar_.Add(
this,
content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
content::Source<RenderWidgetHost>(widget_host));
}
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int hashtable_set(hashtable_t *hashtable,
const char *key, size_t serial,
json_t *value)
{
pair_t *pair;
bucket_t *bucket;
size_t hash, index;
/* rehash if the load ratio exceeds 1 */
if(hashtable->size >= num_buckets(hashtable))
if(hashtable_do_rehash(hashtable))
return -1;
hash = hash_str(key);
index = hash % num_buckets(hashtable);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(pair)
{
json_decref(pair->value);
pair->value = value;
}
else
{
/* offsetof(...) returns the size of pair_t without the last,
flexible member. This way, the correct amount is
allocated. */
pair = jsonp_malloc(offsetof(pair_t, key) + strlen(key) + 1);
if(!pair)
return -1;
pair->hash = hash;
pair->serial = serial;
strcpy(pair->key, key);
pair->value = value;
list_init(&pair->list);
insert_to_bucket(hashtable, bucket, &pair->list);
hashtable->size++;
}
return 0;
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: int netlink_register_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&netlink_chain, nb);
}
CWE ID: CWE-287
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool WebMediaPlayerImpl::DidPassCORSAccessCheck() const {
if (data_source_)
return data_source_->DidPassCORSAccessCheck();
return false;
}
CWE ID: CWE-346
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool dccp_new(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, unsigned int *timeouts)
{
struct net *net = nf_ct_net(ct);
struct dccp_net *dn;
struct dccp_hdr _dh, *dh;
const char *msg;
u_int8_t state;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
BUG_ON(dh == NULL);
state = dccp_state_table[CT_DCCP_ROLE_CLIENT][dh->dccph_type][CT_DCCP_NONE];
switch (state) {
default:
dn = dccp_pernet(net);
if (dn->dccp_loose == 0) {
msg = "nf_ct_dccp: not picking up existing connection ";
goto out_invalid;
}
case CT_DCCP_REQUEST:
break;
case CT_DCCP_INVALID:
msg = "nf_ct_dccp: invalid state transition ";
goto out_invalid;
}
ct->proto.dccp.role[IP_CT_DIR_ORIGINAL] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[IP_CT_DIR_REPLY] = CT_DCCP_ROLE_SERVER;
ct->proto.dccp.state = CT_DCCP_NONE;
ct->proto.dccp.last_pkt = DCCP_PKT_REQUEST;
ct->proto.dccp.last_dir = IP_CT_DIR_ORIGINAL;
ct->proto.dccp.handshake_seq = 0;
return true;
out_invalid:
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, nf_ct_l3num(ct), 0, skb, NULL, NULL,
NULL, "%s", msg);
return false;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int crypto_cbc_encrypt_segment(struct blkcipher_desc *desc,
struct blkcipher_walk *walk,
struct crypto_cipher *tfm)
{
void (*fn)(struct crypto_tfm *, u8 *, const u8 *) =
crypto_cipher_alg(tfm)->cia_encrypt;
int bsize = crypto_cipher_blocksize(tfm);
unsigned int nbytes = walk->nbytes;
u8 *src = walk->src.virt.addr;
u8 *dst = walk->dst.virt.addr;
u8 *iv = walk->iv;
do {
crypto_xor(iv, src, bsize);
fn(crypto_cipher_tfm(tfm), dst, iv);
memcpy(iv, dst, bsize);
src += bsize;
dst += bsize;
} while ((nbytes -= bsize) >= bsize);
return nbytes;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SpoolssEndPagePrinter_q(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree,
dcerpc_info *di, guint8 *drep)
{
e_ctx_hnd policy_hnd;
char *pol_name;
/* Parse packet */
offset = dissect_nt_policy_hnd(
tvb, offset, pinfo, tree, di, drep, hf_hnd, &policy_hnd, NULL,
FALSE, FALSE);
dcerpc_fetch_polhnd_data(&policy_hnd, &pol_name, NULL, NULL, NULL,
pinfo->num);
if (pol_name)
col_append_fstr(pinfo->cinfo, COL_INFO, ", %s",
pol_name);
return offset;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,
xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
{
if (expr == NULL) {
*pred_rtrn = MATCH_ANY_OR_NONE;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
*pred_rtrn = MATCH_EXACTLY;
if (expr->expr.op == EXPR_ACTION_DECL) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);
if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {
log_err(info->ctx,
"Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
return false;
}
expr = expr->action.args;
}
else if (expr->expr.op == EXPR_IDENT) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);
if (pred_txt && istreq(pred_txt, "any")) {
*pred_rtrn = MATCH_ANY;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
}
return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,
mods_rtrn);
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static int compute_data_length_after_meta(modbus_t *ctx, uint8_t *msg,
msg_type_t msg_type)
{
int function = msg[ctx->backend->header_length];
int length;
if (msg_type == MSG_INDICATION) {
switch (function) {
case MODBUS_FC_WRITE_MULTIPLE_COILS:
case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
length = msg[ctx->backend->header_length + 5];
break;
case MODBUS_FC_WRITE_AND_READ_REGISTERS:
length = msg[ctx->backend->header_length + 9];
break;
default:
length = 0;
}
} else {
/* MSG_CONFIRMATION */
if (function <= MODBUS_FC_READ_INPUT_REGISTERS ||
function == MODBUS_FC_REPORT_SLAVE_ID ||
function == MODBUS_FC_WRITE_AND_READ_REGISTERS) {
length = msg[ctx->backend->header_length + 1];
} else {
length = 0;
}
}
length += ctx->backend->checksum_length;
return length;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ceph_x_init(struct ceph_auth_client *ac)
{
struct ceph_x_info *xi;
int ret;
dout("ceph_x_init %p\n", ac);
ret = -ENOMEM;
xi = kzalloc(sizeof(*xi), GFP_NOFS);
if (!xi)
goto out;
ret = -EINVAL;
if (!ac->key) {
pr_err("no secret set (for auth_x protocol)\n");
goto out_nomem;
}
ret = ceph_crypto_key_clone(&xi->secret, ac->key);
if (ret < 0) {
pr_err("cannot clone key: %d\n", ret);
goto out_nomem;
}
xi->starting = true;
xi->ticket_handlers = RB_ROOT;
ac->protocol = CEPH_AUTH_CEPHX;
ac->private = xi;
ac->ops = &ceph_x_ops;
return 0;
out_nomem:
kfree(xi);
out:
return ret;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)
{
const struct icmp6_router_renum *rr6;
const char *cp;
const struct rr_pco_match *match;
const struct rr_pco_use *use;
char hbuf[NI_MAXHOST];
int n;
if (ep < bp)
return;
rr6 = (const struct icmp6_router_renum *)bp;
cp = (const char *)(rr6 + 1);
ND_TCHECK(rr6->rr_reserved);
switch (rr6->rr_code) {
case ICMP6_ROUTER_RENUMBERING_COMMAND:
ND_PRINT((ndo,"router renum: command"));
break;
case ICMP6_ROUTER_RENUMBERING_RESULT:
ND_PRINT((ndo,"router renum: result"));
break;
case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:
ND_PRINT((ndo,"router renum: sequence number reset"));
break;
default:
ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code));
break;
}
ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum)));
if (ndo->ndo_vflag) {
#define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"[")); /*]*/
if (rr6->rr_flags) {
ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"),
F(ICMP6_RR_FLAGS_REQRESULT, "R"),
F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"),
F(ICMP6_RR_FLAGS_SPECSITE, "S"),
F(ICMP6_RR_FLAGS_PREVDONE, "P")));
}
ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum));
ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay)));
if (rr6->rr_reserved)
ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved)));
/*[*/
ND_PRINT((ndo,"]"));
#undef F
}
if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {
match = (const struct rr_pco_match *)cp;
cp = (const char *)(match + 1);
ND_TCHECK(match->rpm_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"match(")); /*)*/
switch (match->rpm_code) {
case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break;
case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break;
case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break;
default: ND_PRINT((ndo,"#%u", match->rpm_code)); break;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,",ord=%u", match->rpm_ordinal));
ND_PRINT((ndo,",min=%u", match->rpm_minlen));
ND_PRINT((ndo,",max=%u", match->rpm_maxlen));
}
if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen));
else
ND_PRINT((ndo,",?/%u", match->rpm_matchlen));
/*(*/
ND_PRINT((ndo,")"));
n = match->rpm_len - 3;
if (n % 4)
goto trunc;
n /= 4;
while (n-- > 0) {
use = (const struct rr_pco_use *)cp;
cp = (const char *)(use + 1);
ND_TCHECK(use->rpu_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"use(")); /*)*/
if (use->rpu_flags) {
#define F(x, y) ((use->rpu_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"%s%s,",
F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"),
F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P")));
#undef F
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask));
ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags));
if (~use->rpu_vltime == 0)
ND_PRINT((ndo,"vltime=infty,"));
else
ND_PRINT((ndo,"vltime=%u,",
EXTRACT_32BITS(&use->rpu_vltime)));
if (~use->rpu_pltime == 0)
ND_PRINT((ndo,"pltime=infty,"));
else
ND_PRINT((ndo,"pltime=%u,",
EXTRACT_32BITS(&use->rpu_pltime)));
}
if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen,
use->rpu_keeplen));
else
ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen,
use->rpu_keeplen));
/*(*/
ND_PRINT((ndo,")"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: PendingExtensionManager* ExtensionService::pending_extension_manager() {
return &pending_extension_manager_;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int jas_image_strtofmt(char *name)
{
jas_image_fmtinfo_t *fmtinfo;
if (!(fmtinfo = jas_image_lookupfmtbyname(name))) {
return -1;
}
return fmtinfo->id;
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: HeadlessWebContentsImpl::HeadlessWebContentsImpl(
content::WebContents* web_contents,
HeadlessBrowserContextImpl* browser_context)
: content::WebContentsObserver(web_contents),
web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)),
web_contents_(web_contents),
agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)),
inject_mojo_services_into_isolated_world_(false),
browser_context_(browser_context),
render_process_host_(web_contents->GetMainFrame()->GetProcess()),
weak_ptr_factory_(this) {
#if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD)
HeadlessPrintManager::CreateForWebContents(web_contents);
//// TODO(weili): Add support for printing OOPIFs.
#endif
web_contents->GetMutableRendererPrefs()->accept_languages =
browser_context->options()->accept_language();
web_contents_->SetDelegate(web_contents_delegate_.get());
render_process_host_->AddObserver(this);
agent_host_->AddObserver(this);
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: NPObject* ScriptController::createScriptObjectForPluginElement(HTMLPlugInElement* plugin)
{
if (!canExecuteScripts(NotAboutToExecuteScript))
return createNoScriptObject();
v8::HandleScope handleScope;
v8::Handle<v8::Context> v8Context = V8Proxy::mainWorldContext(m_frame);
if (v8Context.IsEmpty())
return createNoScriptObject();
v8::Context::Scope scope(v8Context);
DOMWindow* window = m_frame->domWindow();
v8::Handle<v8::Value> v8plugin = toV8(static_cast<HTMLEmbedElement*>(plugin));
if (!v8plugin->IsObject())
return createNoScriptObject();
return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(v8plugin), window);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int hid_device_probe(struct device *dev)
{
struct hid_driver *hdrv = to_hid_driver(dev->driver);
struct hid_device *hdev = to_hid_device(dev);
const struct hid_device_id *id;
int ret = 0;
if (down_interruptible(&hdev->driver_lock))
return -EINTR;
if (down_interruptible(&hdev->driver_input_lock)) {
ret = -EINTR;
goto unlock_driver_lock;
}
hdev->io_started = false;
if (!hdev->driver) {
id = hid_match_device(hdev, hdrv);
if (id == NULL) {
ret = -ENODEV;
goto unlock;
}
hdev->driver = hdrv;
if (hdrv->probe) {
ret = hdrv->probe(hdev, id);
} else { /* default probe */
ret = hid_open_report(hdev);
if (!ret)
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
}
if (ret) {
hid_close_report(hdev);
hdev->driver = NULL;
}
}
unlock:
if (!hdev->io_started)
up(&hdev->driver_input_lock);
unlock_driver_lock:
up(&hdev->driver_lock);
return ret;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const char* Track::GetCodecNameAsUTF8() const
{
return m_info.codecNameAsUTF8;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ACodec::initiateShutdown(bool keepComponentAllocated) {
sp<AMessage> msg = new AMessage(kWhatShutdown, this);
msg->setInt32("keepComponentAllocated", keepComponentAllocated);
msg->post();
if (!keepComponentAllocated) {
(new AMessage(kWhatReleaseCodecInstance, this))->post(3000000);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SyncPromoUI::Source GetSigninSource(const GURL& url, GURL* continue_url) {
std::string value;
net::GetValueForKeyInQuery(url, "service", &value);
bool possibly_an_explicit_signin = value == "chromiumsync";
GURL local_continue_url = SyncPromoUI::GetNextPageURLForSyncPromoURL(url);
while (gaia::IsGaiaSignonRealm(local_continue_url.GetOrigin())) {
GURL next_continue_url =
SyncPromoUI::GetNextPageURLForSyncPromoURL(local_continue_url);
if (!next_continue_url.is_valid())
break;
local_continue_url = next_continue_url;
}
if (continue_url && local_continue_url.is_valid()) {
DCHECK(!continue_url->is_valid() || *continue_url == local_continue_url);
*continue_url = local_continue_url;
}
return possibly_an_explicit_signin ?
SyncPromoUI::GetSourceForSyncPromoURL(local_continue_url) :
SyncPromoUI::SOURCE_UNKNOWN;
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PassRefPtr<DocumentFragment> XSLTProcessor::transformToFragment(Node* sourceNode, Document* outputDoc)
{
String resultMIMEType;
String resultString;
String resultEncoding;
if (outputDoc->isHTMLDocument())
resultMIMEType = "text/html";
if (!transformToString(sourceNode, resultMIMEType, resultString, resultEncoding))
return 0;
return createFragmentFromSource(resultString, resultMIMEType, outputDoc);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: virtual void AnimationProgressed(const ui::Animation* animation) {
TabAnimation::AnimationProgressed(animation);
int x = animation_.CurrentValueBetween(start_bounds_.x(),
target_bounds_.x());
int width = animation_.CurrentValueBetween(start_bounds_.width(),
target_bounds_.width());
gfx::Rect tab_bounds(x, start_bounds_.y(), width,
start_bounds_.height());
tabstrip_->SetTabBounds(tab_, tab_bounds);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view,
scoped_ptr<Delegate> delegate)
: content::RenderViewObserver(render_view),
content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
reset_prep_frame_view_(false),
is_print_ready_metafile_sent_(false),
ignore_css_margins_(false),
is_scripted_printing_blocked_(false),
notify_browser_of_print_failure_(true),
print_for_preview_(false),
delegate_(delegate.Pass()),
print_node_in_progress_(false),
is_loading_(false),
is_scripted_preview_delayed_(false),
weak_ptr_factory_(this) {
if (!delegate_->IsPrintPreviewEnabled())
DisablePreview();
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int main(void)
{
FILE *f;
char *tmpname;
f = xfmkstemp(&tmpname, NULL);
unlink(tmpname);
free(tmpname);
fclose(f);
return EXIT_FAILURE;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: PendingHostCreator::PendingHostCreator(BrowserPpapiHostImpl* host,
BrowserMessageFilter* connection,
int routing_id,
int sequence_id,
size_t nested_msgs_size)
: host_(host),
connection_(connection),
routing_id_(routing_id),
sequence_id_(sequence_id),
pending_resource_host_ids_(nested_msgs_size, 0) {}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __ebt_unregister_table(struct net *net, struct ebt_table *table)
{
int i;
mutex_lock(&ebt_mutex);
list_del(&table->list);
mutex_unlock(&ebt_mutex);
EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size,
ebt_cleanup_entry, net, NULL);
if (table->private->nentries)
module_put(table->me);
vfree(table->private->entries);
if (table->private->chainstack) {
for_each_possible_cpu(i)
vfree(table->private->chainstack[i]);
vfree(table->private->chainstack);
}
vfree(table->private);
kfree(table);
}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: qedi_dbg_err(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (likely(qedi) && likely(qedi->pdev))
pr_err("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev),
nfunc, line, qedi->host_no, &vaf);
else
pr_err("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
va_end(va);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: status_t OMX::fillBuffer(node_id node, buffer_id buffer, int fenceFd) {
return findInstance(node)->fillBuffer(buffer, fenceFd);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: FileTransfer::ExpandFileTransferList( StringList *input_list, FileTransferList &expanded_list )
{
bool rc = true;
if( !input_list ) {
return true;
}
if (X509UserProxy && input_list->contains(X509UserProxy)) {
if( !ExpandFileTransferList( X509UserProxy, "", Iwd, -1, expanded_list ) ) {
rc = false;
}
}
input_list->rewind();
char const *path;
while ( (path=input_list->next()) != NULL ) {
if(!X509UserProxy || (X509UserProxy && strcmp(path, X509UserProxy) != 0)) {
if( !ExpandFileTransferList( path, "", Iwd, -1, expanded_list ) ) {
rc = false;
}
}
}
return rc;
}
CWE ID: CWE-134
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AudioRendererHostTest()
: log_factory(base::MakeUnique<media::FakeAudioLogFactory>()),
audio_manager_(base::MakeUnique<FakeAudioManagerWithAssociations>(
base::ThreadTaskRunnerHandle::Get(),
log_factory.get())),
render_process_host_(&browser_context_, &auth_run_loop_) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
host_ = new MockAudioRendererHost(
&auth_run_loop_, render_process_host_.GetID(), audio_manager_.get(),
&mirroring_manager_, media_stream_manager_.get(), kSalt);
host_->set_peer_process_for_testing(base::Process::Current());
}
CWE ID:
Target: 1
Example 2:
Code: static int prb_previous_blk_num(struct packet_ring_buffer *rb)
{
unsigned int prev;
if (rb->prb_bdqc.kactive_blk_num)
prev = rb->prb_bdqc.kactive_blk_num-1;
else
prev = rb->prb_bdqc.knum_blocks-1;
return prev;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int __attribute__((no_instrument_function)) trace_early_init(void)
{
ulong func_count = gd->mon_len / FUNC_SITE_SIZE;
size_t buff_size = CONFIG_TRACE_EARLY_SIZE;
size_t needed;
/* We can ignore additional calls to this function */
if (trace_enabled)
return 0;
hdr = map_sysmem(CONFIG_TRACE_EARLY_ADDR, CONFIG_TRACE_EARLY_SIZE);
needed = sizeof(*hdr) + func_count * sizeof(uintptr_t);
if (needed > buff_size) {
printf("trace: buffer size is %zd bytes, at least %zd needed\n",
buff_size, needed);
return -ENOSPC;
}
memset(hdr, '\0', needed);
hdr->call_accum = (uintptr_t *)(hdr + 1);
hdr->func_count = func_count;
/* Use any remaining space for the timed function trace */
hdr->ftrace = (struct trace_call *)((char *)hdr + needed);
hdr->ftrace_size = (buff_size - needed) / sizeof(*hdr->ftrace);
add_textbase();
hdr->depth_limit = CONFIG_TRACE_EARLY_CALL_DEPTH_LIMIT;
printf("trace: early enable at %08x\n", CONFIG_TRACE_EARLY_ADDR);
trace_enabled = 1;
return 0;
}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE SoftRaw::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mChannelCount;
pcmParams->nSamplingRate = mSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void NavigationControllerImpl::LoadURL(
const GURL& url,
const Referrer& referrer,
PageTransition transition,
const std::string& extra_headers) {
LoadURLParams params(url);
params.referrer = referrer;
params.transition_type = transition;
params.extra_headers = extra_headers;
LoadURLWithParams(params);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CoordinatorImpl::RequestGlobalMemoryDumpForPid(
base::ProcessId pid,
const RequestGlobalMemoryDumpForPidCallback& callback) {
if (pid == base::kNullProcessId) {
callback.Run(false, nullptr);
return;
}
auto adapter = [](const RequestGlobalMemoryDumpForPidCallback& callback,
bool success, uint64_t,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(
base::trace_event::MemoryDumpType::SUMMARY_ONLY,
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND, {},
false /* addToTrace */, pid);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
CWE ID: CWE-269
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ParamTraits<SkBitmap>::Write(base::Pickle* m, const SkBitmap& p) {
size_t fixed_size = sizeof(SkBitmap_Data);
SkBitmap_Data bmp_data;
bmp_data.InitSkBitmapDataForTransfer(p);
m->WriteData(reinterpret_cast<const char*>(&bmp_data),
static_cast<int>(fixed_size));
size_t pixel_size = p.computeByteSize();
m->WriteData(reinterpret_cast<const char*>(p.getPixels()),
static_cast<int>(pixel_size));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: bool HTMLFormElement::HasLegalLinkAttribute(const QualifiedName& name) const {
return name == actionAttr || HTMLElement::HasLegalLinkAttribute(name);
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long SeekHead::Parse()
{
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
int entry_count = 0;
int void_element_count = 0;
while (pos < stop)
{
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x0DBB) //SeekEntry ID
++entry_count;
else if (id == 0x6C) //Void ID
++void_element_count;
pos += size; //consume payload
assert(pos <= stop);
}
assert(pos == stop);
m_entries = new (std::nothrow) Entry[entry_count];
if (m_entries == NULL)
return -1;
m_void_elements = new (std::nothrow) VoidElement[void_element_count];
if (m_void_elements == NULL)
return -1;
Entry* pEntry = m_entries;
VoidElement* pVoidElement = m_void_elements;
pos = m_start;
while (pos < stop)
{
const long long idpos = pos;
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x0DBB) //SeekEntry ID
{
if (ParseEntry(pReader, pos, size, pEntry))
{
Entry& e = *pEntry++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
}
else if (id == 0x6C) //Void ID
{
VoidElement& e = *pVoidElement++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
pos += size; //consume payload
assert(pos <= stop);
}
assert(pos == stop);
ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries);
assert(count_ >= 0);
assert(count_ <= entry_count);
m_entry_count = static_cast<int>(count_);
count_ = ptrdiff_t(pVoidElement - m_void_elements);
assert(count_ >= 0);
assert(count_ <= void_element_count);
m_void_element_count = static_cast<int>(count_);
return 0;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count,
int preview_request_id) {
VLOG(1) << "Print preview request finished with "
<< expected_pages_count << " pages";
if (!initial_preview_start_time_.is_null()) {
UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime",
base::TimeTicks::Now() - initial_preview_start_time_);
UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial",
expected_pages_count);
initial_preview_start_time_ = base::TimeTicks();
}
base::StringValue ui_identifier(preview_ui_addr_str_);
base::FundamentalValue ui_preview_request_id(preview_request_id);
web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier,
ui_preview_request_id);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: make_random_bytes(png_uint_32* seed, void* pv, size_t size)
{
png_uint_32 u0 = seed[0], u1 = seed[1];
png_bytep bytes = voidcast(png_bytep, pv);
/* There are thirty three bits, the next bit in the sequence is bit-33 XOR
* bit-20. The top 1 bit is in u1, the bottom 32 are in u0.
*/
size_t i;
for (i=0; i<size; ++i)
{
/* First generate 8 new bits then shift them in at the end. */
png_uint_32 u = ((u0 >> (20-8)) ^ ((u1 << 7) | (u0 >> (32-7)))) & 0xff;
u1 <<= 8;
u1 |= u0 >> 24;
u0 <<= 8;
u0 |= u;
*bytes++ = (png_byte)u;
}
seed[0] = u0;
seed[1] = u1;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t DRMSource::read(MediaBuffer **buffer, const ReadOptions *options) {
Mutex::Autolock autoLock(mDRMLock);
status_t err;
if ((err = mOriginalMediaSource->read(buffer, options)) != OK) {
return err;
}
size_t len = (*buffer)->range_length();
char *src = (char *)(*buffer)->data() + (*buffer)->range_offset();
DrmBuffer encryptedDrmBuffer(src, len);
DrmBuffer decryptedDrmBuffer;
decryptedDrmBuffer.length = len;
decryptedDrmBuffer.data = new char[len];
DrmBuffer *pDecryptedDrmBuffer = &decryptedDrmBuffer;
if ((err = mDrmManagerClient->decrypt(mDecryptHandle, mTrackId,
&encryptedDrmBuffer, &pDecryptedDrmBuffer)) != NO_ERROR) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return err;
}
CHECK(pDecryptedDrmBuffer == &decryptedDrmBuffer);
const char *mime;
CHECK(getFormat()->findCString(kKeyMIMEType, &mime));
if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) && !mWantsNALFragments) {
uint8_t *dstData = (uint8_t*)src;
size_t srcOffset = 0;
size_t dstOffset = 0;
len = decryptedDrmBuffer.length;
while (srcOffset < len) {
CHECK(srcOffset + mNALLengthSize <= len);
size_t nalLength = 0;
const uint8_t* data = (const uint8_t*)(&decryptedDrmBuffer.data[srcOffset]);
switch (mNALLengthSize) {
case 1:
nalLength = *data;
break;
case 2:
nalLength = U16_AT(data);
break;
case 3:
nalLength = ((size_t)data[0] << 16) | U16_AT(&data[1]);
break;
case 4:
nalLength = U32_AT(data);
break;
default:
CHECK(!"Should not be here.");
break;
}
srcOffset += mNALLengthSize;
size_t end = srcOffset + nalLength;
if (end > len || end < srcOffset) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
CHECK(dstOffset + 4 <= (*buffer)->size());
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &decryptedDrmBuffer.data[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, len);
(*buffer)->set_range((*buffer)->range_offset(), dstOffset);
} else {
memcpy(src, decryptedDrmBuffer.data, decryptedDrmBuffer.length);
(*buffer)->set_range((*buffer)->range_offset(), decryptedDrmBuffer.length);
}
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return OK;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: key_ref_t keyring_search(key_ref_t keyring,
struct key_type *type,
const char *description)
{
struct keyring_search_context ctx = {
.index_key.type = type,
.index_key.description = description,
.cred = current_cred(),
.match_data.cmp = type->match,
.match_data.raw_data = description,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_DO_STATE_CHECK,
};
key_ref_t key;
int ret;
if (!ctx.match_data.cmp)
return ERR_PTR(-ENOKEY);
if (type->match_preparse) {
ret = type->match_preparse(&ctx.match_data);
if (ret < 0)
return ERR_PTR(ret);
}
key = keyring_search_aux(keyring, &ctx);
if (type->match_free)
type->match_free(&ctx.match_data);
return key;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: struct sock *inet6_lookup_listener(struct net *net,
struct inet_hashinfo *hashinfo, const struct in6_addr *daddr,
const unsigned short hnum, const int dif)
{
struct sock *sk;
const struct hlist_nulls_node *node;
struct sock *result;
int score, hiscore;
unsigned int hash = inet_lhashfn(net, hnum);
struct inet_listen_hashbucket *ilb = &hashinfo->listening_hash[hash];
rcu_read_lock();
begin:
result = NULL;
hiscore = -1;
sk_nulls_for_each(sk, node, &ilb->head) {
score = compute_score(sk, net, hnum, daddr, dif);
if (score > hiscore) {
hiscore = score;
result = sk;
}
}
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (get_nulls_value(node) != hash + LISTENING_NULLS_BASE)
goto begin;
if (result) {
if (unlikely(!atomic_inc_not_zero(&result->sk_refcnt)))
result = NULL;
else if (unlikely(compute_score(result, net, hnum, daddr,
dif) < hiscore)) {
sock_put(result);
goto begin;
}
}
rcu_read_unlock();
return result;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: uiserver_verify (void *engine, gpgme_data_t sig, gpgme_data_t signed_text,
gpgme_data_t plaintext)
{
engine_uiserver_t uiserver = engine;
gpgme_error_t err;
const char *protocol;
char *cmd;
if (!uiserver)
return gpg_error (GPG_ERR_INV_VALUE);
if (uiserver->protocol == GPGME_PROTOCOL_DEFAULT)
protocol = "";
else if (uiserver->protocol == GPGME_PROTOCOL_OpenPGP)
protocol = " --protocol=OpenPGP";
else if (uiserver->protocol == GPGME_PROTOCOL_CMS)
protocol = " --protocol=CMS";
else
return gpgme_error (GPG_ERR_UNSUPPORTED_PROTOCOL);
if (asprintf (&cmd, "VERIFY%s", protocol) < 0)
return gpg_error_from_syserror ();
uiserver->input_cb.data = sig;
err = uiserver_set_fd (uiserver, INPUT_FD,
map_data_enc (uiserver->input_cb.data));
if (err)
{
free (cmd);
return err;
}
if (plaintext)
{
/* Normal or cleartext signature. */
uiserver->output_cb.data = plaintext;
err = uiserver_set_fd (uiserver, OUTPUT_FD, 0);
}
else
{
/* Detached signature. */
uiserver->message_cb.data = signed_text;
err = uiserver_set_fd (uiserver, MESSAGE_FD, 0);
}
uiserver->inline_data = NULL;
if (!err)
err = start (uiserver, cmd);
free (cmd);
return err;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: 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);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: int phar_mount_entry(phar_archive_data *phar, char *filename, int filename_len, char *path, int path_len) /* {{{ */
{
phar_entry_info entry = {0};
php_stream_statbuf ssb;
int is_phar;
const char *err;
if (phar_path_check(&path, &path_len, &err) > pcr_is_ok) {
return FAILURE;
}
if (path_len >= sizeof(".phar")-1 && !memcmp(path, ".phar", sizeof(".phar")-1)) {
/* no creating magic phar files by mounting them */
return FAILURE;
}
is_phar = (filename_len > 7 && !memcmp(filename, "phar://", 7));
entry.phar = phar;
entry.filename = estrndup(path, path_len);
#ifdef PHP_WIN32
phar_unixify_path_separators(entry.filename, path_len);
#endif
entry.filename_len = path_len;
if (is_phar) {
entry.tmp = estrndup(filename, filename_len);
} else {
entry.tmp = expand_filepath(filename, NULL);
if (!entry.tmp) {
entry.tmp = estrndup(filename, filename_len);
}
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && !is_phar && (!php_checkuid(entry.tmp, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
#endif
filename = entry.tmp;
/* only check openbasedir for files, not for phar streams */
if (!is_phar && php_check_open_basedir(filename)) {
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
entry.is_mounted = 1;
entry.is_crc_checked = 1;
entry.fp_type = PHAR_TMP;
if (SUCCESS != php_stream_stat_path(filename, &ssb)) {
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
if (ssb.sb.st_mode & S_IFDIR) {
entry.is_dir = 1;
if (NULL == zend_hash_str_add_ptr(&phar->mounted_dirs, entry.filename, path_len, entry.filename)) {
/* directory already mounted */
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
} else {
entry.is_dir = 0;
entry.uncompressed_filesize = entry.compressed_filesize = ssb.sb.st_size;
}
entry.flags = ssb.sb.st_mode;
if (NULL != zend_hash_str_add_mem(&phar->manifest, entry.filename, path_len, (void*)&entry, sizeof(phar_entry_info))) {
return SUCCESS;
}
efree(entry.tmp);
efree(entry.filename);
return FAILURE;
}
/* }}} */
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int do_remount(struct path *path, int flags, int mnt_flags,
void *data)
{
int err;
struct super_block *sb = path->mnt->mnt_sb;
struct mount *mnt = real_mount(path->mnt);
if (!check_mnt(mnt))
return -EINVAL;
if (path->dentry != path->mnt->mnt_root)
return -EINVAL;
err = security_sb_remount(sb, data);
if (err)
return err;
down_write(&sb->s_umount);
if (flags & MS_BIND)
err = change_mount_flags(path->mnt, flags);
else if (!capable(CAP_SYS_ADMIN))
err = -EPERM;
else
err = do_remount_sb(sb, flags, data, 0);
if (!err) {
lock_mount_hash();
mnt_flags |= mnt->mnt.mnt_flags & MNT_PROPAGATION_MASK;
mnt->mnt.mnt_flags = mnt_flags;
touch_mnt_namespace(mnt->mnt_ns);
unlock_mount_hash();
}
up_write(&sb->s_umount);
return err;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: CryptohomeLibrary* CrosLibrary::GetCryptohomeLibrary() {
return crypto_lib_.GetDefaultImpl(use_stub_impl_);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void VerifyProcessIsBackgrounded(WebContents* web_contents) {
constexpr bool kExpectedIsBackground = true;
VerifyProcessPriority(web_contents->GetMainFrame()->GetProcess(),
kExpectedIsBackground);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void hfsplus_cat_build_key_uni(hfsplus_btree_key *key, u32 parent,
struct hfsplus_unistr *name)
{
int ustrlen;
ustrlen = be16_to_cpu(name->length);
key->cat.parent = cpu_to_be32(parent);
key->cat.name.length = cpu_to_be16(ustrlen);
ustrlen *= 2;
memcpy(key->cat.name.unicode, name->unicode, ustrlen);
key->key_len = cpu_to_be16(6 + ustrlen);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start)
{
int res, bytes, i, indexes, index_bytes, ids;
long long *index, start, end;
struct squashfs_xattr_table id_table;
TRACE("read_xattrs_from_disk\n");
if(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK)
return SQUASHFS_INVALID_BLK;
/*
* Read xattr id table, containing start of xattr metadata and the
* number of xattrs in the file system
*/
res = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table),
&id_table);
if(res == 0)
return 0;
SQUASHFS_INSWAP_XATTR_TABLE(&id_table);
if(flag) {
/*
* id_table.xattr_table_start stores the start of the compressed xattr
* * metadata blocks. This by definition is also the end of the previous
* filesystem table - the id lookup table.
*/
*table_start = id_table.xattr_table_start;
return id_table.xattr_ids;
}
/*
* Allocate and read the index to the xattr id table metadata
* blocks
*/
ids = id_table.xattr_ids;
xattr_table_start = id_table.xattr_table_start;
index_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids);
indexes = SQUASHFS_XATTR_BLOCKS(ids);
index = malloc(index_bytes);
if(index == NULL)
MEM_ERROR();
res = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table),
index_bytes, index);
if(res ==0)
goto failed1;
SQUASHFS_INSWAP_LONG_LONGS(index, indexes);
/*
* Allocate enough space for the uncompressed xattr id table, and
* read and decompress it
*/
bytes = SQUASHFS_XATTR_BYTES(ids);
xattr_ids = malloc(bytes);
if(xattr_ids == NULL)
MEM_ERROR();
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
int length = read_block(fd, index[i], NULL, expected,
((unsigned char *) xattr_ids) +
(i * SQUASHFS_METADATA_SIZE));
TRACE("Read xattr id table block %d, from 0x%llx, length "
"%d\n", i, index[i], length);
if(length == 0) {
ERROR("Failed to read xattr id table block %d, "
"from 0x%llx, length %d\n", i, index[i],
length);
goto failed2;
}
}
/*
* Read and decompress the xattr metadata
*
* Note the first xattr id table metadata block is immediately after
* the last xattr metadata block, so we can use index[0] to work out
* the end of the xattr metadata
*/
start = xattr_table_start;
end = index[0];
for(i = 0; start < end; i++) {
int length;
xattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE);
if(xattrs == NULL)
MEM_ERROR();
/* store mapping from location of compressed block in fs ->
* location of uncompressed block in memory */
save_xattr_block(start, i * SQUASHFS_METADATA_SIZE);
length = read_block(fd, start, &start, 0,
((unsigned char *) xattrs) +
(i * SQUASHFS_METADATA_SIZE));
TRACE("Read xattr block %d, length %d\n", i, length);
if(length == 0) {
ERROR("Failed to read xattr block %d\n", i);
goto failed3;
}
/*
* If this is not the last metadata block in the xattr metadata
* then it should be SQUASHFS_METADATA_SIZE in size.
* Note, we can't use expected in read_block() above for this
* because we don't know if this is the last block until
* after reading.
*/
if(start != end && length != SQUASHFS_METADATA_SIZE) {
ERROR("Xattr block %d should be %d bytes in length, "
"it is %d bytes\n", i, SQUASHFS_METADATA_SIZE,
length);
goto failed3;
}
}
/* swap if necessary the xattr id entries */
for(i = 0; i < ids; i++)
SQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]);
free(index);
return ids;
failed3:
free(xattrs);
failed2:
free(xattr_ids);
failed1:
free(index);
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void WebContentsImpl::Focus() {
view_->Focus();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool MediaStreamManager::SetupTabCaptureRequest(DeviceRequest* request) {
DCHECK(request->audio_type() == MEDIA_TAB_AUDIO_CAPTURE ||
request->video_type() == MEDIA_TAB_VIDEO_CAPTURE);
std::string capture_device_id;
if (!request->controls.audio.device_id.empty()) {
capture_device_id = request->controls.audio.device_id;
} else if (!request->controls.video.device_id.empty()) {
capture_device_id = request->controls.video.device_id;
} else {
return false;
}
WebContentsMediaCaptureId web_id;
bool has_valid_device_id =
WebContentsMediaCaptureId::Parse(capture_device_id, &web_id);
if (!has_valid_device_id ||
(request->audio_type() != MEDIA_TAB_AUDIO_CAPTURE &&
request->audio_type() != MEDIA_NO_SERVICE) ||
(request->video_type() != MEDIA_TAB_VIDEO_CAPTURE &&
request->video_type() != MEDIA_NO_SERVICE)) {
return false;
}
web_id.disable_local_echo = request->controls.disable_local_echo;
request->tab_capture_device_id = web_id.ToString();
request->CreateTabCaptureUIRequest(web_id.render_process_id,
web_id.main_render_frame_id);
DVLOG(3) << "SetupTabCaptureRequest "
<< ", {capture_device_id = " << capture_device_id << "}"
<< ", {target_render_process_id = " << web_id.render_process_id
<< "}"
<< ", {target_render_frame_id = " << web_id.main_render_frame_id
<< "}";
return true;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: print_ipcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 6), 4);
ND_PRINT((ndo, ": src %s, dst %s",
ipaddr_string(ndo, p + 2),
ipaddr_string(ndo, p + 6)));
break;
case IPCPOPT_IPCOMP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
compproto = EXTRACT_16BITS(p+2);
ND_PRINT((ndo, ": %s (0x%02x):",
tok2str(ipcpopt_compproto_values, "Unknown", compproto),
compproto));
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case IPCPOPT_IPCOMP_HDRCOMP:
if (len < IPCPOPT_IPCOMP_MINLEN) {
ND_PRINT((ndo, " (length bogus, should be >= %u)",
IPCPOPT_IPCOMP_MINLEN));
return 0;
}
ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN);
ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12)));
/* suboptions present ? */
if (len > IPCPOPT_IPCOMP_MINLEN) {
ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN;
p += IPCPOPT_IPCOMP_MINLEN;
ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen));
while (ipcomp_subopttotallen >= 2) {
ND_TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u",
tok2str(ipcpopt_compproto_subopt_values,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen));
ipcomp_subopttotallen -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ipcp]"));
return 0;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: archive_read_support_format_xar(struct archive *_a)
{
struct archive_read *a = (struct archive_read *)_a;
archive_check_magic(_a, ARCHIVE_READ_MAGIC,
ARCHIVE_STATE_NEW, "archive_read_support_format_xar");
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Xar not supported on this platform");
return (ARCHIVE_WARN);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WT_Interpolate (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
const EAS_SAMPLE *loopEnd;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pOutputBuffer = pWTIntFrame->pAudioBuffer;
loopEnd = (const EAS_SAMPLE*) pWTVoice->loopEnd + 1;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
/*lint -e{713} truncation is OK */
phaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->frame.phaseIncrement;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* check for loop end */
acc0 = (EAS_I32) (pSamples - loopEnd);
if (acc0 >= 0)
pSamples = (const EAS_SAMPLE*) pWTVoice->loopStart + acc0;
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WebstoreBindings::WebstoreBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("Install",
base::Bind(&WebstoreBindings::Install, base::Unretained(this)));
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void l2cap_conn_del(struct hci_conn *hcon, int err)
{
struct l2cap_conn *conn = hcon->l2cap_data;
struct sock *sk;
if (!conn)
return;
BT_DBG("hcon %p conn %p, err %d", hcon, conn, err);
kfree_skb(conn->rx_skb);
/* Kill channels */
while ((sk = conn->chan_list.head)) {
bh_lock_sock(sk);
l2cap_chan_del(sk, err);
bh_unlock_sock(sk);
l2cap_sock_kill(sk);
}
if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT)
del_timer_sync(&conn->info_timer);
hcon->l2cap_data = NULL;
kfree(conn);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static unsigned long change_prot_numa(struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
return 0;
}
CWE ID: CWE-388
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ChromeRenderProcessObserver::OnSetTcmallocHeapProfiling(
bool profiling, const std::string& filename_prefix) {
#if !defined(OS_WIN)
if (profiling)
HeapProfilerStart(filename_prefix.c_str());
else
HeapProfilerStop();
#endif
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: FFmpegVideoDecoder::FFmpegVideoDecoder(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
: task_runner_(task_runner), state_(kUninitialized) {}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool asn1_write_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob)
{
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(num));
asn1_write(data, blob->data, blob->length);
asn1_pop_tag(data);
return !data->has_error;
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length,
uint32 width, uint16 spp,
struct dump_opts *dump)
{
int i, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
int32 bytes_read = 0;
uint16 bps, nstrips, planar, strips_per_sample;
uint32 src_rowsize, dst_rowsize, rows_processed, rps;
uint32 rows_this_strip = 0;
tsample_t s;
tstrip_t strip;
tsize_t scanlinesize = TIFFScanlineSize(in);
tsize_t stripsize = TIFFStripSize(in);
unsigned char *srcbuffs[MAX_SAMPLES];
unsigned char *buff = NULL;
unsigned char *dst = NULL;
if (obuf == NULL)
{
TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument");
return (0);
}
memset (srcbuffs, '\0', sizeof(srcbuffs));
TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps);
if (rps > length)
rps = length;
bytes_per_sample = (bps + 7) / 8;
bytes_per_pixel = ((bps * spp) + 7) / 8;
if (bytes_per_pixel < (bytes_per_sample + 1))
shift_width = bytes_per_pixel;
else
shift_width = bytes_per_sample + 1;
src_rowsize = ((bps * width) + 7) / 8;
dst_rowsize = ((bps * width * spp) + 7) / 8;
dst = obuf;
if ((dump->infile != NULL) && (dump->level == 3))
{
dump_info (dump->infile, dump->format, "",
"Image width %d, length %d, Scanline size, %4d bytes",
width, length, scanlinesize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d, Shift width %d",
bps, spp, shift_width);
}
/* Libtiff seems to assume/require that data for separate planes are
* written one complete plane after another and not interleaved in any way.
* Multiple scanlines and possibly strips of the same plane must be
* written before data for any other plane.
*/
nstrips = TIFFNumberOfStrips(in);
strips_per_sample = nstrips /spp;
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
srcbuffs[s] = NULL;
buff = _TIFFmalloc(stripsize);
if (!buff)
{
TIFFError ("readSeparateStripsIntoBuffer",
"Unable to allocate strip read buffer for sample %d", s);
for (i = 0; i < s; i++)
_TIFFfree (srcbuffs[i]);
return 0;
}
srcbuffs[s] = buff;
}
rows_processed = 0;
for (j = 0; (j < strips_per_sample) && (result == 1); j++)
{
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
strip = (s * strips_per_sample) + j;
bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize);
rows_this_strip = bytes_read / src_rowsize;
if (bytes_read < 0 && !ignore)
{
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu for sample %d",
(unsigned long) strip, s + 1);
result = 0;
break;
}
#ifdef DEVELMODE
TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d",
strip, bytes_read, rows_this_strip, shift_width);
#endif
}
if (rps > rows_this_strip)
rps = rows_this_strip;
dst = obuf + (dst_rowsize * rows_processed);
if ((bps % 8) == 0)
{
if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
}
else
{
switch (shift_width)
{
case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
case 4:
case 5:
case 6:
case 7:
case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps,
spp, bps, dump->infile,
dump->format, dump->level))
{
result = 0;
break;
}
break;
default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps);
result = 0;
break;
}
}
if ((rows_processed + rps) > length)
{
rows_processed = length;
rps = length - rows_processed;
}
else
rows_processed += rps;
}
/* free any buffers allocated for each plane or scanline and
* any temporary buffers
*/
for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++)
{
buff = srcbuffs[s];
if (buff != NULL)
_TIFFfree(buff);
}
return (result);
} /* end readSeparateStripsIntoBuffer */
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int irda_open_lsap(struct irda_sock *self, int pid)
{
notify_t notify;
if (self->lsap) {
net_warn_ratelimited("%s(), busy!\n", __func__);
return -EBUSY;
}
/* Initialize callbacks to be used by the IrDA stack */
irda_notify_init(¬ify);
notify.udata_indication = irda_data_indication;
notify.instance = self;
strncpy(notify.name, "Ultra", NOTIFY_MAX_NAME);
self->lsap = irlmp_open_lsap(LSAP_CONNLESS, ¬ify, pid);
if (self->lsap == NULL) {
pr_debug("%s(), Unable to allocate LSAP!\n", __func__);
return -ENOMEM;
}
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int lz4hc_compress_crypto(struct crypto_tfm *tfm, const u8 *src,
unsigned int slen, u8 *dst, unsigned int *dlen)
{
struct lz4hc_ctx *ctx = crypto_tfm_ctx(tfm);
size_t tmp_len = *dlen;
int err;
err = lz4hc_compress(src, slen, dst, &tmp_len, ctx->lz4hc_comp_mem);
if (err < 0)
return -EINVAL;
*dlen = tmp_len;
return 0;
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: P2PQuicStreamTest()
: connection_(
new quic::test::MockQuicConnection(&connection_helper_,
&alarm_factory_,
quic::Perspective::IS_CLIENT)),
session_(connection_) {
session_.Initialize();
stream_ = new P2PQuicStreamImpl(kStreamId, &session_);
stream_->SetDelegate(&delegate_);
session_.ActivateStream(std::unique_ptr<P2PQuicStreamImpl>(stream_));
connection_helper_.AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: void WebContext::setAllowedExtraUrlSchemes(const QStringList& schemes) {
std::set<std::string> set;
for (int i = 0; i < schemes.size(); ++i) {
set.insert(base::ToLowerASCII(schemes.at(i).toStdString()));
}
delegate_->SetAllowedExtraURLSchemes(set);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int em_loop(struct x86_emulate_ctxt *ctxt)
{
register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -1);
if ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) &&
(ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))
jmp_rel(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: sysapi_translate_arch( const char *machine, const char *)
{
char tmp[64];
char *tmparch;
#if defined(AIX)
/* AIX machines have a ton of different models encoded into the uname
structure, so go to some other function to decode and group the
architecture together */
struct utsname buf;
if( uname(&buf) < 0 ) {
return NULL;
}
return( get_aix_arch( &buf ) );
#elif defined(HPUX)
return( get_hpux_arch( ) );
#else
if( !strcmp(machine, "alpha") ) {
sprintf( tmp, "ALPHA" );
}
else if( !strcmp(machine, "i86pc") ) {
sprintf( tmp, "INTEL" );
}
else if( !strcmp(machine, "i686") ) {
sprintf( tmp, "INTEL" );
}
else if( !strcmp(machine, "i586") ) {
sprintf( tmp, "INTEL" );
}
else if( !strcmp(machine, "i486") ) {
sprintf( tmp, "INTEL" );
}
else if( !strcmp(machine, "i386") ) { //LDAP entry
#if defined(Darwin)
/* Mac OS X often claims to be i386 in uname, even if the
* hardware is x86_64 and the OS can run 64-bit binaries.
* We'll base our architecture name on the default build
* target for gcc. In 10.5 and earlier, that's i386.
* On 10.6, it's x86_64.
* The value we're querying is the kernel version.
* 10.6 kernels have a version that starts with "10."
* Older versions have a lower first number.
*/
int ret;
char val[32];
size_t len = sizeof(val);
/* assume x86 */
sprintf( tmp, "INTEL" );
ret = sysctlbyname("kern.osrelease", &val, &len, NULL, 0);
if (ret == 0 && strncmp(val, "10.", 3) == 0) {
/* but we could be proven wrong */
sprintf( tmp, "X86_64" );
}
#else
sprintf( tmp, "INTEL" );
#endif
}
else if( !strcmp(machine, "ia64") ) {
sprintf( tmp, "IA64" );
}
else if( !strcmp(machine, "x86_64") ) {
sprintf( tmp, "X86_64" );
}
else if( !strcmp(machine, "amd64") ) {
sprintf( tmp, "X86_64" );
}
else if( !strcmp(machine, "sun4u") ) {
sprintf( tmp, "SUN4u" );
}
else if( !strcmp(machine, "sun4m") ) {
sprintf( tmp, "SUN4x" );
}
else if( !strcmp(machine, "sun4c") ) {
sprintf( tmp, "SUN4x" );
}
else if( !strcmp(machine, "sparc") ) { //LDAP entry
sprintf( tmp, "SUN4x" );
}
else if( !strcmp(machine, "Power Macintosh") ) { //LDAP entry
sprintf( tmp, "PPC" );
}
else if( !strcmp(machine, "ppc") ) {
sprintf( tmp, "PPC" );
}
else if( !strcmp(machine, "ppc32") ) {
sprintf( tmp, "PPC" );
}
else if( !strcmp(machine, "ppc64") ) {
sprintf( tmp, "PPC64" );
}
else {
sprintf( tmp, machine );
}
tmparch = strdup( tmp );
if( !tmparch ) {
EXCEPT( "Out of memory!" );
}
return( tmparch );
#endif /* if HPUX else */
}
CWE ID: CWE-134
Target: 1
Example 2:
Code: fbStore_r8g8b8 (FbBits *bits, const CARD32 *values, int x, int width, miIndexedPtr indexed)
{
int i;
CARD8 *pixel = ((CARD8 *) bits) + 3*x;
for (i = 0; i < width; ++i) {
Store24(pixel, READ(values + i));
pixel += 3;
}
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool edge_tx_empty(struct usb_serial_port *port)
{
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
int ret;
ret = tx_active(edge_port);
if (ret > 0)
return false;
return true;
}
CWE ID: CWE-191
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zval **retval;
char *key;
uint len;
long index;
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!offset) {
return &EG(uninitialized_zval_ptr);
}
if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return &EG(error_zval_ptr);;
}
switch (Z_TYPE_P(offset)) {
case IS_STRING:
key = Z_STRVAL_P(offset);
len = Z_STRLEN_P(offset) + 1;
string_offest:
if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined index: %s", key);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE,"Undefined index: %s", key);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
case IS_NULL:
key = "";
len = 1;
goto string_offest;
case IS_RESOURCE:
zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset));
case IS_DOUBLE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
default:
zend_error(E_WARNING, "Illegal offset type");
return (type == BP_VAR_W || type == BP_VAR_RW) ?
&EG(error_zval_ptr) : &EG(uninitialized_zval_ptr);
}
} /* }}} */
CWE ID: CWE-20
Target: 1
Example 2:
Code: cssp_encode_tspasswordcreds(char *username, char *password, char *domain)
{
STREAM out, h1, h2;
struct stream tmp = { 0 };
struct stream message = { 0 };
memset(&tmp, 0, sizeof(tmp));
memset(&message, 0, sizeof(message));
s_realloc(&tmp, 512 * 4);
s_reset(&tmp);
out_utf16s(&tmp, domain);
s_mark_end(&tmp);
h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2);
s_realloc(&message, s_length(&message) + s_length(h1));
out_uint8p(&message, h1->data, s_length(h1));
s_mark_end(&message);
s_free(h2);
s_free(h1);
s_reset(&tmp);
out_utf16s(&tmp, username);
s_mark_end(&tmp);
h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2);
s_realloc(&message, s_length(&message) + s_length(h1));
out_uint8p(&message, h1->data, s_length(h1));
s_mark_end(&message);
s_free(h2);
s_free(h1);
s_reset(&tmp);
out_utf16s(&tmp, password);
s_mark_end(&tmp);
h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp);
h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2);
s_realloc(&message, s_length(&message) + s_length(h1));
out_uint8p(&message, h1->data, s_length(h1));
s_mark_end(&message);
s_free(h2);
s_free(h1);
out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message);
xfree(tmp.data);
xfree(message.data);
return out;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
searchpath_t *sp;
qboolean havepak;
char *origpos = neededpaks;
int i;
if (!fs_numServerReferencedPaks)
return qfalse; // Server didn't send any pack information along
*neededpaks = 0;
for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ )
{
havepak = qfalse;
if(FS_idPak(fs_serverReferencedPakNames[i], BASEGAME, NUM_ID_PAKS)
#ifndef STANDALONE
|| FS_idPak(fs_serverReferencedPakNames[i], BASETA, NUM_TA_PAKS)
#endif
)
{
continue;
}
if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
{
Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
continue;
}
for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
havepak = qtrue; // This is it!
break;
}
}
if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
if (dlstring)
{
origpos += strlen(origpos);
Q_strcat( neededpaks, len, "@");
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
Q_strcat( neededpaks, len, "@");
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
char st[MAX_ZPATH];
Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
Q_strcat( neededpaks, len, st );
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
}
if(strlen(origpos) + (origpos - neededpaks) >= len - 1)
{
*origpos = '\0';
break;
}
}
else
{
Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
Q_strcat( neededpaks, len, ".pk3" );
if ( FS_SV_FileExists( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
{
Q_strcat( neededpaks, len, " (local file exists with wrong checksum)");
}
Q_strcat( neededpaks, len, "\n");
}
}
}
if ( *neededpaks ) {
return qtrue;
}
return qfalse; // We have them all
}
CWE ID: CWE-269
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ip_build_and_send_pkt(struct sk_buff *skb, struct sock *sk,
__be32 saddr, __be32 daddr, struct ip_options *opt)
{
struct inet_sock *inet = inet_sk(sk);
struct rtable *rt = skb_rtable(skb);
struct iphdr *iph;
/* Build the IP header. */
skb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen : 0));
skb_reset_network_header(skb);
iph = ip_hdr(skb);
iph->version = 4;
iph->ihl = 5;
iph->tos = inet->tos;
if (ip_dont_fragment(sk, &rt->dst))
iph->frag_off = htons(IP_DF);
else
iph->frag_off = 0;
iph->ttl = ip_select_ttl(inet, &rt->dst);
iph->daddr = rt->rt_dst;
iph->saddr = rt->rt_src;
iph->protocol = sk->sk_protocol;
ip_select_ident(iph, &rt->dst, sk);
if (opt && opt->optlen) {
iph->ihl += opt->optlen>>2;
ip_options_build(skb, opt, daddr, rt, 0);
}
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
/* Send it out. */
return ip_local_out(skb);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static void voidMethodElementArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
TestObjectPythonV8Internal::voidMethodElementArgMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const AtomicString& connectionStateToString(
WebPresentationConnectionState state) {
DEFINE_STATIC_LOCAL(const AtomicString, connectingValue, ("connecting"));
DEFINE_STATIC_LOCAL(const AtomicString, connectedValue, ("connected"));
DEFINE_STATIC_LOCAL(const AtomicString, closedValue, ("closed"));
DEFINE_STATIC_LOCAL(const AtomicString, terminatedValue, ("terminated"));
switch (state) {
case WebPresentationConnectionState::Connecting:
return connectingValue;
case WebPresentationConnectionState::Connected:
return connectedValue;
case WebPresentationConnectionState::Closed:
return closedValue;
case WebPresentationConnectionState::Terminated:
return terminatedValue;
}
ASSERT_NOT_REACHED();
return terminatedValue;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: cmsBool CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* NamedColorList,
const char* Name,
cmsUInt16Number PCS[3], cmsUInt16Number Colorant[cmsMAXCHANNELS])
{
cmsUInt32Number i;
if (NamedColorList == NULL) return FALSE;
if (NamedColorList ->nColors + 1 > NamedColorList ->Allocated) {
if (!GrowNamedColorList(NamedColorList)) return FALSE;
}
for (i=0; i < NamedColorList ->ColorantCount; i++)
NamedColorList ->List[NamedColorList ->nColors].DeviceColorant[i] = Colorant == NULL? 0 : Colorant[i];
for (i=0; i < 3; i++)
NamedColorList ->List[NamedColorList ->nColors].PCS[i] = PCS == NULL ? 0 : PCS[i];
if (Name != NULL) {
strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name,
sizeof(NamedColorList ->List[NamedColorList ->nColors].Name));
NamedColorList ->List[NamedColorList ->nColors].Name[cmsMAX_PATH-1] = 0;
}
else
NamedColorList ->List[NamedColorList ->nColors].Name[0] = 0;
NamedColorList ->nColors++;
return TRUE;
}
CWE ID:
Target: 1
Example 2:
Code: void GesturePoint::UpdateForScroll() {
first_touch_position_ = last_touch_position_;
first_touch_time_ = last_touch_time_;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FillMiscNavigationParams(const CommonNavigationParams& common_params,
const CommitNavigationParams& commit_params,
blink::WebNavigationParams* navigation_params) {
navigation_params->navigation_timings = BuildNavigationTimings(
common_params.navigation_start, commit_params.navigation_timing,
common_params.input_start);
navigation_params->is_user_activated =
commit_params.was_activated == WasActivatedOption::kYes;
if (commit_params.origin_to_commit) {
navigation_params->origin_to_commit =
commit_params.origin_to_commit.value();
}
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
size_t ssh1keylen, rlen, slen, ilen, olen;
int r;
u_int ssh1cipher = 0;
if (!compat20) {
if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
(r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
(r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
(r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
(r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
return r;
if (ssh1cipher > INT_MAX)
return SSH_ERR_KEY_UNKNOWN_CIPHER;
ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
(int)ssh1cipher);
if (cipher_get_keyiv_len(state->send_context) != (int)slen ||
cipher_get_keyiv_len(state->receive_context) != (int)rlen)
return SSH_ERR_INVALID_FORMAT;
if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 ||
(r = cipher_set_keyiv(state->receive_context, ivin)) != 0)
return r;
} else {
if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
(r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
(r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
(r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
(r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
(r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
(r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
(r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
(r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
(r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
(r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
(r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
(r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
return r;
/*
* We set the time here so that in post-auth privsep slave we
* count from the completion of the authentication.
*/
state->rekey_time = monotime();
/* XXX ssh_set_newkeys overrides p_read.packets? XXX */
if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
(r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
return r;
}
if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
(r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
return r;
if (cipher_get_keycontext(state->send_context, NULL) != (int)slen ||
cipher_get_keycontext(state->receive_context, NULL) != (int)rlen)
return SSH_ERR_INVALID_FORMAT;
cipher_set_keycontext(state->send_context, keyout);
cipher_set_keycontext(state->receive_context, keyin);
if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 ||
(r = ssh_packet_set_postauth(ssh)) != 0)
return r;
sshbuf_reset(state->input);
sshbuf_reset(state->output);
if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
(r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
(r = sshbuf_put(state->input, input, ilen)) != 0 ||
(r = sshbuf_put(state->output, output, olen)) != 0)
return r;
if (sshbuf_len(m))
return SSH_ERR_INVALID_FORMAT;
debug3("%s: done", __func__);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void PPB_Flash_MessageLoop_Impl::Quit() { InternalQuit(PP_OK); }
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: error::Error GLES2DecoderImpl::HandleReadPixels(
uint32 immediate_data_size, const gles2::ReadPixels& c) {
GLint x = c.x;
GLint y = c.y;
GLsizei width = c.width;
GLsizei height = c.height;
GLenum format = c.format;
GLenum type = c.type;
if (width < 0 || height < 0) {
SetGLError(GL_INVALID_VALUE, "glReadPixels", "dimensions < 0");
return error::kNoError;
}
typedef gles2::ReadPixels::Result Result;
uint32 pixels_size;
if (!GLES2Util::ComputeImageDataSizes(
width, height, format, type, pack_alignment_, &pixels_size, NULL, NULL)) {
return error::kOutOfBounds;
}
void* pixels = GetSharedMemoryAs<void*>(
c.pixels_shm_id, c.pixels_shm_offset, pixels_size);
Result* result = GetSharedMemoryAs<Result*>(
c.result_shm_id, c.result_shm_offset, sizeof(*result));
if (!pixels || !result) {
return error::kOutOfBounds;
}
if (!validators_->read_pixel_format.IsValid(format)) {
SetGLErrorInvalidEnum("glReadPixels", format, "format");
return error::kNoError;
}
if (!validators_->pixel_type.IsValid(type)) {
SetGLErrorInvalidEnum("glReadPixels", type, "type");
return error::kNoError;
}
if (width == 0 || height == 0) {
return error::kNoError;
}
gfx::Size max_size = GetBoundReadFrameBufferSize();
GLint max_x;
GLint max_y;
if (!SafeAdd(x, width, &max_x) || !SafeAdd(y, height, &max_y)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels", "dimensions out of range");
return error::kNoError;
}
if (!CheckBoundFramebuffersValid("glReadPixels")) {
return error::kNoError;
}
CopyRealGLErrorsToWrapper();
ScopedResolvedFrameBufferBinder binder(this, false, true);
if (x < 0 || y < 0 || max_x > max_size.width() || max_y > max_size.height()) {
uint32 temp_size;
uint32 unpadded_row_size;
uint32 padded_row_size;
if (!GLES2Util::ComputeImageDataSizes(
width, 2, format, type, pack_alignment_, &temp_size,
&unpadded_row_size, &padded_row_size)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels", "dimensions out of range");
return error::kNoError;
}
GLint dest_x_offset = std::max(-x, 0);
uint32 dest_row_offset;
if (!GLES2Util::ComputeImageDataSizes(
dest_x_offset, 1, format, type, pack_alignment_, &dest_row_offset, NULL,
NULL)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels", "dimensions out of range");
return error::kNoError;
}
int8* dst = static_cast<int8*>(pixels);
GLint read_x = std::max(0, x);
GLint read_end_x = std::max(0, std::min(max_size.width(), max_x));
GLint read_width = read_end_x - read_x;
for (GLint yy = 0; yy < height; ++yy) {
GLint ry = y + yy;
memset(dst, 0, unpadded_row_size);
if (ry >= 0 && ry < max_size.height() && read_width > 0) {
glReadPixels(
read_x, ry, read_width, 1, format, type, dst + dest_row_offset);
}
dst += padded_row_size;
}
} else {
glReadPixels(x, y, width, height, format, type, pixels);
}
GLenum error = PeekGLError();
if (error == GL_NO_ERROR) {
*result = true;
GLenum read_format = GetBoundReadFrameBufferInternalFormat();
uint32 channels_exist = GLES2Util::GetChannelsForFormat(read_format);
if ((channels_exist & 0x0008) == 0 &&
!feature_info_->feature_flags().disable_workarounds) {
uint32 temp_size;
uint32 unpadded_row_size;
uint32 padded_row_size;
if (!GLES2Util::ComputeImageDataSizes(
width, 2, format, type, pack_alignment_, &temp_size,
&unpadded_row_size, &padded_row_size)) {
SetGLError(GL_INVALID_VALUE, "glReadPixels", "dimensions out of range");
return error::kNoError;
}
if (type != GL_UNSIGNED_BYTE) {
SetGLError(
GL_INVALID_OPERATION, "glReadPixels",
"unsupported readPixel format");
return error::kNoError;
}
switch (format) {
case GL_RGBA:
case GL_BGRA_EXT:
case GL_ALPHA: {
int offset = (format == GL_ALPHA) ? 0 : 3;
int step = (format == GL_ALPHA) ? 1 : 4;
uint8* dst = static_cast<uint8*>(pixels) + offset;
for (GLint yy = 0; yy < height; ++yy) {
uint8* end = dst + unpadded_row_size;
for (uint8* d = dst; d < end; d += step) {
*d = 255;
}
dst += padded_row_size;
}
break;
}
default:
break;
}
}
}
return error::kNoError;
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PrintPreviewMessageHandler::PrintPreviewMessageHandler(
WebContents* web_contents)
: content::WebContentsObserver(web_contents) {
DCHECK(web_contents);
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static int is_good_ext(struct usbtest_dev *tdev, u8 *buf)
{
struct usb_ext_cap_descriptor *ext;
u32 attr;
ext = (struct usb_ext_cap_descriptor *) buf;
if (ext->bLength != USB_DT_USB_EXT_CAP_SIZE) {
ERROR(tdev, "bogus usb 2.0 extension descriptor length\n");
return 0;
}
attr = le32_to_cpu(ext->bmAttributes);
/* bits[1:15] is used and others are reserved */
if (attr & ~0xfffe) { /* reserved == 0 */
ERROR(tdev, "reserved bits set\n");
return 0;
}
return 1;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int get_value(AVIOContext *pb, int type, int type2_size)
{
switch (type) {
case 2:
return (type2_size == 32) ? avio_rl32(pb) : avio_rl16(pb);
case 3:
return avio_rl32(pb);
case 4:
return avio_rl64(pb);
case 5:
return avio_rl16(pb);
default:
return INT_MIN;
}
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: FileStream::FileStream(base::File file,
const scoped_refptr<base::TaskRunner>& task_runner)
: context_(base::MakeUnique<Context>(std::move(file), task_runner)) {}
CWE ID: CWE-311
Target: 1
Example 2:
Code: static inline void frag_kfree_skb(struct sk_buff *skb, unsigned int *work)
{
if (work)
*work -= skb->truesize;
atomic_sub(skb->truesize, &nf_init_frags.mem);
nf_skb_free(skb);
kfree_skb(skb);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithOptionalStringIsNullString(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());
const String& str(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsNullString).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsNullString).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->methodWithOptionalStringIsNullString(str);
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void display_cert_info(struct Curl_easy *data,
CERTCertificate *cert)
{
char *subject, *issuer, *common_name;
PRExplodedTime printableTime;
char timeString[256];
PRTime notBefore, notAfter;
subject = CERT_NameToAscii(&cert->subject);
issuer = CERT_NameToAscii(&cert->issuer);
common_name = CERT_GetCommonName(&cert->subject);
infof(data, "\tsubject: %s\n", subject);
CERT_GetCertTimes(cert, ¬Before, ¬After);
PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
infof(data, "\tstart date: %s\n", timeString);
PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
infof(data, "\texpire date: %s\n", timeString);
infof(data, "\tcommon name: %s\n", common_name);
infof(data, "\tissuer: %s\n", issuer);
PR_Free(subject);
PR_Free(issuer);
PR_Free(common_name);
}
CWE ID: CWE-287
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGL2RenderingContextBase::bindVertexArray(
WebGLVertexArrayObject* vertex_array) {
if (isContextLost())
return;
if (vertex_array &&
(vertex_array->IsDeleted() || !vertex_array->Validate(nullptr, this))) {
SynthesizeGLError(GL_INVALID_OPERATION, "bindVertexArray",
"invalid vertexArray");
return;
}
if (vertex_array && !vertex_array->IsDefaultObject() &&
vertex_array->Object()) {
ContextGL()->BindVertexArrayOES(ObjectOrZero(vertex_array));
vertex_array->SetHasEverBeenBound();
SetBoundVertexArrayObject(vertex_array);
} else {
ContextGL()->BindVertexArrayOES(0);
SetBoundVertexArrayObject(nullptr);
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int btrfs_add_link(struct btrfs_trans_handle *trans,
struct inode *parent_inode, struct inode *inode,
const char *name, int name_len, int add_backref, u64 index)
{
int ret = 0;
struct btrfs_key key;
struct btrfs_root *root = BTRFS_I(parent_inode)->root;
u64 ino = btrfs_ino(inode);
u64 parent_ino = btrfs_ino(parent_inode);
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
} else {
key.objectid = ino;
btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
key.offset = 0;
}
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
key.objectid, root->root_key.objectid,
parent_ino, index, name, name_len);
} else if (add_backref) {
ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
parent_ino, index);
}
/* Nothing to clean up yet */
if (ret)
return ret;
ret = btrfs_insert_dir_item(trans, root, name, name_len,
parent_inode, &key,
btrfs_inode_type(inode), index);
if (ret == -EEXIST)
goto fail_dir_item;
else if (ret) {
btrfs_abort_transaction(trans, root, ret);
return ret;
}
btrfs_i_size_write(parent_inode, parent_inode->i_size +
name_len * 2);
inode_inc_iversion(parent_inode);
parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode(trans, root, parent_inode);
if (ret)
btrfs_abort_transaction(trans, root, ret);
return ret;
fail_dir_item:
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
u64 local_index;
int err;
err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
key.objectid, root->root_key.objectid,
parent_ino, &local_index, name, name_len);
} else if (add_backref) {
u64 local_index;
int err;
err = btrfs_del_inode_ref(trans, root, name, name_len,
ino, parent_ino, &local_index);
}
return ret;
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: static int skcipher_next_copy(struct skcipher_walk *walk)
{
struct skcipher_walk_buffer *p;
u8 *tmp = walk->page;
skcipher_map_src(walk);
memcpy(tmp, walk->src.virt.addr, walk->nbytes);
skcipher_unmap_src(walk);
walk->src.virt.addr = tmp;
walk->dst.virt.addr = tmp;
if (!(walk->flags & SKCIPHER_WALK_PHYS))
return 0;
p = kmalloc(sizeof(*p), skcipher_walk_gfp(walk));
if (!p)
return -ENOMEM;
p->data = walk->page;
p->len = walk->nbytes;
skcipher_queue_write(walk, p);
if (offset_in_page(walk->page) + walk->nbytes + walk->stride >
PAGE_SIZE)
walk->page = NULL;
else
walk->page += walk->nbytes;
return 0;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void scsi_free_request(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
qemu_vfree(r->iov.iov_base);
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: store_init(png_store* ps)
{
memset(ps, 0, sizeof *ps);
init_exception_context(&ps->exception_context);
store_pool_init(ps, &ps->read_memory_pool);
store_pool_init(ps, &ps->write_memory_pool);
ps->verbose = 0;
ps->treat_warnings_as_errors = 0;
ps->expect_error = 0;
ps->expect_warning = 0;
ps->saw_warning = 0;
ps->speed = 0;
ps->progressive = 0;
ps->validated = 0;
ps->nerrors = ps->nwarnings = 0;
ps->pread = NULL;
ps->piread = NULL;
ps->saved = ps->current = NULL;
ps->next = NULL;
ps->readpos = 0;
ps->image = NULL;
ps->cb_image = 0;
ps->cb_row = 0;
ps->image_h = 0;
ps->pwrite = NULL;
ps->piwrite = NULL;
ps->writepos = 0;
ps->new.prev = NULL;
ps->palette = NULL;
ps->npalette = 0;
ps->noptions = 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) {
clock_for_test_ = std::move(clock);
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param) {
case EQ_PARAM_CUR_PRESET:
preset = (int32_t)(*(uint16_t *)pValue);
if ((preset >= EqualizerGetNumPresets())||(preset < 0)) {
status = -EINVAL;
break;
}
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
if (band >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
EqualizerSetBandLevel(pContext, band, level);
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
if ((int)p[0] >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
if (p[0] >= 0) {
EqualizerSetPreset(pContext, (int)p[0]);
} else {
if ((int)p[1] != FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
}
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_setParameter */
CWE ID: CWE-200
Target: 1
Example 2:
Code: static const char *valid_domain_label(const char *label)
{
unsigned char ch;
unsigned pos = 0;
for (;;) {
ch = *label;
if ((ch|0x20) < 'a' || (ch|0x20) > 'z') {
if (ch < '0' || ch > '9') {
if (ch == '\0' || ch == '.')
return label;
/* DNS allows only '-', but we are more permissive */
if (ch != '-' && ch != '_')
return NULL;
}
}
label++;
pos++;
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int cuse_parse_devinfo(char *p, size_t len, struct cuse_devinfo *devinfo)
{
char *end = p + len;
char *uninitialized_var(key), *uninitialized_var(val);
int rc;
while (true) {
rc = cuse_parse_one(&p, end, &key, &val);
if (rc < 0)
return rc;
if (!rc)
break;
if (strcmp(key, "DEVNAME") == 0)
devinfo->name = val;
else
printk(KERN_WARNING "CUSE: unknown device info \"%s\"\n",
key);
}
if (!devinfo->name || !strlen(devinfo->name)) {
printk(KERN_ERR "CUSE: DEVNAME unspecified\n");
return -EINVAL;
}
return 0;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void SendHandwritingStroke(const HandwritingStroke& stroke) {
if (!initialized_successfully_)
return;
chromeos::SendHandwritingStroke(input_method_status_connection_, stroke);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void GLES2Implementation::ReadPixels(GLint xoffset,
GLint yoffset,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type,
void* pixels) {
const char* func_name = "glReadPixels";
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glReadPixels(" << xoffset << ", "
<< yoffset << ", " << width << ", " << height << ", "
<< GLES2Util::GetStringReadPixelFormat(format) << ", "
<< GLES2Util::GetStringPixelType(type) << ", "
<< static_cast<const void*>(pixels) << ")");
if (width < 0 || height < 0) {
SetGLError(GL_INVALID_VALUE, func_name, "dimensions < 0");
return;
}
if (pack_skip_pixels_ + width >
(pack_row_length_ ? pack_row_length_ : width)) {
SetGLError(GL_INVALID_OPERATION, func_name,
"invalid pack params combination");
return;
}
TRACE_EVENT0("gpu", "GLES2::ReadPixels");
typedef cmds::ReadPixels::Result Result;
uint32_t size;
uint32_t unpadded_row_size;
uint32_t padded_row_size;
uint32_t skip_size;
PixelStoreParams params;
params.alignment = pack_alignment_;
params.row_length = pack_row_length_;
params.skip_pixels = pack_skip_pixels_;
params.skip_rows = pack_skip_rows_;
if (!GLES2Util::ComputeImageDataSizesES3(
width, height, 1, format, type, params, &size, &unpadded_row_size,
&padded_row_size, &skip_size, nullptr)) {
SetGLError(GL_INVALID_VALUE, func_name, "size too large.");
return;
}
if (bound_pixel_pack_buffer_) {
base::CheckedNumeric<GLuint> offset = ToGLuint(pixels);
offset += skip_size;
if (!offset.IsValid()) {
SetGLError(GL_INVALID_VALUE, func_name, "skip size too large.");
return;
}
helper_->ReadPixels(xoffset, yoffset, width, height, format, type, 0,
offset.ValueOrDefault(0), 0, 0, false);
InvalidateReadbackBufferShadowDataCHROMIUM(bound_pixel_pack_buffer_);
CheckGLError();
return;
}
uint32_t service_padded_row_size = 0;
if (pack_row_length_ > 0 && pack_row_length_ != width) {
if (!GLES2Util::ComputeImagePaddedRowSize(
width, format, type, pack_alignment_, &service_padded_row_size)) {
SetGLError(GL_INVALID_VALUE, func_name, "size too large.");
return;
}
} else {
service_padded_row_size = padded_row_size;
}
if (bound_pixel_pack_transfer_buffer_id_) {
if (pack_row_length_ > 0 || pack_skip_pixels_ > 0 || pack_skip_rows_ > 0) {
SetGLError(GL_INVALID_OPERATION, func_name,
"No ES3 pack parameters with pixel pack transfer buffer.");
return;
}
DCHECK_EQ(0u, skip_size);
GLuint offset = ToGLuint(pixels);
BufferTracker::Buffer* buffer = GetBoundPixelTransferBufferIfValid(
bound_pixel_pack_transfer_buffer_id_, func_name, offset, size);
if (buffer && buffer->shm_id() != -1) {
helper_->ReadPixels(xoffset, yoffset, width, height, format, type,
buffer->shm_id(), buffer->shm_offset() + offset, 0, 0,
true);
CheckGLError();
}
return;
}
if (!pixels) {
SetGLError(GL_INVALID_OPERATION, func_name, "pixels = NULL");
return;
}
int8_t* dest = reinterpret_cast<int8_t*>(pixels);
dest += skip_size;
GLsizei remaining_rows = height;
GLint y_index = yoffset;
uint32_t group_size = GLES2Util::ComputeImageGroupSize(format, type);
uint32_t skip_row_bytes = 0;
if (xoffset < 0) {
skip_row_bytes = static_cast<uint32_t>(-xoffset) * group_size;
}
do {
GLsizei desired_size =
remaining_rows == 0 ? 0
: service_padded_row_size * (remaining_rows - 1) +
unpadded_row_size;
ScopedTransferBufferPtr buffer(desired_size, helper_, transfer_buffer_);
if (!buffer.valid()) {
break;
}
GLint num_rows = ComputeNumRowsThatFitInBuffer(
service_padded_row_size, unpadded_row_size, buffer.size(),
remaining_rows);
auto result = GetResultAs<Result>();
if (!result) {
break;
}
result->success = 0; // mark as failed.
result->row_length = 0;
result->num_rows = 0;
helper_->ReadPixels(xoffset, y_index, width, num_rows, format, type,
buffer.shm_id(), buffer.offset(), GetResultShmId(),
result.offset(), false);
WaitForCmd();
if (!result->success) {
break;
}
if (remaining_rows == 0) {
break;
}
const uint8_t* src = static_cast<const uint8_t*>(buffer.address());
if (padded_row_size == unpadded_row_size &&
(pack_row_length_ == 0 || pack_row_length_ == width) &&
result->row_length == width && result->num_rows == num_rows) {
uint32_t copy_size = unpadded_row_size * num_rows;
memcpy(dest, src, copy_size);
dest += copy_size;
} else if (result->row_length > 0 && result->num_rows > 0) {
uint32_t copy_row_size = result->row_length * group_size;
uint32_t copy_last_row_size = copy_row_size;
if (copy_row_size + skip_row_bytes > padded_row_size) {
copy_row_size = padded_row_size - skip_row_bytes;
}
GLint copied_rows = 0;
for (GLint yy = 0; yy < num_rows; ++yy) {
if (y_index + yy >= 0 && copied_rows < result->num_rows) {
if (yy + 1 == num_rows && remaining_rows == num_rows) {
memcpy(dest + skip_row_bytes, src + skip_row_bytes,
copy_last_row_size);
} else {
memcpy(dest + skip_row_bytes, src + skip_row_bytes, copy_row_size);
}
++copied_rows;
}
dest += padded_row_size;
src += service_padded_row_size;
}
DCHECK_EQ(result->num_rows, copied_rows);
}
y_index += num_rows;
remaining_rows -= num_rows;
} while (remaining_rows);
CheckGLError();
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cifs_relock_file(struct cifsFileInfo *cfile)
{
struct cifs_sb_info *cifs_sb = CIFS_SB(cfile->dentry->d_sb);
struct cifsInodeInfo *cinode = CIFS_I(cfile->dentry->d_inode);
struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
int rc = 0;
down_read(&cinode->lock_sem);
if (cinode->can_cache_brlcks) {
/* can cache locks - no need to relock */
up_read(&cinode->lock_sem);
return rc;
}
if (cap_unix(tcon->ses) &&
(CIFS_UNIX_FCNTL_CAP & le64_to_cpu(tcon->fsUnixInfo.Capability)) &&
((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NOPOSIXBRL) == 0))
rc = cifs_push_posix_locks(cfile);
else
rc = tcon->ses->server->ops->push_mand_locks(cfile);
up_read(&cinode->lock_sem);
return rc;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void handle_stdfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr)
{
unsigned long pc = regs->tpc;
unsigned long tstate = regs->tstate;
u32 insn;
u64 value;
u8 freg;
int flag;
struct fpustate *f = FPUSTATE;
if (tstate & TSTATE_PRIV)
die_if_kernel("stdfmna from kernel", regs);
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, sfar);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc) != -EFAULT) {
int asi = decode_asi(insn, regs);
freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
value = 0;
flag = (freg < 32) ? FPRS_DL : FPRS_DU;
if ((asi > ASI_SNFL) ||
(asi < ASI_P))
goto daex;
save_and_clear_fpu();
if (current_thread_info()->fpsaved[0] & flag)
value = *(u64 *)&f->regs[freg];
switch (asi) {
case ASI_P:
case ASI_S: break;
case ASI_PL:
case ASI_SL:
value = __swab64p(&value); break;
default: goto daex;
}
if (put_user (value >> 32, (u32 __user *) sfar) ||
__put_user ((u32)value, (u32 __user *)(sfar + 4)))
goto daex;
} else {
daex:
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, sfar, sfsr);
else
spitfire_data_access_exception(regs, sfsr, sfar);
return;
}
advance(regs);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: hook_search_command (struct t_weechat_plugin *plugin, const char *command)
{
struct t_hook *ptr_hook;
for (ptr_hook = weechat_hooks[HOOK_TYPE_COMMAND]; ptr_hook;
ptr_hook = ptr_hook->next_hook)
{
if (!ptr_hook->deleted
&& (ptr_hook->plugin == plugin)
&& (string_strcasecmp (HOOK_COMMAND(ptr_hook, command), command) == 0))
return ptr_hook;
}
/* command hook not found for plugin */
return NULL;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int net_get(int s, void *arg, int *len)
{
struct net_hdr nh;
int plen;
if (net_read_exact(s, &nh, sizeof(nh)) == -1)
{
return -1;
}
plen = ntohl(nh.nh_len);
if (!(plen <= *len))
printf("PLEN %d type %d len %d\n",
plen, nh.nh_type, *len);
assert(plen <= *len); /* XXX */
*len = plen;
if ((*len) && (net_read_exact(s, arg, *len) == -1))
{
return -1;
}
return nh.nh_type;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PlatformSensorProviderMac::CreateSensorInternal(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
switch (type) {
case mojom::SensorType::AMBIENT_LIGHT: {
scoped_refptr<PlatformSensor> sensor =
new PlatformSensorAmbientLightMac(std::move(mapping), this);
callback.Run(std::move(sensor));
break;
}
case mojom::SensorType::ACCELEROMETER: {
callback.Run(base::MakeRefCounted<PlatformSensorAccelerometerMac>(
std::move(mapping), this));
break;
}
case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES: {
auto fusion_algorithm = std::make_unique<
RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometer>();
PlatformSensorFusion::Create(std::move(mapping), this,
std::move(fusion_algorithm), callback);
break;
}
case mojom::SensorType::RELATIVE_ORIENTATION_QUATERNION: {
auto orientation_quaternion_fusion_algorithm_using_euler_angles =
std::make_unique<
OrientationQuaternionFusionAlgorithmUsingEulerAngles>(
false /* absolute */);
PlatformSensorFusion::Create(
std::move(mapping), this,
std::move(orientation_quaternion_fusion_algorithm_using_euler_angles),
callback);
break;
}
default:
callback.Run(nullptr);
}
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: static void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter)
{
if (iter->tr->allocated_snapshot)
seq_puts(m, "#\n# * Snapshot is allocated *\n#\n");
else
seq_puts(m, "#\n# * Snapshot is freed *\n#\n");
seq_puts(m, "# Snapshot commands:\n");
if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
show_snapshot_main_help(m);
else
show_snapshot_percpu_help(m);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ChromePluginServiceFilter::IsPluginEnabled(
int render_process_id,
int render_view_id,
const void* context,
const GURL& url,
const GURL& policy_url,
webkit::WebPluginInfo* plugin) {
base::AutoLock auto_lock(lock_);
const ProcessDetails* details = GetProcess(render_process_id);
if (details) {
for (size_t i = 0; i < details->overridden_plugins.size(); ++i) {
if (details->overridden_plugins[i].render_view_id == render_view_id &&
(details->overridden_plugins[i].url == url ||
details->overridden_plugins[i].url.is_empty())) {
bool use = details->overridden_plugins[i].plugin.path == plugin->path;
if (!use)
return false;
*plugin = details->overridden_plugins[i].plugin;
break;
}
}
}
ResourceContextMap::iterator prefs_it =
resource_context_map_.find(context);
if (prefs_it == resource_context_map_.end())
return false;
PluginPrefs* plugin_prefs = prefs_it->second.get();
if (!plugin_prefs->IsPluginEnabled(*plugin))
return false;
RestrictedPluginMap::const_iterator it =
restricted_plugins_.find(plugin->path);
if (it != restricted_plugins_.end()) {
if (it->second.first != plugin_prefs)
return false;
const GURL& origin = it->second.second;
if (!origin.is_empty() &&
(policy_url.scheme() != origin.scheme() ||
policy_url.host() != origin.host() ||
policy_url.port() != origin.port())) {
return false;
}
}
return true;
}
CWE ID: CWE-287
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
msg->msg_namelen = 0;
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: error::Error GLES2DecoderImpl::HandleBeginQueryEXT(
uint32 immediate_data_size, const gles2::BeginQueryEXT& c) {
GLenum target = static_cast<GLenum>(c.target);
GLuint client_id = static_cast<GLuint>(c.id);
int32 sync_shm_id = static_cast<int32>(c.sync_data_shm_id);
uint32 sync_shm_offset = static_cast<uint32>(c.sync_data_shm_offset);
switch (target) {
case GL_COMMANDS_ISSUED_CHROMIUM:
break;
default:
if (!feature_info_->feature_flags().occlusion_query_boolean) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT: not enabled");
return error::kNoError;
}
break;
}
if (current_query_) {
SetGLError(
GL_INVALID_OPERATION, "glBeginQueryEXT: query already in progress");
return error::kNoError;
}
if (client_id == 0) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT: id is 0");
return error::kNoError;
}
QueryManager::Query* query = query_manager_->GetQuery(client_id);
if (!query) {
query = query_manager_->CreateQuery(
target, client_id, sync_shm_id, sync_shm_offset);
}
if (query->target() != target) {
SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT: target does not match");
return error::kNoError;
} else if (query->shm_id() != sync_shm_id ||
query->shm_offset() != sync_shm_offset) {
DLOG(ERROR) << "Shared memory used by query not the same as before";
return error::kInvalidArguments;
}
if (!query_manager_->BeginQuery(query)) {
return error::kOutOfBounds;
}
current_query_ = query;
return error::kNoError;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id) {
CancelRequestsForRoute(
GlobalFrameRoutingId(child_id, MSG_ROUTING_NONE /* cancel all */));
const auto& map = keepalive_statistics_recorder_.per_process_records();
if (map.find(child_id) != map.end())
keepalive_statistics_recorder_.Unregister(child_id);
}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void HostCache::ClearForHosts(
const base::Callback<bool(const std::string&)>& host_filter) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (host_filter.is_null()) {
clear();
return;
}
base::TimeTicks now = base::TimeTicks::Now();
for (EntryMap::iterator it = entries_.begin(); it != entries_.end();) {
EntryMap::iterator next_it = std::next(it);
if (host_filter.Run(it->first.hostname)) {
RecordErase(ERASE_CLEAR, now, it->second);
entries_.erase(it);
}
it = next_it;
}
}
CWE ID:
Target: 1
Example 2:
Code: blink::WebLocalizedString::Name GetSwitchToLocalMessage(
MediaObserverClient::ReasonToSwitchToLocal reason) {
switch (reason) {
case MediaObserverClient::ReasonToSwitchToLocal::NORMAL:
return blink::WebLocalizedString::kMediaRemotingStopText;
case MediaObserverClient::ReasonToSwitchToLocal::POOR_PLAYBACK_QUALITY:
return blink::WebLocalizedString::kMediaRemotingStopByPlaybackQualityText;
case MediaObserverClient::ReasonToSwitchToLocal::PIPELINE_ERROR:
return blink::WebLocalizedString::kMediaRemotingStopByErrorText;
case MediaObserverClient::ReasonToSwitchToLocal::ROUTE_TERMINATED:
return blink::WebLocalizedString::kMediaRemotingStopNoText;
}
NOTREACHED();
return blink::WebLocalizedString::kMediaRemotingStopNoText;
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual ~InputMethodLibraryImpl() {
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CloudPolicyController::SetState(
CloudPolicyController::ControllerState new_state) {
state_ = new_state;
backend_.reset(); // Discard any pending requests.
base::Time now(base::Time::NowFromSystemTime());
base::Time refresh_at;
base::Time last_refresh(cache_->last_policy_refresh_time());
if (last_refresh.is_null())
last_refresh = now;
bool inform_notifier_done = false;
switch (state_) {
case STATE_TOKEN_UNMANAGED:
notifier_->Inform(CloudPolicySubsystem::UNMANAGED,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::POLICY_CONTROLLER);
break;
case STATE_TOKEN_UNAVAILABLE:
case STATE_TOKEN_VALID:
refresh_at = now;
break;
case STATE_POLICY_VALID:
effective_policy_refresh_error_delay_ms_ =
kPolicyRefreshErrorDelayInMilliseconds;
refresh_at =
last_refresh + base::TimeDelta::FromMilliseconds(GetRefreshDelay());
notifier_->Inform(CloudPolicySubsystem::SUCCESS,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::POLICY_CONTROLLER);
break;
case STATE_TOKEN_ERROR:
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::BAD_DMTOKEN,
PolicyNotifier::POLICY_CONTROLLER);
inform_notifier_done = true;
case STATE_POLICY_ERROR:
if (!inform_notifier_done) {
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::POLICY_NETWORK_ERROR,
PolicyNotifier::POLICY_CONTROLLER);
}
refresh_at = now + base::TimeDelta::FromMilliseconds(
effective_policy_refresh_error_delay_ms_);
effective_policy_refresh_error_delay_ms_ =
std::min(effective_policy_refresh_error_delay_ms_ * 2,
policy_refresh_rate_ms_);
break;
case STATE_POLICY_UNAVAILABLE:
effective_policy_refresh_error_delay_ms_ = policy_refresh_rate_ms_;
refresh_at = now + base::TimeDelta::FromMilliseconds(
effective_policy_refresh_error_delay_ms_);
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::POLICY_NETWORK_ERROR,
PolicyNotifier::POLICY_CONTROLLER);
break;
}
scheduler_->CancelDelayedWork();
if (!refresh_at.is_null()) {
int64 delay = std::max<int64>((refresh_at - now).InMilliseconds(), 0);
scheduler_->PostDelayedWork(
base::Bind(&CloudPolicyController::DoWork, base::Unretained(this)),
delay);
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: BasePage* ThreadHeap::FindPageFromAddress(Address address) {
for (int i = 0; i < BlinkGC::kNumberOfArenas; ++i) {
if (BasePage* page = arenas_[i]->FindPageFromAddress(address))
return page;
}
return nullptr;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: CheckClientDownloadRequest(
content::DownloadItem* item,
const CheckDownloadCallback& callback,
DownloadProtectionService* service,
const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager,
BinaryFeatureExtractor* binary_feature_extractor)
: item_(item),
url_chain_(item->GetUrlChain()),
referrer_url_(item->GetReferrerUrl()),
tab_url_(item->GetTabUrl()),
tab_referrer_url_(item->GetTabReferrerUrl()),
zipped_executable_(false),
callback_(callback),
service_(service),
binary_feature_extractor_(binary_feature_extractor),
database_manager_(database_manager),
pingback_enabled_(service_->enabled()),
finished_(false),
type_(ClientDownloadRequest::WIN_EXECUTABLE),
start_time_(base::TimeTicks::Now()),
weakptr_factory_(this) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
item_->AddObserver(this);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int DefragTrackerReuseTest(void)
{
int ret = 0;
int id = 1;
Packet *p1 = NULL;
DefragTracker *tracker1 = NULL, *tracker2 = NULL;
DefragInit();
/* Build a packet, its not a fragment but shouldn't matter for
* this test. */
p1 = BuildTestPacket(id, 0, 0, 'A', 8);
if (p1 == NULL) {
goto end;
}
/* Get a tracker. It shouldn't look like its already in use. */
tracker1 = DefragGetTracker(NULL, NULL, p1);
if (tracker1 == NULL) {
goto end;
}
if (tracker1->seen_last) {
goto end;
}
if (tracker1->remove) {
goto end;
}
DefragTrackerRelease(tracker1);
/* Get a tracker again, it should be the same one. */
tracker2 = DefragGetTracker(NULL, NULL, p1);
if (tracker2 == NULL) {
goto end;
}
if (tracker2 != tracker1) {
goto end;
}
DefragTrackerRelease(tracker1);
/* Now mark the tracker for removal. It should not be returned
* when we get a tracker for a packet that may have the same
* attributes. */
tracker1->remove = 1;
tracker2 = DefragGetTracker(NULL, NULL, p1);
if (tracker2 == NULL) {
goto end;
}
if (tracker2 == tracker1) {
goto end;
}
if (tracker2->remove) {
goto end;
}
ret = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
DefragDestroy();
return ret;
}
CWE ID: CWE-358
Target: 1
Example 2:
Code: void ChildProcessSecurityPolicyImpl::GrantWebUIBindings(int child_id) {
base::AutoLock lock(lock_);
SecurityStateMap::iterator state = security_state_.find(child_id);
if (state == security_state_.end())
return;
state->second->GrantBindings(BINDINGS_POLICY_WEB_UI);
state->second->GrantScheme(kChromeUIScheme);
state->second->GrantScheme(url::kFileScheme);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void webkit_web_view_base_init(WebKitWebViewBase* webkitWebViewBase)
{
WebKitWebViewBasePrivate* priv = G_TYPE_INSTANCE_GET_PRIVATE(webkitWebViewBase, WEBKIT_TYPE_WEB_VIEW_BASE, WebKitWebViewBasePrivate);
webkitWebViewBase->priv = priv;
new (priv) WebKitWebViewBasePrivate();
priv->isPageActive = TRUE;
priv->shouldForwardNextKeyEvent = FALSE;
GtkWidget* viewWidget = GTK_WIDGET(webkitWebViewBase);
gtk_widget_set_double_buffered(viewWidget, FALSE);
gtk_widget_set_can_focus(viewWidget, TRUE);
priv->imContext = adoptGRef(gtk_im_multicontext_new());
priv->pageClient = PageClientImpl::create(viewWidget);
priv->dragAndDropHelper.setWidget(viewWidget);
gtk_drag_dest_set(viewWidget, static_cast<GtkDestDefaults>(0), 0, 0,
static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK | GDK_ACTION_PRIVATE));
gtk_drag_dest_set_target_list(viewWidget, PasteboardHelper::defaultPasteboardHelper()->targetList());
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool LocalFrame::ShouldReuseDefaultView(const KURL& url) const {
if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument())
return false;
return GetDocument()->IsSecureTransitionTo(url);
}
CWE ID: CWE-285
Target: 1
Example 2:
Code: void RendererSchedulerImpl::EndIdlePeriodForTesting(
const base::Closure& callback,
base::TimeTicks time_remaining) {
main_thread_only().in_idle_period_for_testing = false;
EndIdlePeriod();
callback.Run();
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void tg3_mdio_fini(struct tg3 *tp)
{
if (tg3_flag(tp, MDIOBUS_INITED)) {
tg3_flag_clear(tp, MDIOBUS_INITED);
mdiobus_unregister(tp->mdio_bus);
mdiobus_free(tp->mdio_bus);
}
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, true);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool GetBrowserLoginFunction::RunImpl() {
if (!IsWebStoreURL(profile_, source_url()))
return false;
result_.reset(CreateLoginResult(GetDefaultProfile(profile_)));
return true;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: NodeIterator::~NodeIterator()
{
root()->document().detachNodeIterator(this);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!arp_checkentry(&e->arp))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e, e->target_offset,
e->next_offset);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static inline void SetImpl(FixedArrayBase* backing_store, uint32_t entry,
Object* value, WriteBarrierMode mode) {
FixedDoubleArray::cast(backing_store)->set(entry, value->Number());
}
CWE ID: CWE-704
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BrowserViewRenderer::OnComputeScroll(base::TimeTicks animation_time) {
if (!compositor_)
return;
TRACE_EVENT0("android_webview", "BrowserViewRenderer::OnComputeScroll");
compositor_->OnComputeScroll(animation_time);
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof)
{
char *ksep, *vsep, *val;
size_t klen, vlen;
size_t new_vlen;
if (var->ptr >= var->end) {
return 0;
}
vsep = memchr(var->ptr, '&', var->end - var->ptr);
if (!vsep) {
if (!eof) {
return 0;
} else {
vsep = var->end;
}
}
ksep = memchr(var->ptr, '=', vsep - var->ptr);
if (ksep) {
*ksep = '\0';
/* "foo=bar&" or "foo=&" */
klen = ksep - var->ptr;
vlen = vsep - ++ksep;
} else {
ksep = "";
/* "foo&" */
klen = vsep - var->ptr;
vlen = 0;
}
php_url_decode(var->ptr, klen);
val = estrndup(ksep, vlen);
if (vlen) {
vlen = php_url_decode(val, vlen);
}
if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) {
php_register_variable_safe(var->ptr, val, new_vlen, arr);
}
efree(val);
var->ptr = vsep + (vsep != var->end);
return 1;
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: populate_recordset_object_start(void *state)
{
PopulateRecordsetState *_state = (PopulateRecordsetState *) state;
int lex_level = _state->lex->lex_level;
HASHCTL ctl;
/* Reject object at top level: we must have an array at level 0 */
if (lex_level == 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("cannot call %s on an object",
_state->function_name)));
/* Nested objects require no special processing */
if (lex_level > 1)
return;
/* Object at level 1: set up a new hash table for this object */
memset(&ctl, 0, sizeof(ctl));
ctl.keysize = NAMEDATALEN;
ctl.entrysize = sizeof(JsonHashEntry);
ctl.hcxt = CurrentMemoryContext;
_state->json_hash = hash_create("json object hashtable",
100,
&ctl,
HASH_ELEM | HASH_CONTEXT);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int snd_seq_ioctl_running_mode(struct snd_seq_client *client, void *arg)
{
struct snd_seq_running_info *info = arg;
struct snd_seq_client *cptr;
int err = 0;
/* requested client number */
cptr = snd_seq_client_use_ptr(info->client);
if (cptr == NULL)
return -ENOENT; /* don't change !!! */
#ifdef SNDRV_BIG_ENDIAN
if (!info->big_endian) {
err = -EINVAL;
goto __err;
}
#else
if (info->big_endian) {
err = -EINVAL;
goto __err;
}
#endif
if (info->cpu_mode > sizeof(long)) {
err = -EINVAL;
goto __err;
}
cptr->convert32 = (info->cpu_mode < sizeof(long));
__err:
snd_seq_client_unlock(cptr);
return err;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int vcc_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct atm_vcc *vcc;
int len;
if (get_user(len, optlen))
return -EFAULT;
if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname))
return -EINVAL;
vcc = ATM_SD(sock);
switch (optname) {
case SO_ATMQOS:
if (!test_bit(ATM_VF_HASQOS, &vcc->flags))
return -EINVAL;
return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos))
? -EFAULT : 0;
case SO_SETCLP:
return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0,
(unsigned long __user *)optval) ? -EFAULT : 0;
case SO_ATMPVC:
{
struct sockaddr_atmpvc pvc;
if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags))
return -ENOTCONN;
pvc.sap_family = AF_ATMPVC;
pvc.sap_addr.itf = vcc->dev->number;
pvc.sap_addr.vpi = vcc->vpi;
pvc.sap_addr.vci = vcc->vci;
return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0;
}
default:
if (level == SOL_SOCKET)
return -EINVAL;
break;
}
if (!vcc->dev || !vcc->dev->ops->getsockopt)
return -EINVAL;
return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void Document::serviceScriptedAnimations(double monotonicAnimationStartTime)
{
if (!m_scriptedAnimationController)
return;
m_scriptedAnimationController->serviceScriptedAnimations(monotonicAnimationStartTime);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int jp2_box_put(jp2_box_t *box, jas_stream_t *out)
{
jas_stream_t *tmpstream;
bool extlen;
bool dataflag;
tmpstream = 0;
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (box->ops->putdata) {
if ((*box->ops->putdata)(box, tmpstream)) {
goto error;
}
}
box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false);
jas_stream_rewind(tmpstream);
}
extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0;
if (jp2_putuint32(out, extlen ? 1 : box->len)) {
goto error;
}
if (jp2_putuint32(out, box->type)) {
goto error;
}
if (extlen) {
if (jp2_putuint64(out, box->len)) {
goto error;
}
}
if (dataflag) {
if (jas_stream_copy(out, tmpstream, box->len - JP2_BOX_HDRLEN(false))) {
goto error;
}
jas_stream_close(tmpstream);
}
return 0;
error:
if (tmpstream) {
jas_stream_close(tmpstream);
}
return -1;
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: pixHtmlViewer(const char *dirin,
const char *dirout,
const char *rootname,
l_int32 thumbwidth,
l_int32 viewwidth)
{
char *fname, *fullname, *outname;
char *mainname, *linkname, *linknameshort;
char *viewfile, *thumbfile;
char *shtml, *slink;
char charbuf[512];
char htmlstring[] = "<html>";
char framestring[] = "</frameset></html>";
l_int32 i, nfiles, index, w, d, nimages, ret;
l_float32 factor;
PIX *pix, *pixthumb, *pixview;
SARRAY *safiles, *sathumbs, *saviews, *sahtml, *salink;
PROCNAME("pixHtmlViewer");
if (!dirin)
return ERROR_INT("dirin not defined", procName, 1);
if (!dirout)
return ERROR_INT("dirout not defined", procName, 1);
if (!rootname)
return ERROR_INT("rootname not defined", procName, 1);
if (thumbwidth == 0)
thumbwidth = DEFAULT_THUMB_WIDTH;
if (thumbwidth < MIN_THUMB_WIDTH) {
L_WARNING("thumbwidth too small; using min value\n", procName);
thumbwidth = MIN_THUMB_WIDTH;
}
if (viewwidth == 0)
viewwidth = DEFAULT_VIEW_WIDTH;
if (viewwidth < MIN_VIEW_WIDTH) {
L_WARNING("viewwidth too small; using min value\n", procName);
viewwidth = MIN_VIEW_WIDTH;
}
/* Make the output directory if it doesn't already exist */
#ifndef _WIN32
snprintf(charbuf, sizeof(charbuf), "mkdir -p %s", dirout);
ret = system(charbuf);
#else
ret = CreateDirectory(dirout, NULL) ? 0 : 1;
#endif /* !_WIN32 */
if (ret) {
L_ERROR("output directory %s not made\n", procName, dirout);
return 1;
}
/* Capture the filenames in the input directory */
if ((safiles = getFilenamesInDirectory(dirin)) == NULL)
return ERROR_INT("safiles not made", procName, 1);
/* Generate output text file names */
sprintf(charbuf, "%s/%s.html", dirout, rootname);
mainname = stringNew(charbuf);
sprintf(charbuf, "%s/%s-links.html", dirout, rootname);
linkname = stringNew(charbuf);
linknameshort = stringJoin(rootname, "-links.html");
/* Generate the thumbs and views */
sathumbs = sarrayCreate(0);
saviews = sarrayCreate(0);
nfiles = sarrayGetCount(safiles);
index = 0;
for (i = 0; i < nfiles; i++) {
fname = sarrayGetString(safiles, i, L_NOCOPY);
fullname = genPathname(dirin, fname);
fprintf(stderr, "name: %s\n", fullname);
if ((pix = pixRead(fullname)) == NULL) {
fprintf(stderr, "file %s not a readable image\n", fullname);
lept_free(fullname);
continue;
}
lept_free(fullname);
/* Make and store the thumbnail images */
pixGetDimensions(pix, &w, NULL, &d);
factor = (l_float32)thumbwidth / (l_float32)w;
pixthumb = pixScale(pix, factor, factor);
sprintf(charbuf, "%s_thumb_%03d", rootname, index);
sarrayAddString(sathumbs, charbuf, L_COPY);
outname = genPathname(dirout, charbuf);
WriteFormattedPix(outname, pixthumb);
lept_free(outname);
pixDestroy(&pixthumb);
/* Make and store the view images */
factor = (l_float32)viewwidth / (l_float32)w;
if (factor >= 1.0)
pixview = pixClone(pix); /* no upscaling */
else
pixview = pixScale(pix, factor, factor);
snprintf(charbuf, sizeof(charbuf), "%s_view_%03d", rootname, index);
sarrayAddString(saviews, charbuf, L_COPY);
outname = genPathname(dirout, charbuf);
WriteFormattedPix(outname, pixview);
lept_free(outname);
pixDestroy(&pixview);
pixDestroy(&pix);
index++;
}
/* Generate the main html file */
sahtml = sarrayCreate(0);
sarrayAddString(sahtml, htmlstring, L_COPY);
sprintf(charbuf, "<frameset cols=\"%d, *\">", thumbwidth + 30);
sarrayAddString(sahtml, charbuf, L_COPY);
sprintf(charbuf, "<frame name=\"thumbs\" src=\"%s\">", linknameshort);
sarrayAddString(sahtml, charbuf, L_COPY);
sprintf(charbuf, "<frame name=\"views\" src=\"%s\">",
sarrayGetString(saviews, 0, L_NOCOPY));
sarrayAddString(sahtml, charbuf, L_COPY);
sarrayAddString(sahtml, framestring, L_COPY);
shtml = sarrayToString(sahtml, 1);
l_binaryWrite(mainname, "w", shtml, strlen(shtml));
fprintf(stderr, "******************************************\n"
"Writing html file: %s\n"
"******************************************\n", mainname);
lept_free(shtml);
lept_free(mainname);
/* Generate the link html file */
nimages = sarrayGetCount(saviews);
fprintf(stderr, "num. images = %d\n", nimages);
salink = sarrayCreate(0);
for (i = 0; i < nimages; i++) {
viewfile = sarrayGetString(saviews, i, L_NOCOPY);
thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY);
sprintf(charbuf, "<a href=\"%s\" TARGET=views><img src=\"%s\"></a>",
viewfile, thumbfile);
sarrayAddString(salink, charbuf, L_COPY);
}
slink = sarrayToString(salink, 1);
l_binaryWrite(linkname, "w", slink, strlen(slink));
lept_free(slink);
lept_free(linkname);
lept_free(linknameshort);
sarrayDestroy(&safiles);
sarrayDestroy(&sathumbs);
sarrayDestroy(&saviews);
sarrayDestroy(&sahtml);
sarrayDestroy(&salink);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int qcow2_create(const char *filename, QEMUOptionParameter *options,
Error **errp)
{
const char *backing_file = NULL;
const char *backing_fmt = NULL;
uint64_t sectors = 0;
int flags = 0;
size_t cluster_size = DEFAULT_CLUSTER_SIZE;
int prealloc = 0;
int version = 3;
Error *local_err = NULL;
int ret;
/* Read out options */
while (options && options->name) {
if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
sectors = options->value.n / 512;
} else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
backing_file = options->value.s;
} else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
backing_fmt = options->value.s;
} else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
} else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
if (options->value.n) {
cluster_size = options->value.n;
}
} else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
if (!options->value.s || !strcmp(options->value.s, "off")) {
prealloc = 0;
} else if (!strcmp(options->value.s, "metadata")) {
prealloc = 1;
} else {
error_setg(errp, "Invalid preallocation mode: '%s'",
options->value.s);
return -EINVAL;
}
} else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
if (!options->value.s) {
/* keep the default */
} else if (!strcmp(options->value.s, "0.10")) {
version = 2;
} else if (!strcmp(options->value.s, "1.1")) {
version = 3;
} else {
error_setg(errp, "Invalid compatibility level: '%s'",
options->value.s);
return -EINVAL;
}
} else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
}
options++;
}
if (backing_file && prealloc) {
error_setg(errp, "Backing file and preallocation cannot be used at "
"the same time");
return -EINVAL;
}
if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
error_setg(errp, "Lazy refcounts only supported with compatibility "
"level 1.1 and above (use compat=1.1 or greater)");
return -EINVAL;
}
ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
cluster_size, prealloc, options, version, &local_err);
if (local_err) {
error_propagate(errp, local_err);
}
return ret;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int credssp_sizeof_ts_password_creds(rdpCredssp* credssp)
{
int length = 0;
length += ber_sizeof_sequence_octet_string(credssp->identity.DomainLength * 2);
length += ber_sizeof_sequence_octet_string(credssp->identity.UserLength * 2);
length += ber_sizeof_sequence_octet_string(credssp->identity.PasswordLength * 2);
return length;
}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AudioRendererHost::AudioRendererHost(int render_process_id,
media::AudioManager* audio_manager,
AudioMirroringManager* mirroring_manager,
MediaStreamManager* media_stream_manager,
const std::string& salt)
: BrowserMessageFilter(AudioMsgStart),
render_process_id_(render_process_id),
audio_manager_(audio_manager),
mirroring_manager_(mirroring_manager),
media_stream_manager_(media_stream_manager),
salt_(salt),
validate_render_frame_id_function_(&ValidateRenderFrameId),
authorization_handler_(audio_manager_,
media_stream_manager,
render_process_id_,
salt) {
DCHECK(audio_manager_);
}
CWE ID:
Target: 1
Example 2:
Code: static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
{
int ret;
if (addr > (unsigned int)(-3 * PAGE_SIZE))
return -EINVAL;
ret = kvm_x86_ops->set_tss_addr(kvm, addr);
return ret;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool RunLoop::BeforeRun() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
#if DCHECK_IS_ON()
DCHECK(!run_called_);
run_called_ = true;
#endif // DCHECK_IS_ON()
if (quit_called_)
return false;
auto& active_run_loops_ = delegate_->active_run_loops_;
active_run_loops_.push(this);
const bool is_nested = active_run_loops_.size() > 1;
if (is_nested) {
CHECK(delegate_->allow_nesting_);
for (auto& observer : delegate_->nesting_observers_)
observer.OnBeginNestedRunLoop();
}
running_ = true;
return true;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void UnloadController::TabDetachedImpl(TabContents* contents) {
if (is_attempting_to_close_browser_)
ClearUnloadState(contents->web_contents(), false);
registrar_.Remove(
this,
content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::Source<content::WebContents>(contents->web_contents()));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: find_file(const char *env_name, const char *file_name)
{
char* config_source = NULL;
char* env = NULL;
int fd = 0;
if( env_name && (env = getenv( env_name )) ) {
config_source = strdup( env );
StatInfo si( config_source );
switch( si.Error() ) {
case SIGood:
if( si.IsDirectory() ) {
fprintf( stderr, "File specified in %s environment "
"variable:\n\"%s\" is a directory. "
"Please specify a file.\n", env_name,
config_source );
free( config_source );
config_source = NULL;
exit( 1 );
}
return config_source;
break;
case SINoFile:
if (!is_piped_command(config_source) ||
!is_valid_command(config_source)) {
fprintf( stderr, "File specified in %s environment "
"variable:\n\"%s\" does not exist.\n",
env_name, config_source );
free( config_source );
exit( 1 );
break;
}
return config_source;
case SIFailure:
fprintf( stderr, "Cannot stat file specified in %s "
"environment variable:\n\"%s\", errno: %d\n",
env_name, config_source, si.Errno() );
free( config_source );
exit( 1 );
break;
}
}
# ifdef UNIX
if (!config_source) {
int locations_length = 4;
MyString locations[locations_length];
locations[0].sprintf( "/etc/%s/%s", myDistro->Get(), file_name );
locations[1].sprintf( "/usr/local/etc/%s", file_name );
if (tilde) {
locations[2].sprintf( "%s/%s", tilde, file_name );
}
char *globus_location;
if ((globus_location = getenv("GLOBUS_LOCATION"))) {
locations[3].sprintf( "%s/etc/%s", globus_location, file_name );
}
int ctr;
for (ctr = 0 ; ctr < locations_length; ctr++) {
if (!locations[ctr].IsEmpty()) {
config_source = strdup(locations[ctr].Value());
if ((fd = safe_open_wrapper_follow(config_source, O_RDONLY)) < 0) {
free(config_source);
config_source = NULL;
} else {
close(fd);
dprintf(D_FULLDEBUG, "Reading condor configuration "
"from '%s'\n", config_source);
break;
}
}
} // FOR
} // IF
# elif defined WIN32 // ifdef UNIX
HKEY handle;
char regKey[256];
snprintf( regKey, 256, "Software\\%s", myDistro->GetCap() );
if ( !config_source && RegOpenKeyEx(HKEY_LOCAL_MACHINE, regKey,
0, KEY_READ, &handle) == ERROR_SUCCESS ) {
char the_path[MAX_PATH];
DWORD valType;
DWORD valSize = MAX_PATH - 2;
the_path[0] = '\0';
if ( RegQueryValueEx(handle, env_name, 0,
&valType, (unsigned char *)the_path, &valSize) == ERROR_SUCCESS ) {
if ( valType == REG_SZ && the_path[0] ) {
config_source = strdup(the_path);
if ( strncmp(config_source, "\\\\", 2 ) == 0 ) {
NETRESOURCE nr;
nr.dwType = RESOURCETYPE_DISK;
nr.lpLocalName = NULL;
nr.lpRemoteName = condor_dirname(config_source);
nr.lpProvider = NULL;
if ( NO_ERROR != WNetAddConnection2(
&nr, /* NetResource */
NULL, /* password (default) */
NULL, /* username (default) */
0 /* flags (none) */
) ) {
if ( GetLastError() == ERROR_INVALID_PASSWORD ) {
WNetAddConnection2(
&nr, /* NetResource */
"", /* password (none) */
NULL, /* username (default) */
0 /* flags (none) */
);
}
}
if (nr.lpRemoteName) {
free(nr.lpRemoteName);
}
}
if( !(is_piped_command(config_source) &&
is_valid_command(config_source)) &&
(fd = safe_open_wrapper_follow( config_source, O_RDONLY)) < 0 ) {
free( config_source );
config_source = NULL;
} else {
if (fd != 0) {
close( fd );
}
}
}
}
RegCloseKey(handle);
}
# else
# error "Unknown O/S"
# endif /* ifdef UNIX / Win32 */
return config_source;
}
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: _dbus_make_file_world_readable(const DBusString *filename,
DBusError *error)
{
return TRUE;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int asf_build_simple_index(AVFormatContext *s, int stream_index)
{
ff_asf_guid g;
ASFContext *asf = s->priv_data;
int64_t current_pos = avio_tell(s->pb);
int64_t ret;
if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) {
return ret;
}
if ((ret = ff_get_guid(s->pb, &g)) < 0)
goto end;
/* the data object can be followed by other top-level objects,
* skip them until the simple index object is reached */
while (ff_guidcmp(&g, &ff_asf_simple_index_header)) {
int64_t gsize = avio_rl64(s->pb);
if (gsize < 24 || avio_feof(s->pb)) {
goto end;
}
avio_skip(s->pb, gsize - 24);
if ((ret = ff_get_guid(s->pb, &g)) < 0)
goto end;
}
{
int64_t itime, last_pos = -1;
int pct, ict;
int i;
int64_t av_unused gsize = avio_rl64(s->pb);
if ((ret = ff_get_guid(s->pb, &g)) < 0)
goto end;
itime = avio_rl64(s->pb);
pct = avio_rl32(s->pb);
ict = avio_rl32(s->pb);
av_log(s, AV_LOG_DEBUG,
"itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict);
for (i = 0; i < ict; i++) {
int pktnum = avio_rl32(s->pb);
int pktct = avio_rl16(s->pb);
int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum;
int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);
if (pos != last_pos) {
av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n",
pktnum, pktct, index_pts);
av_add_index_entry(s->streams[stream_index], pos, index_pts,
s->packet_size, 0, AVINDEX_KEYFRAME);
last_pos = pos;
}
}
asf->index_read = ict > 1;
}
end:
avio_seek(s->pb, current_pos, SEEK_SET);
return ret;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void QuotaManager::DidGetLRUOrigin(const GURL* origin,
bool success) {
DidDatabaseWork(success);
if (origins_in_use_.find(*origin) != origins_in_use_.end() ||
access_notified_origins_.find(*origin) != access_notified_origins_.end())
lru_origin_callback_.Run(GURL());
else
lru_origin_callback_.Run(*origin);
access_notified_origins_.clear();
lru_origin_callback_.Reset();
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
if (cnt == 1)
return 0;
new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int yyinput (yyscan_t yyscanner)
#else
static int input (yyscan_t yyscanner)
#endif
{
int c;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
*yyg->yy_c_buf_p = yyg->yy_hold_char;
if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
/* This was really a NUL. */
*yyg->yy_c_buf_p = '\0';
else
{ /* need more input */
yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
re_yyrestart(yyin ,yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( re_yywrap(yyscanner ) )
return EOF;
if ( ! yyg->yy_did_buffer_switch_on_eof )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput(yyscanner);
#else
return input(yyscanner);
#endif
}
case EOB_ACT_CONTINUE_SCAN:
yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
break;
}
}
}
c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */
*yyg->yy_c_buf_p = '\0'; /* preserve yytext */
yyg->yy_hold_char = *++yyg->yy_c_buf_p;
if ( c == '\n' )
do{ yylineno++;
yycolumn=0;
}while(0)
;
return c;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void unforgeableVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
TestObjectPythonV8Internal::unforgeableVoidMethodMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: pax_decode_header (struct tar_sparse_file *file)
{
if (file->stat_info->sparse_major > 0)
{
uintmax_t u;
char nbuf[UINTMAX_STRSIZE_BOUND];
union block *blk;
char *p;
size_t i;
off_t start;
#define COPY_BUF(b,buf,src) do \
{ \
char *endp = b->buffer + BLOCKSIZE; \
char *dst = buf; \
do \
{ \
if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \
{ \
ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \
file->stat_info->orig_file_name)); \
return false; \
} \
if (src == endp) \
{ \
set_next_block_after (b); \
b = find_next_block (); \
src = b->buffer; \
endp = b->buffer + BLOCKSIZE; \
} \
while (*dst++ != '\n'); \
dst[-1] = 0; \
} while (0)
start = current_block_ordinal ();
set_next_block_after (current_header);
start = current_block_ordinal ();
set_next_block_after (current_header);
blk = find_next_block ();
p = blk->buffer;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t)))
}
file->stat_info->sparse_map_size = u;
file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size,
sizeof (*file->stat_info->sparse_map));
file->stat_info->sparse_map_avail = 0;
for (i = 0; i < file->stat_info->sparse_map_size; i++)
{
struct sp_array sp;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.offset = u;
COPY_BUF (blk,nbuf,p);
if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t)))
{
ERROR ((0, 0, _("%s: malformed sparse archive member"),
file->stat_info->orig_file_name));
return false;
}
sp.numbytes = u;
sparse_add_map (file->stat_info, &sp);
}
set_next_block_after (blk);
file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start);
}
return true;
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RuntimeCustomBindings::GetExtensionViews(
const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 2)
return;
if (!args[0]->IsInt32() || !args[1]->IsString())
return;
int browser_window_id = args[0]->Int32Value();
std::string view_type_string =
base::ToUpperASCII(*v8::String::Utf8Value(args[1]));
ViewType view_type = VIEW_TYPE_INVALID;
if (view_type_string == kViewTypeBackgroundPage) {
view_type = VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
} else if (view_type_string == kViewTypeTabContents) {
view_type = VIEW_TYPE_TAB_CONTENTS;
} else if (view_type_string == kViewTypePopup) {
view_type = VIEW_TYPE_EXTENSION_POPUP;
} else if (view_type_string == kViewTypeExtensionDialog) {
view_type = VIEW_TYPE_EXTENSION_DIALOG;
} else if (view_type_string == kViewTypeAppWindow) {
view_type = VIEW_TYPE_APP_WINDOW;
} else if (view_type_string == kViewTypeLauncherPage) {
view_type = VIEW_TYPE_LAUNCHER_PAGE;
} else if (view_type_string == kViewTypePanel) {
view_type = VIEW_TYPE_PANEL;
} else if (view_type_string != kViewTypeAll) {
return;
}
std::string extension_id = context()->GetExtensionID();
if (extension_id.empty())
return;
std::vector<content::RenderFrame*> frames =
ExtensionFrameHelper::GetExtensionFrames(extension_id, browser_window_id,
view_type);
v8::Local<v8::Array> v8_views = v8::Array::New(args.GetIsolate());
int v8_index = 0;
for (content::RenderFrame* frame : frames) {
if (frame->GetWebFrame()->top() != frame->GetWebFrame())
continue;
v8::Local<v8::Context> context =
frame->GetWebFrame()->mainWorldScriptContext();
if (!context.IsEmpty()) {
v8::Local<v8::Value> window = context->Global();
DCHECK(!window.IsEmpty());
v8_views->Set(v8::Integer::New(args.GetIsolate(), v8_index++), window);
}
}
args.GetReturnValue().Set(v8_views);
}
CWE ID:
Target: 1
Example 2:
Code: static void blk_rq_timed_out_timer(struct timer_list *t)
{
struct request_queue *q = from_timer(q, t, timeout);
kblockd_schedule_work(&q->timeout_work);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ThreadHeap::CommitCallbackStacks() {
marking_worklist_.reset(new MarkingWorklist());
not_fully_constructed_worklist_.reset(new NotFullyConstructedWorklist());
weak_callback_worklist_.reset(new WeakCallbackWorklist());
DCHECK(ephemeron_callbacks_.IsEmpty());
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline int hpel_motion(MpegEncContext *s,
uint8_t *dest, uint8_t *src,
int src_x, int src_y,
op_pixels_func *pix_op,
int motion_x, int motion_y)
{
int dxy = 0;
int emu = 0;
src_x += motion_x >> 1;
src_y += motion_y >> 1;
/* WARNING: do no forget half pels */
src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu?
if (src_x != s->width)
dxy |= motion_x & 1;
src_y = av_clip(src_y, -16, s->height);
if (src_y != s->height)
dxy |= (motion_y & 1) << 1;
src += src_y * s->linesize + src_x;
if (s->unrestricted_mv) {
if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) ||
(unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) {
s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src,
s->linesize, s->linesize,
9, 9,
src_x, src_y, s->h_edge_pos,
s->v_edge_pos);
src = s->sc.edge_emu_buffer;
emu = 1;
}
}
pix_op[dxy](dest, src, s->linesize, 8);
return emu;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: process_bmpcache2(STREAM s, uint16 flags, RD_BOOL compressed)
{
RD_HBITMAP bitmap;
int y;
uint8 cache_id, cache_idx_low, width, height, Bpp;
uint16 cache_idx, bufsize;
uint8 *data, *bmpdata, *bitmap_id;
bitmap_id = NULL; /* prevent compiler warning */
cache_id = flags & ID_MASK;
Bpp = ((flags & MODE_MASK) >> MODE_SHIFT) - 2;
if (flags & PERSIST)
{
in_uint8p(s, bitmap_id, 8);
}
if (flags & SQUARE)
{
in_uint8(s, width);
height = width;
}
else
{
in_uint8(s, width);
in_uint8(s, height);
}
in_uint16_be(s, bufsize);
bufsize &= BUFSIZE_MASK;
in_uint8(s, cache_idx);
if (cache_idx & LONG_FORMAT)
{
in_uint8(s, cache_idx_low);
cache_idx = ((cache_idx ^ LONG_FORMAT) << 8) + cache_idx_low;
}
in_uint8p(s, data, bufsize);
logger(Graphics, Debug,
"process_bmpcache2(), compr=%d, flags=%x, cx=%d, cy=%d, id=%d, idx=%d, Bpp=%d, bs=%d",
compressed, flags, width, height, cache_id, cache_idx, Bpp, bufsize);
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
if (compressed)
{
if (!bitmap_decompress(bmpdata, width, height, data, bufsize, Bpp))
{
logger(Graphics, Error,
"process_bmpcache2(), failed to decompress bitmap data");
xfree(bmpdata);
return;
}
}
else
{
for (y = 0; y < height; y++)
memcpy(&bmpdata[(height - y - 1) * (width * Bpp)],
&data[y * (width * Bpp)], width * Bpp);
}
bitmap = ui_create_bitmap(width, height, bmpdata);
if (bitmap)
{
cache_put_bitmap(cache_id, cache_idx, bitmap);
if (flags & PERSIST)
pstcache_save_bitmap(cache_id, cache_idx, bitmap_id, width, height,
width * height * Bpp, bmpdata);
}
else
{
logger(Graphics, Error, "process_bmpcache2(), ui_create_bitmap(), failed");
}
xfree(bmpdata);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static u8 nfc_llcp_dsap(struct sk_buff *pdu)
{
return (pdu->data[0] & 0xfc) >> 2;
}
CWE ID: CWE-476
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.