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: static int em_jmp_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned short sel; memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = load_segment_descriptor(ctxt, sel, VCPU_SREG_CS); if (rc != X86EMUL_CONTINUE) return rc; ctxt->_eip = 0; memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes); return X86EMUL_CONTINUE; } CWE ID: CWE-264 Target: 1 Example 2: Code: void Gfx::opFillStroke(Object args[], int numArgs) { if (!state->isCurPt()) { return; } if (state->isPath() && !contentIsHidden()) { if (state->getFillColorSpace()->getMode() == csPattern) { doPatternFill(gFalse); } else { out->fill(state); } if (state->getStrokeColorSpace()->getMode() == csPattern) { doPatternStroke(); } else { out->stroke(state); } } doEndPath(); } 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 BluetoothDeviceChromeOS::OnPair( const base::Closure& callback, const ConnectErrorCallback& error_callback) { VLOG(1) << object_path_.value() << ": Paired"; if (!pairing_delegate_used_) UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_NONE, UMA_PAIRING_METHOD_COUNT); UnregisterAgent(); SetTrusted(); ConnectInternal(true, callback, error_callback); } 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 ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename, const std::string& mime_type) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); ScopedJavaLocalRef<jstring> jmime_type = ConvertUTF8ToJavaString(env, mime_type); Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename, jmime_type); } CWE ID: CWE-254 Target: 1 Example 2: Code: void rpc_killall_tasks(struct rpc_clnt *clnt) { struct rpc_task *rovr; if (list_empty(&clnt->cl_tasks)) return; dprintk("RPC: killing all tasks for client %p\n", clnt); /* * Spin lock all_tasks to prevent changes... */ spin_lock(&clnt->cl_lock); list_for_each_entry(rovr, &clnt->cl_tasks, tk_task) { if (!RPC_IS_ACTIVATED(rovr)) continue; if (!(rovr->tk_flags & RPC_TASK_KILLED)) { rovr->tk_flags |= RPC_TASK_KILLED; rpc_exit(rovr, -EIO); if (RPC_IS_QUEUED(rovr)) rpc_wake_up_queued_task(rovr->tk_waitqueue, rovr); } } spin_unlock(&clnt->cl_lock); } 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 inline int file_list_cpu(struct file *file) { #ifdef CONFIG_SMP return file->f_sb_list_cpu; #else return smp_processor_id(); #endif } CWE ID: CWE-17 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 save_dev(blkid_dev dev, FILE *file) { struct list_head *p; if (!dev || dev->bid_name[0] != '/') return 0; DBG(SAVE, ul_debug("device %s, type %s", dev->bid_name, dev->bid_type ? dev->bid_type : "(null)")); fprintf(file, "<device DEVNO=\"0x%04lx\" TIME=\"%ld.%ld\"", (unsigned long) dev->bid_devno, (long) dev->bid_time, (long) dev->bid_utime); if (dev->bid_pri) fprintf(file, " PRI=\"%d\"", dev->bid_pri); list_for_each(p, &dev->bid_tags) { blkid_tag tag = list_entry(p, struct blkid_struct_tag, bit_tags); fprintf(file, " %s=\"%s\"", tag->bit_name,tag->bit_val); } fprintf(file, ">%s</device>\n", dev->bid_name); return 0; } CWE ID: CWE-77 Target: 1 Example 2: Code: string_replace (const char *string, const char *search, const char *replace) { const char *pos; char *new_string; int length1, length2, length_new, count; if (!string || !search || !replace) return NULL; length1 = strlen (search); length2 = strlen (replace); /* count number of strings to replace */ count = 0; pos = string; while (pos && pos[0] && (pos = strstr (pos, search))) { count++; pos += length1; } /* easy: no string to replace! */ if (count == 0) return strdup (string); /* compute needed memory for new string */ length_new = strlen (string) - (count * length1) + (count * length2) + 1; /* allocate new string */ new_string = malloc (length_new); if (!new_string) return strdup (string); /* replace all occurrences */ new_string[0] = '\0'; while (string && string[0]) { pos = strstr (string, search); if (pos) { strncat (new_string, string, pos - string); strcat (new_string, replace); pos += length1; } else strcat (new_string, string); string = pos; } return new_string; } 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 perf_event_free_bpf_handler(struct perf_event *event) { } 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 bool parse_notify(struct pool *pool, json_t *val) { char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime, *header; size_t cb1_len, cb2_len, alloc_len; unsigned char *cb1, *cb2; bool clean, ret = false; int merkles, i; json_t *arr; arr = json_array_get(val, 4); if (!arr || !json_is_array(arr)) goto out; merkles = json_array_size(arr); job_id = json_array_string(val, 0); prev_hash = json_array_string(val, 1); coinbase1 = json_array_string(val, 2); coinbase2 = json_array_string(val, 3); bbversion = json_array_string(val, 5); nbit = json_array_string(val, 6); ntime = json_array_string(val, 7); clean = json_is_true(json_array_get(val, 8)); if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) { /* Annoying but we must not leak memory */ if (job_id) free(job_id); if (prev_hash) free(prev_hash); if (coinbase1) free(coinbase1); if (coinbase2) free(coinbase2); if (bbversion) free(bbversion); if (nbit) free(nbit); if (ntime) free(ntime); goto out; } cg_wlock(&pool->data_lock); free(pool->swork.job_id); free(pool->swork.prev_hash); free(pool->swork.bbversion); free(pool->swork.nbit); free(pool->swork.ntime); pool->swork.job_id = job_id; pool->swork.prev_hash = prev_hash; cb1_len = strlen(coinbase1) / 2; cb2_len = strlen(coinbase2) / 2; pool->swork.bbversion = bbversion; pool->swork.nbit = nbit; pool->swork.ntime = ntime; pool->swork.clean = clean; alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len; pool->nonce2_offset = cb1_len + pool->n1_len; for (i = 0; i < pool->swork.merkles; i++) free(pool->swork.merkle_bin[i]); if (merkles) { pool->swork.merkle_bin = (unsigned char **)realloc(pool->swork.merkle_bin, sizeof(char *) * merkles + 1); for (i = 0; i < merkles; i++) { char *merkle = json_array_string(arr, i); pool->swork.merkle_bin[i] = (unsigned char *)malloc(32); if (unlikely(!pool->swork.merkle_bin[i])) quit(1, "Failed to malloc pool swork merkle_bin"); hex2bin(pool->swork.merkle_bin[i], merkle, 32); free(merkle); } } pool->swork.merkles = merkles; if (clean) pool->nonce2 = 0; pool->merkle_offset = strlen(pool->swork.bbversion) + strlen(pool->swork.prev_hash); pool->swork.header_len = pool->merkle_offset + /* merkle_hash */ 32 + strlen(pool->swork.ntime) + strlen(pool->swork.nbit) + /* nonce */ 8 + /* workpadding */ 96; pool->merkle_offset /= 2; pool->swork.header_len = pool->swork.header_len * 2 + 1; align_len(&pool->swork.header_len); header = (char *)alloca(pool->swork.header_len); snprintf(header, pool->swork.header_len, "%s%s%s%s%s%s%s", pool->swork.bbversion, pool->swork.prev_hash, blank_merkel, pool->swork.ntime, pool->swork.nbit, "00000000", /* nonce */ workpadding); if (unlikely(!hex2bin(pool->header_bin, header, 128))) quit(1, "Failed to convert header to header_bin in parse_notify"); cb1 = (unsigned char *)calloc(cb1_len, 1); if (unlikely(!cb1)) quithere(1, "Failed to calloc cb1 in parse_notify"); hex2bin(cb1, coinbase1, cb1_len); cb2 = (unsigned char *)calloc(cb2_len, 1); if (unlikely(!cb2)) quithere(1, "Failed to calloc cb2 in parse_notify"); hex2bin(cb2, coinbase2, cb2_len); free(pool->coinbase); align_len(&alloc_len); pool->coinbase = (unsigned char *)calloc(alloc_len, 1); if (unlikely(!pool->coinbase)) quit(1, "Failed to calloc pool coinbase in parse_notify"); memcpy(pool->coinbase, cb1, cb1_len); memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len); memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len); cg_wunlock(&pool->data_lock); if (opt_protocol) { applog(LOG_DEBUG, "job_id: %s", job_id); applog(LOG_DEBUG, "prev_hash: %s", prev_hash); applog(LOG_DEBUG, "coinbase1: %s", coinbase1); applog(LOG_DEBUG, "coinbase2: %s", coinbase2); applog(LOG_DEBUG, "bbversion: %s", bbversion); applog(LOG_DEBUG, "nbit: %s", nbit); applog(LOG_DEBUG, "ntime: %s", ntime); applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no"); } free(coinbase1); free(coinbase2); free(cb1); free(cb2); /* A notify message is the closest stratum gets to a getwork */ pool->getwork_requested++; total_getworks++; ret = true; if (pool == current_pool()) opt_work_update = true; out: return ret; } CWE ID: CWE-20 Target: 1 Example 2: Code: void AppCacheUpdateJob::URLFetcher::OnWriteComplete(int result) { if (result < 0) { request_->Cancel(); result_ = DISKCACHE_ERROR; OnResponseCompleted(); return; } ReadResponseData(); } 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: PowerPopupView() { SetHorizontalAlignment(ALIGN_RIGHT); UpdateText(); } 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: bool GLES2DecoderPassthroughImpl::IsEmulatedQueryTarget(GLenum target) const { switch (target) { case GL_COMMANDS_COMPLETED_CHROMIUM: case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: return true; default: return false; } } CWE ID: CWE-416 Target: 1 Example 2: Code: void LayerTreeHostImpl::FrameData::AppendRenderPass( std::unique_ptr<RenderPass> render_pass) { render_passes.push_back(std::move(render_pass)); } 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: create_principal_2_svc(cprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_ADD; log_unauth("kadm5_create_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_principal((void *)handle, &arg->rec, arg->mask, arg->passwd); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_create_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } 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: ExtensionTtsController::ExtensionTtsController() : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), current_utterance_(NULL), platform_impl_(NULL) { } CWE ID: CWE-20 Target: 1 Example 2: Code: static int php_curl_ssl_mutex_destroy(void **m) { tsrm_mutex_free(*((MUTEX_T *) m)); return SUCCESS; } 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: aspath_dup (struct aspath *aspath) { unsigned short buflen = aspath->str_len + 1; struct aspath *new; new = XCALLOC (MTYPE_AS_PATH, sizeof (struct aspath)); if (aspath->segments) new->segments = assegment_dup_all (aspath->segments); if (!aspath->str) return new; new->str = XMALLOC (MTYPE_AS_STR, buflen); new->str_len = aspath->str_len; /* copy the string data */ if (aspath->str_len > 0) memcpy (new->str, aspath->str, buflen); else new->str[0] = '\0'; return new; } 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: unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct *desc; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return -1L; if (v8086_mode(regs)) /* * Base is simply the segment selector shifted 4 * bits to the right. */ return (unsigned long)(sel << 4); if (user_64bit_mode(regs)) { /* * Only FS or GS will have a base address, the rest of * the segments' bases are forced to 0. */ unsigned long base; if (seg_reg_idx == INAT_SEG_REG_FS) rdmsrl(MSR_FS_BASE, base); else if (seg_reg_idx == INAT_SEG_REG_GS) /* * swapgs was called at the kernel entry point. Thus, * MSR_KERNEL_GS_BASE will have the user-space GS base. */ rdmsrl(MSR_KERNEL_GS_BASE, base); else base = 0; return base; } /* In protected mode the segment selector cannot be null. */ if (!sel) return -1L; desc = get_desc(sel); if (!desc) return -1L; return get_desc_base(desc); } CWE ID: CWE-362 Target: 1 Example 2: Code: is_token(apr_array_header_t *tokens, apr_size_t index, TokenType type, const char *value) { if (index >= tokens->nelts) { return false; } Token token = APR_ARRAY_IDX(tokens, index, Token); if (token.type != type) { return false; } if (value) { if (!g_str_equal(token.str, value)) { return false; } } return true; } CWE ID: CWE-601 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: PluginInfoMessageFilterTest() : foo_plugin_path_(FILE_PATH_LITERAL("/path/to/foo")), bar_plugin_path_(FILE_PATH_LITERAL("/path/to/bar")), file_thread_(content::BrowserThread::FILE, &message_loop_) { } CWE ID: CWE-287 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 SoftMP3::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 > 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 = mNumChannels; pcmParams->nSamplingRate = mSamplingRate; return OMX_ErrorNone; } case OMX_IndexParamAudioMp3: { OMX_AUDIO_PARAM_MP3TYPE *mp3Params = (OMX_AUDIO_PARAM_MP3TYPE *)params; if (mp3Params->nPortIndex > 1) { return OMX_ErrorUndefined; } mp3Params->nChannels = mNumChannels; mp3Params->nBitRate = 0 /* unknown */; mp3Params->nSampleRate = mSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: FT_Match_Size( FT_Face face, FT_Size_Request req, FT_Bool ignore_width, FT_ULong* size_index ) { FT_Int i; FT_Long w, h; if ( !FT_HAS_FIXED_SIZES( face ) ) return FT_Err_Invalid_Face_Handle; /* FT_Bitmap_Size doesn't provide enough info... */ if ( req->type != FT_SIZE_REQUEST_TYPE_NOMINAL ) return FT_Err_Unimplemented_Feature; w = FT_REQUEST_WIDTH ( req ); h = FT_REQUEST_HEIGHT( req ); if ( req->width && !req->height ) h = w; else if ( !req->width && req->height ) w = h; w = FT_PIX_ROUND( w ); h = FT_PIX_ROUND( h ); for ( i = 0; i < face->num_fixed_sizes; i++ ) { FT_Bitmap_Size* bsize = face->available_sizes + i; if ( h != FT_PIX_ROUND( bsize->y_ppem ) ) continue; if ( w == FT_PIX_ROUND( bsize->x_ppem ) || ignore_width ) { if ( size_index ) *size_index = (FT_ULong)i; return FT_Err_Ok; } } return FT_Err_Invalid_Pixel_Size; } 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: Strnew() { Str x = GC_MALLOC(sizeof(struct _Str)); x->ptr = GC_MALLOC_ATOMIC(INITIAL_STR_SIZE); x->ptr[0] = '\0'; x->area_size = INITIAL_STR_SIZE; x->length = 0; return x; } 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: update_info_partition_on_linux_dmmp (Device *device) { const gchar *dm_name; const gchar* const *targets_type; const gchar* const *targets_params; gchar *params; gint linear_slave_major; gint linear_slave_minor; guint64 offset_sectors; Device *linear_slave; gchar *s; params = NULL; dm_name = g_udev_device_get_property (device->priv->d, "DM_NAME"); if (dm_name == NULL) goto out; targets_type = g_udev_device_get_property_as_strv (device->priv->d, "UDISKS_DM_TARGETS_TYPE"); if (targets_type == NULL || g_strcmp0 (targets_type[0], "linear") != 0) goto out; goto out; params = decode_udev_encoded_string (targets_params[0]); if (sscanf (params, "%d:%d %" G_GUINT64_FORMAT, &linear_slave_major, &linear_slave_minor, &offset_sectors) != 3) goto out; linear_slave = daemon_local_find_by_dev (device->priv->daemon, makedev (linear_slave_major, linear_slave_minor)); if (linear_slave == NULL) goto out; if (!linear_slave->priv->device_is_linux_dmmp) goto out; /* The Partition* properties has been set as part of * update_info_partition() by reading UDISKS_PARTITION_* * properties.. so here we bascially just update the presentation * device file name and and whether the device is a drive. */ s = g_strdup_printf ("/dev/mapper/%s", dm_name); device_set_device_file_presentation (device, s); g_free (s); device_set_device_is_drive (device, FALSE); out: g_free (params); return TRUE; } CWE ID: CWE-200 Target: 1 Example 2: Code: gs_id get_mem_hdr_id (void *ptr) { return (*((hdr_id_t *)((byte *)ptr) - HDR_ID_OFFSET)); } 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: static void limitedWithInvalidAndMissingDefaultAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectV8Internal::limitedWithInvalidAndMissingDefaultAttributeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } 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: zlib_end(struct zlib *zlib) { /* Output the summary line now; this ensures a summary line always gets * output regardless of the manner of exit. */ if (!zlib->global->quiet) { if (zlib->ok_bits < 16) /* stream was read ok */ { const char *reason; if (zlib->cksum) reason = "CHK"; /* checksum error */ else if (zlib->ok_bits > zlib->file_bits) reason = "TFB"; /* fixing a too-far-back error */ else if (zlib->ok_bits == zlib->file_bits) reason = "OK "; else reason = "OPT"; /* optimizing window bits */ /* SUMMARY FORMAT (for a successful zlib inflate): * * IDAT reason flevel file-bits ok-bits compressed uncompressed file */ type_name(zlib->chunk->chunk_type, stdout); printf(" %s %s %d %d ", reason, zlib_flevel(zlib), zlib->file_bits, zlib->ok_bits); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); uarb_print(zlib->uncompressed_bytes, zlib->uncompressed_digits, stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } else { /* This is a zlib read error; the chunk will be skipped. For an IDAT * stream this will also cause a fatal read error (via stop()). * * SUMMARY FORMAT: * * IDAT SKP flevel file-bits z-rc compressed message file * * z-rc is the zlib failure code; message is the error message with * spaces replaced by '-'. The compressed byte count indicates where * in the zlib stream the error occured. */ type_name(zlib->chunk->chunk_type, stdout); printf(" SKP %s %d %s ", zlib_flevel(zlib), zlib->file_bits, zlib_rc(zlib)); uarb_print(zlib->compressed_bytes, zlib->compressed_digits, stdout); putc(' ', stdout); emit_string(zlib->z.msg ? zlib->z.msg : "[no_message]", stdout); putc(' ', stdout); fputs(zlib->file->file_name, stdout); putc('\n', stdout); } } if (zlib->state >= 0) { zlib->rc = inflateEnd(&zlib->z); if (zlib->rc != Z_OK) zlib_message(zlib, 1/*unexpected*/); } CLEAR(*zlib); } CWE ID: Target: 1 Example 2: Code: void refresh_sit_entry(struct f2fs_sb_info *sbi, block_t old, block_t new) { update_sit_entry(sbi, new, 1); if (GET_SEGNO(sbi, old) != NULL_SEGNO) update_sit_entry(sbi, old, -1); locate_dirty_segment(sbi, GET_SEGNO(sbi, old)); locate_dirty_segment(sbi, GET_SEGNO(sbi, new)); } 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: void GraphicsContext::setPlatformShouldAntialias(bool enable) { if (paintingDisabled()) return; notImplemented(); } 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 ssize_t o2nm_node_local_store(struct config_item *item, const char *page, size_t count) { struct o2nm_node *node = to_o2nm_node(item); struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node); unsigned long tmp; char *p = (char *)page; ssize_t ret; tmp = simple_strtoul(p, &p, 0); if (!p || (*p && (*p != '\n'))) return -EINVAL; tmp = !!tmp; /* boolean of whether this node wants to be local */ /* setting local turns on networking rx for now so we require having * set everything else first */ if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) || !test_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes) || !test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes)) return -EINVAL; /* XXX */ /* the only failure case is trying to set a new local node * when a different one is already set */ if (tmp && tmp == cluster->cl_has_local && cluster->cl_local_node != node->nd_num) return -EBUSY; /* bring up the rx thread if we're setting the new local node. */ if (tmp && !cluster->cl_has_local) { ret = o2net_start_listening(node); if (ret) return ret; } if (!tmp && cluster->cl_has_local && cluster->cl_local_node == node->nd_num) { o2net_stop_listening(node); cluster->cl_local_node = O2NM_INVALID_NODE_NUM; } node->nd_local = tmp; if (node->nd_local) { cluster->cl_has_local = tmp; cluster->cl_local_node = node->nd_num; } return count; } CWE ID: CWE-476 Target: 1 Example 2: Code: bool GLES2DecoderImpl::DoIsFramebuffer(GLuint client_id) { const FramebufferManager::FramebufferInfo* framebuffer = GetFramebufferInfo(client_id); return framebuffer && framebuffer->IsValid() && !framebuffer->IsDeleted(); } 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: GF_Err iref_dump(GF_Box *a, FILE * trace) { GF_ItemReferenceBox *p = (GF_ItemReferenceBox *)a; gf_isom_box_dump_start(a, "ItemReferenceBox", trace); fprintf(trace, ">\n"); gf_isom_box_array_dump(p->references, trace); gf_isom_box_dump_done("ItemReferenceBox", a, trace); return GF_OK; } 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 rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, struct cmsghdr *cmsg) { struct page *page = NULL; struct rds_atomic_args *args; int ret = 0; if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args)) || rm->atomic.op_active) return -EINVAL; args = CMSG_DATA(cmsg); /* Nonmasked & masked cmsg ops converted to masked hw ops */ switch (cmsg->cmsg_type) { case RDS_CMSG_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->fadd.add; rm->atomic.op_m_fadd.nocarry_mask = 0; break; case RDS_CMSG_MASKED_ATOMIC_FADD: rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD; rm->atomic.op_m_fadd.add = args->m_fadd.add; rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask; break; case RDS_CMSG_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->cswp.compare; rm->atomic.op_m_cswp.swap = args->cswp.swap; rm->atomic.op_m_cswp.compare_mask = ~0; rm->atomic.op_m_cswp.swap_mask = ~0; break; case RDS_CMSG_MASKED_ATOMIC_CSWP: rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP; rm->atomic.op_m_cswp.compare = args->m_cswp.compare; rm->atomic.op_m_cswp.swap = args->m_cswp.swap; rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask; rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask; break; default: BUG(); /* should never happen */ } rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME); rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT); rm->atomic.op_active = 1; rm->atomic.op_recverr = rs->rs_recverr; rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1); if (!rm->atomic.op_sg) { ret = -ENOMEM; goto err; } /* verify 8 byte-aligned */ if (args->local_addr & 0x7) { ret = -EFAULT; goto err; } ret = rds_pin_pages(args->local_addr, 1, &page, 1); if (ret != 1) goto err; ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); if (rm->atomic.op_notify || rm->atomic.op_recverr) { /* We allocate an uninitialized notifier here, because * we don't want to do that in the completion handler. We * would have to use GFP_ATOMIC there, and don't want to deal * with failed allocations. */ rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL); if (!rm->atomic.op_notifier) { ret = -ENOMEM; goto err; } rm->atomic.op_notifier->n_user_token = args->user_token; rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS; } rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie); rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie); return ret; err: if (page) put_page(page); kfree(rm->atomic.op_notifier); return ret; } CWE ID: CWE-476 Target: 1 Example 2: Code: AppViewGuestDelegate* ChromeExtensionsAPIClient::CreateAppViewGuestDelegate() const { return new ChromeAppViewGuestDelegate(); } 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 TabStripModel::SelectNextTab() { SelectRelativeTab(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: bool dstBufferSizeHasOverflow(ParsedOptions options) { CheckedNumeric<size_t> totalBytes = options.cropRect.width(); totalBytes *= options.cropRect.height(); totalBytes *= options.bytesPerPixel; if (!totalBytes.IsValid()) return true; if (!options.shouldScaleInput) return false; totalBytes = options.resizeWidth; totalBytes *= options.resizeHeight; totalBytes *= options.bytesPerPixel; if (!totalBytes.IsValid()) return true; return false; } CWE ID: CWE-787 Target: 1 Example 2: Code: void DownloadInsertFilesErrorCheckErrors(size_t count, FileErrorInjectInfo* info) { DownloadFilesCheckErrorsSetup(); scoped_refptr<content::TestFileErrorInjector> injector( content::TestFileErrorInjector::Create( DownloadManagerForBrowser(browser()))); for (size_t i = 0; i < count; ++i) { DownloadInsertFilesErrorCheckErrorsLoopBody(injector, info[i], i); } } CWE ID: CWE-284 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: TestWebKitPlatformSupport::~TestWebKitPlatformSupport() { } 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 DiceTurnSyncOnHelper::AbortAndDelete() { if (signin_aborted_mode_ == SigninAbortedMode::REMOVE_ACCOUNT) { token_service_->RevokeCredentials(account_info_.account_id); } delete this; } CWE ID: CWE-20 Target: 1 Example 2: Code: void perf_tp_event(u64 addr, u64 count, void *record, int entry_size, struct pt_regs *regs, struct hlist_head *head, int rctx, struct task_struct *task) { struct perf_sample_data data; struct perf_event *event; struct perf_raw_record raw = { .size = entry_size, .data = record, }; perf_sample_data_init(&data, addr, 0); data.raw = &raw; hlist_for_each_entry_rcu(event, head, hlist_entry) { if (perf_tp_event_match(event, &data, regs)) perf_swevent_event(event, count, &data, regs); } /* * If we got specified a target task, also iterate its context and * deliver this event there too. */ if (task && task != current) { struct perf_event_context *ctx; struct trace_entry *entry = record; rcu_read_lock(); ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]); if (!ctx) goto unlock; list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { if (event->attr.type != PERF_TYPE_TRACEPOINT) continue; if (event->attr.config != entry->type) continue; if (perf_tp_event_match(event, &data, regs)) perf_swevent_event(event, count, &data, regs); } unlock: rcu_read_unlock(); } perf_swevent_put_recursion_context(rctx); } 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 int usb_dev_prepare(struct device *dev) { return 0; /* Implement eventually? */ } CWE ID: CWE-400 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 start_daemon() { struct usb_sock_t *usb_sock; if (g_options.noprinter_mode == 0) { usb_sock = usb_open(); if (usb_sock == NULL) goto cleanup_usb; } else usb_sock = NULL; uint16_t desired_port = g_options.desired_port; struct tcp_sock_t *tcp_socket; while ((tcp_socket = tcp_open(desired_port)) == NULL && g_options.only_desired_port == 0) { desired_port ++; if (desired_port == 1 || desired_port == 0) desired_port = 49152; } if (tcp_socket == NULL) goto cleanup_tcp; uint16_t real_port = tcp_port_number_get(tcp_socket); if (desired_port != 0 && g_options.only_desired_port == 1 && desired_port != real_port) { ERR("Received port number did not match requested port number." " The requested port number may be too high."); goto cleanup_tcp; } printf("%u|", real_port); fflush(stdout); uint16_t pid; if (!g_options.nofork_mode && (pid = fork()) > 0) { printf("%u|", pid); exit(0); } if (usb_can_callback(usb_sock)) usb_register_callback(usb_sock); for (;;) { struct service_thread_param *args = calloc(1, sizeof(*args)); if (args == NULL) { ERR("Failed to alloc space for thread args"); goto cleanup_thread; } args->usb_sock = usb_sock; args->tcp = tcp_conn_accept(tcp_socket); if (args->tcp == NULL) { ERR("Failed to open tcp connection"); goto cleanup_thread; } int status = pthread_create(&args->thread_handle, NULL, &service_connection, args); if (status) { ERR("Failed to spawn thread, error %d", status); goto cleanup_thread; } continue; cleanup_thread: if (args != NULL) { if (args->tcp != NULL) tcp_conn_close(args->tcp); free(args); } break; } cleanup_tcp: if (tcp_socket!= NULL) tcp_close(tcp_socket); cleanup_usb: if (usb_sock != NULL) usb_close(usb_sock); return; } CWE ID: CWE-264 Target: 1 Example 2: Code: static void ipgre_tap_setup(struct net_device *dev) { ether_setup(dev); dev->netdev_ops = &ipgre_tap_netdev_ops; dev->destructor = ipgre_dev_free; dev->iflink = 0; dev->features |= NETIF_F_NETNS_LOCAL; } 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: struct dst_entry *ip6_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = NULL; int err; err = ip6_dst_lookup_tail(sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; return xfrm_lookup_route(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } 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 __exit pf_exit(void) { struct pf_unit *pf; int unit; unregister_blkdev(major, name); for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { if (pf->present) del_gendisk(pf->disk); blk_cleanup_queue(pf->disk->queue); blk_mq_free_tag_set(&pf->tag_set); put_disk(pf->disk); if (pf->present) pi_release(pf->pi); } } CWE ID: CWE-476 Target: 1 Example 2: Code: static void voidMethodStringArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::voidMethodStringArgMethod(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: static int port_is_power_on(struct usb_hub *hub, unsigned portstatus) { int ret = 0; if (hub_is_superspeed(hub->hdev)) { if (portstatus & USB_SS_PORT_STAT_POWER) ret = 1; } else { if (portstatus & USB_PORT_STAT_POWER) ret = 1; } return ret; } 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: http_splitline(struct worker *w, int fd, struct http *hp, const struct http_conn *htc, int h1, int h2, int h3) { char *p, *q; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); /* XXX: Assert a NUL at rx.e ? */ Tcheck(htc->rxbuf); /* Skip leading LWS */ for (p = htc->rxbuf.b ; vct_islws(*p); p++) continue; /* First field cannot contain SP, CRLF or CTL */ q = p; for (; !vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h1].b = q; hp->hd[h1].e = p; /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Second field cannot contain LWS or CTL */ q = p; for (; !vct_islws(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h2].b = q; hp->hd[h2].e = p; if (!Tlen(hp->hd[h2])) return (400); /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Third field is optional and cannot contain CTL */ q = p; if (!vct_iscrlf(*p)) { for (; !vct_iscrlf(*p); p++) if (!vct_issep(*p) && vct_isctl(*p)) return (400); } hp->hd[h3].b = q; hp->hd[h3].e = p; /* Skip CRLF */ p += vct_skipcrlf(p); *hp->hd[h1].e = '\0'; WSLH(w, fd, hp, h1); *hp->hd[h2].e = '\0'; WSLH(w, fd, hp, h2); if (hp->hd[h3].e != NULL) { *hp->hd[h3].e = '\0'; WSLH(w, fd, hp, h3); } return (http_dissect_hdrs(w, hp, fd, p, htc)); } CWE ID: Target: 1 Example 2: Code: bool QQuickWebView::allowAnyHTTPSCertificateForLocalHost() const { Q_D(const QQuickWebView); return d->m_allowAnyHTTPSCertificateForLocalHost; } 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 LocalDOMWindow::alert(ScriptState* script_state, const String& message) { if (!GetFrame()) return; if (document()->IsSandboxed(kSandboxModals)) { UseCounter::Count(document(), WebFeature::kDialogInSandboxedContext); GetFrameConsole()->AddMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Ignored call to 'alert()'. The document is sandboxed, and the " "'allow-modals' keyword is not set.")); return; } switch (document()->GetEngagementLevel()) { case mojom::blink::EngagementLevel::NONE: UseCounter::Count(document(), WebFeature::kAlertEngagementNone); break; case mojom::blink::EngagementLevel::MINIMAL: UseCounter::Count(document(), WebFeature::kAlertEngagementMinimal); break; case mojom::blink::EngagementLevel::LOW: UseCounter::Count(document(), WebFeature::kAlertEngagementLow); break; case mojom::blink::EngagementLevel::MEDIUM: UseCounter::Count(document(), WebFeature::kAlertEngagementMedium); break; case mojom::blink::EngagementLevel::HIGH: UseCounter::Count(document(), WebFeature::kAlertEngagementHigh); break; case mojom::blink::EngagementLevel::MAX: UseCounter::Count(document(), WebFeature::kAlertEngagementMax); break; } if (v8::MicrotasksScope::IsRunningMicrotasks(script_state->GetIsolate())) { UseCounter::Count(document(), WebFeature::kDuring_Microtask_Alert); } document()->UpdateStyleAndLayoutTree(); Page* page = GetFrame()->GetPage(); if (!page) return; UseCounter::CountCrossOriginIframe(*document(), WebFeature::kCrossOriginWindowAlert); page->GetChromeClient().OpenJavaScriptAlert(GetFrame(), message); } 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: InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() { InputMethodDescriptors* descriptors = new InputMethodDescriptors; descriptors->push_back( input_method::GetFallbackInputMethodDescriptor()); return descriptors; } CWE ID: CWE-399 Target: 1 Example 2: Code: void ImageLoader::updatedHasPendingEvent() { bool wasProtected = m_elementIsProtected; m_elementIsProtected = m_hasPendingLoadEvent || m_hasPendingErrorEvent; if (wasProtected == m_elementIsProtected) return; if (m_elementIsProtected) { if (m_derefElementTimer.isActive()) m_derefElementTimer.stop(); else m_element->ref(); } else { ASSERT(!m_derefElementTimer.isActive()); m_derefElementTimer.startOneShot(0); } } 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: static void php_xml_free_wrapper(void *ptr) { if (ptr != NULL) { efree(ptr); } } 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 int snd_ctl_elem_user_tlv(struct snd_kcontrol *kcontrol, int op_flag, unsigned int size, unsigned int __user *tlv) { struct user_element *ue = kcontrol->private_data; int change = 0; void *new_data; if (op_flag > 0) { if (size > 1024 * 128) /* sane value */ return -EINVAL; new_data = memdup_user(tlv, size); if (IS_ERR(new_data)) return PTR_ERR(new_data); change = ue->tlv_data_size != size; if (!change) change = memcmp(ue->tlv_data, new_data, size); kfree(ue->tlv_data); ue->tlv_data = new_data; ue->tlv_data_size = size; } else { if (! ue->tlv_data_size || ! ue->tlv_data) return -ENXIO; if (size < ue->tlv_data_size) return -ENOSPC; if (copy_to_user(tlv, ue->tlv_data, ue->tlv_data_size)) return -EFAULT; } return change; } CWE ID: CWE-362 Target: 1 Example 2: Code: bool TestSynchronousCompositor::DemandDrawSw(SkCanvas* canvas) { DCHECK(canvas); return true; } 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: std::string OutOfProcessInstance::ShowFileSelectionDialog() { NOTREACHED(); return std::string(); } 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 *proc_pid_follow_link(struct dentry *dentry, struct nameidata *nd) { struct inode *inode = dentry->d_inode; int error = -EACCES; /* We don't need a base pointer in the /proc filesystem */ path_put(&nd->path); /* Are we allowed to snoop on the tasks file descriptors? */ if (!proc_fd_access_allowed(inode)) goto out; error = PROC_I(inode)->op.proc_get_link(inode, &nd->path); nd->last_type = LAST_BIND; out: return ERR_PTR(error); } CWE ID: CWE-20 Target: 1 Example 2: Code: modifier_read_imp(png_modifier *pm, png_bytep pb, png_size_t st) { while (st > 0) { size_t cb; png_uint_32 len, chunk; png_modification *mod; if (pm->buffer_position >= pm->buffer_count) switch (pm->state) { static png_byte sign[8] = { 137, 80, 78, 71, 13, 10, 26, 10 }; case modifier_start: store_read_imp(&pm->this, pm->buffer, 8); /* size of signature. */ pm->buffer_count = 8; pm->buffer_position = 0; if (memcmp(pm->buffer, sign, 8) != 0) png_error(pm->this.pread, "invalid PNG file signature"); pm->state = modifier_signature; break; case modifier_signature: store_read_imp(&pm->this, pm->buffer, 13+12); /* size of IHDR */ pm->buffer_count = 13+12; pm->buffer_position = 0; if (png_get_uint_32(pm->buffer) != 13 || png_get_uint_32(pm->buffer+4) != CHUNK_IHDR) png_error(pm->this.pread, "invalid IHDR"); /* Check the list of modifiers for modifications to the IHDR. */ mod = pm->modifications; while (mod != NULL) { if (mod->chunk == CHUNK_IHDR && mod->modify_fn && (*mod->modify_fn)(pm, mod, 0)) { mod->modified = 1; modifier_setbuffer(pm); } /* Ignore removal or add if IHDR! */ mod = mod->next; } /* Cache information from the IHDR (the modified one.) */ pm->bit_depth = pm->buffer[8+8]; pm->colour_type = pm->buffer[8+8+1]; pm->state = modifier_IHDR; pm->flush = 0; break; case modifier_IHDR: default: /* Read a new chunk and process it until we see PLTE, IDAT or * IEND. 'flush' indicates that there is still some data to * output from the preceding chunk. */ if ((cb = pm->flush) > 0) { if (cb > st) cb = st; pm->flush -= cb; store_read_imp(&pm->this, pb, cb); pb += cb; st -= cb; if (st == 0) return; } /* No more bytes to flush, read a header, or handle a pending * chunk. */ if (pm->pending_chunk != 0) { png_save_uint_32(pm->buffer, pm->pending_len); png_save_uint_32(pm->buffer+4, pm->pending_chunk); pm->pending_len = 0; pm->pending_chunk = 0; } else store_read_imp(&pm->this, pm->buffer, 8); pm->buffer_count = 8; pm->buffer_position = 0; /* Check for something to modify or a terminator chunk. */ len = png_get_uint_32(pm->buffer); chunk = png_get_uint_32(pm->buffer+4); /* Terminators first, they may have to be delayed for added * chunks */ if (chunk == CHUNK_PLTE || chunk == CHUNK_IDAT || chunk == CHUNK_IEND) { mod = pm->modifications; while (mod != NULL) { if ((mod->add == chunk || (mod->add == CHUNK_PLTE && chunk == CHUNK_IDAT)) && mod->modify_fn != NULL && !mod->modified && !mod->added) { /* Regardless of what the modify function does do not run * this again. */ mod->added = 1; if ((*mod->modify_fn)(pm, mod, 1 /*add*/)) { /* Reset the CRC on a new chunk */ if (pm->buffer_count > 0) modifier_setbuffer(pm); else { pm->buffer_position = 0; mod->removed = 1; } /* The buffer has been filled with something (we assume) * so output this. Pend the current chunk. */ pm->pending_len = len; pm->pending_chunk = chunk; break; /* out of while */ } } mod = mod->next; } /* Don't do any further processing if the buffer was modified - * otherwise the code will end up modifying a chunk that was * just added. */ if (mod != NULL) break; /* out of switch */ } /* If we get to here then this chunk may need to be modified. To * do this it must be less than 1024 bytes in total size, otherwise * it just gets flushed. */ if (len+12 <= sizeof pm->buffer) { store_read_imp(&pm->this, pm->buffer+pm->buffer_count, len+12-pm->buffer_count); pm->buffer_count = len+12; /* Check for a modification, else leave it be. */ mod = pm->modifications; while (mod != NULL) { if (mod->chunk == chunk) { if (mod->modify_fn == NULL) { /* Remove this chunk */ pm->buffer_count = pm->buffer_position = 0; mod->removed = 1; break; /* Terminate the while loop */ } else if ((*mod->modify_fn)(pm, mod, 0)) { mod->modified = 1; /* The chunk may have been removed: */ if (pm->buffer_count == 0) { pm->buffer_position = 0; break; } modifier_setbuffer(pm); } } mod = mod->next; } } else pm->flush = len+12 - pm->buffer_count; /* data + crc */ /* Take the data from the buffer (if there is any). */ break; } /* Here to read from the modifier buffer (not directly from * the store, as in the flush case above.) */ cb = pm->buffer_count - pm->buffer_position; if (cb > st) cb = st; memcpy(pb, pm->buffer + pm->buffer_position, cb); st -= cb; pb += cb; pm->buffer_position += cb; } } 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: ProcXSendExtensionEvent(ClientPtr client) { int ret; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); if (!((EXTENSION_EVENT_BASE <= first->u.u.type) && (first->u.u.type < lastEvent))) { client->errorValue = first->u.u.type; return BadValue; } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; } 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: uint64_t esp_reg_read(ESPState *s, uint32_t saddr) { uint32_t old_val; trace_esp_mem_readb(saddr, s->rregs[saddr]); switch (saddr) { case ESP_FIFO: if (s->ti_size > 0) { s->ti_size--; if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) { /* Data out. */ qemu_log_mask(LOG_UNIMP, "esp: PIO data read not implemented\n"); s->rregs[ESP_FIFO] = 0; } else { s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++]; } esp_raise_irq(s); } if (s->ti_size == 0) { s->ti_rptr = 0; s->ti_wptr = 0; } s->ti_wptr = 0; } break; case ESP_RINTR: /* Clear sequence step, interrupt register and all status bits except TC */ old_val = s->rregs[ESP_RINTR]; s->rregs[ESP_RINTR] = 0; s->rregs[ESP_RSTAT] &= ~STAT_TC; s->rregs[ESP_RSEQ] = SEQ_CD; esp_lower_irq(s); return old_val; case ESP_TCHI: /* Return the unique id if the value has never been written */ if (!s->tchi_written) { return s->chip_id; } default: break; } CWE ID: CWE-20 Target: 1 Example 2: Code: status_t CameraClient::startRecordingMode() { LOG1("startRecordingMode"); status_t result = NO_ERROR; if (mHardware->recordingEnabled()) { return NO_ERROR; } if (!mHardware->previewEnabled()) { result = startPreviewMode(); if (result != NO_ERROR) { return result; } } enableMsgType(CAMERA_MSG_VIDEO_FRAME); mCameraService->playSound(CameraService::SOUND_RECORDING); result = mHardware->startRecording(); if (result != NO_ERROR) { ALOGE("mHardware->startRecording() failed with status %d", result); } return result; } 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: void LauncherView::Init() { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); model_->AddObserver(this); const LauncherItems& items(model_->items()); for (LauncherItems::const_iterator i = items.begin(); i != items.end(); ++i) { views::View* child = CreateViewForItem(*i); child->SetPaintToLayer(true); view_model_->Add(child, static_cast<int>(i - items.begin())); AddChildView(child); } UpdateFirstButtonPadding(); overflow_button_ = new views::ImageButton(this); overflow_button_->set_accessibility_focusable(true); overflow_button_->SetImage( views::CustomButton::BS_NORMAL, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW).ToImageSkia()); overflow_button_->SetImage( views::CustomButton::BS_HOT, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_HOT).ToImageSkia()); overflow_button_->SetImage( views::CustomButton::BS_PUSHED, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_PUSHED).ToImageSkia()); overflow_button_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_AURA_LAUNCHER_OVERFLOW_NAME)); overflow_button_->set_context_menu_controller(this); ConfigureChildView(overflow_button_); AddChildView(overflow_button_); } 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 klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc < 0) dev_err(&port->dev, "Reading line status failed (error = %d)\n", rc); else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; } CWE ID: CWE-532 Target: 1 Example 2: Code: void ManifestUmaUtil::ParseSucceeded(const Manifest& manifest) { UMA_HISTOGRAM_BOOLEAN(kUMANameParseSuccess, true); UMA_HISTOGRAM_BOOLEAN("Manifest.IsEmpty", manifest.IsEmpty()); if (manifest.IsEmpty()) return; UMA_HISTOGRAM_BOOLEAN("Manifest.HasProperty.name", !manifest.name.is_null()); UMA_HISTOGRAM_BOOLEAN("Manifest.HasProperty.short_name", !manifest.short_name.is_null()); UMA_HISTOGRAM_BOOLEAN("Manifest.HasProperty.start_url", !manifest.start_url.is_empty()); UMA_HISTOGRAM_BOOLEAN("Manifest.HasProperty.display", manifest.display != blink::kWebDisplayModeUndefined); UMA_HISTOGRAM_BOOLEAN( "Manifest.HasProperty.orientation", manifest.orientation != blink::kWebScreenOrientationLockDefault); UMA_HISTOGRAM_BOOLEAN("Manifest.HasProperty.icons", !manifest.icons.empty()); UMA_HISTOGRAM_BOOLEAN("Manifest.HasProperty.share_target", manifest.share_target.has_value()); UMA_HISTOGRAM_BOOLEAN("Manifest.HasProperty.gcm_sender_id", !manifest.gcm_sender_id.is_null()); } 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 l2tp_ip_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct sk_buff *skb; int rc; struct l2tp_ip_sock *lsa = l2tp_ip_sk(sk); struct inet_sock *inet = inet_sk(sk); struct ip_options *opt = inet->opt; struct rtable *rt = NULL; int connected = 0; __be32 daddr; if (sock_flag(sk, SOCK_DEAD)) return -ENOTCONN; /* Get and verify the address. */ if (msg->msg_name) { struct sockaddr_l2tpip *lip = (struct sockaddr_l2tpip *) msg->msg_name; if (msg->msg_namelen < sizeof(*lip)) return -EINVAL; if (lip->l2tp_family != AF_INET) { if (lip->l2tp_family != AF_UNSPEC) return -EAFNOSUPPORT; } daddr = lip->l2tp_addr.s_addr; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = inet->inet_daddr; connected = 1; } /* Allocate a socket buffer */ rc = -ENOMEM; skb = sock_wmalloc(sk, 2 + NET_SKB_PAD + sizeof(struct iphdr) + 4 + len, 0, GFP_KERNEL); if (!skb) goto error; /* Reserve space for headers, putting IP header on 4-byte boundary. */ skb_reserve(skb, 2 + NET_SKB_PAD); skb_reset_network_header(skb); skb_reserve(skb, sizeof(struct iphdr)); skb_reset_transport_header(skb); /* Insert 0 session_id */ *((__be32 *) skb_put(skb, 4)) = 0; /* Copy user data into skb */ rc = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len); if (rc < 0) { kfree_skb(skb); goto error; } if (connected) rt = (struct rtable *) __sk_dst_check(sk, 0); if (rt == NULL) { /* Use correct destination address if we have options. */ if (opt && opt->srr) daddr = opt->faddr; /* If this fails, retransmit mechanism of transport layer will * keep trying until route appears or the connection times * itself out. */ rt = ip_route_output_ports(sock_net(sk), sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (IS_ERR(rt)) goto no_route; sk_setup_caps(sk, &rt->dst); } skb_dst_set(skb, dst_clone(&rt->dst)); /* Queue the packet to IP for output */ rc = ip_queue_xmit(skb); error: /* Update stats */ if (rc >= 0) { lsa->tx_packets++; lsa->tx_bytes += len; rc = len; } else { lsa->tx_errors++; } return rc; no_route: IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EHOSTUNREACH; } 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: void opj_get_all_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ) { /* loop*/ OPJ_UINT32 compno, resno; /* pointers*/ const opj_tcp_t *tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* to store l_dx, l_dy, w and h for each resolution and component.*/ OPJ_UINT32 * lResolutionPtr; /* position in x and y of tile*/ OPJ_UINT32 p, q; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(tileno < p_cp->tw * p_cp->th); /* initializations*/ tcp = &p_cp->tcps [tileno]; l_tccp = tcp->tccps; l_img_comp = p_image->comps; /* position in x and y of tile*/ p = tileno % p_cp->tw; q = tileno / p_cp->tw; /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision and resolution is 0 (can only grow)*/ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min*/ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* aritmetic variables to calculate*/ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph; lResolutionPtr = p_resolutions[compno]; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts*/ l_level_no = l_tccp->numresolutions - 1; for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height*/ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; *lResolutionPtr++ = l_pdx; *lResolutionPtr++ = l_pdy; l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no)); /* take the minimum size for l_dx for each comp and resolution*/ *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx); *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy); /* various calculations of extents*/ l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); *lResolutionPtr++ = l_pw; *lResolutionPtr++ = l_ph; l_product = l_pw * l_ph; /* update precision*/ if (l_product > *p_max_prec) { *p_max_prec = l_product; } --l_level_no; } ++l_tccp; ++l_img_comp; } } CWE ID: CWE-190 Target: 1 Example 2: Code: static IndexPacket *GetAuthenticIndexesFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->indexes); } 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 ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } 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: xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); xmlDefaultSAXHandlerInit(); xmlDetectSAX2(ctxt); GROW; /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ if ((ctxt->input->end - ctxt->input->cur) >= 4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. */ GROW; if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); /* * Doing validity checking on chunk doesn't make sense */ ctxt->instate = XML_PARSER_CONTENT; ctxt->validate = 0; ctxt->loadsubset = 0; ctxt->depth = 0; xmlParseContent(ctxt); if ((RAW == '<') && (NXT(1) == '/')) { xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); } else if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL); } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); if (! ctxt->wellFormed) return(-1); return(0); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void nfs4_xdr_enc_open_downgrade(struct rpc_rqst *req, struct xdr_stream *xdr, struct nfs_closeargs *args) { struct compound_hdr hdr = { .minorversion = nfs4_xdr_minorversion(&args->seq_args), }; encode_compound_hdr(xdr, req, &hdr); encode_sequence(xdr, &args->seq_args, &hdr); encode_putfh(xdr, args->fh, &hdr); encode_open_downgrade(xdr, args, &hdr); encode_getfattr(xdr, args->bitmask, &hdr); encode_nops(&hdr); } 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: ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin, const GURL& embedding_origin) { DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin()); DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin()); if (!CanRequestObjectPermission(requesting_origin, embedding_origin)) return {}; std::vector<std::unique_ptr<Object>> results; auto* info = new content_settings::SettingInfo(); std::unique_ptr<base::DictionaryValue> setting = GetWebsiteSetting(requesting_origin, embedding_origin, info); std::unique_ptr<base::Value> objects; if (!setting->Remove(kObjectListKey, &objects)) return results; std::unique_ptr<base::ListValue> object_list = base::ListValue::From(std::move(objects)); if (!object_list) return results; for (auto& object : *object_list) { base::DictionaryValue* object_dict; if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) { results.push_back(std::make_unique<Object>( requesting_origin, embedding_origin, object_dict, info->source, host_content_settings_map_->is_incognito())); } } return results; } CWE ID: CWE-190 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: header_seek (SF_PRIVATE *psf, sf_count_t position, int whence) { switch (whence) { case SEEK_SET : if (position > SIGNED_SIZEOF (psf->header)) { /* Too much header to cache so just seek instead. */ psf_fseek (psf, position, whence) ; return ; } ; if (position > psf->headend) psf->headend += psf_fread (psf->header + psf->headend, 1, position - psf->headend, psf) ; psf->headindex = position ; break ; case SEEK_CUR : if (psf->headindex + position < 0) break ; if (psf->headindex >= SIGNED_SIZEOF (psf->header)) { psf_fseek (psf, position, whence) ; return ; } ; if (psf->headindex + position <= psf->headend) { psf->headindex += position ; break ; } ; if (psf->headindex + position > SIGNED_SIZEOF (psf->header)) { /* Need to jump this without caching it. */ psf->headindex = psf->headend ; psf_fseek (psf, position, SEEK_CUR) ; break ; } ; psf->headend += psf_fread (psf->header + psf->headend, 1, position - (psf->headend - psf->headindex), psf) ; psf->headindex = psf->headend ; break ; case SEEK_END : default : psf_log_printf (psf, "Bad whence param in header_seek().\n") ; break ; } ; return ; } /* header_seek */ CWE ID: CWE-119 Target: 1 Example 2: Code: virtual ~WorkerTerminationObserver() {} 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 UDPSocketLibevent::DoBind(const IPEndPoint& address) { SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; int rv = bind(socket_, storage.addr, storage.addr_len); if (rv == 0) return OK; int last_error = errno; UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromPosix", last_error); return MapSystemError(last_error); } 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: int rose_parse_facilities(unsigned char *p, struct rose_facilities_struct *facilities) { int facilities_len, len; facilities_len = *p++; if (facilities_len == 0) return 0; while (facilities_len > 0) { if (*p == 0x00) { facilities_len--; p++; switch (*p) { case FAC_NATIONAL: /* National */ len = rose_parse_national(p + 1, facilities, facilities_len - 1); facilities_len -= len + 1; p += len + 1; break; case FAC_CCITT: /* CCITT */ len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1); facilities_len -= len + 1; p += len + 1; break; default: printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p); facilities_len--; p++; break; } } else break; /* Error in facilities format */ } return 1; } CWE ID: CWE-20 Target: 1 Example 2: Code: int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt, int format, size_t *olen, unsigned char *buf, size_t blen ) { int ret; /* * buffer length must be at least one, for our length byte */ if( blen < 1 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); if( ( ret = mbedtls_ecp_point_write_binary( grp, pt, format, olen, buf + 1, blen - 1) ) != 0 ) return( ret ); /* * write length to the first byte and update total length */ buf[0] = (unsigned char) *olen; ++*olen; 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: image_transform_png_set_palette_to_rgb_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return colour_type == PNG_COLOR_TYPE_PALETTE; } 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: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t ofs = CDF_GETUINT32(p, (i << 1) + 1); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int DefragTrackerCompare(DefragTracker *t, Packet *p) { uint32_t id; if (PKT_IS_IPV4(p)) { id = (uint32_t)IPV4_GET_IPID(p); } else { id = IPV6_EXTHDR_GET_FH_ID(p); } return CMP_DEFRAGTRACKER(t, p, id); } CWE ID: CWE-358 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 record_recent_object(struct object *obj, struct strbuf *path, const char *last, void *data) { sha1_array_append(&recent_objects, obj->oid.hash); } 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 ip_options_build(struct sk_buff * skb, struct ip_options * opt, __be32 daddr, struct rtable *rt, int is_frag) { unsigned char *iph = skb_network_header(skb); memcpy(&(IPCB(skb)->opt), opt, sizeof(struct ip_options)); memcpy(iph+sizeof(struct iphdr), opt->__data, opt->optlen); opt = &(IPCB(skb)->opt); if (opt->srr) memcpy(iph+opt->srr+iph[opt->srr+1]-4, &daddr, 4); if (!is_frag) { if (opt->rr_needaddr) ip_rt_get_source(iph+opt->rr+iph[opt->rr+2]-5, rt); if (opt->ts_needaddr) ip_rt_get_source(iph+opt->ts+iph[opt->ts+2]-9, rt); if (opt->ts_needtime) { struct timespec tv; __be32 midtime; getnstimeofday(&tv); midtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC); memcpy(iph+opt->ts+iph[opt->ts+2]-5, &midtime, 4); } return; } if (opt->rr) { memset(iph+opt->rr, IPOPT_NOP, iph[opt->rr+1]); opt->rr = 0; opt->rr_needaddr = 0; } if (opt->ts) { memset(iph+opt->ts, IPOPT_NOP, iph[opt->ts+1]); opt->ts = 0; opt->ts_needaddr = opt->ts_needtime = 0; } } CWE ID: CWE-362 Target: 1 Example 2: Code: const char *ipx_frame_name(__be16 frame) { char* rc = "None"; switch (ntohs(frame)) { case ETH_P_IPX: rc = "EtherII"; break; case ETH_P_802_2: rc = "802.2"; break; case ETH_P_SNAP: rc = "SNAP"; break; case ETH_P_802_3: rc = "802.3"; break; } return rc; } 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 php_curl_ssl_lock(int mode, int n, const char * file, int line) { if (mode & CRYPTO_LOCK) { tsrm_mutex_lock(php_curl_openssl_tsl[n]); } else { tsrm_mutex_unlock(php_curl_openssl_tsl[n]); } } 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: static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h) { PadContext *s = inlink->dst->priv; AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0], w + (s->w - s->in_w), h + (s->h - s->in_h)); int plane; if (!frame) return NULL; frame->width = w; frame->height = h; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { int hsub = s->draw.hsub[plane]; int vsub = s->draw.vsub[plane]; frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] + (s->y >> vsub) * frame->linesize[plane]; } return frame; } CWE ID: CWE-119 Target: 1 Example 2: Code: do_include(struct xkb_compose_table *table, struct scanner *s, const char *path, unsigned include_depth) { FILE *file; bool ok; char *string; size_t size; struct scanner new_s; if (include_depth >= MAX_INCLUDE_DEPTH) { scanner_err(s, "maximum include depth (%d) exceeded; maybe there is an include loop?", MAX_INCLUDE_DEPTH); return false; } file = fopen(path, "r"); if (!file) { scanner_err(s, "failed to open included Compose file \"%s\": %s", path, strerror(errno)); return false; } ok = map_file(file, &string, &size); if (!ok) { scanner_err(s, "failed to read included Compose file \"%s\": %s", path, strerror(errno)); goto err_file; } scanner_init(&new_s, table->ctx, string, size, path, s->priv); ok = parse(table, &new_s, include_depth + 1); if (!ok) goto err_unmap; err_unmap: unmap_file(string, size); err_file: fclose(file); return ok; } 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: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); } CWE ID: CWE-200 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 Plugin::LoadNaClModuleContinuationIntern(ErrorInfo* error_info) { if (using_ipc_proxy_) return true; if (!main_subprocess_.StartSrpcServices()) { error_info->SetReport(ERROR_SRPC_CONNECTION_FAIL, "SRPC connection failure for " + main_subprocess_.description()); return false; } if (!main_subprocess_.StartJSObjectProxy(this, error_info)) { return false; } PLUGIN_PRINTF(("Plugin::LoadNaClModule (%s)\n", main_subprocess_.detailed_description().c_str())); return true; } CWE ID: CWE-399 Target: 1 Example 2: Code: void RenderProcessHostImpl::OnUserMetricsRecordAction( const std::string& action) { RecordComputedAction(action); } 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 mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical, struct buffer_head *exbh) { struct inode *inode = mpd->inode; struct address_space *mapping = inode->i_mapping; int blocks = exbh->b_size >> inode->i_blkbits; sector_t pblock = exbh->b_blocknr, cur_logical; struct buffer_head *head, *bh; pgoff_t index, end; struct pagevec pvec; int nr_pages, i; index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits); end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits); cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits); pagevec_init(&pvec, 0); while (index <= end) { /* XXX: optimize tail */ nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE); if (nr_pages == 0) break; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; index = page->index; if (index > end) break; index++; BUG_ON(!PageLocked(page)); BUG_ON(PageWriteback(page)); BUG_ON(!page_has_buffers(page)); bh = page_buffers(page); head = bh; /* skip blocks out of the range */ do { if (cur_logical >= logical) break; cur_logical++; } while ((bh = bh->b_this_page) != head); do { if (cur_logical >= logical + blocks) break; if (buffer_delay(bh) || buffer_unwritten(bh)) { BUG_ON(bh->b_bdev != inode->i_sb->s_bdev); if (buffer_delay(bh)) { clear_buffer_delay(bh); bh->b_blocknr = pblock; } else { /* * unwritten already should have * blocknr assigned. Verify that */ clear_buffer_unwritten(bh); BUG_ON(bh->b_blocknr != pblock); } } else if (buffer_mapped(bh)) BUG_ON(bh->b_blocknr != pblock); cur_logical++; pblock++; } while ((bh = bh->b_this_page) != head); } pagevec_release(&pvec); } } 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 CameraSource::dataCallbackTimestamp(int64_t timestampUs, int32_t msgType __unused, const sp<IMemory> &data) { ALOGV("dataCallbackTimestamp: timestamp %lld us", (long long)timestampUs); Mutex::Autolock autoLock(mLock); if (!mStarted || (mNumFramesReceived == 0 && timestampUs < mStartTimeUs)) { ALOGV("Drop frame at %lld/%lld us", (long long)timestampUs, (long long)mStartTimeUs); releaseOneRecordingFrame(data); return; } if (skipCurrentFrame(timestampUs)) { releaseOneRecordingFrame(data); return; } if (mNumFramesReceived > 0) { if (timestampUs <= mLastFrameTimestampUs) { ALOGW("Dropping frame with backward timestamp %lld (last %lld)", (long long)timestampUs, (long long)mLastFrameTimestampUs); releaseOneRecordingFrame(data); return; } if (timestampUs - mLastFrameTimestampUs > mGlitchDurationThresholdUs) { ++mNumGlitches; } } mLastFrameTimestampUs = timestampUs; if (mNumFramesReceived == 0) { mFirstFrameTimeUs = timestampUs; if (mStartTimeUs > 0) { if (timestampUs < mStartTimeUs) { releaseOneRecordingFrame(data); return; } mStartTimeUs = timestampUs - mStartTimeUs; } } ++mNumFramesReceived; CHECK(data != NULL && data->size() > 0); mFramesReceived.push_back(data); int64_t timeUs = mStartTimeUs + (timestampUs - mFirstFrameTimeUs); mFrameTimes.push_back(timeUs); ALOGV("initial delay: %" PRId64 ", current time stamp: %" PRId64, mStartTimeUs, timeUs); mFrameAvailableCondition.signal(); } CWE ID: CWE-200 Target: 1 Example 2: Code: void HTMLScriptRunner::detach() { if (!m_document) return; m_parserBlockingScript.stopWatchingForLoad(this); m_parserBlockingScript.releaseElementAndClear(); while (!m_scriptsToExecuteAfterParsing.isEmpty()) { PendingScript pendingScript = m_scriptsToExecuteAfterParsing.takeFirst(); pendingScript.stopWatchingForLoad(this); pendingScript.releaseElementAndClear(); } m_document = nullptr; } CWE ID: CWE-254 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 AppCacheDatabase::FindLastStorageIds( int64_t* last_group_id, int64_t* last_cache_id, int64_t* last_response_id, int64_t* last_deletable_response_rowid) { DCHECK(last_group_id && last_cache_id && last_response_id && last_deletable_response_rowid); *last_group_id = 0; *last_cache_id = 0; *last_response_id = 0; *last_deletable_response_rowid = 0; if (!LazyOpen(kDontCreate)) return false; static const char kMaxGroupIdSql[] = "SELECT MAX(group_id) FROM Groups"; static const char kMaxCacheIdSql[] = "SELECT MAX(cache_id) FROM Caches"; static const char kMaxResponseIdFromEntriesSql[] = "SELECT MAX(response_id) FROM Entries"; static const char kMaxResponseIdFromDeletablesSql[] = "SELECT MAX(response_id) FROM DeletableResponseIds"; static const char kMaxDeletableResponseRowIdSql[] = "SELECT MAX(rowid) FROM DeletableResponseIds"; int64_t max_group_id; int64_t max_cache_id; int64_t max_response_id_from_entries; int64_t max_response_id_from_deletables; int64_t max_deletable_response_rowid; if (!RunUniqueStatementWithInt64Result(kMaxGroupIdSql, &max_group_id) || !RunUniqueStatementWithInt64Result(kMaxCacheIdSql, &max_cache_id) || !RunUniqueStatementWithInt64Result(kMaxResponseIdFromEntriesSql, &max_response_id_from_entries) || !RunUniqueStatementWithInt64Result(kMaxResponseIdFromDeletablesSql, &max_response_id_from_deletables) || !RunUniqueStatementWithInt64Result(kMaxDeletableResponseRowIdSql, &max_deletable_response_rowid)) { return false; } *last_group_id = max_group_id; *last_cache_id = max_cache_id; *last_response_id = std::max(max_response_id_from_entries, max_response_id_from_deletables); *last_deletable_response_rowid = max_deletable_response_rowid; return true; } 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 AppControllerImpl::GetArcAndroidId( mojom::AppController::GetArcAndroidIdCallback callback) { arc::GetAndroidId(base::BindOnce( [](mojom::AppController::GetArcAndroidIdCallback callback, bool success, int64_t android_id) { std::move(callback).Run(success, base::NumberToString(android_id)); }, std::move(callback))); } CWE ID: CWE-416 Target: 1 Example 2: Code: static int fxrstor_fixup(struct x86_emulate_ctxt *ctxt, struct fxregs_state *new) { int rc = X86EMUL_CONTINUE; struct fxregs_state old; rc = asm_safe("fxsave %[fx]", , [fx] "+m"(old)); if (rc != X86EMUL_CONTINUE) return rc; /* * 64 bit host will restore XMM 8-15, which is not correct on non-64 * bit guests. Load the current values in order to preserve 64 bit * XMMs after fxrstor. */ #ifdef CONFIG_X86_64 /* XXX: accessing XMM 8-15 very awkwardly */ memcpy(&new->xmm_space[8 * 16/4], &old.xmm_space[8 * 16/4], 8 * 16); #endif /* * Hardware doesn't save and restore XMM 0-7 without CR4.OSFXSR, but * does save and restore MXCSR. */ if (!(ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR)) memcpy(new->xmm_space, old.xmm_space, 8 * 16); return rc; } 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: FileSystemOperation::TaskParamsForDidGetQuota::TaskParamsForDidGetQuota() : type(kFileSystemTypeUnknown) { } 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: image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { return image_transform_png_set_expand_add(this, that, colour_type, bit_depth); } CWE ID: Target: 1 Example 2: Code: nfsd4_set_closestateid(struct nfsd4_compound_state *cstate, struct nfsd4_close *close) { put_stateid(cstate, &close->cl_stateid); } CWE ID: CWE-404 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 cifs_copy_posix_acl(char *trgt, char *src, const int buflen, const int acl_type, const int size_of_data_area) { int size = 0; int i; __u16 count; struct cifs_posix_ace *pACE; struct cifs_posix_acl *cifs_acl = (struct cifs_posix_acl *)src; posix_acl_xattr_header *local_acl = (posix_acl_xattr_header *)trgt; if (le16_to_cpu(cifs_acl->version) != CIFS_ACL_VERSION) return -EOPNOTSUPP; if (acl_type & ACL_TYPE_ACCESS) { count = le16_to_cpu(cifs_acl->access_entry_count); pACE = &cifs_acl->ace_array[0]; size = sizeof(struct cifs_posix_acl); size += sizeof(struct cifs_posix_ace) * count; /* check if we would go beyond end of SMB */ if (size_of_data_area < size) { cFYI(1, "bad CIFS POSIX ACL size %d vs. %d", size_of_data_area, size); return -EINVAL; } } else if (acl_type & ACL_TYPE_DEFAULT) { count = le16_to_cpu(cifs_acl->access_entry_count); size = sizeof(struct cifs_posix_acl); size += sizeof(struct cifs_posix_ace) * count; /* skip past access ACEs to get to default ACEs */ pACE = &cifs_acl->ace_array[count]; count = le16_to_cpu(cifs_acl->default_entry_count); size += sizeof(struct cifs_posix_ace) * count; /* check if we would go beyond end of SMB */ if (size_of_data_area < size) return -EINVAL; } else { /* illegal type */ return -EINVAL; } size = posix_acl_xattr_size(count); if ((buflen == 0) || (local_acl == NULL)) { /* used to query ACL EA size */ } else if (size > buflen) { return -ERANGE; } else /* buffer big enough */ { local_acl->a_version = cpu_to_le32(POSIX_ACL_XATTR_VERSION); for (i = 0; i < count ; i++) { cifs_convert_ace(&local_acl->a_entries[i], pACE); pACE++; } } return size; } 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: static struct fileIdentDesc *udf_find_entry(struct inode *dir, const struct qstr *child, struct udf_fileident_bh *fibh, struct fileIdentDesc *cfi) { struct fileIdentDesc *fi = NULL; loff_t f_pos; int block, flen; unsigned char *fname = NULL; unsigned char *nameptr; uint8_t lfi; uint16_t liu; loff_t size; struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; struct extent_position epos = {}; struct udf_inode_info *dinfo = UDF_I(dir); int isdotdot = child->len == 2 && child->name[0] == '.' && child->name[1] == '.'; size = udf_ext0_offset(dir) + dir->i_size; f_pos = udf_ext0_offset(dir); fibh->sbh = fibh->ebh = NULL; fibh->soffset = fibh->eoffset = f_pos & (dir->i_sb->s_blocksize - 1); if (dinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { if (inode_bmap(dir, f_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) != (EXT_RECORDED_ALLOCATED >> 30)) goto out_err; block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else offset = 0; fibh->sbh = fibh->ebh = udf_tread(dir->i_sb, block); if (!fibh->sbh) goto out_err; } fname = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!fname) goto out_err; while (f_pos < size) { fi = udf_fileident_read(dir, &f_pos, fibh, cfi, &epos, &eloc, &elen, &offset); if (!fi) goto out_err; liu = le16_to_cpu(cfi->lengthOfImpUse); lfi = cfi->lengthFileIdent; if (fibh->sbh == fibh->ebh) { nameptr = fi->fileIdent + liu; } else { int poffset; /* Unpaded ending offset */ poffset = fibh->soffset + sizeof(struct fileIdentDesc) + liu + lfi; if (poffset >= lfi) nameptr = (uint8_t *)(fibh->ebh->b_data + poffset - lfi); else { nameptr = fname; memcpy(nameptr, fi->fileIdent + liu, lfi - poffset); memcpy(nameptr + lfi - poffset, fibh->ebh->b_data, poffset); } } if ((cfi->fileCharacteristics & FID_FILE_CHAR_DELETED) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNDELETE)) continue; } if ((cfi->fileCharacteristics & FID_FILE_CHAR_HIDDEN) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNHIDE)) continue; } if ((cfi->fileCharacteristics & FID_FILE_CHAR_PARENT) && isdotdot) goto out_ok; if (!lfi) continue; flen = udf_get_filename(dir->i_sb, nameptr, fname, lfi); if (flen && udf_match(flen, fname, child->len, child->name)) goto out_ok; } out_err: fi = NULL; if (fibh->sbh != fibh->ebh) brelse(fibh->ebh); brelse(fibh->sbh); out_ok: brelse(epos.bh); kfree(fname); return fi; } CWE ID: CWE-17 Target: 1 Example 2: Code: void MediaPlayerService::AudioOutput::setNextOutput(const sp<AudioOutput>& nextOutput) { Mutex::Autolock lock(mLock); mNextOutput = nextOutput; } 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: xsltRegisterAllElement(xsltTransformContextPtr ctxt) { xsltRegisterExtElement(ctxt, (const xmlChar *) "apply-templates", XSLT_NAMESPACE, (xsltTransformFunction) xsltApplyTemplates); xsltRegisterExtElement(ctxt, (const xmlChar *) "apply-imports", XSLT_NAMESPACE, (xsltTransformFunction) xsltApplyImports); xsltRegisterExtElement(ctxt, (const xmlChar *) "call-template", XSLT_NAMESPACE, (xsltTransformFunction) xsltCallTemplate); xsltRegisterExtElement(ctxt, (const xmlChar *) "element", XSLT_NAMESPACE, (xsltTransformFunction) xsltElement); xsltRegisterExtElement(ctxt, (const xmlChar *) "attribute", XSLT_NAMESPACE, (xsltTransformFunction) xsltAttribute); xsltRegisterExtElement(ctxt, (const xmlChar *) "text", XSLT_NAMESPACE, (xsltTransformFunction) xsltText); xsltRegisterExtElement(ctxt, (const xmlChar *) "processing-instruction", XSLT_NAMESPACE, (xsltTransformFunction) xsltProcessingInstruction); xsltRegisterExtElement(ctxt, (const xmlChar *) "comment", XSLT_NAMESPACE, (xsltTransformFunction) xsltComment); xsltRegisterExtElement(ctxt, (const xmlChar *) "copy", XSLT_NAMESPACE, (xsltTransformFunction) xsltCopy); xsltRegisterExtElement(ctxt, (const xmlChar *) "value-of", XSLT_NAMESPACE, (xsltTransformFunction) xsltValueOf); xsltRegisterExtElement(ctxt, (const xmlChar *) "number", XSLT_NAMESPACE, (xsltTransformFunction) xsltNumber); xsltRegisterExtElement(ctxt, (const xmlChar *) "for-each", XSLT_NAMESPACE, (xsltTransformFunction) xsltForEach); xsltRegisterExtElement(ctxt, (const xmlChar *) "if", XSLT_NAMESPACE, (xsltTransformFunction) xsltIf); xsltRegisterExtElement(ctxt, (const xmlChar *) "choose", XSLT_NAMESPACE, (xsltTransformFunction) xsltChoose); xsltRegisterExtElement(ctxt, (const xmlChar *) "sort", XSLT_NAMESPACE, (xsltTransformFunction) xsltSort); xsltRegisterExtElement(ctxt, (const xmlChar *) "copy-of", XSLT_NAMESPACE, (xsltTransformFunction) xsltCopyOf); xsltRegisterExtElement(ctxt, (const xmlChar *) "message", XSLT_NAMESPACE, (xsltTransformFunction) xsltMessage); /* * Those don't have callable entry points but are registered anyway */ xsltRegisterExtElement(ctxt, (const xmlChar *) "variable", XSLT_NAMESPACE, (xsltTransformFunction) xsltDebug); xsltRegisterExtElement(ctxt, (const xmlChar *) "param", XSLT_NAMESPACE, (xsltTransformFunction) xsltDebug); xsltRegisterExtElement(ctxt, (const xmlChar *) "with-param", XSLT_NAMESPACE, (xsltTransformFunction) xsltDebug); xsltRegisterExtElement(ctxt, (const xmlChar *) "decimal-format", XSLT_NAMESPACE, (xsltTransformFunction) xsltDebug); xsltRegisterExtElement(ctxt, (const xmlChar *) "when", XSLT_NAMESPACE, (xsltTransformFunction) xsltDebug); xsltRegisterExtElement(ctxt, (const xmlChar *) "otherwise", XSLT_NAMESPACE, (xsltTransformFunction) xsltDebug); xsltRegisterExtElement(ctxt, (const xmlChar *) "fallback", XSLT_NAMESPACE, (xsltTransformFunction) xsltDebug); } 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 fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fdct16x16_c(in, out, stride); } CWE ID: CWE-119 Target: 1 Example 2: Code: void GM2TabStyle::HideHover(HideHoverStyle style) { if (hover_controller_) hover_controller_->Hide(style); } 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 install_exec_creds(struct linux_binprm *bprm) { security_bprm_committing_creds(bprm); commit_creds(bprm->cred); bprm->cred = NULL; /* * Disable monitoring for regular users * when executing setuid binaries. Must * wait until new credentials are committed * by commit_creds() above */ if (get_dumpable(current->mm) != SUID_DUMP_USER) perf_event_exit_task(current); /* * cred_guard_mutex must be held at least to this point to prevent * ptrace_attach() from altering our determination of the task's * credentials; any time after this it may be unlocked. */ security_bprm_committed_creds(bprm); mutex_unlock(&current->signal->cred_guard_mutex); } 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: static scoped_refptr<Extension> MakeSyncTestExtension( SyncTestExtensionType type, const GURL& update_url, const GURL& launch_url, Manifest::Location location, int num_plugins, const base::FilePath& extension_path, int creation_flags) { base::DictionaryValue source; source.SetString(keys::kName, "PossiblySyncableExtension"); source.SetString(keys::kVersion, "0.0.0.0"); if (type == APP) source.SetString(keys::kApp, "true"); if (type == THEME) source.Set(keys::kTheme, new base::DictionaryValue()); if (!update_url.is_empty()) { source.SetString(keys::kUpdateURL, update_url.spec()); } if (!launch_url.is_empty()) { source.SetString(keys::kLaunchWebURL, launch_url.spec()); } if (type != THEME) { source.SetBoolean(keys::kConvertedFromUserScript, type == USER_SCRIPT); base::ListValue* plugins = new base::ListValue(); for (int i = 0; i < num_plugins; ++i) { base::DictionaryValue* plugin = new base::DictionaryValue(); plugin->SetString(keys::kPluginsPath, std::string()); plugins->Set(i, plugin); } source.Set(keys::kPlugins, plugins); } std::string error; scoped_refptr<Extension> extension = Extension::Create( extension_path, location, source, creation_flags, &error); EXPECT_TRUE(extension.get()); EXPECT_EQ("", error); return extension; } CWE ID: Target: 1 Example 2: Code: static void arcmsr_handle_virtual_command(struct AdapterControlBlock *acb, struct scsi_cmnd *cmd) { switch (cmd->cmnd[0]) { case INQUIRY: { unsigned char inqdata[36]; char *buffer; struct scatterlist *sg; if (cmd->device->lun) { cmd->result = (DID_TIME_OUT << 16); cmd->scsi_done(cmd); return; } inqdata[0] = TYPE_PROCESSOR; /* Periph Qualifier & Periph Dev Type */ inqdata[1] = 0; /* rem media bit & Dev Type Modifier */ inqdata[2] = 0; /* ISO, ECMA, & ANSI versions */ inqdata[4] = 31; /* length of additional data */ strncpy(&inqdata[8], "Areca ", 8); /* Vendor Identification */ strncpy(&inqdata[16], "RAID controller ", 16); /* Product Identification */ strncpy(&inqdata[32], "R001", 4); /* Product Revision */ sg = scsi_sglist(cmd); buffer = kmap_atomic(sg_page(sg)) + sg->offset; memcpy(buffer, inqdata, sizeof(inqdata)); sg = scsi_sglist(cmd); kunmap_atomic(buffer - sg->offset); cmd->scsi_done(cmd); } break; case WRITE_BUFFER: case READ_BUFFER: { if (arcmsr_iop_message_xfer(acb, cmd)) cmd->result = (DID_ERROR << 16); cmd->scsi_done(cmd); } break; default: cmd->scsi_done(cmd); } } 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: String HTMLInputElement::selectionDirectionForBinding(ExceptionState& exceptionState) const { if (!m_inputType->supportsSelectionAPI()) { exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection."); return String(); } return HTMLTextFormControlElement::selectionDirection(); } 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: int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) { for (int page_index : visible_pages_) { if (pages_[page_index]->GetPage() == page) return page_index; } return -1; } CWE ID: CWE-20 Target: 1 Example 2: Code: struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode, ext4_lblk_t block, int create, int *err) { struct buffer_head *bh; bh = ext4_getblk(handle, inode, block, create, err); if (!bh) return bh; if (buffer_uptodate(bh)) return bh; ll_rw_block(READ_META, 1, &bh); wait_on_buffer(bh); if (buffer_uptodate(bh)) return bh; put_bh(bh); *err = -EIO; return NULL; } 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 VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitSlice( const H264PPS* pps, const H264SliceHeader* slice_hdr, const H264Picture::Vector& ref_pic_list0, const H264Picture::Vector& ref_pic_list1, const scoped_refptr<H264Picture>& pic, const uint8_t* data, size_t size) { VASliceParameterBufferH264 slice_param; memset(&slice_param, 0, sizeof(slice_param)); slice_param.slice_data_size = slice_hdr->nalu_size; slice_param.slice_data_offset = 0; slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; slice_param.slice_data_bit_offset = slice_hdr->header_bit_size; #define SHDRToSP(a) slice_param.a = slice_hdr->a SHDRToSP(first_mb_in_slice); slice_param.slice_type = slice_hdr->slice_type % 5; SHDRToSP(direct_spatial_mv_pred_flag); SHDRToSP(num_ref_idx_l0_active_minus1); SHDRToSP(num_ref_idx_l1_active_minus1); SHDRToSP(cabac_init_idc); SHDRToSP(slice_qp_delta); SHDRToSP(disable_deblocking_filter_idc); SHDRToSP(slice_alpha_c0_offset_div2); SHDRToSP(slice_beta_offset_div2); if (((slice_hdr->IsPSlice() || slice_hdr->IsSPSlice()) && pps->weighted_pred_flag) || (slice_hdr->IsBSlice() && pps->weighted_bipred_idc == 1)) { SHDRToSP(luma_log2_weight_denom); SHDRToSP(chroma_log2_weight_denom); SHDRToSP(luma_weight_l0_flag); SHDRToSP(luma_weight_l1_flag); SHDRToSP(chroma_weight_l0_flag); SHDRToSP(chroma_weight_l1_flag); for (int i = 0; i <= slice_param.num_ref_idx_l0_active_minus1; ++i) { slice_param.luma_weight_l0[i] = slice_hdr->pred_weight_table_l0.luma_weight[i]; slice_param.luma_offset_l0[i] = slice_hdr->pred_weight_table_l0.luma_offset[i]; for (int j = 0; j < 2; ++j) { slice_param.chroma_weight_l0[i][j] = slice_hdr->pred_weight_table_l0.chroma_weight[i][j]; slice_param.chroma_offset_l0[i][j] = slice_hdr->pred_weight_table_l0.chroma_offset[i][j]; } } if (slice_hdr->IsBSlice()) { for (int i = 0; i <= slice_param.num_ref_idx_l1_active_minus1; ++i) { slice_param.luma_weight_l1[i] = slice_hdr->pred_weight_table_l1.luma_weight[i]; slice_param.luma_offset_l1[i] = slice_hdr->pred_weight_table_l1.luma_offset[i]; for (int j = 0; j < 2; ++j) { slice_param.chroma_weight_l1[i][j] = slice_hdr->pred_weight_table_l1.chroma_weight[i][j]; slice_param.chroma_offset_l1[i][j] = slice_hdr->pred_weight_table_l1.chroma_offset[i][j]; } } } } static_assert( arraysize(slice_param.RefPicList0) == arraysize(slice_param.RefPicList1), "Invalid RefPicList sizes"); for (size_t i = 0; i < arraysize(slice_param.RefPicList0); ++i) { InitVAPicture(&slice_param.RefPicList0[i]); InitVAPicture(&slice_param.RefPicList1[i]); } for (size_t i = 0; i < ref_pic_list0.size() && i < arraysize(slice_param.RefPicList0); ++i) { if (ref_pic_list0[i]) FillVAPicture(&slice_param.RefPicList0[i], ref_pic_list0[i]); } for (size_t i = 0; i < ref_pic_list1.size() && i < arraysize(slice_param.RefPicList1); ++i) { if (ref_pic_list1[i]) FillVAPicture(&slice_param.RefPicList1[i], ref_pic_list1[i]); } if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType, sizeof(slice_param), &slice_param)) return false; void* non_const_ptr = const_cast<uint8_t*>(data); return vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, size, non_const_ptr); } 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 EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod5(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) { setDOMException(exec, TYPE_MISMATCH_ERR); return JSValue::encode(jsUndefined()); } RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject()); impl->overloadedMethod(callback); return JSValue::encode(jsUndefined()); } CWE ID: CWE-20 Target: 1 Example 2: Code: void HTMLFormElement::setEnctype(const AtomicString& value) { setAttribute(enctypeAttr, value); } 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: void SupervisedUserService::UpdateApprovedExtensions() { const base::DictionaryValue* dict = profile_->GetPrefs()->GetDictionary( prefs::kSupervisedUserApprovedExtensions); std::set<std::string> extensions_to_be_checked; for (const auto& extension : approved_extensions_map_) extensions_to_be_checked.insert(extension.first); approved_extensions_map_.clear(); for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { std::string version_str; bool result = it.value().GetAsString(&version_str); DCHECK(result); base::Version version(version_str); if (version.IsValid()) { approved_extensions_map_[it.key()] = version; extensions_to_be_checked.insert(it.key()); } else { LOG(WARNING) << "Invalid version number " << version_str; } } for (const auto& extension_id : extensions_to_be_checked) { ChangeExtensionStateIfNecessary(extension_id); } } 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: struct request *blk_mq_tag_to_rq(struct blk_mq_tags *tags, unsigned int tag) { struct request *rq = tags->rqs[tag]; /* mq_ctx of flush rq is always cloned from the corresponding req */ struct blk_flush_queue *fq = blk_get_flush_queue(rq->q, rq->mq_ctx); if (!is_flush_request(rq, fq, tag)) return rq; return fq->flush_rq; } CWE ID: CWE-362 Target: 1 Example 2: Code: static PaintChunk Chunk(const PropertyTreeState& state) { DEFINE_STATIC_LOCAL(FakeDisplayItemClient, fake_client, ()); DEFINE_STATIC_LOCAL( base::Optional<PaintChunk::Id>, id, (PaintChunk::Id(fake_client, DisplayItem::kDrawingFirst))); PaintChunk chunk(0, 0, *id, state); return chunk; } 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 del_session(SSL_CTX *sctx, SSL_SESSION *session) { simple_ssl_session *sess, *prev = NULL; const unsigned char *id; unsigned int idlen; id = SSL_SESSION_get_id(session, &idlen); for (sess = first; sess; sess = sess->next) { if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) { if (prev) prev->next = sess->next; else first = sess->next; OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return; } prev = sess; } } 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: g_NPN_GetValue(NPP instance, NPNVariable variable, void *value) { D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable))); if (!thread_check()) { npw_printf("WARNING: NPN_GetValue not called from the main thread\n"); return NPERR_INVALID_INSTANCE_ERROR; } PluginInstance *plugin = NULL; if (instance) plugin = PLUGIN_INSTANCE(instance); switch (variable) { case NPNVxDisplay: *(void **)value = x_display; break; case NPNVxtAppContext: *(void **)value = XtDisplayToApplicationContext(x_display); break; case NPNVToolkit: *(NPNToolkitType *)value = NPW_TOOLKIT; break; #if USE_XPCOM case NPNVserviceManager: { nsIServiceManager *sm; int ret = NS_GetServiceManager(&sm); if (NS_FAILED(ret)) { npw_printf("WARNING: NS_GetServiceManager failed\n"); return NPERR_GENERIC_ERROR; } *(nsIServiceManager **)value = sm; break; } case NPNVDOMWindow: case NPNVDOMElement: npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable)); return NPERR_INVALID_PARAM; #endif case NPNVnetscapeWindow: if (plugin == NULL) { npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n"); return NPERR_INVALID_INSTANCE_ERROR; } if (plugin->browser_toplevel == NULL) { GdkNativeWindow netscape_xid = None; NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid); if (error != NPERR_NO_ERROR) return error; if (netscape_xid == None) return NPERR_GENERIC_ERROR; plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid); if (plugin->browser_toplevel == NULL) return NPERR_GENERIC_ERROR; } *((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel); break; #if ALLOW_WINDOWLESS_PLUGINS case NPNVSupportsWindowless: #endif case NPNVSupportsXEmbedBool: case NPNVWindowNPObject: case NPNVPluginElementNPObject: return g_NPN_GetValue_real(instance, variable, value); default: switch (variable & 0xff) { case 13: /* NPNVToolkit */ if (NPW_TOOLKIT == NPNVGtk2) { *(NPNToolkitType *)value = NPW_TOOLKIT; return NPERR_NO_ERROR; } break; } D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable))); return NPERR_INVALID_PARAM; } return NPERR_NO_ERROR; } CWE ID: CWE-264 Target: 1 Example 2: Code: void PopupContainer::paintBorder(GraphicsContext* gc, const IntRect& rect) { Color borderColor(127, 157, 185); gc->setStrokeStyle(NoStroke); gc->setFillColor(borderColor, ColorSpaceDeviceRGB); int tx = x(); int ty = y(); gc->drawRect(IntRect(tx, ty, width(), kBorderSize)); gc->drawRect(IntRect(tx, ty, kBorderSize, height())); gc->drawRect(IntRect(tx, ty + height() - kBorderSize, width(), kBorderSize)); gc->drawRect(IntRect(tx + width() - kBorderSize, ty, kBorderSize, height())); } 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: SProcRenderTrapezoids (ClientPtr client) { register int n; REQUEST(xRenderTrapezoidsReq); REQUEST_AT_LEAST_SIZE(xRenderTrapezoidsReq); swaps (&stuff->length, n); swapl (&stuff->src, n); swapl (&stuff->dst, n); swapl (&stuff->maskFormat, n); swaps (&stuff->xSrc, n); swaps (&stuff->ySrc, n); SwapRestL(stuff); return (*ProcRenderVector[stuff->renderReqType]) (client); } 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 em_ret(struct x86_emulate_ctxt *ctxt) { ctxt->dst.type = OP_REG; ctxt->dst.addr.reg = &ctxt->_eip; ctxt->dst.bytes = ctxt->op_bytes; return em_pop(ctxt); } CWE ID: CWE-264 Target: 1 Example 2: Code: concat_opt_exact(OptStr* to, OptStr* add, OnigEncoding enc) { int i, j, len, r; UChar *p, *end; OptAnc tanc; if (add->case_fold != 0) { if (! to->case_fold) { if (to->len > 1 || to->len >= add->len) return 0; /* avoid */ to->case_fold = 1; } else { if (to->good_case_fold != 0) { if (add->good_case_fold == 0) return 0; } } } r = 0; p = add->s; end = p + add->len; for (i = to->len; p < end; ) { len = enclen(enc, p); if (i + len > OPT_EXACT_MAXLEN) { r = 1; /* 1:full */ break; } for (j = 0; j < len && p < end; j++) to->s[i++] = *p++; } to->len = i; to->reach_end = (p == end ? add->reach_end : 0); concat_opt_anc_info(&tanc, &to->anc, &add->anc, 1, 1); if (! to->reach_end) tanc.right = 0; copy_opt_anc_info(&to->anc, &tanc); return r; } 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 wvlan_rts(struct rtsreq *rrq, __u32 io_base) { int ioctl_ret = 0; /*------------------------------------------------------------------------*/ DBG_FUNC("wvlan_rts"); DBG_ENTER(DbgInfo); DBG_PRINT("io_base: 0x%08x\n", io_base); switch (rrq->typ) { case WL_IOCTL_RTS_READ: DBG_TRACE(DbgInfo, "IOCTL: WVLAN2_IOCTL_RTS -- WL_IOCTL_RTS_READ\n"); rrq->data[0] = IN_PORT_WORD(io_base + rrq->reg); DBG_TRACE(DbgInfo, " reg 0x%04x ==> 0x%04x\n", rrq->reg, CNV_LITTLE_TO_SHORT(rrq->data[0])); break; case WL_IOCTL_RTS_WRITE: DBG_TRACE(DbgInfo, "IOCTL: WVLAN2_IOCTL_RTS -- WL_IOCTL_RTS_WRITE\n"); OUT_PORT_WORD(io_base + rrq->reg, rrq->data[0]); DBG_TRACE(DbgInfo, " reg 0x%04x <== 0x%04x\n", rrq->reg, CNV_LITTLE_TO_SHORT(rrq->data[0])); break; case WL_IOCTL_RTS_BATCH_READ: DBG_TRACE(DbgInfo, "IOCTL: WVLAN2_IOCTL_RTS -- WL_IOCTL_RTS_BATCH_READ\n"); IN_PORT_STRING_16(io_base + rrq->reg, rrq->data, rrq->len); DBG_TRACE(DbgInfo, " reg 0x%04x ==> %d bytes\n", rrq->reg, rrq->len * sizeof(__u16)); break; case WL_IOCTL_RTS_BATCH_WRITE: DBG_TRACE(DbgInfo, "IOCTL: WVLAN2_IOCTL_RTS -- WL_IOCTL_RTS_BATCH_WRITE\n"); OUT_PORT_STRING_16(io_base + rrq->reg, rrq->data, rrq->len); DBG_TRACE(DbgInfo, " reg 0x%04x <== %d bytes\n", rrq->reg, rrq->len * sizeof(__u16)); break; default: DBG_TRACE(DbgInfo, "IOCTL: WVLAN2_IOCTL_RTS -- UNSUPPORTED RTS CODE: 0x%X", rrq->typ); ioctl_ret = -EOPNOTSUPP; break; } DBG_LEAVE(DbgInfo); return ioctl_ret; } /* wvlan_rts */ 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: asmlinkage long sys_oabi_semtimedop(int semid, struct oabi_sembuf __user *tsops, unsigned nsops, const struct timespec __user *timeout) { struct sembuf *sops; struct timespec local_timeout; long err; int i; if (nsops < 1) return -EINVAL; sops = kmalloc(sizeof(*sops) * nsops, GFP_KERNEL); if (!sops) return -ENOMEM; err = 0; for (i = 0; i < nsops; i++) { __get_user_error(sops[i].sem_num, &tsops->sem_num, err); __get_user_error(sops[i].sem_op, &tsops->sem_op, err); __get_user_error(sops[i].sem_flg, &tsops->sem_flg, err); tsops++; } if (timeout) { /* copy this as well before changing domain protection */ err |= copy_from_user(&local_timeout, timeout, sizeof(*timeout)); timeout = &local_timeout; } if (err) { err = -EFAULT; } else { mm_segment_t fs = get_fs(); set_fs(KERNEL_DS); err = sys_semtimedop(semid, sops, nsops, timeout); set_fs(fs); } kfree(sops); return err; } CWE ID: CWE-189 Target: 1 Example 2: Code: static inline int compare_keys(struct rtable *rt1, struct rtable *rt2) { return (((__force u32)rt1->rt_key_dst ^ (__force u32)rt2->rt_key_dst) | ((__force u32)rt1->rt_key_src ^ (__force u32)rt2->rt_key_src) | (rt1->rt_mark ^ rt2->rt_mark) | (rt1->rt_key_tos ^ rt2->rt_key_tos) | (rt1->rt_oif ^ rt2->rt_oif) | (rt1->rt_iif ^ rt2->rt_iif)) == 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 ChromeContentBrowserClient::RegisterIOThreadServiceHandlers( content::ServiceManagerConnection* connection) { connection->AddServiceRequestHandler( chrome::mojom::kServiceName, ChromeService::GetInstance()->CreateChromeServiceRequestHandler()); #if defined(OS_ANDROID) connection->AddServiceRequestHandler( proxy_resolver::mojom::kProxyResolverServiceName, base::BindRepeating([](service_manager::mojom::ServiceRequest request) { service_manager::Service::RunAsyncUntilTermination( std::make_unique<proxy_resolver::ProxyResolverService>( std::move(request))); })); connection->AddServiceRequestHandler( "download_manager", base::BindRepeating(&StartDownloadManager)); #endif if (heap_profiling::IsInProcessModeEnabled()) { connection->AddServiceRequestHandler( heap_profiling::mojom::kServiceName, heap_profiling::HeapProfilingService::GetServiceFactory()); } } 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 BlobURLRequestJob::DidGetFileItemLength(size_t index, int64 result) { if (error_) return; if (result == net::ERR_UPLOAD_FILE_CHANGED) { NotifyFailure(net::ERR_FILE_NOT_FOUND); return; } else if (result < 0) { NotifyFailure(result); return; } DCHECK_LT(index, blob_data_->items().size()); const BlobData::Item& item = blob_data_->items().at(index); DCHECK(IsFileType(item.type())); int64 item_length = static_cast<int64>(item.length()); if (item_length == -1) item_length = result - item.offset(); DCHECK_LT(index, item_length_list_.size()); item_length_list_[index] = item_length; total_size_ += item_length; if (--pending_get_file_info_count_ == 0) DidCountSize(net::OK); } CWE ID: CWE-189 Target: 1 Example 2: Code: const base::UnguessableToken& RenderFrameHostImpl::GetOverlayRoutingToken() { if (!overlay_routing_token_) { overlay_routing_token_ = base::UnguessableToken::Create(); g_token_frame_map.Get().emplace(*overlay_routing_token_, this); } return *overlay_routing_token_; } 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: static uint8_t *extend_raw_data(LHAFileHeader **header, LHAInputStream *stream, size_t nbytes) { LHAFileHeader *new_header; size_t new_raw_len; uint8_t *result; new_raw_len = RAW_DATA_LEN(header) + nbytes; new_header = realloc(*header, sizeof(LHAFileHeader) + new_raw_len); if (new_header == NULL) { return NULL; } *header = new_header; new_header->raw_data = (uint8_t *) (new_header + 1); result = new_header->raw_data + new_header->raw_data_len; if (!lha_input_stream_read(stream, result, nbytes)) { return NULL; } new_header->raw_data_len = new_raw_len; return result; } CWE ID: CWE-190 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 BackendImpl::OnEntryDestroyEnd() { DecreaseNumRefs(); if (data_->header.num_bytes > max_size_ && !read_only_ && (up_ticks_ > kTrimDelay || user_flags_ & kNoRandom)) eviction_.TrimCache(false); } CWE ID: CWE-20 Target: 1 Example 2: Code: bool ndp_msgna_flag_solicited(struct ndp_msgna *msgna) { return msgna->na->nd_na_flags_reserved & ND_NA_FLAG_SOLICITED; } CWE ID: CWE-284 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: xsltElementComp(xsltStylesheetPtr style, xmlNodePtr inst) { #ifdef XSLT_REFACTORED xsltStyleItemElementPtr comp; #else xsltStylePreCompPtr comp; #endif /* * <xsl:element * name = { qname } * namespace = { uri-reference } * use-attribute-sets = qnames> * <!-- Content: template --> * </xsl:element> */ if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE)) return; #ifdef XSLT_REFACTORED comp = (xsltStyleItemElementPtr) xsltNewStylePreComp(style, XSLT_FUNC_ELEMENT); #else comp = xsltNewStylePreComp(style, XSLT_FUNC_ELEMENT); #endif if (comp == NULL) return; inst->psvi = comp; comp->inst = inst; /* * Attribute "name". */ /* * TODO: Precompile the AVT. See bug #344894. */ comp->name = xsltEvalStaticAttrValueTemplate(style, inst, (const xmlChar *)"name", NULL, &comp->has_name); if (! comp->has_name) { xsltTransformError(NULL, style, inst, "xsl:element: The attribute 'name' is missing.\n"); style->errors++; goto error; } /* * Attribute "namespace". */ /* * TODO: Precompile the AVT. See bug #344894. */ comp->ns = xsltEvalStaticAttrValueTemplate(style, inst, (const xmlChar *)"namespace", NULL, &comp->has_ns); if (comp->name != NULL) { if (xmlValidateQName(comp->name, 0)) { xsltTransformError(NULL, style, inst, "xsl:element: The value '%s' of the attribute 'name' is " "not a valid QName.\n", comp->name); style->errors++; } else { const xmlChar *prefix = NULL, *name; name = xsltSplitQName(style->dict, comp->name, &prefix); if (comp->has_ns == 0) { xmlNsPtr ns; /* * SPEC XSLT 1.0: * "If the namespace attribute is not present, then the QName is * expanded into an expanded-name using the namespace declarations * in effect for the xsl:element element, including any default * namespace declaration. */ ns = xmlSearchNs(inst->doc, inst, prefix); if (ns != NULL) { comp->ns = xmlDictLookup(style->dict, ns->href, -1); comp->has_ns = 1; #ifdef XSLT_REFACTORED comp->nsPrefix = prefix; comp->name = name; #endif } else if (prefix != NULL) { xsltTransformError(NULL, style, inst, "xsl:element: The prefixed QName '%s' " "has no namespace binding in scope in the " "stylesheet; this is an error, since the namespace was " "not specified by the instruction itself.\n", comp->name); style->errors++; } } if ((prefix != NULL) && (!xmlStrncasecmp(prefix, (xmlChar *)"xml", 3))) { /* * Mark is to be skipped. */ comp->has_name = 0; } } } /* * Attribute "use-attribute-sets", */ comp->use = xsltEvalStaticAttrValueTemplate(style, inst, (const xmlChar *)"use-attribute-sets", NULL, &comp->has_use); error: return; } 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 PPVarToNPVariant(PP_Var var, NPVariant* result) { switch (var.type) { case PP_VARTYPE_UNDEFINED: VOID_TO_NPVARIANT(*result); break; case PP_VARTYPE_NULL: NULL_TO_NPVARIANT(*result); break; case PP_VARTYPE_BOOL: BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result); break; case PP_VARTYPE_INT32: INT32_TO_NPVARIANT(var.value.as_int, *result); break; case PP_VARTYPE_DOUBLE: DOUBLE_TO_NPVARIANT(var.value.as_double, *result); break; case PP_VARTYPE_STRING: { scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); if (!string) { VOID_TO_NPVARIANT(*result); return false; } const std::string& value = string->value(); STRINGN_TO_NPVARIANT(base::strdup(value.c_str()), value.size(), *result); break; } case PP_VARTYPE_OBJECT: { scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); if (!object) { VOID_TO_NPVARIANT(*result); return false; } OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()), *result); break; } case PP_VARTYPE_ARRAY: case PP_VARTYPE_DICTIONARY: VOID_TO_NPVARIANT(*result); break; } return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int __init seed_init(void) { return crypto_register_alg(&seed_alg); } 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 byte cencrypt(byte plain, unsigned short *cr) { const byte cipher = (byte) (plain ^ (*cr >> 8)); *cr = (unsigned short) ((cipher + *cr) * t1_c1 + t1_c2); return cipher; } 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 LauncherView::CalculateIdealBounds(IdealBounds* bounds) { int available_size = primary_axis_coordinate(width(), height()); if (!available_size) return; int x = primary_axis_coordinate(kLeadingInset, 0); int y = primary_axis_coordinate(0, kLeadingInset); for (int i = 0; i < view_model_->view_size(); ++i) { view_model_->set_ideal_bounds(i, gfx::Rect( x, y, kLauncherPreferredSize, kLauncherPreferredSize)); x = primary_axis_coordinate(x + kLauncherPreferredSize + kButtonSpacing, 0); y = primary_axis_coordinate(0, y + kLauncherPreferredSize + kButtonSpacing); } if (view_model_->view_size() > 0) { view_model_->set_ideal_bounds(0, gfx::Rect(gfx::Size( primary_axis_coordinate(kLeadingInset + kLauncherPreferredSize, kLauncherPreferredSize), primary_axis_coordinate(kLauncherPreferredSize, kLeadingInset + kLauncherPreferredSize)))); } bounds->overflow_bounds.set_size( gfx::Size(kLauncherPreferredSize, kLauncherPreferredSize)); last_visible_index_ = DetermineLastVisibleIndex( available_size - kLeadingInset - kLauncherPreferredSize - kButtonSpacing - kLauncherPreferredSize); int app_list_index = view_model_->view_size() - 1; bool show_overflow = (last_visible_index_ + 1 < app_list_index); for (int i = 0; i < view_model_->view_size(); ++i) { view_model_->view_at(i)->SetVisible( i == app_list_index || i <= last_visible_index_); } overflow_button_->SetVisible(show_overflow); if (show_overflow) { DCHECK_NE(0, view_model_->view_size()); if (last_visible_index_ == -1) { x = primary_axis_coordinate(kLeadingInset, 0); y = primary_axis_coordinate(0, kLeadingInset); } else { x = primary_axis_coordinate( view_model_->ideal_bounds(last_visible_index_).right(), 0); y = primary_axis_coordinate(0, view_model_->ideal_bounds(last_visible_index_).bottom()); } gfx::Rect app_list_bounds = view_model_->ideal_bounds(app_list_index); app_list_bounds.set_x(x); app_list_bounds.set_y(y); view_model_->set_ideal_bounds(app_list_index, app_list_bounds); x = primary_axis_coordinate(x + kLauncherPreferredSize + kButtonSpacing, 0); y = primary_axis_coordinate(0, y + kLauncherPreferredSize + kButtonSpacing); bounds->overflow_bounds.set_x(x); bounds->overflow_bounds.set_y(y); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void __freed_request(struct request_list *rl, int sync) { struct request_queue *q = rl->q; if (rl->count[sync] < queue_congestion_off_threshold(q)) blk_clear_congested(rl, sync); if (rl->count[sync] + 1 <= q->nr_requests) { if (waitqueue_active(&rl->wait[sync])) wake_up(&rl->wait[sync]); blk_clear_rl_full(rl, sync); } } 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: int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index) { struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table; int i, err = 0; int free = -1; mutex_lock(&table->mutex); for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) { if (free < 0 && (table->refs[i] == 0)) { free = i; continue; } if (table->refs[i] && (vlan == (MLX4_VLAN_MASK & be32_to_cpu(table->entries[i])))) { /* Vlan already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } if (table->total == table->max) { /* No free vlan entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID); err = mlx4_set_port_vlan_table(dev, port, table->entries); if (unlikely(err)) { mlx4_warn(dev, "Failed adding vlan: %u\n", vlan); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; } 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: status_t SampleTable::setCompositionTimeToSampleParams( off64_t data_offset, size_t data_size) { ALOGI("There are reordered frames present."); if (mCompositionTimeDeltaEntries != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } size_t numEntries = U32_AT(&header[4]); if (data_size != (numEntries + 1) * 8) { return ERROR_MALFORMED; } mNumCompositionTimeDeltaEntries = numEntries; uint64_t allocSize = numEntries * 2 * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mCompositionTimeDeltaEntries = new uint32_t[2 * numEntries]; if (mDataSource->readAt( data_offset + 8, mCompositionTimeDeltaEntries, numEntries * 8) < (ssize_t)numEntries * 8) { delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; return ERROR_IO; } for (size_t i = 0; i < 2 * numEntries; ++i) { mCompositionTimeDeltaEntries[i] = ntohl(mCompositionTimeDeltaEntries[i]); } mCompositionDeltaLookup->setEntries( mCompositionTimeDeltaEntries, mNumCompositionTimeDeltaEntries); return OK; } CWE ID: CWE-189 Target: 1 Example 2: Code: SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events, int, maxevents, int, timeout, const sigset_t __user *, sigmask, size_t, sigsetsize) { int error; sigset_t ksigmask, sigsaved; /* * If the caller wants a certain signal mask to be set during the wait, * we apply it here. */ if (sigmask) { if (sigsetsize != sizeof(sigset_t)) return -EINVAL; if (copy_from_user(&ksigmask, sigmask, sizeof(ksigmask))) return -EFAULT; sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP)); sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved); } error = sys_epoll_wait(epfd, events, maxevents, timeout); /* * If we changed the signal mask, we need to restore the original one. * In case we've got a signal while waiting, we do not restore the * signal mask yet, and we allow do_signal() to deliver the signal on * the way back to userspace, before the signal mask is restored. */ if (sigmask) { if (error == -EINTR) { memcpy(&current->saved_sigmask, &sigsaved, sizeof(sigsaved)); set_restore_sigmask(); } else sigprocmask(SIG_SETMASK, &sigsaved, NULL); } return 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: int BackendImpl::RunTaskForTest(const base::Closure& task, const CompletionCallback& callback) { background_queue_.RunTask(task, callback); return net::ERR_IO_PENDING; } 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: int sanity_check_ckpt(struct f2fs_sb_info *sbi) { unsigned int total, fsmeta; struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); unsigned int ovp_segments, reserved_segments; total = le32_to_cpu(raw_super->segment_count); fsmeta = le32_to_cpu(raw_super->segment_count_ckpt); fsmeta += le32_to_cpu(raw_super->segment_count_sit); fsmeta += le32_to_cpu(raw_super->segment_count_nat); fsmeta += le32_to_cpu(ckpt->rsvd_segment_count); fsmeta += le32_to_cpu(raw_super->segment_count_ssa); if (unlikely(fsmeta >= total)) return 1; ovp_segments = le32_to_cpu(ckpt->overprov_segment_count); reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count); if (unlikely(fsmeta < F2FS_MIN_SEGMENTS || ovp_segments == 0 || reserved_segments == 0)) { f2fs_msg(sbi->sb, KERN_ERR, "Wrong layout: check mkfs.f2fs version"); return 1; } if (unlikely(f2fs_cp_error(sbi))) { f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck"); return 1; } return 0; } CWE ID: CWE-129 Target: 1 Example 2: Code: static struct inode *shmem_alloc_inode(struct super_block *sb) { struct shmem_inode_info *info; info = kmem_cache_alloc(shmem_inode_cachep, GFP_KERNEL); if (!info) return NULL; return &info->vfs_inode; } 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 RenderViewImpl::OnMediaPlayerActionAt(const gfx::Point& location, const WebMediaPlayerAction& action) { if (webview()) webview()->PerformMediaPlayerAction(action, location); } 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: static void ffs_user_copy_worker(struct work_struct *work) { struct ffs_io_data *io_data = container_of(work, struct ffs_io_data, work); int ret = io_data->req->status ? io_data->req->status : io_data->req->actual; if (io_data->read && ret > 0) { use_mm(io_data->mm); ret = copy_to_iter(io_data->buf, ret, &io_data->data); if (iov_iter_count(&io_data->data)) ret = -EFAULT; unuse_mm(io_data->mm); } io_data->kiocb->ki_complete(io_data->kiocb, ret, ret); if (io_data->ffs->ffs_eventfd && !(io_data->kiocb->ki_flags & IOCB_EVENTFD)) eventfd_signal(io_data->ffs->ffs_eventfd, 1); usb_ep_free_request(io_data->ep, io_data->req); io_data->kiocb->private = NULL; if (io_data->read) kfree(io_data->to_free); kfree(io_data->buf); kfree(io_data); } CWE ID: CWE-416 Target: 1 Example 2: Code: static PHP_FUNCTION(xmlwriter_start_attribute_ns) { zval *pind; xmlwriter_object *intern; xmlTextWriterPtr ptr; char *name, *prefix, *uri; int name_len, prefix_len, uri_len, retval; #ifdef ZEND_ENGINE_2 zval *this = getThis(); if (this) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss!", &prefix, &prefix_len, &name, &name_len, &uri, &uri_len) == FAILURE) { return; } XMLWRITER_FROM_OBJECT(intern, this); } else #endif { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsss!", &pind, &prefix, &prefix_len, &name, &name_len, &uri, &uri_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(intern,xmlwriter_object *, &pind, -1, "XMLWriter", le_xmlwriter); } XMLW_NAME_CHK("Invalid Attribute Name"); ptr = intern->ptr; if (ptr) { retval = xmlTextWriterStartAttributeNS(ptr, (xmlChar *)prefix, (xmlChar *)name, (xmlChar *)uri); if (retval != -1) { RETURN_TRUE; } } RETURN_FALSE; } CWE ID: CWE-254 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 crypto_rng_reset(struct crypto_rng *tfm, const u8 *seed, unsigned int slen) { u8 *buf = NULL; int err; if (!seed && slen) { buf = kmalloc(slen, GFP_KERNEL); if (!buf) return -ENOMEM; get_random_bytes(buf, slen); seed = buf; } err = tfm->seed(tfm, seed, slen); kfree(buf); return err; } 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: string16 ExtensionInstallUI::Prompt::GetDialogTitle( const Extension* extension) const { if (type_ == INSTALL_PROMPT) { return l10n_util::GetStringUTF16(extension->is_app() ? IDS_EXTENSION_INSTALL_APP_PROMPT_TITLE : IDS_EXTENSION_INSTALL_EXTENSION_PROMPT_TITLE); } else if (type_ == INLINE_INSTALL_PROMPT) { return l10n_util::GetStringFUTF16( kTitleIds[type_], l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); } else { return l10n_util::GetStringUTF16(kTitleIds[type_]); } } CWE ID: CWE-119 Target: 1 Example 2: Code: StoragePartition* RenderProcessHostImpl::GetStoragePartition() const { return storage_partition_impl_; } 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 TestAppInstancesHelper(const std::string& app_name) { LOG(INFO) << "Start of test."; extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser()->profile()); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII(app_name))); const Extension* extension = GetSingleLoadedExtension(); GURL base_url = GetTestBaseURL(app_name); ui_test_utils::NavigateToURLWithDisposition( browser(), base_url.Resolve("path1/empty.html"), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); LOG(INFO) << "Nav 1."; EXPECT_TRUE(process_map->Contains( browser()->tab_strip_model()->GetWebContentsAt(1)-> GetRenderProcessHost()->GetID())); EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(1)->GetWebUI()); content::WindowedNotificationObserver tab_added_observer( chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); chrome::NewTab(browser()); tab_added_observer.Wait(); LOG(INFO) << "New tab."; ui_test_utils::NavigateToURL(browser(), base_url.Resolve("path2/empty.html")); LOG(INFO) << "Nav 2."; EXPECT_TRUE(process_map->Contains( browser()->tab_strip_model()->GetWebContentsAt(2)-> GetRenderProcessHost()->GetID())); EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(2)->GetWebUI()); ASSERT_EQ(3, browser()->tab_strip_model()->count()); WebContents* tab1 = browser()->tab_strip_model()->GetWebContentsAt(1); WebContents* tab2 = browser()->tab_strip_model()->GetWebContentsAt(2); EXPECT_NE(tab1->GetRenderProcessHost(), tab2->GetRenderProcessHost()); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); OpenWindow(tab1, base_url.Resolve("path1/empty.html"), true, NULL); LOG(INFO) << "WindowOpenHelper 1."; OpenWindow(tab2, base_url.Resolve("path2/empty.html"), true, NULL); LOG(INFO) << "End of test."; UnloadExtension(extension->id()); } 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: my_object_send_car (MyObject *obj, GValueArray *invals, GValueArray **outvals, GError **error) { if (invals->n_values != 3 || G_VALUE_TYPE (g_value_array_get_nth (invals, 0)) != G_TYPE_STRING || G_VALUE_TYPE (g_value_array_get_nth (invals, 1)) != G_TYPE_UINT || G_VALUE_TYPE (g_value_array_get_nth (invals, 2)) != G_TYPE_VALUE) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid incoming values"); return FALSE; } *outvals = g_value_array_new (2); g_value_array_append (*outvals, NULL); g_value_init (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), G_TYPE_UINT); g_value_set_uint (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), g_value_get_uint (g_value_array_get_nth (invals, 1)) + 1); g_value_array_append (*outvals, NULL); g_value_init (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), DBUS_TYPE_G_OBJECT_PATH); g_value_set_boxed (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject2")); return TRUE; } CWE ID: CWE-264 Target: 1 Example 2: Code: KURL Document::OpenSearchDescriptionURL() { static const char kOpenSearchMIMEType[] = "application/opensearchdescription+xml"; static const char kOpenSearchRelation[] = "search"; if (!GetFrame() || GetFrame()->Tree().Parent()) return KURL(); if (!LoadEventFinished()) return KURL(); if (!head()) return KURL(); for (HTMLLinkElement* link_element = Traversal<HTMLLinkElement>::FirstChild(*head()); link_element; link_element = Traversal<HTMLLinkElement>::NextSibling(*link_element)) { if (!DeprecatedEqualIgnoringCase(link_element->GetType(), kOpenSearchMIMEType) || !DeprecatedEqualIgnoringCase(link_element->Rel(), kOpenSearchRelation)) continue; if (link_element->Href().IsEmpty()) continue; WebFeature osd_disposition; scoped_refptr<SecurityOrigin> target = SecurityOrigin::Create(link_element->Href()); if (IsSecureContext()) { osd_disposition = target->IsPotentiallyTrustworthy() ? WebFeature::kOpenSearchSecureOriginSecureTarget : WebFeature::kOpenSearchSecureOriginInsecureTarget; } else { osd_disposition = target->IsPotentiallyTrustworthy() ? WebFeature::kOpenSearchInsecureOriginSecureTarget : WebFeature::kOpenSearchInsecureOriginInsecureTarget; } UseCounter::Count(*this, osd_disposition); return link_element->Href(); } return KURL(); } 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: static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path) { if (tx_path) return skb->ip_summed != CHECKSUM_PARTIAL; else return skb->ip_summed == CHECKSUM_NONE; } CWE ID: CWE-400 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 DownloadFileManager::RenameCompletingDownloadFile( DownloadId global_id, const FilePath& full_path, bool overwrite_existing_file, const RenameCompletionCallback& callback) { VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id << " overwrite_existing_file = " << overwrite_existing_file << " full_path = \"" << full_path.value() << "\""; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); DownloadFile* download_file = GetDownloadFile(global_id); if (!download_file) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(callback, FilePath())); return; } VLOG(20) << __FUNCTION__ << "()" << " download_file = " << download_file->DebugString(); FilePath new_path = full_path; if (!overwrite_existing_file) { int uniquifier = file_util::GetUniquePathNumber(new_path, FILE_PATH_LITERAL("")); if (uniquifier > 0) { new_path = new_path.InsertBeforeExtensionASCII( StringPrintf(" (%d)", uniquifier)); } } net::Error rename_error = download_file->Rename(new_path); if (net::OK != rename_error) { CancelDownloadOnRename(global_id, rename_error); new_path.clear(); } else { download_file->AnnotateWithSourceInformation(); } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(callback, new_path)); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int xfer_init(const char *toserver, struct xfer_header **xferptr) { struct xfer_header *xfer = xzmalloc(sizeof(struct xfer_header)); int r; syslog(LOG_INFO, "XFER: connecting to server '%s'", toserver); /* Get a connection to the remote backend */ xfer->be = proxy_findserver(toserver, &imap_protocol, "", &backend_cached, NULL, NULL, imapd_in); if (!xfer->be) { syslog(LOG_ERR, "Failed to connect to server '%s'", toserver); r = IMAP_SERVER_UNAVAILABLE; goto fail; } xfer->remoteversion = backend_version(xfer->be); if (xfer->be->capability & CAPA_REPLICATION) { syslog(LOG_INFO, "XFER: destination supports replication"); xfer->use_replication = 1; /* attach our IMAP tag buffer to our protstreams as userdata */ xfer->be->in->userdata = xfer->be->out->userdata = &xfer->tagbuf; } xfer->toserver = xstrdup(toserver); xfer->topart = NULL; xfer->seendb = NULL; /* connect to mupdate server if configured */ if (config_mupdate_server && !mupdate_h) { syslog(LOG_INFO, "XFER: connecting to mupdate '%s'", config_mupdate_server); r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL); if (r) { syslog(LOG_INFO, "Failed to connect to mupdate '%s'", config_mupdate_server); goto fail; } } *xferptr = xfer; return 0; fail: xfer_done(&xfer); return r; } 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 struct sock *__llc_lookup(struct llc_sap *sap, struct llc_addr *daddr, struct llc_addr *laddr) { struct sock *sk = __llc_lookup_established(sap, daddr, laddr); return sk ? : llc_lookup_listener(sap, laddr); } 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: mm_answer_pam_free_ctx(int sock, Buffer *m) { debug3("%s", __func__); (sshpam_device.free_ctx)(sshpam_ctxt); buffer_clear(m); mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m); auth_method = "keyboard-interactive"; auth_submethod = "pam"; return (sshpam_authok == sshpam_ctxt); } CWE ID: CWE-264 Target: 1 Example 2: Code: static void crypto_remove_spawn(struct crypto_spawn *spawn, struct list_head *list) { struct crypto_instance *inst = spawn->inst; struct crypto_template *tmpl = inst->tmpl; if (crypto_is_dead(&inst->alg)) return; inst->alg.cra_flags |= CRYPTO_ALG_DEAD; if (hlist_unhashed(&inst->list)) return; if (!tmpl || !crypto_tmpl_get(tmpl)) return; crypto_notify(CRYPTO_MSG_ALG_UNREGISTER, &inst->alg); list_move(&inst->alg.cra_list, list); hlist_del(&inst->list); inst->alg.cra_destroy = crypto_destroy_instance; BUG_ON(!list_empty(&inst->alg.cra_users)); } 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: void NotifyPluginDirChanged(const FilePath& path, bool error) { if (error) { NOTREACHED(); return; } VLOG(1) << "Watched path changed: " << path.value(); webkit::npapi::PluginList::Singleton()->RefreshPlugins(); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&PluginService::PurgePluginListCache, static_cast<BrowserContext*>(NULL), false)); } CWE ID: CWE-287 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 ehci_advance_state(EHCIState *ehci, int async) { EHCIQueue *q = NULL; int again; do { case EST_WAITLISTHEAD: again = ehci_state_waitlisthead(ehci, async); break; case EST_FETCHENTRY: again = ehci_state_fetchentry(ehci, async); break; case EST_FETCHQH: q = ehci_state_fetchqh(ehci, async); if (q != NULL) { assert(q->async == async); again = 1; } else { again = 0; } break; case EST_FETCHITD: again = ehci_state_fetchitd(ehci, async); break; case EST_FETCHSITD: again = ehci_state_fetchsitd(ehci, async); break; case EST_ADVANCEQUEUE: case EST_FETCHQTD: assert(q != NULL); again = ehci_state_fetchqtd(q); break; case EST_HORIZONTALQH: assert(q != NULL); again = ehci_state_horizqh(q); break; case EST_EXECUTE: assert(q != NULL); again = ehci_state_execute(q); if (async) { ehci->async_stepdown = 0; } break; case EST_EXECUTING: assert(q != NULL); if (async) { ehci->async_stepdown = 0; } again = ehci_state_executing(q); break; case EST_WRITEBACK: assert(q != NULL); again = ehci_state_writeback(q); if (!async) { ehci->periodic_sched_active = PERIODIC_ACTIVE; } break; default: fprintf(stderr, "Bad state!\n"); again = -1; g_assert_not_reached(); break; } break; } CWE ID: CWE-20 Target: 1 Example 2: Code: int ChromeNetworkDelegate::OnHeadersReceived( net::URLRequest* request, const net::CompletionCallback& callback, const net::HttpResponseHeaders* original_response_headers, scoped_refptr<net::HttpResponseHeaders>* override_response_headers) { return ExtensionWebRequestEventRouter::GetInstance()->OnHeadersReceived( profile_, extension_info_map_.get(), request, callback, original_response_headers, override_response_headers); } 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 put_filp(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { security_file_free(file); file_sb_list_del(file); file_free(file); } } CWE ID: CWE-17 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: unsigned long long Track::GetDefaultDuration() const { return m_info.defaultDuration; } CWE ID: CWE-119 Target: 1 Example 2: Code: void V8Console::countCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { ConsoleHelper helper(info); String16 title = helper.firstArgToString(String16()); String16 identifier; if (title.isEmpty()) { std::unique_ptr<V8StackTraceImpl> stackTrace = V8StackTraceImpl::capture(nullptr, 0, 1); if (stackTrace) identifier = stackTrace->topSourceURL() + ":" + String16::fromInteger(stackTrace->topLineNumber()); } else { identifier = title + "@"; } v8::Local<v8::Map> countMap; if (!helper.privateMap("V8Console#countMap").ToLocal(&countMap)) return; int64_t count = helper.getIntFromMap(countMap, identifier, 0) + 1; helper.setIntOnMap(countMap, identifier, count); helper.reportCallWithArgument(ConsoleAPIType::kCount, title + ": " + String16::fromInteger(count)); } CWE ID: CWE-79 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 do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr, unsigned long shmlba) { struct shmid_kernel *shp; unsigned long addr; unsigned long size; struct file * file; int err; unsigned long flags; unsigned long prot; int acc_mode; struct ipc_namespace *ns; struct shm_file_data *sfd; struct path path; fmode_t f_mode; unsigned long populate = 0; err = -EINVAL; if (shmid < 0) goto out; else if ((addr = (ulong)shmaddr)) { if (addr & (shmlba - 1)) { if (shmflg & SHM_RND) addr &= ~(shmlba - 1); /* round down */ else #ifndef __ARCH_FORCE_SHMLBA if (addr & ~PAGE_MASK) #endif goto out; } flags = MAP_SHARED | MAP_FIXED; } else { if ((shmflg & SHM_REMAP)) goto out; flags = MAP_SHARED; } if (shmflg & SHM_RDONLY) { prot = PROT_READ; acc_mode = S_IRUGO; f_mode = FMODE_READ; } else { prot = PROT_READ | PROT_WRITE; acc_mode = S_IRUGO | S_IWUGO; f_mode = FMODE_READ | FMODE_WRITE; } if (shmflg & SHM_EXEC) { prot |= PROT_EXEC; acc_mode |= S_IXUGO; } /* * We cannot rely on the fs check since SYSV IPC does have an * additional creator id... */ ns = current->nsproxy->ipc_ns; rcu_read_lock(); shp = shm_obtain_object_check(ns, shmid); if (IS_ERR(shp)) { err = PTR_ERR(shp); goto out_unlock; } err = -EACCES; if (ipcperms(ns, &shp->shm_perm, acc_mode)) goto out_unlock; err = security_shm_shmat(shp, shmaddr, shmflg); if (err) goto out_unlock; ipc_lock_object(&shp->shm_perm); path = shp->shm_file->f_path; path_get(&path); shp->shm_nattch++; size = i_size_read(path.dentry->d_inode); ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); err = -ENOMEM; sfd = kzalloc(sizeof(*sfd), GFP_KERNEL); if (!sfd) { path_put(&path); goto out_nattch; } file = alloc_file(&path, f_mode, is_file_hugepages(shp->shm_file) ? &shm_file_operations_huge : &shm_file_operations); err = PTR_ERR(file); if (IS_ERR(file)) { kfree(sfd); path_put(&path); goto out_nattch; } file->private_data = sfd; file->f_mapping = shp->shm_file->f_mapping; sfd->id = shp->shm_perm.id; sfd->ns = get_ipc_ns(ns); sfd->file = shp->shm_file; sfd->vm_ops = NULL; err = security_mmap_file(file, prot, flags); if (err) goto out_fput; down_write(&current->mm->mmap_sem); if (addr && !(shmflg & SHM_REMAP)) { err = -EINVAL; if (find_vma_intersection(current->mm, addr, addr + size)) goto invalid; /* * If shm segment goes below stack, make sure there is some * space left for the stack to grow (at least 4 pages). */ if (addr < current->mm->start_stack && addr > current->mm->start_stack - size - PAGE_SIZE * 5) goto invalid; } addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate); *raddr = addr; err = 0; if (IS_ERR_VALUE(addr)) err = (long)addr; invalid: up_write(&current->mm->mmap_sem); if (populate) mm_populate(addr, populate); out_fput: fput(file); out_nattch: down_write(&shm_ids(ns).rwsem); shp = shm_lock(ns, shmid); BUG_ON(IS_ERR(shp)); shp->shm_nattch--; if (shm_may_destroy(ns, shp)) shm_destroy(ns, shp); else shm_unlock(shp); up_write(&shm_ids(ns).rwsem); return err; out_unlock: rcu_read_unlock(); out: return err; } 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: long long BlockGroup::GetDurationTimeCode() const { return m_duration; } CWE ID: CWE-119 Target: 1 Example 2: Code: static ssize_t ib_ucm_send_info(struct ib_ucm_file *file, const char __user *inbuf, int in_len, int (*func)(struct ib_cm_id *cm_id, int status, const void *info, u8 info_len, const void *data, u8 data_len)) { struct ib_ucm_context *ctx; struct ib_ucm_info cmd; const void *data = NULL; const void *info = NULL; int result; if (copy_from_user(&cmd, inbuf, sizeof(cmd))) return -EFAULT; result = ib_ucm_alloc_data(&data, cmd.data, cmd.data_len); if (result) goto done; result = ib_ucm_alloc_data(&info, cmd.info, cmd.info_len); if (result) goto done; ctx = ib_ucm_ctx_get(file, cmd.id); if (!IS_ERR(ctx)) { result = func(ctx->cm_id, cmd.status, info, cmd.info_len, data, cmd.data_len); ib_ucm_ctx_put(ctx); } else result = PTR_ERR(ctx); done: kfree(data); kfree(info); return result; } 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: void TabletModeWindowManager::ArrangeWindowsForClamshellMode( base::flat_map<aura::Window*, WindowStateType> windows_in_splitview) { int divider_position = CalculateCarryOverDividerPostion(windows_in_splitview); while (window_state_map_.size()) { aura::Window* window = window_state_map_.begin()->first; ForgetWindow(window, /*destroyed=*/false); } if (IsClamshellSplitViewModeEnabled()) { DoSplitViewTransition(windows_in_splitview, divider_position); } } 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 scoped_refptr<ScrollPaintPropertyNode> CreateScroll( scoped_refptr<const ScrollPaintPropertyNode> parent, const ScrollPaintPropertyNode::State& state_arg, MainThreadScrollingReasons main_thread_scrolling_reasons = MainThreadScrollingReason::kNotScrollingOnMain, CompositorElementId scroll_element_id = CompositorElementId()) { ScrollPaintPropertyNode::State state = state_arg; state.main_thread_scrolling_reasons = main_thread_scrolling_reasons; state.compositor_element_id = scroll_element_id; return ScrollPaintPropertyNode::Create(parent, std::move(state)); } CWE ID: Target: 1 Example 2: Code: int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq) { int rc; if (txq < 1 || txq > dev->num_tx_queues) return -EINVAL; if (dev->reg_state == NETREG_REGISTERED) { ASSERT_RTNL(); rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues, txq); if (rc) return rc; if (txq < dev->real_num_tx_queues) qdisc_reset_all_tx_gt(dev, txq); } dev->real_num_tx_queues = txq; return 0; } 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: void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode& node) { if (render_accessibility()) render_accessibility()->AccessibilityFocusedNodeChanged(node); } 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: _prolog_error(batch_job_launch_msg_t *req, int rc) { char *err_name_ptr, err_name[256], path_name[MAXPATHLEN]; char *fmt_char; int fd; if (req->std_err || req->std_out) { if (req->std_err) strncpy(err_name, req->std_err, sizeof(err_name)); else strncpy(err_name, req->std_out, sizeof(err_name)); if ((fmt_char = strchr(err_name, (int) '%')) && (fmt_char[1] == 'j') && !strchr(fmt_char+1, (int) '%')) { char tmp_name[256]; fmt_char[1] = 'u'; snprintf(tmp_name, sizeof(tmp_name), err_name, req->job_id); strncpy(err_name, tmp_name, sizeof(err_name)); } } else { snprintf(err_name, sizeof(err_name), "slurm-%u.out", req->job_id); } err_name_ptr = err_name; if (err_name_ptr[0] == '/') snprintf(path_name, MAXPATHLEN, "%s", err_name_ptr); else if (req->work_dir) snprintf(path_name, MAXPATHLEN, "%s/%s", req->work_dir, err_name_ptr); else snprintf(path_name, MAXPATHLEN, "/%s", err_name_ptr); if ((fd = open(path_name, (O_CREAT|O_APPEND|O_WRONLY), 0644)) == -1) { error("Unable to open %s: %s", path_name, slurm_strerror(errno)); return; } snprintf(err_name, sizeof(err_name), "Error running slurm prolog: %d\n", WEXITSTATUS(rc)); safe_write(fd, err_name, strlen(err_name)); if (fchown(fd, (uid_t) req->uid, (gid_t) req->gid) == -1) { snprintf(err_name, sizeof(err_name), "Couldn't change fd owner to %u:%u: %m\n", req->uid, req->gid); } rwfail: close(fd); } CWE ID: CWE-284 Target: 1 Example 2: Code: bool AXLayoutObject::ariaRoleHasPresentationalChildren() const { switch (m_ariaRole) { case ButtonRole: case SliderRole: case ImageRole: case ProgressIndicatorRole: case SpinButtonRole: return true; default: return false; } } CWE ID: CWE-254 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 sock *dccp_v4_request_recv_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet_request_sock *ireq; struct inet_sock *newinet; struct sock *newsk; if (sk_acceptq_is_full(sk)) goto exit_overflow; if (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL) goto exit; newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto exit_nonewsk; sk_setup_caps(newsk, dst); newinet = inet_sk(newsk); ireq = inet_rsk(req); newinet->inet_daddr = ireq->rmt_addr; newinet->inet_rcv_saddr = ireq->loc_addr; newinet->inet_saddr = ireq->loc_addr; newinet->opt = ireq->opt; ireq->opt = NULL; newinet->mc_index = inet_iif(skb); newinet->mc_ttl = ip_hdr(skb)->ttl; newinet->inet_id = jiffies; dccp_sync_mss(newsk, dst_mtu(dst)); if (__inet_inherit_port(sk, newsk) < 0) { sock_put(newsk); goto exit; } __inet_hash_nolisten(newsk, NULL); return newsk; exit_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); exit_nonewsk: dst_release(dst); exit: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); 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: void HttpAuthFilterWhitelist::AddRuleToBypassLocal() { rules_.AddRuleToBypassLocal(); } CWE ID: CWE-20 Target: 1 Example 2: Code: void RemoteFrame::SetWebLayer(WebLayer* web_layer) { if (web_layer_) GraphicsLayer::UnregisterContentsLayer(web_layer_); web_layer_ = web_layer; if (web_layer_) GraphicsLayer::RegisterContentsLayer(web_layer_); DCHECK(Owner()); ToHTMLFrameOwnerElement(Owner())->SetNeedsCompositingUpdate(); } 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: static ssize_t o2nm_node_num_store(struct config_item *item, const char *page, size_t count) { struct o2nm_node *node = to_o2nm_node(item); struct o2nm_cluster *cluster = to_o2nm_cluster_from_node(node); unsigned long tmp; char *p = (char *)page; int ret = 0; tmp = simple_strtoul(p, &p, 0); if (!p || (*p && (*p != '\n'))) return -EINVAL; if (tmp >= O2NM_MAX_NODES) return -ERANGE; /* once we're in the cl_nodes tree networking can look us up by * node number and try to use our address and port attributes * to connect to this node.. make sure that they've been set * before writing the node attribute? */ if (!test_bit(O2NM_NODE_ATTR_ADDRESS, &node->nd_set_attributes) || !test_bit(O2NM_NODE_ATTR_PORT, &node->nd_set_attributes)) return -EINVAL; /* XXX */ write_lock(&cluster->cl_nodes_lock); if (cluster->cl_nodes[tmp]) ret = -EEXIST; else if (test_and_set_bit(O2NM_NODE_ATTR_NUM, &node->nd_set_attributes)) ret = -EBUSY; else { cluster->cl_nodes[tmp] = node; node->nd_num = tmp; set_bit(tmp, cluster->cl_nodes_bitmap); } write_unlock(&cluster->cl_nodes_lock); if (ret) return ret; return count; } 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: OMX_ERRORTYPE omx_video::use_output_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, OMX_IN OMX_U8* buffer) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter unsigned char *buf_addr = NULL; #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("Inside use_output_buffer()"); if (bytes != m_sOutPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: use_output_buffer: Size Mismatch!! " "bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sOutPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_out_mem_ptr) { output_use_buffer = true; int nBufHdrSize = 0; DEBUG_PRINT_LOW("Allocating First Output Buffer(%u)",(unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); if (m_out_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_out_mem_ptr"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif if (m_out_mem_ptr) { bufHdr = m_out_mem_ptr; DEBUG_PRINT_LOW("Memory Allocation Succeeded for OUT port%p",m_out_mem_ptr); for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: Output buf mem alloc failed[0x%p]",m_out_mem_ptr); eRet = OMX_ErrorInsufficientResources; } } for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)buffer; (*bufferHdr)->pAppPrivate = appData; if (!m_use_output_pmem) { #ifdef USE_ION #ifdef _MSM8974_ align_size = (m_sOutPortDef.nBufferSize + (SZ_4K - 1)) & ~(SZ_4K - 1); m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,0); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory( m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap() Failed"); close(m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } } else { OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO*>((*bufferHdr)->pAppPrivate); DEBUG_PRINT_LOW("Inside qcom_ext pParam: %p", pParam); if (pParam) { DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (int)pParam->offset); m_pOutput_pmem[i].fd = pParam->pmem_fd; m_pOutput_pmem[i].offset = pParam->offset; m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].buffer = (unsigned char *)buffer; } else { DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM o/p UseBuffer case"); return OMX_ErrorBadParameter; } buf_addr = (unsigned char *)buffer; } DEBUG_PRINT_LOW("use_out:: bufhdr = %p, pBuffer = %p, m_pOutput_pmem[i].buffer = %p", (*bufferHdr), (*bufferHdr)->pBuffer, m_pOutput_pmem[i].buffer); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf Failed for o/p buf"); return OMX_ErrorInsufficientResources; } BITMASK_SET(&m_out_bm_count,i); } else { DEBUG_PRINT_ERROR("ERROR: All o/p Buffers have been Used, invalid use_buf call for " "index = %u", i); eRet = OMX_ErrorInsufficientResources; } } return eRet; } CWE ID: CWE-200 Target: 1 Example 2: Code: PanoramiXRenderSetPictureTransform(ClientPtr client) { REQUEST(xRenderSetPictureTransformReq); int result = Success, j; PanoramiXRes *pict; REQUEST_AT_LEAST_SIZE(xRenderSetPictureTransformReq); VERIFY_XIN_PICTURE(pict, stuff->picture, client, DixWriteAccess); FOR_NSCREENS_BACKWARD(j) { stuff->picture = pict->info[j].id; result = (*PanoramiXSaveRenderVector[X_RenderSetPictureTransform]) (client); if (result != Success) break; } return result; } 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: mp_capable_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_capable *mpc = (const struct mp_capable *) opt; if (!(opt_len == 12 && flags & TH_SYN) && !(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK)) return 0; if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) { ND_PRINT((ndo, " Unknown Version (%d)", MP_CAPABLE_OPT_VERSION(mpc->sub_ver))); return 1; } if (mpc->flags & MP_CAPABLE_C) ND_PRINT((ndo, " csum")); ND_PRINT((ndo, " {0x%" PRIx64, EXTRACT_64BITS(mpc->sender_key))); if (opt_len == 20) /* ACK */ ND_PRINT((ndo, ",0x%" PRIx64, EXTRACT_64BITS(mpc->receiver_key))); ND_PRINT((ndo, "}")); return 1; } CWE ID: CWE-125 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 WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(interstitial_page); GetRenderManager()->set_interstitial_page(interstitial_page); CancelActiveAndPendingDialogs(); for (auto& observer : observers_) observer.DidAttachInterstitialPage(); if (frame_tree_.IsLoading()) LoadingStateChanged(true, true, nullptr); if (node_.OuterContentsFrameTreeNode()) { if (GetRenderManager()->GetProxyToOuterDelegate()) { DCHECK( static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView()) ->IsRenderWidgetHostViewChildFrame()); RenderWidgetHostViewChildFrame* view = static_cast<RenderWidgetHostViewChildFrame*>( interstitial_page->GetView()); GetRenderManager()->SetRWHViewForInnerContents(view); } } } CWE ID: CWE-20 Target: 1 Example 2: Code: static inline dma_addr_t desc_to_dma(struct netdev_desc *desc) { return le64_to_cpu(desc->fraginfo) & DMA_BIT_MASK(48); } 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 __scm_send(struct socket *sock, struct msghdr *msg, struct scm_cookie *p) { struct cmsghdr *cmsg; int err; for_each_cmsghdr(cmsg, msg) { err = -EINVAL; /* Verify that cmsg_len is at least sizeof(struct cmsghdr) */ /* The first check was omitted in <= 2.2.5. The reasoning was that parser checks cmsg_len in any case, so that additional check would be work duplication. But if cmsg_level is not SOL_SOCKET, we do not check for too short ancillary data object at all! Oops. OK, let's add it... */ if (!CMSG_OK(msg, cmsg)) goto error; if (cmsg->cmsg_level != SOL_SOCKET) continue; switch (cmsg->cmsg_type) { case SCM_RIGHTS: if (!sock->ops || sock->ops->family != PF_UNIX) goto error; err=scm_fp_copy(cmsg, &p->fp); if (err<0) goto error; break; case SCM_CREDENTIALS: { struct ucred creds; kuid_t uid; kgid_t gid; if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct ucred))) goto error; memcpy(&creds, CMSG_DATA(cmsg), sizeof(struct ucred)); err = scm_check_creds(&creds); if (err) goto error; p->creds.pid = creds.pid; if (!p->pid || pid_vnr(p->pid) != creds.pid) { struct pid *pid; err = -ESRCH; pid = find_get_pid(creds.pid); if (!pid) goto error; put_pid(p->pid); p->pid = pid; } err = -EINVAL; uid = make_kuid(current_user_ns(), creds.uid); gid = make_kgid(current_user_ns(), creds.gid); if (!uid_valid(uid) || !gid_valid(gid)) goto error; p->creds.uid = uid; p->creds.gid = gid; break; } default: goto error; } } if (p->fp && !p->fp->count) { kfree(p->fp); p->fp = NULL; } return 0; error: scm_destroy(p); return err; } 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: void SoftHEVC::onQueueFilled(OMX_U32 portIndex) { UNUSED(portIndex); if (mSignalledError) { return; } if (mOutputPortSettingsChange != NONE) { return; } if (NULL == mCodecCtx) { if (OK != initDecoder()) { return; } } if (outputBufferWidth() != mStride) { /* Set the run-time (dynamic) parameters */ mStride = outputBufferWidth(); setParams(mStride); } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); /* If input EOS is seen and decoder is not in flush mode, * set the decoder in flush mode. * There can be a case where EOS is sent along with last picture data * In that case, only after decoding that input data, decoder has to be * put in flush. This case is handled here */ if (mReceivedEOS && !mIsInFlush) { setFlushMode(); } while (!outQueue.empty()) { BufferInfo *inInfo; OMX_BUFFERHEADERTYPE *inHeader; BufferInfo *outInfo; OMX_BUFFERHEADERTYPE *outHeader; size_t timeStampIx; inInfo = NULL; inHeader = NULL; if (!mIsInFlush) { if (!inQueue.empty()) { inInfo = *inQueue.begin(); inHeader = inInfo->mHeader; } else { break; } } outInfo = *outQueue.begin(); outHeader = outInfo->mHeader; outHeader->nFlags = 0; outHeader->nTimeStamp = 0; outHeader->nOffset = 0; if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { mReceivedEOS = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inHeader = NULL; setFlushMode(); } } /* Get a free slot in timestamp array to hold input timestamp */ { size_t i; timeStampIx = 0; for (i = 0; i < MAX_TIME_STAMPS; i++) { if (!mTimeStampsValid[i]) { timeStampIx = i; break; } } if (inHeader != NULL) { mTimeStampsValid[timeStampIx] = true; mTimeStamps[timeStampIx] = inHeader->nTimeStamp; } } { ivd_video_decode_ip_t s_dec_ip; ivd_video_decode_op_t s_dec_op; WORD32 timeDelay, timeTaken; size_t sizeY, sizeUV; setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx); GETTIME(&mTimeStart, NULL); /* Compute time elapsed between end of previous decode() * to start of current decode() */ TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); IV_API_CALL_STATUS_T status; status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); GETTIME(&mTimeEnd, NULL); /* Compute time taken for decode() */ TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay, s_dec_op.u4_num_bytes_consumed); if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { mFlushNeeded = true; } if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { /* If the input did not contain picture data, then ignore * the associated timestamp */ mTimeStampsValid[timeStampIx] = false; } if (mChangingResolution && !s_dec_op.u4_output_present) { mChangingResolution = false; resetDecoder(); resetPlugin(); continue; } if (resChanged) { mChangingResolution = true; if (mFlushNeeded) { setFlushMode(); } continue; } if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { uint32_t width = s_dec_op.u4_pic_wd; uint32_t height = s_dec_op.u4_pic_ht; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { resetDecoder(); return; } } if (s_dec_op.u4_output_present) { outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2; outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts]; mTimeStampsValid[s_dec_op.u4_ts] = false; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } else { /* If in flush mode and no output is returned by the codec, * then come out of flush mode */ mIsInFlush = false; /* If EOS was recieved on input port and there is no output * from the codec, then signal EOS on output port */ if (mReceivedEOS) { outHeader->nFilledLen = 0; outHeader->nFlags |= OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; resetPlugin(); } } } if (inHeader != NULL) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } } CWE ID: CWE-20 Target: 1 Example 2: Code: WORD32 ih264d_init_dec_mb_grp(dec_struct_t *ps_dec) { dec_seq_params_t *ps_seq = ps_dec->ps_cur_sps; UWORD8 u1_frm = ps_seq->u1_frame_mbs_only_flag; ps_dec->u1_recon_mb_grp = ps_dec->u2_frm_wd_in_mbs << ps_seq->u1_mb_aff_flag; ps_dec->u1_recon_mb_grp_pair = ps_dec->u1_recon_mb_grp >> 1; if(!ps_dec->u1_recon_mb_grp) { return ERROR_MB_GROUP_ASSGN_T; } ps_dec->u4_num_mbs_prev_nmb = ps_dec->u1_recon_mb_grp; return OK; } 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 eventHandlerAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); TestObjectPythonV8Internal::eventHandlerAttributeAttributeSetter(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } 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: void SetManualFallbacksForFilling(bool enabled) { if (enabled) { scoped_feature_list_.InitAndEnableFeature( password_manager::features::kEnableManualFallbacksFilling); } else { scoped_feature_list_.InitAndDisableFeature( password_manager::features::kEnableManualFallbacksFilling); } } CWE ID: CWE-264 Target: 1 Example 2: Code: void WebGL2RenderingContextBase::texSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLenum format, GLenum type, ImageBitmap* bitmap, ExceptionState& exception_state) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage2D", "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } WebGLRenderingContextBase::texSubImage2D( target, level, xoffset, yoffset, format, type, bitmap, exception_state); } 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 ForeignSessionHelper::TriggerSessionSync( JNIEnv* env, const JavaParamRef<jobject>& obj) { browser_sync::ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_); if (!service) return; const syncer::ModelTypeSet types(syncer::SESSIONS); service->TriggerRefresh(types); } CWE ID: CWE-254 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 setRewriteURLFolder(const char* folder) { m_rewriteFolder = folder; } CWE ID: CWE-119 Target: 1 Example 2: Code: JsVar *jsvAsString(JsVar *v, bool unlockVar) { JsVar *str = 0; if (jsvHasCharacterData(v) && jsvIsName(v)) { str = jsvNewFromStringVar(v,0,JSVAPPENDSTRINGVAR_MAXLENGTH); } else if (jsvIsString(v)) { // If it is a string - just return a reference str = jsvLockAgain(v); } else if (jsvIsObject(v)) { // If it is an object and we can call toString on it JsVar *toStringFn = jspGetNamedField(v, "toString", false); if (toStringFn && toStringFn->varData.native.ptr != (void (*)(void))jswrap_object_toString) { JsVar *result = jspExecuteFunction(toStringFn,v,0,0); jsvUnLock(toStringFn); str = jsvAsString(result, true); } else { jsvUnLock(toStringFn); str = jsvNewFromString("[object Object]"); } } else { const char *constChar = jsvGetConstString(v); assert(JS_NUMBER_BUFFER_SIZE>=10); char buf[JS_NUMBER_BUFFER_SIZE]; if (constChar) { str = jsvNewFromString(constChar); } else if (jsvIsPin(v)) { jshGetPinString(buf, (Pin)v->varData.integer); str = jsvNewFromString(buf); } else if (jsvIsInt(v)) { itostr(v->varData.integer, buf, 10); str = jsvNewFromString(buf); } else if (jsvIsFloat(v)) { ftoa_bounded(v->varData.floating, buf, sizeof(buf)); str = jsvNewFromString(buf); } else if (jsvIsArray(v) || jsvIsArrayBuffer(v)) { JsVar *filler = jsvNewFromString(","); str = jsvArrayJoin(v, filler); jsvUnLock(filler); } else if (jsvIsFunction(v)) { str = jsvNewFromEmptyString(); if (str) jsfGetJSON(v, str, JSON_NONE); } else { jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string"); str = 0; } } if (unlockVar) jsvUnLock(v); return str; } 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: ExprCreateArrayRef(xkb_atom_t element, xkb_atom_t field, ExprDef *entry) { EXPR_CREATE(ExprArrayRef, expr, EXPR_ARRAY_REF, EXPR_TYPE_UNKNOWN); expr->array_ref.element = element; expr->array_ref.field = field; expr->array_ref.entry = entry; return expr; } 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: static int handle_vmon(struct kvm_vcpu *vcpu) { int ret; gpa_t vmptr; struct page *page; struct vcpu_vmx *vmx = to_vmx(vcpu); const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX; /* * The Intel VMX Instruction Reference lists a bunch of bits that are * prerequisite to running VMXON, most notably cr4.VMXE must be set to * 1 (see vmx_set_cr4() for when we allow the guest to set this). * Otherwise, we should fail with #UD. But most faulting conditions * have already been checked by hardware, prior to the VM-exit for * VMXON. We do test guest cr4.VMXE because processor CR4 always has * that bit set to 1 in non-root mode. */ if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } if (vmx->nested.vmxon) { nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION); return kvm_skip_emulated_instruction(vcpu); } if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES) != VMXON_NEEDED_FEATURES) { kvm_inject_gp(vcpu, 0); return 1; } if (nested_vmx_get_vmptr(vcpu, &vmptr)) return 1; /* * SDM 3: 24.11.5 * The first 4 bytes of VMXON region contain the supported * VMCS revision identifier * * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case; * which replaces physical address width with 32 */ if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } page = kvm_vcpu_gpa_to_page(vcpu, vmptr); if (is_error_page(page)) { nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } if (*(u32 *)kmap(page) != VMCS12_REVISION) { kunmap(page); kvm_release_page_clean(page); nested_vmx_failInvalid(vcpu); return kvm_skip_emulated_instruction(vcpu); } kunmap(page); kvm_release_page_clean(page); vmx->nested.vmxon_ptr = vmptr; ret = enter_vmx_operation(vcpu); if (ret) return ret; nested_vmx_succeed(vcpu); return kvm_skip_emulated_instruction(vcpu); } CWE ID: Target: 1 Example 2: Code: void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*cb) (SSL *ssl, X509 **x509, EVP_PKEY **pkey)) { ctx->client_cert_cb = cb; } 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: void WebstoreBindings::Install( const v8::FunctionCallbackInfo<v8::Value>& args) { content::RenderFrame* render_frame = context()->GetRenderFrame(); if (!render_frame) return; int listener_mask = 0; CHECK(args[0]->IsBoolean()); if (args[0]->BooleanValue()) listener_mask |= api::webstore::INSTALL_STAGE_LISTENER; CHECK(args[1]->IsBoolean()); if (args[1]->BooleanValue()) listener_mask |= api::webstore::DOWNLOAD_PROGRESS_LISTENER; std::string preferred_store_link_url; if (!args[2]->IsUndefined()) { CHECK(args[2]->IsString()); preferred_store_link_url = std::string(*v8::String::Utf8Value(args[2])); } std::string webstore_item_id; std::string error; blink::WebLocalFrame* frame = context()->web_frame(); if (!GetWebstoreItemIdFromFrame( frame, preferred_store_link_url, &webstore_item_id, &error)) { args.GetIsolate()->ThrowException( v8::String::NewFromUtf8(args.GetIsolate(), error.c_str())); return; } int install_id = g_next_install_id++; Send(new ExtensionHostMsg_InlineWebstoreInstall( render_frame->GetRoutingID(), install_id, GetRoutingID(), webstore_item_id, frame->document().url(), listener_mask)); args.GetReturnValue().Set(static_cast<int32_t>(install_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: xfs_attr3_leaf_getvalue( struct xfs_buf *bp, struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; int valuelen; leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8); ASSERT(args->index < ichdr.count); entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); ASSERT(name_loc->namelen == args->namelen); ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0); valuelen = be16_to_cpu(name_loc->valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; memcpy(args->value, &name_loc->nameval[args->namelen], valuelen); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); ASSERT(name_rmt->namelen == args->namelen); ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0); valuelen = be32_to_cpu(name_rmt->valuelen); args->rmtblkno = be32_to_cpu(name_rmt->valueblk); args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount, valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; } return 0; } CWE ID: CWE-19 Target: 1 Example 2: Code: xmlParse3986Userinfo(xmlURIPtr uri, const char **str) { const char *cur; cur = *str; while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) || ISA_SUB_DELIM(cur) || (*cur == ':')) NEXT(cur); if (*cur == '@') { if (uri != NULL) { if (uri->user != NULL) xmlFree(uri->user); if (uri->cleanup & 2) uri->user = STRNDUP(*str, cur - *str); else uri->user = xmlURIUnescapeString(*str, cur - *str, NULL); } *str = cur; 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: void RenderThreadImpl::CreateFrameProxy( int32_t routing_id, int32_t render_view_routing_id, int32_t opener_routing_id, int32_t parent_routing_id, const FrameReplicationState& replicated_state) { RenderFrameProxy::CreateFrameProxy( routing_id, render_view_routing_id, RenderFrameImpl::ResolveOpener(opener_routing_id), parent_routing_id, replicated_state); } CWE ID: CWE-310 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 RenderFrameHostImpl::RegisterMojoInterfaces() { #if !defined(OS_ANDROID) registry_->AddInterface(base::Bind(&InstalledAppProviderImplDefault::Create)); #endif // !defined(OS_ANDROID) PermissionControllerImpl* permission_controller = PermissionControllerImpl::FromBrowserContext( GetProcess()->GetBrowserContext()); if (delegate_) { auto* geolocation_context = delegate_->GetGeolocationContext(); if (geolocation_context) { geolocation_service_.reset(new GeolocationServiceImpl( geolocation_context, permission_controller, this)); registry_->AddInterface( base::Bind(&GeolocationServiceImpl::Bind, base::Unretained(geolocation_service_.get()))); } } registry_->AddInterface<device::mojom::WakeLock>(base::Bind( &RenderFrameHostImpl::BindWakeLockRequest, base::Unretained(this))); #if defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebNfc)) { registry_->AddInterface<device::mojom::NFC>(base::Bind( &RenderFrameHostImpl::BindNFCRequest, base::Unretained(this))); } #endif if (!permission_service_context_) permission_service_context_.reset(new PermissionServiceContext(this)); registry_->AddInterface( base::Bind(&PermissionServiceContext::CreateService, base::Unretained(permission_service_context_.get()))); registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindPresentationServiceRequest, base::Unretained(this))); registry_->AddInterface( base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this))); registry_->AddInterface(base::Bind( base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService), base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebUsbService, base::Unretained(this))); registry_->AddInterface<media::mojom::InterfaceFactory>( base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebSocket, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateDedicatedWorkerHostFactory, base::Unretained(this))); registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create, process_->GetID(), routing_id_)); registry_->AddInterface(base::BindRepeating(&device::GamepadMonitor::Create)); registry_->AddInterface<device::mojom::VRService>(base::Bind( &WebvrServiceProvider::BindWebvrService, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioInputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioOutputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::Bind(&CreateFrameResourceCoordinator, base::Unretained(this))); if (BrowserMainLoop::GetInstance()) { MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); registry_->AddInterface( base::Bind(&MediaDevicesDispatcherHost::Create, GetProcess()->GetID(), GetRoutingID(), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); registry_->AddInterface( base::BindRepeating( &RenderFrameHostImpl::CreateMediaStreamDispatcherHost, base::Unretained(this), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } #if BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::Bind(&RemoterFactoryImpl::Bind, GetProcess()->GetID(), GetRoutingID())); #endif // BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::BindRepeating( &KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this))); registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create)); #if !defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebAuth)) { registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest, base::Unretained(this))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableWebAuthTestingAPI)) { auto* environment_singleton = ScopedVirtualAuthenticatorEnvironment::GetInstance(); registry_->AddInterface(base::BindRepeating( &ScopedVirtualAuthenticatorEnvironment::AddBinding, base::Unretained(environment_singleton))); } } #endif // !defined(OS_ANDROID) sensor_provider_proxy_.reset( new SensorProviderProxyImpl(permission_controller, this)); registry_->AddInterface( base::Bind(&SensorProviderProxyImpl::Bind, base::Unretained(sensor_provider_proxy_.get()))); media::VideoDecodePerfHistory::SaveCallback save_stats_cb; if (GetSiteInstance()->GetBrowserContext()->GetVideoDecodePerfHistory()) { save_stats_cb = GetSiteInstance() ->GetBrowserContext() ->GetVideoDecodePerfHistory() ->GetSaveCallback(); } registry_->AddInterface(base::BindRepeating( &media::MediaMetricsProvider::Create, frame_tree_node_->IsMainFrame(), base::BindRepeating( &RenderFrameHostDelegate::GetUkmSourceIdForLastCommittedSource, base::Unretained(delegate_)), std::move(save_stats_cb))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( cc::switches::kEnableGpuBenchmarking)) { registry_->AddInterface( base::Bind(&InputInjectorImpl::Create, weak_ptr_factory_.GetWeakPtr())); } registry_->AddInterface(base::BindRepeating( &QuotaDispatcherHost::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface( base::BindRepeating(SpeechRecognitionDispatcherHost::Create, GetProcess()->GetID(), routing_id_), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); file_system_manager_.reset(new FileSystemManagerImpl( GetProcess()->GetID(), routing_id_, GetProcess()->GetStoragePartition()->GetFileSystemContext(), ChromeBlobStorageContext::GetFor(GetProcess()->GetBrowserContext()))); registry_->AddInterface( base::BindRepeating(&FileSystemManagerImpl::BindRequest, base::Unretained(file_system_manager_.get())), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); if (Portal::IsEnabled()) { registry_->AddInterface(base::BindRepeating(IgnoreResult(&Portal::Create), base::Unretained(this))); } registry_->AddInterface(base::BindRepeating( &BackgroundFetchServiceImpl::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface(base::BindRepeating(&ContactsManagerImpl::Create)); registry_->AddInterface( base::BindRepeating(&FileChooserImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&AudioContextManagerImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&WakeLockServiceImpl::Create, base::Unretained(this))); } CWE ID: CWE-189 Target: 1 Example 2: Code: void GpuProcessHost::EstablishChannelError( const EstablishChannelCallback& callback, const IPC::ChannelHandle& channel_handle, base::ProcessHandle renderer_process_for_gpu, const GPUInfo& gpu_info) { callback.Run(channel_handle, gpu_info); } 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 req_table_t* req_subprocess_env(request_rec *r) { req_table_t* t = apr_palloc(r->pool, sizeof(req_table_t)); t->r = r; t->t = r->subprocess_env; t->n = "subprocess_env"; return t; } 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: void ImageBitmapFactories::ImageBitmapLoader::RejectPromise( ImageBitmapRejectionReason reason) { switch (reason) { case kUndecodableImageBitmapRejectionReason: resolver_->Reject( DOMException::Create(DOMExceptionCode::kInvalidStateError, "The source image could not be decoded.")); break; case kAllocationFailureImageBitmapRejectionReason: resolver_->Reject( DOMException::Create(DOMExceptionCode::kInvalidStateError, "The ImageBitmap could not be allocated.")); break; default: NOTREACHED(); } factory_->DidFinishLoading(this); } CWE ID: CWE-416 Target: 1 Example 2: Code: void RenderFrameHostImpl::SimulateBeforeUnloadAck() { DCHECK(is_waiting_for_beforeunload_ack_); base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_; OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now()); } CWE ID: CWE-254 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 WebLocalFrameImpl::LoadJavaScriptURL(const KURL& url) { DCHECK(GetFrame()); Document* owner_document = GetFrame()->GetDocument(); if (!owner_document || !GetFrame()->GetPage()) return; if (SchemeRegistry::ShouldTreatURLSchemeAsNotAllowingJavascriptURLs( owner_document->Url().Protocol())) return; String script = DecodeURLEscapeSequences( url.GetString().Substring(strlen("javascript:"))); UserGestureIndicator gesture_indicator( UserGestureToken::Create(owner_document, UserGestureToken::kNewGesture)); v8::HandleScope handle_scope(ToIsolate(GetFrame())); v8::Local<v8::Value> result = GetFrame()->GetScriptController().ExecuteScriptInMainWorldAndReturnValue( ScriptSourceCode(script)); if (result.IsEmpty() || !result->IsString()) return; String script_result = ToCoreString(v8::Local<v8::String>::Cast(result)); if (!GetFrame()->GetNavigationScheduler().LocationChangePending()) { GetFrame()->Loader().ReplaceDocumentWhileExecutingJavaScriptURL( script_result, owner_document); } } 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: static int hns_gmac_get_sset_count(int stringset) { if (stringset == ETH_SS_STATS) return ARRAY_SIZE(g_gmac_stats_string); return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: tcpport_string(netdissect_options *ndo, u_short port) { register struct hnamemem *tp; register uint32_t i = port; char buf[sizeof("00000")]; for (tp = &tporttable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt) if (tp->addr == i) return (tp->name); tp->addr = i; tp->nxt = newhnamemem(ndo); (void)snprintf(buf, sizeof(buf), "%u", i); tp->name = strdup(buf); if (tp->name == NULL) (*ndo->ndo_error)(ndo, "tcpport_string: strdup(buf)"); return (tp->name); } 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 u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft) { return sched_group_rt_period(cgroup_tg(cgrp)); } 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: const BlockEntry* Cluster::GetEntry( const Track* pTrack, long long time_ns) const { assert(pTrack); if (m_pSegment == NULL) //this is the special EOS cluster return pTrack->GetEOS(); #if 0 LoadBlockEntries(); if ((m_entries == NULL) || (m_entries_count <= 0)) return NULL; //return EOS here? const BlockEntry* pResult = pTrack->GetEOS(); BlockEntry** i = m_entries; assert(i); BlockEntry** const j = i + m_entries_count; while (i != j) { const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) continue; if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; pResult = pEntry; } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; } } return pResult; #else const BlockEntry* pResult = pTrack->GetEOS(); long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); assert(status >= 0); if (status > 0) //completely parsed, and no more entries return pResult; if (status < 0) //should never happen return 0; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) { ++index; continue; } if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; pResult = pEntry; //have a candidate } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; } ++index; } #endif } CWE ID: CWE-119 Target: 1 Example 2: Code: BrowserGpuChannelHostFactory::EstablishRequest::~EstablishRequest() { } 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: raptor_turtle_writer_quoted_counted_string(raptor_turtle_writer* turtle_writer, const unsigned char *s, size_t len) { const unsigned char *quotes = (const unsigned char *)"\"\"\"\""; const unsigned char *q; size_t q_len; int flags; int rc = 0; if(!s) return 1; /* Turtle """longstring""" (2) or "string" (1) */ flags = raptor_turtle_writer_contains_newline(s) ? 2 : 1; q = (flags == 2) ? quotes : quotes + 2; q_len = (q == quotes) ? 3 : 1; raptor_iostream_counted_string_write(q, q_len, turtle_writer->iostr); rc = raptor_string_python_write(s, strlen((const char*)s), '"', flags, turtle_writer->iostr); raptor_iostream_counted_string_write(q, q_len, turtle_writer->iostr); return rc; } 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 int php_stream_memory_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */ { php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; size_t newsize; switch(option) { case PHP_STREAM_OPTION_TRUNCATE_API: switch (value) { case PHP_STREAM_TRUNCATE_SUPPORTED: return PHP_STREAM_OPTION_RETURN_OK; case PHP_STREAM_TRUNCATE_SET_SIZE: if (ms->mode & TEMP_STREAM_READONLY) { return PHP_STREAM_OPTION_RETURN_ERR; } newsize = *(size_t*)ptrparam; if (newsize <= ms->fsize) { if (newsize < ms->fpos) { ms->fpos = newsize; } } else { ms->data = erealloc(ms->data, newsize); memset(ms->data+ms->fsize, 0, newsize - ms->fsize); ms->fsize = newsize; } ms->fsize = newsize; return PHP_STREAM_OPTION_RETURN_OK; } default: return PHP_STREAM_OPTION_RETURN_NOTIMPL; } } /* }}} */ CWE ID: CWE-20 Target: 1 Example 2: Code: static struct PointerBarrierDevice *GetBarrierDevice(struct PointerBarrierClient *c, int deviceid) { struct PointerBarrierDevice *pbd = NULL; xorg_list_for_each_entry(pbd, &c->per_device, entry) { if (pbd->deviceid == deviceid) break; } BUG_WARN(!pbd); return pbd; } 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: void RenderWidgetHostImpl::ForwardWheelEvent( const WebMouseWheelEvent& wheel_event) { TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::ForwardWheelEvent"); if (ignore_input_events_ || process_->IgnoreInputEvents()) return; if (mouse_wheel_pending_) { if (coalesced_mouse_wheel_events_.empty() || !ShouldCoalesceMouseWheelEvents(coalesced_mouse_wheel_events_.back(), wheel_event)) { coalesced_mouse_wheel_events_.push_back(wheel_event); } else { WebMouseWheelEvent* last_wheel_event = &coalesced_mouse_wheel_events_.back(); last_wheel_event->deltaX += wheel_event.deltaX; last_wheel_event->deltaY += wheel_event.deltaY; last_wheel_event->wheelTicksX += wheel_event.wheelTicksX; last_wheel_event->wheelTicksY += wheel_event.wheelTicksY; DCHECK_GE(wheel_event.timeStampSeconds, last_wheel_event->timeStampSeconds); last_wheel_event->timeStampSeconds = wheel_event.timeStampSeconds; } return; } mouse_wheel_pending_ = true; current_wheel_event_ = wheel_event; HISTOGRAM_COUNTS_100("MPArch.RWH_WheelQueueSize", coalesced_mouse_wheel_events_.size()); ForwardInputEvent(wheel_event, sizeof(WebMouseWheelEvent), false); } 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: static void parse_cfg(int flags, int argc, const char **argv, cfg_t *cfg) { int i; memset(cfg, 0, sizeof(cfg_t)); cfg->debug_file = stderr; for (i = 0; i < argc; i++) { if (strncmp(argv[i], "max_devices=", 12) == 0) sscanf(argv[i], "max_devices=%u", &cfg->max_devs); if (strcmp(argv[i], "manual") == 0) cfg->manual = 1; if (strcmp(argv[i], "debug") == 0) cfg->debug = 1; if (strcmp(argv[i], "nouserok") == 0) cfg->nouserok = 1; if (strcmp(argv[i], "openasuser") == 0) cfg->openasuser = 1; if (strcmp(argv[i], "alwaysok") == 0) cfg->alwaysok = 1; if (strcmp(argv[i], "interactive") == 0) cfg->interactive = 1; if (strcmp(argv[i], "cue") == 0) cfg->cue = 1; if (strcmp(argv[i], "nodetect") == 0) cfg->nodetect = 1; if (strncmp(argv[i], "authfile=", 9) == 0) cfg->auth_file = argv[i] + 9; if (strncmp(argv[i], "authpending_file=", 17) == 0) cfg->authpending_file = argv[i] + 17; if (strncmp(argv[i], "origin=", 7) == 0) cfg->origin = argv[i] + 7; if (strncmp(argv[i], "appid=", 6) == 0) cfg->appid = argv[i] + 6; if (strncmp(argv[i], "prompt=", 7) == 0) cfg->prompt = argv[i] + 7; if (strncmp (argv[i], "debug_file=", 11) == 0) { const char *filename = argv[i] + 11; if(strncmp (filename, "stdout", 6) == 0) { cfg->debug_file = stdout; } else if(strncmp (filename, "stderr", 6) == 0) { cfg->debug_file = stderr; } else if( strncmp (filename, "syslog", 6) == 0) { cfg->debug_file = (FILE *)-1; } else { struct stat st; FILE *file; if(lstat(filename, &st) == 0) { if(S_ISREG(st.st_mode)) { file = fopen(filename, "a"); if(file != NULL) { cfg->debug_file = file; } } } } } } if (cfg->debug) { D(cfg->debug_file, "called."); D(cfg->debug_file, "flags %d argc %d", flags, argc); for (i = 0; i < argc; i++) { D(cfg->debug_file, "argv[%d]=%s", i, argv[i]); } D(cfg->debug_file, "max_devices=%d", cfg->max_devs); D(cfg->debug_file, "debug=%d", cfg->debug); D(cfg->debug_file, "interactive=%d", cfg->interactive); D(cfg->debug_file, "cue=%d", cfg->cue); D(cfg->debug_file, "nodetect=%d", cfg->nodetect); D(cfg->debug_file, "manual=%d", cfg->manual); D(cfg->debug_file, "nouserok=%d", cfg->nouserok); D(cfg->debug_file, "openasuser=%d", cfg->openasuser); D(cfg->debug_file, "alwaysok=%d", cfg->alwaysok); D(cfg->debug_file, "authfile=%s", cfg->auth_file ? cfg->auth_file : "(null)"); D(cfg->debug_file, "authpending_file=%s", cfg->authpending_file ? cfg->authpending_file : "(null)"); D(cfg->debug_file, "origin=%s", cfg->origin ? cfg->origin : "(null)"); D(cfg->debug_file, "appid=%s", cfg->appid ? cfg->appid : "(null)"); D(cfg->debug_file, "prompt=%s", cfg->prompt ? cfg->prompt : "(null)"); } } CWE ID: CWE-200 Target: 1 Example 2: Code: PHP_METHOD(Phar, startBuffering) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } phar_obj->archive->donotflush = 1; } 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 ecc_ctx_set_salt(ecEncCtx* ctx, int flags, WC_RNG* rng) { byte* saltBuffer = NULL; if (ctx == NULL || rng == NULL || flags == 0) return BAD_FUNC_ARG; saltBuffer = (flags == REQ_RESP_CLIENT) ? ctx->clientSalt : ctx->serverSalt; return wc_RNG_GenerateBlock(rng, saltBuffer, EXCHANGE_SALT_SZ); } 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 jsR_calllwfunction(js_State *J, int n, js_Function *F, js_Environment *scope) { js_Value v; int i; jsR_savescope(J, scope); if (n > F->numparams) { js_pop(J, F->numparams - n); n = F->numparams; } for (i = n; i < F->varlen; ++i) js_pushundefined(J); jsR_run(J, F); v = *stackidx(J, -1); TOP = --BOT; /* clear stack */ js_pushvalue(J, v); jsR_restorescope(J); } CWE ID: CWE-119 Target: 1 Example 2: Code: MagickExport const char **GetXMLTreeProcessingInstructions( XMLTreeInfo *xml_info,const char *target) { register ssize_t i; XMLTreeRoot *root; assert(xml_info != (XMLTreeInfo *) NULL); assert((xml_info->signature == MagickSignature) || (((XMLTreeRoot *) xml_info)->signature == MagickSignature)); if (xml_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); root=(XMLTreeRoot *) xml_info; while (root->root.parent != (XMLTreeInfo *) NULL) root=(XMLTreeRoot *) root->root.parent; i=0; while ((root->processing_instructions[i] != (char **) NULL) && (strcmp(root->processing_instructions[i][0],target) != 0)) i++; if (root->processing_instructions[i] == (char **) NULL) return((const char **) sentinel); return((const char **) (root->processing_instructions[i]+1)); } 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: static void UpdatePropertyCallback(IBusPanelService* panel, IBusProperty* ibus_prop, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateProperty(ibus_prop); } 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: do_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax) { #ifdef USE_AMD64_ASM return _gcry_aes_amd64_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, encT); #elif defined(USE_ARM_ASM) return _gcry_aes_arm_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, encT); #else return do_encrypt_fn (ctx, bx, ax); #endif /* !USE_ARM_ASM && !USE_AMD64_ASM*/ } CWE ID: CWE-310 Target: 1 Example 2: Code: static int snd_compr_mmap(struct file *f, struct vm_area_struct *vma) { return -ENXIO; } 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 FolderHeaderView::SetFolderItem(AppListFolderItem* folder_item) { if (folder_item_) folder_item_->RemoveObserver(this); folder_item_ = folder_item; if (!folder_item_) return; folder_item_->AddObserver(this); folder_name_view_->SetEnabled(folder_item->folder_type() != AppListFolderItem::FOLDER_TYPE_OEM); Update(); } 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: EncodedJSValue JSC_HOST_CALL JSTestInterfaceConstructor::constructJSTestInterface(ExecState* exec) { JSTestInterfaceConstructor* castedThis = jsCast<JSTestInterfaceConstructor*>(exec->callee()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); ExceptionCode ec = 0; const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); ScriptExecutionContext* context = castedThis->scriptExecutionContext(); if (!context) return throwVMError(exec, createReferenceError(exec, "TestInterface constructor associated document is unavailable")); RefPtr<TestInterface> object = TestInterface::create(context, str1, str2, ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get()))); } CWE ID: CWE-20 Target: 1 Example 2: Code: inline int megasas_cmd_type(struct scsi_cmnd *cmd) { int ret; switch (cmd->cmnd[0]) { case READ_10: case WRITE_10: case READ_12: case WRITE_12: case READ_6: case WRITE_6: case READ_16: case WRITE_16: ret = (MEGASAS_IS_LOGICAL(cmd->device)) ? READ_WRITE_LDIO : READ_WRITE_SYSPDIO; break; default: ret = (MEGASAS_IS_LOGICAL(cmd->device)) ? NON_READ_WRITE_LDIO : NON_READ_WRITE_SYSPDIO; } 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: bool DrawingBuffer::Initialize(const IntSize& size, bool use_multisampling) { ScopedStateRestorer scoped_state_restorer(this); if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { return false; } gl_->GetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size_); int max_sample_count = 0; anti_aliasing_mode_ = kNone; if (use_multisampling) { gl_->GetIntegerv(GL_MAX_SAMPLES_ANGLE, &max_sample_count); anti_aliasing_mode_ = kMSAAExplicitResolve; if (extensions_util_->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) { anti_aliasing_mode_ = kMSAAImplicitResolve; } else if (extensions_util_->SupportsExtension( "GL_CHROMIUM_screen_space_antialiasing")) { anti_aliasing_mode_ = kScreenSpaceAntialiasing; } } storage_texture_supported_ = (web_gl_version_ > kWebGL1 || extensions_util_->SupportsExtension("GL_EXT_texture_storage")) && anti_aliasing_mode_ == kScreenSpaceAntialiasing; sample_count_ = std::min(4, max_sample_count); state_restorer_->SetFramebufferBindingDirty(); gl_->GenFramebuffers(1, &fbo_); gl_->BindFramebuffer(GL_FRAMEBUFFER, fbo_); if (WantExplicitResolve()) { gl_->GenFramebuffers(1, &multisample_fbo_); gl_->BindFramebuffer(GL_FRAMEBUFFER, multisample_fbo_); gl_->GenRenderbuffers(1, &multisample_renderbuffer_); } if (!ResizeFramebufferInternal(size)) return false; if (depth_stencil_buffer_) { DCHECK(WantDepthOrStencil()); has_implicit_stencil_buffer_ = !want_stencil_; } if (gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { return false; } return true; } 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 inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res) { unsigned char found; const uni_to_enc *table; size_t table_size; switch (charset) { case cs_8859_1: /* identity mapping of code points to unicode */ if (code > 0xFF) { return FAILURE; } *res = code; break; case cs_8859_5: if (code <= 0xA0 || code == 0xAD /* soft hyphen */) { *res = code; } else if (code == 0x2116) { *res = 0xF0; /* numero sign */ } else if (code == 0xA7) { *res = 0xFD; /* section sign */ } else if (code >= 0x0401 && code <= 0x044F) { if (code == 0x040D || code == 0x0450 || code == 0x045D) return FAILURE; *res = code - 0x360; } else { return FAILURE; } break; case cs_8859_15: if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) { *res = code; } else { /* between A4 and 0xBE */ found = unimap_bsearch(unimap_iso885915, code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915)); if (found) *res = found; else return FAILURE; } break; case cs_cp1252: if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) { *res = code; } else { found = unimap_bsearch(unimap_win1252, code, sizeof(unimap_win1252) / sizeof(*unimap_win1252)); if (found) *res = found; else return FAILURE; } break; case cs_macroman: if (code == 0x7F) return FAILURE; table = unimap_macroman; table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman); goto table_over_7F; case cs_cp1251: table = unimap_win1251; table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251); goto table_over_7F; case cs_koi8r: table = unimap_koi8r; table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r); goto table_over_7F; case cs_cp866: table = unimap_cp866; table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866); table_over_7F: if (code <= 0x7F) { *res = code; } else { found = unimap_bsearch(table, code, table_size); if (found) *res = found; else return FAILURE; } break; /* from here on, only map the possible characters in the ASCII range. * to improve support here, it's a matter of building the unicode mappings. * See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */ case cs_sjis: case cs_eucjp: /* we interpret 0x5C as the Yen symbol. This is not universal. * See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */ if (code >= 0x20 && code <= 0x7D) { if (code == 0x5C) return FAILURE; *res = code; } else { return FAILURE; } break; case cs_big5: case cs_big5hkscs: case cs_gb2312: if (code >= 0x20 && code <= 0x7D) { *res = code; } else { return FAILURE; } break; default: return FAILURE; } return SUCCESS; } CWE ID: CWE-190 Target: 1 Example 2: Code: void RenderWidgetHostImpl::WasResized() { WasResized(false); } 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: xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { const xmlChar *in; int nbchar = 0; int line = ctxt->input->line; int col = ctxt->input->col; int ccol; SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ if (!cdata) { in = ctxt->input->cur; do { get_more_space: while (*in == 0x20) { in++; ctxt->input->col++; } if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more_space; } if (*in == '<') { nbchar = in - ctxt->input->cur; if (nbchar > 0) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters)) { if (areBlanks(ctxt, tmp, nbchar, 1)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } } else if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL)) { ctxt->sax->characters(ctxt->userData, tmp, nbchar); } } return; } get_more: ccol = ctxt->input->col; while (test_char_data[*in]) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } if (*in == ']') { if ((in[1] == ']') && (in[2] == '>')) { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); ctxt->input->cur = in; return; } in++; ctxt->input->col++; goto get_more; } nbchar = in - ctxt->input->cur; if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters) && (IS_BLANK_CH(*ctxt->input->cur))) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if (areBlanks(ctxt, tmp, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } line = ctxt->input->line; col = ctxt->input->col; } else if (ctxt->sax != NULL) { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, nbchar); line = ctxt->input->line; col = ctxt->input->col; } /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } ctxt->input->cur = in; if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } if (*in == '<') { return; } if (*in == '&') { return; } SHRINK; GROW; in = ctxt->input->cur; } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); nbchar = 0; } ctxt->input->line = line; ctxt->input->col = col; xmlParseCharDataComplex(ctxt, cdata); } 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 virtio_load(VirtIODevice *vdev, QEMUFile *f) { int i, ret; uint32_t num; uint32_t features; uint32_t supported_features; VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); if (k->load_config) { ret = k->load_config(qbus->parent, f); if (ret) return ret; } qemu_get_8s(f, &vdev->status); qemu_get_8s(f, &vdev->isr); qemu_get_be16s(f, &vdev->queue_sel); if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) { return -1; } qemu_get_be32s(f, &features); if (virtio_set_features(vdev, features) < 0) { supported_features = k->get_features(qbus->parent); error_report("Features 0x%x unsupported. Allowed features: 0x%x", features, supported_features); features, supported_features); return -1; } vdev->config_len = qemu_get_be32(f); qemu_get_buffer(f, vdev->config, vdev->config_len); num = qemu_get_be32(f); for (i = 0; i < num; i++) { vdev->vq[i].vring.num = qemu_get_be32(f); if (k->has_variable_vring_alignment) { vdev->vq[i].vring.align = qemu_get_be32(f); } vdev->vq[i].pa = qemu_get_be64(f); qemu_get_be16s(f, &vdev->vq[i].last_avail_idx); vdev->vq[i].signalled_used_valid = false; vdev->vq[i].notification = true; if (vdev->vq[i].pa) { uint16_t nheads; virtqueue_init(&vdev->vq[i]); nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx; /* Check it isn't doing very strange things with descriptor numbers. */ if (nheads > vdev->vq[i].vring.num) { error_report("VQ %d size 0x%x Guest index 0x%x " "inconsistent with Host index 0x%x: delta 0x%x", i, vdev->vq[i].vring.num, vring_avail_idx(&vdev->vq[i]), vdev->vq[i].last_avail_idx, nheads); return -1; } } else if (vdev->vq[i].last_avail_idx) { error_report("VQ %d address 0x0 " "inconsistent with Host index 0x%x", i, vdev->vq[i].last_avail_idx); return -1; } if (k->load_queue) { ret = k->load_queue(qbus->parent, i, f); if (ret) return ret; } } virtio_notify_vector(vdev, VIRTIO_NO_VECTOR); return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: void drm_crtc_init(struct drm_device *dev, struct drm_crtc *crtc, const struct drm_crtc_funcs *funcs) { crtc->dev = dev; crtc->funcs = funcs; mutex_lock(&dev->mode_config.mutex); drm_mode_object_get(dev, &crtc->base, DRM_MODE_OBJECT_CRTC); list_add_tail(&crtc->head, &dev->mode_config.crtc_list); dev->mode_config.num_crtc++; mutex_unlock(&dev->mode_config.mutex); } 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: AudioParameters GetInputParametersOnDeviceThread(AudioManager* audio_manager, const std::string& device_id) { DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread()); if (!audio_manager->HasAudioInputDevices()) return AudioParameters(); return audio_manager->GetInputStreamParameters(device_id); } 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 inline realpath_cache_bucket* realpath_cache_find(const char *path, int path_len, time_t t TSRMLS_DC) /* {{{ */ { #ifdef PHP_WIN32 unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC); #else unsigned long key = realpath_cache_key(path, path_len); #endif unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0])); realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n]; while (*bucket != NULL) { if (CWDG(realpath_cache_ttl) && (*bucket)->expires < t) { realpath_cache_bucket *r = *bucket; *bucket = (*bucket)->next; /* if the pointers match then only subtract the length of the path */ if(r->path == r->realpath) { CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1; } else { CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1; } free(r); } else if (key == (*bucket)->key && path_len == (*bucket)->path_len && memcmp(path, (*bucket)->path, path_len) == 0) { return *bucket; } else { bucket = &(*bucket)->next; } } return NULL; } /* }}} */ CWE ID: CWE-190 Target: 1 Example 2: Code: static void plugin_instance_finalize(PluginInstance *plugin) { if (plugin->browser_toplevel) { g_object_unref(plugin->browser_toplevel); plugin->browser_toplevel = NULL; } if (plugin->instance) { free(plugin->instance); plugin->instance = NULL; } } 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 ssize_t show_ibdev(struct device *device, struct device_attribute *attr, char *buf) { int ret = -ENODEV; int srcu_key; struct ib_uverbs_device *dev = dev_get_drvdata(device); struct ib_device *ib_dev; if (!dev) return -ENODEV; srcu_key = srcu_read_lock(&dev->disassociate_srcu); ib_dev = srcu_dereference(dev->ib_dev, &dev->disassociate_srcu); if (ib_dev) ret = sprintf(buf, "%s\n", ib_dev->name); srcu_read_unlock(&dev->disassociate_srcu, srcu_key); return ret; } 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: static int srpt_rx_mgmt_fn_tag(struct srpt_send_ioctx *ioctx, u64 tag) { struct srpt_device *sdev; struct srpt_rdma_ch *ch; struct srpt_send_ioctx *target; int ret, i; ret = -EINVAL; ch = ioctx->ch; BUG_ON(!ch); BUG_ON(!ch->sport); sdev = ch->sport->sdev; BUG_ON(!sdev); spin_lock_irq(&sdev->spinlock); for (i = 0; i < ch->rq_size; ++i) { target = ch->ioctx_ring[i]; if (target->cmd.se_lun == ioctx->cmd.se_lun && target->cmd.tag == tag && srpt_get_cmd_state(target) != SRPT_STATE_DONE) { ret = 0; /* now let the target core abort &target->cmd; */ break; } } spin_unlock_irq(&sdev->spinlock); return ret; } CWE ID: CWE-476 Target: 1 Example 2: Code: static av_cold int init(AVFilterContext *ctx) { FPSContext *s = ctx->priv; if (!(s->fifo = av_fifo_alloc(2*sizeof(AVFrame*)))) return AVERROR(ENOMEM); s->pts = AV_NOPTS_VALUE; s->first_pts = AV_NOPTS_VALUE; av_log(ctx, AV_LOG_VERBOSE, "fps=%d/%d\n", s->framerate.num, s->framerate.den); return 0; } 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 test_unsigned_long_formatting(void) { int i, j; int num_ulong_tests; int failed = 0; #if (CURL_SIZEOF_LONG == 2) i=1; ul_test[i].num = 0xFFFFUL; ul_test[i].expected = "65535"; i++; ul_test[i].num = 0xFF00UL; ul_test[i].expected = "65280"; i++; ul_test[i].num = 0x00FFUL; ul_test[i].expected = "255"; i++; ul_test[i].num = 0xF000UL; ul_test[i].expected = "61440"; i++; ul_test[i].num = 0x0F00UL; ul_test[i].expected = "3840"; i++; ul_test[i].num = 0x00F0UL; ul_test[i].expected = "240"; i++; ul_test[i].num = 0x000FUL; ul_test[i].expected = "15"; i++; ul_test[i].num = 0xC000UL; ul_test[i].expected = "49152"; i++; ul_test[i].num = 0x0C00UL; ul_test[i].expected = "3072"; i++; ul_test[i].num = 0x00C0UL; ul_test[i].expected = "192"; i++; ul_test[i].num = 0x000CUL; ul_test[i].expected = "12"; i++; ul_test[i].num = 0x0001UL; ul_test[i].expected = "1"; i++; ul_test[i].num = 0x0000UL; ul_test[i].expected = "0"; num_ulong_tests = i; #elif (CURL_SIZEOF_LONG == 4) i=1; ul_test[i].num = 0xFFFFFFFFUL; ul_test[i].expected = "4294967295"; i++; ul_test[i].num = 0xFFFF0000UL; ul_test[i].expected = "4294901760"; i++; ul_test[i].num = 0x0000FFFFUL; ul_test[i].expected = "65535"; i++; ul_test[i].num = 0xFF000000UL; ul_test[i].expected = "4278190080"; i++; ul_test[i].num = 0x00FF0000UL; ul_test[i].expected = "16711680"; i++; ul_test[i].num = 0x0000FF00UL; ul_test[i].expected = "65280"; i++; ul_test[i].num = 0x000000FFUL; ul_test[i].expected = "255"; i++; ul_test[i].num = 0xF0000000UL; ul_test[i].expected = "4026531840"; i++; ul_test[i].num = 0x0F000000UL; ul_test[i].expected = "251658240"; i++; ul_test[i].num = 0x00F00000UL; ul_test[i].expected = "15728640"; i++; ul_test[i].num = 0x000F0000UL; ul_test[i].expected = "983040"; i++; ul_test[i].num = 0x0000F000UL; ul_test[i].expected = "61440"; i++; ul_test[i].num = 0x00000F00UL; ul_test[i].expected = "3840"; i++; ul_test[i].num = 0x000000F0UL; ul_test[i].expected = "240"; i++; ul_test[i].num = 0x0000000FUL; ul_test[i].expected = "15"; i++; ul_test[i].num = 0xC0000000UL; ul_test[i].expected = "3221225472"; i++; ul_test[i].num = 0x0C000000UL; ul_test[i].expected = "201326592"; i++; ul_test[i].num = 0x00C00000UL; ul_test[i].expected = "12582912"; i++; ul_test[i].num = 0x000C0000UL; ul_test[i].expected = "786432"; i++; ul_test[i].num = 0x0000C000UL; ul_test[i].expected = "49152"; i++; ul_test[i].num = 0x00000C00UL; ul_test[i].expected = "3072"; i++; ul_test[i].num = 0x000000C0UL; ul_test[i].expected = "192"; i++; ul_test[i].num = 0x0000000CUL; ul_test[i].expected = "12"; i++; ul_test[i].num = 0x00000001UL; ul_test[i].expected = "1"; i++; ul_test[i].num = 0x00000000UL; ul_test[i].expected = "0"; num_ulong_tests = i; #elif (CURL_SIZEOF_LONG == 8) i=1; ul_test[i].num = 0xFFFFFFFFFFFFFFFFUL; ul_test[i].expected = "18446744073709551615"; i++; ul_test[i].num = 0xFFFFFFFF00000000UL; ul_test[i].expected = "18446744069414584320"; i++; ul_test[i].num = 0x00000000FFFFFFFFUL; ul_test[i].expected = "4294967295"; i++; ul_test[i].num = 0xFFFF000000000000UL; ul_test[i].expected = "18446462598732840960"; i++; ul_test[i].num = 0x0000FFFF00000000UL; ul_test[i].expected = "281470681743360"; i++; ul_test[i].num = 0x00000000FFFF0000UL; ul_test[i].expected = "4294901760"; i++; ul_test[i].num = 0x000000000000FFFFUL; ul_test[i].expected = "65535"; i++; ul_test[i].num = 0xFF00000000000000UL; ul_test[i].expected = "18374686479671623680"; i++; ul_test[i].num = 0x00FF000000000000UL; ul_test[i].expected = "71776119061217280"; i++; ul_test[i].num = 0x0000FF0000000000UL; ul_test[i].expected = "280375465082880"; i++; ul_test[i].num = 0x000000FF00000000UL; ul_test[i].expected = "1095216660480"; i++; ul_test[i].num = 0x00000000FF000000UL; ul_test[i].expected = "4278190080"; i++; ul_test[i].num = 0x0000000000FF0000UL; ul_test[i].expected = "16711680"; i++; ul_test[i].num = 0x000000000000FF00UL; ul_test[i].expected = "65280"; i++; ul_test[i].num = 0x00000000000000FFUL; ul_test[i].expected = "255"; i++; ul_test[i].num = 0xF000000000000000UL; ul_test[i].expected = "17293822569102704640"; i++; ul_test[i].num = 0x0F00000000000000UL; ul_test[i].expected = "1080863910568919040"; i++; ul_test[i].num = 0x00F0000000000000UL; ul_test[i].expected = "67553994410557440"; i++; ul_test[i].num = 0x000F000000000000UL; ul_test[i].expected = "4222124650659840"; i++; ul_test[i].num = 0x0000F00000000000UL; ul_test[i].expected = "263882790666240"; i++; ul_test[i].num = 0x00000F0000000000UL; ul_test[i].expected = "16492674416640"; i++; ul_test[i].num = 0x000000F000000000UL; ul_test[i].expected = "1030792151040"; i++; ul_test[i].num = 0x0000000F00000000UL; ul_test[i].expected = "64424509440"; i++; ul_test[i].num = 0x00000000F0000000UL; ul_test[i].expected = "4026531840"; i++; ul_test[i].num = 0x000000000F000000UL; ul_test[i].expected = "251658240"; i++; ul_test[i].num = 0x0000000000F00000UL; ul_test[i].expected = "15728640"; i++; ul_test[i].num = 0x00000000000F0000UL; ul_test[i].expected = "983040"; i++; ul_test[i].num = 0x000000000000F000UL; ul_test[i].expected = "61440"; i++; ul_test[i].num = 0x0000000000000F00UL; ul_test[i].expected = "3840"; i++; ul_test[i].num = 0x00000000000000F0UL; ul_test[i].expected = "240"; i++; ul_test[i].num = 0x000000000000000FUL; ul_test[i].expected = "15"; i++; ul_test[i].num = 0xC000000000000000UL; ul_test[i].expected = "13835058055282163712"; i++; ul_test[i].num = 0x0C00000000000000UL; ul_test[i].expected = "864691128455135232"; i++; ul_test[i].num = 0x00C0000000000000UL; ul_test[i].expected = "54043195528445952"; i++; ul_test[i].num = 0x000C000000000000UL; ul_test[i].expected = "3377699720527872"; i++; ul_test[i].num = 0x0000C00000000000UL; ul_test[i].expected = "211106232532992"; i++; ul_test[i].num = 0x00000C0000000000UL; ul_test[i].expected = "13194139533312"; i++; ul_test[i].num = 0x000000C000000000UL; ul_test[i].expected = "824633720832"; i++; ul_test[i].num = 0x0000000C00000000UL; ul_test[i].expected = "51539607552"; i++; ul_test[i].num = 0x00000000C0000000UL; ul_test[i].expected = "3221225472"; i++; ul_test[i].num = 0x000000000C000000UL; ul_test[i].expected = "201326592"; i++; ul_test[i].num = 0x0000000000C00000UL; ul_test[i].expected = "12582912"; i++; ul_test[i].num = 0x00000000000C0000UL; ul_test[i].expected = "786432"; i++; ul_test[i].num = 0x000000000000C000UL; ul_test[i].expected = "49152"; i++; ul_test[i].num = 0x0000000000000C00UL; ul_test[i].expected = "3072"; i++; ul_test[i].num = 0x00000000000000C0UL; ul_test[i].expected = "192"; i++; ul_test[i].num = 0x000000000000000CUL; ul_test[i].expected = "12"; i++; ul_test[i].num = 0x00000001UL; ul_test[i].expected = "1"; i++; ul_test[i].num = 0x00000000UL; ul_test[i].expected = "0"; num_ulong_tests = i; #endif for(i=1; i<=num_ulong_tests; i++) { for(j=0; j<BUFSZ; j++) ul_test[i].result[j] = 'X'; ul_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(ul_test[i].result, "%lu", ul_test[i].num); if(memcmp(ul_test[i].result, ul_test[i].expected, strlen(ul_test[i].expected))) { printf("unsigned long test #%.2d: Failed (Expected: %s Got: %s)\n", i, ul_test[i].expected, ul_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() unsigned long tests OK!\n"); else printf("Some curl_mprintf() unsigned long tests Failed!\n"); return failed; } 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: int xt_compat_check_entry_offsets(const void *base, unsigned int target_offset, unsigned int next_offset) { const struct compat_xt_entry_target *t; const char *e = base; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct compat_xt_standard_target) != next_offset) return -EINVAL; return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: void Layer::RemoveDependentNeedsPushProperties() { num_dependents_need_push_properties_--; DCHECK_GE(num_dependents_need_push_properties_, 0); if (!parent_should_know_need_push_properties() && parent_) parent_->RemoveDependentNeedsPushProperties(); } 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 WebGL2RenderingContextBase::uniformMatrix2x4fv( const WebGLUniformLocation* location, GLboolean transpose, Vector<GLfloat>& value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix2x4fv", location, transpose, value.data(), value.size(), 8, src_offset, src_length)) return; ContextGL()->UniformMatrix2x4fv( location->Location(), (src_length ? src_length : (value.size() - src_offset)) >> 3, transpose, value.data() + src_offset); } 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: int svc_rdma_xdr_encode_error(struct svcxprt_rdma *xprt, struct rpcrdma_msg *rmsgp, enum rpcrdma_errcode err, __be32 *va) { __be32 *startp = va; *va++ = rmsgp->rm_xid; *va++ = rmsgp->rm_vers; *va++ = xprt->sc_fc_credits; *va++ = rdma_error; *va++ = cpu_to_be32(err); if (err == ERR_VERS) { *va++ = rpcrdma_version; *va++ = rpcrdma_version; } return (int)((unsigned long)va - (unsigned long)startp); } CWE ID: CWE-404 Target: 1 Example 2: Code: pipe_write(struct kiocb *iocb, struct iov_iter *from) { struct file *filp = iocb->ki_filp; struct pipe_inode_info *pipe = filp->private_data; ssize_t ret = 0; int do_wakeup = 0; size_t total_len = iov_iter_count(from); ssize_t chars; /* Null write succeeds. */ if (unlikely(total_len == 0)) return 0; __pipe_lock(pipe); if (!pipe->readers) { send_sig(SIGPIPE, current, 0); ret = -EPIPE; goto out; } /* We try to merge small writes */ chars = total_len & (PAGE_SIZE-1); /* size of the last buffer */ if (pipe->nrbufs && chars != 0) { int lastbuf = (pipe->curbuf + pipe->nrbufs - 1) & (pipe->buffers - 1); struct pipe_buffer *buf = pipe->bufs + lastbuf; int offset = buf->offset + buf->len; if (pipe_buf_can_merge(buf) && offset + chars <= PAGE_SIZE) { ret = pipe_buf_confirm(pipe, buf); if (ret) goto out; ret = copy_page_from_iter(buf->page, offset, chars, from); if (unlikely(ret < chars)) { ret = -EFAULT; goto out; } do_wakeup = 1; buf->len += ret; if (!iov_iter_count(from)) goto out; } } for (;;) { int bufs; if (!pipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } bufs = pipe->nrbufs; if (bufs < pipe->buffers) { int newbuf = (pipe->curbuf + bufs) & (pipe->buffers-1); struct pipe_buffer *buf = pipe->bufs + newbuf; struct page *page = pipe->tmp_page; int copied; if (!page) { page = alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT); if (unlikely(!page)) { ret = ret ? : -ENOMEM; break; } pipe->tmp_page = page; } /* Always wake up, even if the copy fails. Otherwise * we lock up (O_NONBLOCK-)readers that sleep due to * syscall merging. * FIXME! Is this really true? */ do_wakeup = 1; copied = copy_page_from_iter(page, 0, PAGE_SIZE, from); if (unlikely(copied < PAGE_SIZE && iov_iter_count(from))) { if (!ret) ret = -EFAULT; break; } ret += copied; /* Insert it into the buffer array */ buf->page = page; buf->ops = &anon_pipe_buf_ops; buf->offset = 0; buf->len = copied; buf->flags = 0; if (is_packetized(filp)) { buf->ops = &packet_pipe_buf_ops; buf->flags = PIPE_BUF_FLAG_PACKET; } pipe->nrbufs = ++bufs; pipe->tmp_page = NULL; if (!iov_iter_count(from)) break; } if (bufs < pipe->buffers) continue; if (filp->f_flags & O_NONBLOCK) { if (!ret) ret = -EAGAIN; break; } if (signal_pending(current)) { if (!ret) ret = -ERESTARTSYS; break; } if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, EPOLLIN | EPOLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); do_wakeup = 0; } pipe->waiting_writers++; pipe_wait(pipe); pipe->waiting_writers--; } out: __pipe_unlock(pipe); if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, EPOLLIN | EPOLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); } if (ret > 0 && sb_start_write_trylock(file_inode(filp)->i_sb)) { int err = file_update_time(filp); if (err) ret = err; sb_end_write(file_inode(filp)->i_sb); } return ret; } 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: static void nfs4_close_prepare(struct rpc_task *task, void *data) { struct nfs4_closedata *calldata = data; struct nfs4_state *state = calldata->state; int clear_rd, clear_wr, clear_rdwr; if (nfs_wait_on_sequence(calldata->arg.seqid, task) != 0) return; clear_rd = clear_wr = clear_rdwr = 0; spin_lock(&state->owner->so_lock); /* Calculate the change in open mode */ if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { clear_rd |= test_and_clear_bit(NFS_O_RDONLY_STATE, &state->flags); clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { clear_wr |= test_and_clear_bit(NFS_O_WRONLY_STATE, &state->flags); clear_rdwr |= test_and_clear_bit(NFS_O_RDWR_STATE, &state->flags); } } spin_unlock(&state->owner->so_lock); if (!clear_rd && !clear_wr && !clear_rdwr) { /* Note: exit _without_ calling nfs4_close_done */ task->tk_action = NULL; return; } nfs_fattr_init(calldata->res.fattr); if (test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE]; calldata->arg.open_flags = FMODE_READ; } else if (test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_DOWNGRADE]; calldata->arg.open_flags = FMODE_WRITE; } calldata->timestamp = jiffies; rpc_call_start(task); } 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: MagickExport int LocaleLowercase(const int c) { if (c < 0) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); } CWE ID: CWE-125 Target: 1 Example 2: Code: short HTMLAnchorElement::tabIndex() const { return Element::tabIndex(); } CWE ID: CWE-284 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 bta_hh_co_open(UINT8 dev_handle, UINT8 sub_class, tBTA_HH_ATTR_MASK attr_mask, UINT8 app_id) { UINT32 i; btif_hh_device_t *p_dev = NULL; if (dev_handle == BTA_HH_INVALID_HANDLE) { APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...", __FUNCTION__, dev_handle); return; } for (i = 0; i < BTIF_HH_MAX_HID; i++) { p_dev = &btif_hh_cb.devices[i]; if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN && p_dev->dev_handle == dev_handle) { APPL_TRACE_WARNING("%s: Found an existing device with the same handle " "dev_status = %d",__FUNCTION__, p_dev->dev_status); APPL_TRACE_WARNING("%s: bd_addr = [%02X:%02X:%02X:%02X:%02X:]", __FUNCTION__, p_dev->bd_addr.address[0], p_dev->bd_addr.address[1], p_dev->bd_addr.address[2], p_dev->bd_addr.address[3], p_dev->bd_addr.address[4]); APPL_TRACE_WARNING("%s: attr_mask = 0x%04x, sub_class = 0x%02x, app_id = %d", __FUNCTION__, p_dev->attr_mask, p_dev->sub_class, p_dev->app_id); if(p_dev->fd<0) { p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC); if (p_dev->fd < 0){ APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s", __FUNCTION__,strerror(errno)); return; }else APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd); } p_dev->hh_keep_polling = 1; p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev); break; } p_dev = NULL; } if (p_dev == NULL) { for (i = 0; i < BTIF_HH_MAX_HID; i++) { if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_UNKNOWN) { p_dev = &btif_hh_cb.devices[i]; p_dev->dev_handle = dev_handle; p_dev->attr_mask = attr_mask; p_dev->sub_class = sub_class; p_dev->app_id = app_id; p_dev->local_vup = FALSE; btif_hh_cb.device_num++; p_dev->fd = open(dev_path, O_RDWR | O_CLOEXEC); if (p_dev->fd < 0){ APPL_TRACE_ERROR("%s: Error: failed to open uhid, err:%s", __FUNCTION__,strerror(errno)); return; }else{ APPL_TRACE_DEBUG("%s: uhid fd = %d", __FUNCTION__, p_dev->fd); p_dev->hh_keep_polling = 1; p_dev->hh_poll_thread_id = create_thread(btif_hh_poll_event_thread, p_dev); } break; } } } if (p_dev == NULL) { APPL_TRACE_ERROR("%s: Error: too many HID devices are connected", __FUNCTION__); return; } p_dev->dev_status = BTHH_CONN_STATE_CONNECTED; APPL_TRACE_DEBUG("%s: Return device status %d", __FUNCTION__, p_dev->dev_status); } CWE ID: CWE-284 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 tcp_read_sock(struct sock *sk, read_descriptor_t *desc, sk_read_actor_t recv_actor) { struct sk_buff *skb; struct tcp_sock *tp = tcp_sk(sk); u32 seq = tp->copied_seq; u32 offset; int copied = 0; if (sk->sk_state == TCP_LISTEN) return -ENOTCONN; while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) { if (offset < skb->len) { int used; size_t len; len = skb->len - offset; /* Stop reading if we hit a patch of urgent data */ if (tp->urg_data) { u32 urg_offset = tp->urg_seq - seq; if (urg_offset < len) len = urg_offset; if (!len) break; } used = recv_actor(desc, skb, offset, len); if (used < 0) { if (!copied) copied = used; break; } else if (used <= len) { seq += used; copied += used; offset += used; } /* * If recv_actor drops the lock (e.g. TCP splice * receive) the skb pointer might be invalid when * getting here: tcp_collapse might have deleted it * while aggregating skbs from the socket queue. */ skb = tcp_recv_skb(sk, seq-1, &offset); if (!skb || (offset+1 != skb->len)) break; } if (tcp_hdr(skb)->fin) { sk_eat_skb(sk, skb, 0); ++seq; break; } sk_eat_skb(sk, skb, 0); if (!desc->count) break; } tp->copied_seq = seq; tcp_rcv_space_adjust(sk); /* Clean up data we have read: This will do ACK frames. */ if (copied > 0) tcp_cleanup_rbuf(sk, copied); return copied; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int dccp_v4_rcv(struct sk_buff *skb) { const struct dccp_hdr *dh; const struct iphdr *iph; struct sock *sk; int min_cov; /* Step 1: Check header basics */ if (dccp_invalid_packet(skb)) goto discard_it; iph = ip_hdr(skb); /* Step 1: If header checksum is incorrect, drop packet and return */ if (dccp_v4_csum_finish(skb, iph->saddr, iph->daddr)) { DCCP_WARN("dropped packet with invalid checksum\n"); goto discard_it; } dh = dccp_hdr(skb); DCCP_SKB_CB(skb)->dccpd_seq = dccp_hdr_seq(dh); DCCP_SKB_CB(skb)->dccpd_type = dh->dccph_type; dccp_pr_debug("%8.8s src=%pI4@%-5d dst=%pI4@%-5d seq=%llu", dccp_packet_name(dh->dccph_type), &iph->saddr, ntohs(dh->dccph_sport), &iph->daddr, ntohs(dh->dccph_dport), (unsigned long long) DCCP_SKB_CB(skb)->dccpd_seq); if (dccp_packet_without_ack(skb)) { DCCP_SKB_CB(skb)->dccpd_ack_seq = DCCP_PKT_WITHOUT_ACK_SEQ; dccp_pr_debug_cat("\n"); } else { DCCP_SKB_CB(skb)->dccpd_ack_seq = dccp_hdr_ack_seq(skb); dccp_pr_debug_cat(", ack=%llu\n", (unsigned long long) DCCP_SKB_CB(skb)->dccpd_ack_seq); } /* Step 2: * Look up flow ID in table and get corresponding socket */ sk = __inet_lookup_skb(&dccp_hashinfo, skb, dh->dccph_sport, dh->dccph_dport); /* * Step 2: * If no socket ... */ if (sk == NULL) { dccp_pr_debug("failed to look up flow ID in table and " "get corresponding socket\n"); goto no_dccp_socket; } /* * Step 2: * ... or S.state == TIMEWAIT, * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return */ if (sk->sk_state == DCCP_TIME_WAIT) { dccp_pr_debug("sk->sk_state == DCCP_TIME_WAIT: do_time_wait\n"); inet_twsk_put(inet_twsk(sk)); goto no_dccp_socket; } /* * RFC 4340, sec. 9.2.1: Minimum Checksum Coverage * o if MinCsCov = 0, only packets with CsCov = 0 are accepted * o if MinCsCov > 0, also accept packets with CsCov >= MinCsCov */ min_cov = dccp_sk(sk)->dccps_pcrlen; if (dh->dccph_cscov && (min_cov == 0 || dh->dccph_cscov < min_cov)) { dccp_pr_debug("Packet CsCov %d does not satisfy MinCsCov %d\n", dh->dccph_cscov, min_cov); /* FIXME: "Such packets SHOULD be reported using Data Dropped * options (Section 11.7) with Drop Code 0, Protocol * Constraints." */ goto discard_and_relse; } if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_and_relse; nf_reset(skb); return sk_receive_skb(sk, skb, 1); no_dccp_socket: if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto discard_it; /* * Step 2: * If no socket ... * Generate Reset(No Connection) unless P.type == Reset * Drop packet and return */ if (dh->dccph_type != DCCP_PKT_RESET) { DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_NO_CONNECTION; dccp_v4_ctl_send_reset(sk, skb); } discard_it: kfree_skb(skb); return 0; discard_and_relse: sock_put(sk); goto discard_it; } 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: gss_wrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_args(minor_status, context_handle, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_wrap) { status = mech->gss_wrap(minor_status, ctx->internal_ctx_id, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else if (mech->gss_wrap_aead || (mech->gss_wrap_iov && mech->gss_wrap_iov_length)) { status = gssint_wrap_aead(mech, minor_status, ctx, conf_req_flag, (gss_qop_t)qop_req, GSS_C_NO_BUFFER, input_message_buffer, conf_state, output_message_buffer); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } CWE ID: CWE-415 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 MediaStreamDispatcherHost::CancelRequest(int page_request_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); media_stream_manager_->CancelRequest(render_process_id_, render_frame_id_, page_request_id); } CWE ID: CWE-189 Target: 1 Example 2: Code: static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr, unsigned long end, struct page **pages, int *nr) { BUILD_BUG(); return 0; } 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: static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state) { struct nfs_delegation *delegation; struct nfs4_opendata *opendata; int delegation_type = 0; int status; opendata = nfs4_open_recoverdata_alloc(ctx, state); if (IS_ERR(opendata)) return PTR_ERR(opendata); opendata->o_arg.claim = NFS4_OPEN_CLAIM_PREVIOUS; opendata->o_arg.fh = NFS_FH(state->inode); rcu_read_lock(); delegation = rcu_dereference(NFS_I(state->inode)->delegation); if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0) delegation_type = delegation->type; rcu_read_unlock(); opendata->o_arg.u.delegation_type = delegation_type; status = nfs4_open_recover(opendata, state); nfs4_opendata_put(opendata); return status; } 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 DownloadController::OnDownloadStarted( DownloadItem* download_item) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = download_item->GetWebContents(); if (!web_contents) return; download_item->AddObserver(this); ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted( download_item->GetTargetFilePath().BaseName().value(), download_item->GetMimeType()); } CWE ID: CWE-254 Target: 1 Example 2: Code: bool WebRuntimeFeatures::IsSlimmingPaintV2Enabled() { return RuntimeEnabledFeatures::SlimmingPaintV2Enabled(); } CWE ID: CWE-254 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 ensure_open_passwd(pool *p) { /* Make sure pass/group is open. */ pr_auth_setpwent(p); pr_auth_setgrent(p); /* On some unices the following is necessary to ensure the files * are open (BSDI 3.1) */ pr_auth_getpwent(p); pr_auth_getgrent(p); /* Per Debian bug report: * https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=717235 * we might want to do another set{pw,gr}ent(), to play better with * some NSS modules. */ pr_auth_setpwent(p); pr_auth_setgrent(p); } CWE ID: CWE-59 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 DownloadRequestLimiter::TabDownloadState::DidStartNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; download_seen_ = false; ui_status_ = DOWNLOAD_UI_DEFAULT; if (navigation_handle->IsRendererInitiated() && (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED)) { return; } if (status_ == DownloadRequestLimiter::ALLOW_ALL_DOWNLOADS || status_ == DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED) { if (!initial_page_host_.empty() && navigation_handle->GetURL().host_piece() == initial_page_host_) { return; } } NotifyCallbacks(false); host_->Remove(this, web_contents()); } CWE ID: Target: 1 Example 2: Code: QuicPeerForTest( std::unique_ptr<FakePacketTransport> packet_transport, std::unique_ptr<MockP2PQuicTransportDelegate> quic_transport_delegate, std::unique_ptr<P2PQuicTransportImpl> quic_transport, rtc::scoped_refptr<rtc::RTCCertificate> certificate) : packet_transport_(std::move(packet_transport)), quic_transport_delegate_(std::move(quic_transport_delegate)), quic_transport_(std::move(quic_transport)), certificate_(certificate) {} CWE ID: CWE-284 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 ExtensionsUpdatedObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (!automation_) { delete this; return; } switch (type) { case chrome::NOTIFICATION_EXTENSION_UPDATE_FOUND: in_progress_updates_.insert( *(content::Details<const std::string>(details).ptr())); break; case chrome::NOTIFICATION_EXTENSION_UPDATING_FINISHED: updater_finished_ = true; break; case chrome::NOTIFICATION_EXTENSION_LOADED: case chrome::NOTIFICATION_EXTENSION_INSTALL_NOT_ALLOWED: case chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED: { const extensions::Extension* extension = content::Details<extensions::Extension>(details).ptr(); in_progress_updates_.erase(extension->id()); break; } case chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR: { extensions::CrxInstaller* installer = content::Source<extensions::CrxInstaller>(source).ptr(); in_progress_updates_.erase(installer->expected_id()); break; } case content::NOTIFICATION_LOAD_STOP: break; default: NOTREACHED(); break; } if (updater_finished_ && in_progress_updates_.empty() && DidExtensionViewsStopLoading(manager_)) { AutomationJSONReply reply(automation_, reply_message_.release()); reply.SendSuccess(NULL); delete this; } } 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_process_variant_of_array_of_ints123 (MyObject *obj, GValue *variant, GError **error) { GArray *array; int i; int j; j = 0; array = (GArray *)g_value_get_boxed (variant); for (i = 0; i <= 2; i++) { j = g_array_index (array, int, i); if (j != i + 1) goto error; } return TRUE; error: *error = g_error_new (MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "Error decoding a variant of type ai (i + 1 = %i, j = %i)", i, j + 1); return FALSE; } CWE ID: CWE-264 Target: 1 Example 2: Code: static nad_t _sx_sasl_success(sx_t s, const char *data, int dlen) { nad_t nad; int ns; nad = nad_new(); ns = nad_add_namespace(nad, uri_SASL, NULL); nad_append_elem(nad, ns, "success", 0); if(data != NULL) nad_append_cdata(nad, data, dlen, 1); return nad; } 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: static int pppol2tp_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int val; int err; if (level != SOL_PPPOL2TP) return udp_prot.setsockopt(sk, level, optname, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get session context from the socket */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_setsockopt(sk, session, optname, val); err = 0; end_put_sess: sock_put(sk); end: 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: InRegionScrollableArea::InRegionScrollableArea(WebPagePrivate* webPage, RenderLayer* layer) : m_webPage(webPage) , m_layer(layer) { ASSERT(webPage); ASSERT(layer); m_isNull = false; RenderObject* layerRenderer = layer->renderer(); ASSERT(layerRenderer); if (layerRenderer->isRenderView()) { // #document case FrameView* view = toRenderView(layerRenderer)->frameView(); ASSERT(view); Frame* frame = view->frame(); ASSERT_UNUSED(frame, frame); m_scrollPosition = m_webPage->mapToTransformed(view->scrollPosition()); m_contentsSize = m_webPage->mapToTransformed(view->contentsSize()); m_viewportSize = m_webPage->mapToTransformed(view->visibleContentRect(false /*includeScrollbars*/)).size(); m_visibleWindowRect = m_webPage->mapToTransformed(m_webPage->getRecursiveVisibleWindowRect(view)); IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize()); m_visibleWindowRect.intersect(transformedWindowRect); m_scrollsHorizontally = view->contentsWidth() > view->visibleWidth(); m_scrollsVertically = view->contentsHeight() > view->visibleHeight(); m_minimumScrollPosition = m_webPage->mapToTransformed(calculateMinimumScrollPosition( view->visibleContentRect().size(), 0.0 /*overscrollLimit*/)); m_maximumScrollPosition = m_webPage->mapToTransformed(calculateMaximumScrollPosition( view->visibleContentRect().size(), view->contentsSize(), 0.0 /*overscrollLimit*/)); } else { // RenderBox-based elements case (scrollable boxes (div's, p's, textarea's, etc)). RenderBox* box = m_layer->renderBox(); ASSERT(box); ASSERT(box->canBeScrolledAndHasScrollableArea()); ScrollableArea* scrollableArea = static_cast<ScrollableArea*>(m_layer); m_scrollPosition = m_webPage->mapToTransformed(scrollableArea->scrollPosition()); m_contentsSize = m_webPage->mapToTransformed(scrollableArea->contentsSize()); m_viewportSize = m_webPage->mapToTransformed(scrollableArea->visibleContentRect(false /*includeScrollbars*/)).size(); m_visibleWindowRect = m_layer->renderer()->absoluteClippedOverflowRect(); m_visibleWindowRect = m_layer->renderer()->frame()->view()->contentsToWindow(m_visibleWindowRect); IntRect visibleFrameWindowRect = m_webPage->getRecursiveVisibleWindowRect(m_layer->renderer()->frame()->view()); m_visibleWindowRect.intersect(visibleFrameWindowRect); m_visibleWindowRect = m_webPage->mapToTransformed(m_visibleWindowRect); IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize()); m_visibleWindowRect.intersect(transformedWindowRect); m_scrollsHorizontally = box->scrollWidth() != box->clientWidth() && box->scrollsOverflowX(); m_scrollsVertically = box->scrollHeight() != box->clientHeight() && box->scrollsOverflowY(); m_minimumScrollPosition = m_webPage->mapToTransformed(calculateMinimumScrollPosition( Platform::IntSize(box->clientWidth(), box->clientHeight()), 0.0 /*overscrollLimit*/)); m_maximumScrollPosition = m_webPage->mapToTransformed(calculateMaximumScrollPosition( Platform::IntSize(box->clientWidth(), box->clientHeight()), Platform::IntSize(box->scrollWidth(), box->scrollHeight()), 0.0 /*overscrollLimit*/)); } } CWE ID: CWE-119 Target: 1 Example 2: Code: void LayerTreeCoordinator::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer) { m_nonCompositedContentLayer->removeAllChildren(); m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground()); if (graphicsLayer) m_nonCompositedContentLayer->addChild(graphicsLayer); } 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 GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; access_token_.clear(); expires_in_seconds_ = 0; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; request_.reset(new UrlFetcher(GURL(provider_info_.access_token_url), UrlFetcher::POST)); request_->SetRequestContext(request_context_getter_); request_->SetUploadData("application/x-www-form-urlencoded", post_body); request_->Start( base::Bind(&GaiaOAuthClient::Core::OnAuthTokenFetchComplete, this)); } 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 ProfileDependencyManager::AssertFactoriesBuilt() { if (built_factories_) return; #if defined(ENABLE_BACKGROUND) BackgroundContentsServiceFactory::GetInstance(); #endif BookmarkModelFactory::GetInstance(); #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION) captive_portal::CaptivePortalServiceFactory::GetInstance(); #endif ChromeURLDataManagerFactory::GetInstance(); #if defined(ENABLE_PRINTING) CloudPrintProxyServiceFactory::GetInstance(); #endif CookieSettings::Factory::GetInstance(); #if defined(ENABLE_NOTIFICATIONS) DesktopNotificationServiceFactory::GetInstance(); #endif DownloadServiceFactory::GetInstance(); #if defined(ENABLE_EXTENSIONS) extensions::AppRestoreServiceFactory::GetInstance(); extensions::BluetoothAPIFactory::GetInstance(); extensions::CommandServiceFactory::GetInstance(); extensions::CookiesAPIFactory::GetInstance(); extensions::ExtensionSystemFactory::GetInstance(); extensions::FontSettingsAPIFactory::GetInstance(); extensions::IdleManagerFactory::GetInstance(); extensions::ManagedModeAPIFactory::GetInstance(); extensions::ProcessesAPIFactory::GetInstance(); extensions::SuggestedLinksRegistryFactory::GetInstance(); extensions::TabCaptureRegistryFactory::GetInstance(); extensions::WebNavigationAPIFactory::GetInstance(); ExtensionManagementAPIFactory::GetInstance(); #endif FaviconServiceFactory::GetInstance(); FindBarStateFactory::GetInstance(); #if defined(USE_AURA) GesturePrefsObserverFactoryAura::GetInstance(); #endif GlobalErrorServiceFactory::GetInstance(); GoogleURLTrackerFactory::GetInstance(); HistoryServiceFactory::GetInstance(); MediaGalleriesPreferencesFactory::GetInstance(); NTPResourceCacheFactory::GetInstance(); PasswordStoreFactory::GetInstance(); PersonalDataManagerFactory::GetInstance(); #if !defined(OS_ANDROID) PinnedTabServiceFactory::GetInstance(); #endif PluginPrefsFactory::GetInstance(); #if defined(ENABLE_CONFIGURATION_POLICY) && !defined(OS_CHROMEOS) policy::UserPolicySigninServiceFactory::GetInstance(); #endif predictors::AutocompleteActionPredictorFactory::GetInstance(); predictors::PredictorDatabaseFactory::GetInstance(); predictors::ResourcePrefetchPredictorFactory::GetInstance(); prerender::PrerenderManagerFactory::GetInstance(); prerender::PrerenderLinkManagerFactory::GetInstance(); ProfileSyncServiceFactory::GetInstance(); ProtocolHandlerRegistryFactory::GetInstance(); #if defined(ENABLE_PROTECTOR_SERVICE) protector::ProtectorServiceFactory::GetInstance(); #endif #if defined(ENABLE_SESSION_SERVICE) SessionServiceFactory::GetInstance(); #endif ShortcutsBackendFactory::GetInstance(); ThumbnailServiceFactory::GetInstance(); SigninManagerFactory::GetInstance(); #if defined(ENABLE_INPUT_SPEECH) SpeechInputExtensionManager::InitializeFactory(); ChromeSpeechRecognitionPreferences::InitializeFactory(); #endif SpellcheckServiceFactory::GetInstance(); TabRestoreServiceFactory::GetInstance(); TemplateURLFetcherFactory::GetInstance(); TemplateURLServiceFactory::GetInstance(); #if defined(ENABLE_THEMES) ThemeServiceFactory::GetInstance(); #endif TokenServiceFactory::GetInstance(); UserStyleSheetWatcherFactory::GetInstance(); VisitedLinkMasterFactory::GetInstance(); WebDataServiceFactory::GetInstance(); #if defined(ENABLE_WEB_INTENTS) WebIntentsRegistryFactory::GetInstance(); #endif built_factories_ = true; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int cirrus_bitblt_common_patterncopy(CirrusVGAState * s, const uint8_t * src) { uint8_t *dst; dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); if (blit_is_unsafe(s)) return 0; (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); 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: void SocketStream::Connect() { DCHECK(base::MessageLoop::current()) << "The current base::MessageLoop must exist"; DCHECK_EQ(base::MessageLoop::TYPE_IO, base::MessageLoop::current()->type()) << "The current base::MessageLoop must be TYPE_IO"; if (context_.get()) { context_->ssl_config_service()->GetSSLConfig(&server_ssl_config_); proxy_ssl_config_ = server_ssl_config_; } CheckPrivacyMode(); DCHECK_EQ(next_state_, STATE_NONE); AddRef(); // Released in Finish() next_state_ = STATE_BEFORE_CONNECT; net_log_.BeginEvent( NetLog::TYPE_SOCKET_STREAM_CONNECT, NetLog::StringCallback("url", &url_.possibly_invalid_spec())); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&SocketStream::DoLoop, this, OK)); } 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 void uv__process_child_init(const uv_process_options_t* options, int stdio_count, int (*pipes)[2], int error_fd) { int close_fd; int use_fd; int fd; if (options->flags & UV_PROCESS_DETACHED) setsid(); for (fd = 0; fd < stdio_count; fd++) { close_fd = pipes[fd][0]; use_fd = pipes[fd][1]; if (use_fd < 0) { if (fd >= 3) continue; else { /* redirect stdin, stdout and stderr to /dev/null even if UV_IGNORE is * set */ use_fd = open("/dev/null", fd == 0 ? O_RDONLY : O_RDWR); close_fd = use_fd; if (use_fd == -1) { uv__write_int(error_fd, -errno); perror("failed to open stdio"); _exit(127); } } } if (fd == use_fd) uv__cloexec(use_fd, 0); else dup2(use_fd, fd); if (fd <= 2) uv__nonblock(fd, 0); if (close_fd != -1) uv__close(close_fd); } for (fd = 0; fd < stdio_count; fd++) { use_fd = pipes[fd][1]; if (use_fd >= 0 && fd != use_fd) close(use_fd); } if (options->cwd != NULL && chdir(options->cwd)) { uv__write_int(error_fd, -errno); perror("chdir()"); _exit(127); } if ((options->flags & UV_PROCESS_SETGID) && setgid(options->gid)) { uv__write_int(error_fd, -errno); perror("setgid()"); _exit(127); } if ((options->flags & UV_PROCESS_SETUID) && setuid(options->uid)) { uv__write_int(error_fd, -errno); perror("setuid()"); _exit(127); } if (options->env != NULL) { environ = options->env; } execvp(options->file, options->args); uv__write_int(error_fd, -errno); perror("execvp()"); _exit(127); } CWE ID: CWE-264 Target: 1 Example 2: Code: toomany(struct magic_set *ms, const char *name, uint16_t num) { if (file_printf(ms, ", too many %s header sections (%u)", name, num ) == -1) return -1; return 0; } 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 iowarrior_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(interface); struct iowarrior *dev = NULL; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int i; int retval = -ENOMEM; /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(struct iowarrior), GFP_KERNEL); if (dev == NULL) { dev_err(&interface->dev, "Out of memory\n"); return retval; } mutex_init(&dev->mutex); atomic_set(&dev->intr_idx, 0); atomic_set(&dev->read_idx, 0); spin_lock_init(&dev->intr_idx_lock); atomic_set(&dev->overflow_flag, 0); init_waitqueue_head(&dev->read_wait); atomic_set(&dev->write_busy, 0); init_waitqueue_head(&dev->write_wait); dev->udev = udev; dev->interface = interface; iface_desc = interface->cur_altsetting; dev->product_id = le16_to_cpu(udev->descriptor.idProduct); /* set up the endpoint information */ for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) { endpoint = &iface_desc->endpoint[i].desc; if (usb_endpoint_is_int_in(endpoint)) dev->int_in_endpoint = endpoint; if (usb_endpoint_is_int_out(endpoint)) /* this one will match for the IOWarrior56 only */ dev->int_out_endpoint = endpoint; } /* we have to check the report_size often, so remember it in the endianness suitable for our machine */ dev->report_size = usb_endpoint_maxp(dev->int_in_endpoint); if ((dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) && (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW56)) /* IOWarrior56 has wMaxPacketSize different from report size */ dev->report_size = 7; /* create the urb and buffer for reading */ dev->int_in_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->int_in_urb) { dev_err(&interface->dev, "Couldn't allocate interrupt_in_urb\n"); goto error; } dev->int_in_buffer = kmalloc(dev->report_size, GFP_KERNEL); if (!dev->int_in_buffer) { dev_err(&interface->dev, "Couldn't allocate int_in_buffer\n"); goto error; } usb_fill_int_urb(dev->int_in_urb, dev->udev, usb_rcvintpipe(dev->udev, dev->int_in_endpoint->bEndpointAddress), dev->int_in_buffer, dev->report_size, iowarrior_callback, dev, dev->int_in_endpoint->bInterval); /* create an internal buffer for interrupt data from the device */ dev->read_queue = kmalloc(((dev->report_size + 1) * MAX_INTERRUPT_BUFFER), GFP_KERNEL); if (!dev->read_queue) { dev_err(&interface->dev, "Couldn't allocate read_queue\n"); goto error; } /* Get the serial-number of the chip */ memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial)); usb_string(udev, udev->descriptor.iSerialNumber, dev->chip_serial, sizeof(dev->chip_serial)); if (strlen(dev->chip_serial) != 8) memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial)); /* Set the idle timeout to 0, if this is interface 0 */ if (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) { usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0A, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); } /* allow device read and ioctl */ dev->present = 1; /* we can register the device now, as it is ready */ usb_set_intfdata(interface, dev); retval = usb_register_dev(interface, &iowarrior_class); if (retval) { /* something prevented us from registering this driver */ dev_err(&interface->dev, "Not able to get a minor for this device.\n"); usb_set_intfdata(interface, NULL); goto error; } dev->minor = interface->minor; /* let the user know what node this device is now attached to */ dev_info(&interface->dev, "IOWarrior product=0x%x, serial=%s interface=%d " "now attached to iowarrior%d\n", dev->product_id, dev->chip_serial, iface_desc->desc.bInterfaceNumber, dev->minor - IOWARRIOR_MINOR_BASE); return retval; error: iowarrior_delete(dev); return retval; } 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 spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */ CWE ID: CWE-190 Target: 1 Example 2: Code: static int StreamTcpTest12 (void) { Packet *p = SCMalloc(SIZE_OF_PACKET); if (unlikely(p == NULL)) return 0; Flow f; ThreadVars tv; StreamTcpThread stt; TCPHdr tcph; uint8_t payload[4]; memset(p, 0, SIZE_OF_PACKET); PacketQueue pq; memset(&pq,0,sizeof(PacketQueue)); memset (&f, 0, sizeof(Flow)); memset(&tv, 0, sizeof (ThreadVars)); memset(&stt, 0, sizeof (StreamTcpThread)); memset(&tcph, 0, sizeof (TCPHdr)); FLOW_INITIALIZE(&f); p->flow = &f; StreamTcpUTInit(&stt.ra_ctx); tcph.th_win = htons(5480); tcph.th_seq = htonl(10); tcph.th_ack = htonl(11); tcph.th_flags = TH_ACK; p->tcph = &tcph; int ret = 0; if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) goto end; p->tcph->th_seq = htonl(10); p->tcph->th_ack = htonl(11); p->tcph->th_flags = TH_ACK|TH_PUSH; p->flowflags = FLOW_PKT_TOSERVER; StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/ p->payload = payload; p->payload_len = 3; if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) goto end; p->tcph->th_seq = htonl(6); p->tcph->th_ack = htonl(11); p->tcph->th_flags = TH_ACK|TH_PUSH; p->flowflags = FLOW_PKT_TOSERVER; StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/ p->payload = payload; p->payload_len = 3; if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) goto end; if (stream_config.async_oneside != TRUE) { ret = 1; goto end; } if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) { printf("failed in setting asynchronous session\n"); goto end; } if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) { printf("failed in setting state\n"); goto end; } if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 && ((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) { printf("failed in seq %"PRIu32" match\n", ((TcpSession *)(p->flow->protoctx))->client.last_ack); goto end; } StreamTcpSessionClear(p->flow->protoctx); ret = 1; end: SCFree(p); FLOW_DESTROY(&f); StreamTcpUTDeinit(stt.ra_ctx); return ret; } 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: CoordinatorImpl::CoordinatorImpl(service_manager::Connector* connector) : next_dump_id_(0), client_process_timeout_(base::TimeDelta::FromSeconds(15)) { process_map_ = std::make_unique<ProcessMap>(connector); DCHECK(!g_coordinator_impl); g_coordinator_impl = this; base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id( mojom::kServiceTracingProcessId); tracing_observer_ = std::make_unique<TracingObserver>( base::trace_event::TraceLog::GetInstance(), nullptr); } 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: void AppShortcutManager::OnceOffCreateShortcuts() { bool was_enabled = prefs_->GetBoolean(prefs::kAppShortcutsHaveBeenCreated); #if defined(OS_MACOSX) bool is_now_enabled = apps::IsAppShimsEnabled(); #else bool is_now_enabled = true; #endif // defined(OS_MACOSX) if (was_enabled != is_now_enabled) prefs_->SetBoolean(prefs::kAppShortcutsHaveBeenCreated, is_now_enabled); if (was_enabled || !is_now_enabled) return; extensions::ExtensionSystem* extension_system; ExtensionServiceInterface* extension_service; if (!(extension_system = extensions::ExtensionSystem::Get(profile_)) || !(extension_service = extension_system->extension_service())) return; const extensions::ExtensionSet* apps = extension_service->extensions(); for (extensions::ExtensionSet::const_iterator it = apps->begin(); it != apps->end(); ++it) { if (ShouldCreateShortcutFor(profile_, it->get())) CreateShortcutsInApplicationsMenu(profile_, it->get()); } } CWE ID: CWE-399 Target: 1 Example 2: Code: static int ipgre_tunnel_validate(struct nlattr *tb[], struct nlattr *data[]) { __be16 flags; if (!data) return 0; flags = 0; if (data[IFLA_GRE_IFLAGS]) flags |= nla_get_be16(data[IFLA_GRE_IFLAGS]); if (data[IFLA_GRE_OFLAGS]) flags |= nla_get_be16(data[IFLA_GRE_OFLAGS]); if (flags & (GRE_VERSION|GRE_ROUTING)) return -EINVAL; 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: SPL_METHOD(SplDoublyLinkedList, offsetSet) { zval *zindex, *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (Z_TYPE_P(zindex) == IS_NULL) { /* $obj[] = ... */ spl_ptr_llist_push(intern->llist, value); } else { /* $obj[$foo] = ... */ zend_long index; spl_ptr_llist_element *element; index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* call dtor on the old element as in spl_ptr_llist_pop */ if (intern->llist->dtor) { intern->llist->dtor(element); } /* the element is replaced, delref the old one as in * SplDoublyLinkedList::pop() */ zval_ptr_dtor(&element->data); ZVAL_COPY_VALUE(&element->data, value); /* new element, call ctor as in spl_ptr_llist_push */ if (intern->llist->ctor) { intern->llist->ctor(element); } } else { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0); return; } } } /* }}} */ /* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index) CWE ID: CWE-415 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 br_multicast_del_pg(struct net_bridge *br, struct net_bridge_port_group *pg) { struct net_bridge_mdb_htable *mdb; struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &pg->addr); if (WARN_ON(!mp)) return; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (p != pg) continue; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); if (!mp->ports && !mp->mglist && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); return; } WARN_ON(1); } CWE ID: CWE-20 Target: 1 Example 2: Code: static int translate_compat_table(struct xt_table_info **pinfo, void **pentry0, const struct compat_arpt_replace *compatr) { unsigned int i, j; struct xt_table_info *newinfo, *info; void *pos, *entry0, *entry1; struct compat_arpt_entry *iter0; struct arpt_replace repl; unsigned int size; int ret = 0; info = *pinfo; entry0 = *pentry0; size = compatr->size; info->number = compatr->num_entries; j = 0; xt_compat_lock(NFPROTO_ARP); xt_compat_init_offsets(NFPROTO_ARP, compatr->num_entries); /* Walk through entries, checking offsets. */ xt_entry_foreach(iter0, entry0, compatr->size) { ret = check_compat_entry_size_and_hooks(iter0, info, &size, entry0, entry0 + compatr->size); if (ret != 0) goto out_unlock; ++j; } ret = -EINVAL; if (j != compatr->num_entries) goto out_unlock; ret = -ENOMEM; newinfo = xt_alloc_table_info(size); if (!newinfo) goto out_unlock; newinfo->number = compatr->num_entries; for (i = 0; i < NF_ARP_NUMHOOKS; i++) { newinfo->hook_entry[i] = compatr->hook_entry[i]; newinfo->underflow[i] = compatr->underflow[i]; } entry1 = newinfo->entries; pos = entry1; size = compatr->size; xt_entry_foreach(iter0, entry0, compatr->size) compat_copy_entry_from_user(iter0, &pos, &size, newinfo, entry1); /* all module references in entry0 are now gone */ xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); memcpy(&repl, compatr, sizeof(*compatr)); for (i = 0; i < NF_ARP_NUMHOOKS; i++) { repl.hook_entry[i] = newinfo->hook_entry[i]; repl.underflow[i] = newinfo->underflow[i]; } repl.num_counters = 0; repl.counters = NULL; repl.size = newinfo->size; ret = translate_table(newinfo, entry1, &repl); if (ret) goto free_newinfo; *pinfo = newinfo; *pentry0 = entry1; xt_free_table_info(info); return 0; free_newinfo: xt_free_table_info(newinfo); return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_ARP); xt_compat_unlock(NFPROTO_ARP); xt_entry_foreach(iter0, entry0, compatr->size) { if (j-- == 0) break; compat_release_entry(iter0); } 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: virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); } 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: QuicErrorCode QuicStreamSequencerBuffer::OnStreamData( QuicStreamOffset starting_offset, QuicStringPiece data, QuicTime timestamp, size_t* const bytes_buffered, std::string* error_details) { CHECK_EQ(destruction_indicator_, 123456) << "This object has been destructed"; *bytes_buffered = 0; QuicStreamOffset offset = starting_offset; size_t size = data.size(); if (size == 0) { *error_details = "Received empty stream frame without FIN."; return QUIC_EMPTY_STREAM_FRAME_NO_FIN; } std::list<Gap>::iterator current_gap = gaps_.begin(); while (current_gap != gaps_.end() && current_gap->end_offset <= offset) { ++current_gap; } DCHECK(current_gap != gaps_.end()); if (offset < current_gap->begin_offset && offset + size <= current_gap->begin_offset) { QUIC_DVLOG(1) << "Duplicated data at offset: " << offset << " length: " << size; return QUIC_NO_ERROR; } if (offset < current_gap->begin_offset && offset + size > current_gap->begin_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat("Beginning of received data overlaps with buffered data.\n", "New frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", GapsDebugString(), "\n", "Current gaps: ", ReceivedFramesDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > current_gap->end_offset) { string prefix(data.data(), data.length() < 128 ? data.length() : 128); *error_details = QuicStrCat( "End of received data overlaps with buffered data.\nNew frame range [", offset, ", ", offset + size, ") with first 128 bytes: ", prefix, "\n", "Currently received frames: ", ReceivedFramesDebugString(), "\n", "Current gaps: ", GapsDebugString()); return QUIC_OVERLAPPING_STREAM_DATA; } if (offset + size > total_bytes_read_ + max_buffer_capacity_bytes_) { *error_details = "Received data beyond available range."; return QUIC_INTERNAL_ERROR; } if (current_gap->begin_offset != starting_offset && current_gap->end_offset != starting_offset + data.length() && gaps_.size() >= kMaxNumGapsAllowed) { *error_details = "Too many gaps created for this stream."; return QUIC_TOO_MANY_FRAME_GAPS; } size_t total_written = 0; size_t source_remaining = size; const char* source = data.data(); while (source_remaining > 0) { const size_t write_block_num = GetBlockIndex(offset); const size_t write_block_offset = GetInBlockOffset(offset); DCHECK_GT(blocks_count_, write_block_num); size_t block_capacity = GetBlockCapacity(write_block_num); size_t bytes_avail = block_capacity - write_block_offset; if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) { bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset; } if (blocks_ == nullptr) { blocks_.reset(new BufferBlock*[blocks_count_]()); for (size_t i = 0; i < blocks_count_; ++i) { blocks_[i] = nullptr; } } if (write_block_num >= blocks_count_) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds." "write offset = ", offset, " write_block_num = ", write_block_num, " blocks_count_ = ", blocks_count_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_ == nullptr) { *error_details = "QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null"; return QUIC_STREAM_SEQUENCER_INVALID_STATE; } if (blocks_[write_block_num] == nullptr) { blocks_[write_block_num] = new BufferBlock(); } const size_t bytes_to_copy = std::min<size_t>(bytes_avail, source_remaining); char* dest = blocks_[write_block_num]->buffer + write_block_offset; QUIC_DVLOG(1) << "Write at offset: " << offset << " length: " << bytes_to_copy; if (dest == nullptr || source == nullptr) { *error_details = QuicStrCat( "QuicStreamSequencerBuffer error: OnStreamData()" " dest == nullptr: ", (dest == nullptr), " source == nullptr: ", (source == nullptr), " Writing at offset ", offset, " Gaps: ", GapsDebugString(), " Remaining frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } memcpy(dest, source, bytes_to_copy); source += bytes_to_copy; source_remaining -= bytes_to_copy; offset += bytes_to_copy; total_written += bytes_to_copy; } DCHECK_GT(total_written, 0u); *bytes_buffered = total_written; UpdateGapList(current_gap, starting_offset, total_written); frame_arrival_time_map_.insert( std::make_pair(starting_offset, FrameInfo(size, timestamp))); num_bytes_buffered_ += total_written; return QUIC_NO_ERROR; } CWE ID: CWE-787 Target: 1 Example 2: Code: static void exit_mm(struct task_struct * tsk) { struct mm_struct *mm = tsk->mm; struct core_state *core_state; mm_release(tsk, mm); if (!mm) return; /* * Serialize with any possible pending coredump. * We must hold mmap_sem around checking core_state * and clearing tsk->mm. The core-inducing thread * will increment ->nr_threads for each thread in the * group with ->mm != NULL. */ down_read(&mm->mmap_sem); core_state = mm->core_state; if (core_state) { struct core_thread self; up_read(&mm->mmap_sem); self.task = tsk; self.next = xchg(&core_state->dumper.next, &self); /* * Implies mb(), the result of xchg() must be visible * to core_state->dumper. */ if (atomic_dec_and_test(&core_state->nr_threads)) complete(&core_state->startup); for (;;) { set_task_state(tsk, TASK_UNINTERRUPTIBLE); if (!self.task) /* see coredump_finish() */ break; schedule(); } __set_task_state(tsk, TASK_RUNNING); down_read(&mm->mmap_sem); } atomic_inc(&mm->mm_count); BUG_ON(mm != tsk->active_mm); /* more a memory barrier than a real lock */ task_lock(tsk); tsk->mm = NULL; up_read(&mm->mmap_sem); enter_lazy_tlb(mm, current); /* We don't want this task to be frozen prematurely */ clear_freeze_flag(tsk); task_unlock(tsk); mm_update_next_owner(mm); mmput(mm); } 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: void PropertyTreeManager::Finalize() { while (effect_stack_.size()) CloseCcEffect(); } 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: static void Np_toString(js_State *J) { char buf[32]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, "invalid radix"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[100]; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, "0"); return; } if (isnan(number)) { js_pushstring(J, "NaN"); return; } if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } } CWE ID: CWE-119 Target: 1 Example 2: Code: qreal QQuickWebViewExperimental::contentX() const { Q_D(const QQuickWebView); ASSERT(d->flickProvider); return d->flickProvider->contentX(); } 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 int ldb_dn_escape_internal(char *dst, const char *src, int len) { const char *p, *s; char *d; size_t l; p = s = src; d = dst; while (p - src < len) { p += strcspn(p, ",=\n\r+<>#;\\\" "); if (p - src == len) /* found no escapable chars */ break; /* copy the part of the string before the stop */ memcpy(d, s, p - s); d += (p - s); /* move to current position */ switch (*p) { case ' ': if (p == src || (p-src)==(len-1)) { /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = *p++; } else { /* otherwise don't escape */ *d++ = *p++; } break; /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = *p++; } else { /* otherwise don't escape */ *d++ = *p++; } break; case '?': /* these must be escaped using \c form */ *d++ = '\\'; *d++ = *p++; break; default: { /* any others get \XX form */ unsigned char v; const char *hexbytes = "0123456789ABCDEF"; v = *(const unsigned char *)p; *d++ = '\\'; *d++ = hexbytes[v>>4]; *d++ = hexbytes[v&0xF]; p++; break; } } s = p; /* move forward */ } CWE ID: CWE-200 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 btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst, UINT16 proto, const char* buf, UINT16 len, BOOLEAN ext, BOOLEAN forward) { UNUSED(ext); UNUSED(forward); if (tap_fd != INVALID_FD) { tETH_HDR eth_hdr; memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN); memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN); eth_hdr.h_proto = htons(proto); char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)]; memcpy(packet, &eth_hdr, sizeof(tETH_HDR)); if (len > TAP_MAX_PKT_WRITE_LEN) { LOG_ERROR("btpan_tap_send eth packet size:%d is exceeded limit!", len); return -1; } memcpy(packet + sizeof(tETH_HDR), buf, len); /* Send data to network interface */ int ret = write(tap_fd, packet, len + sizeof(tETH_HDR)); BTIF_TRACE_DEBUG("ret:%d", ret); return ret; } return -1; } CWE ID: CWE-284 Target: 1 Example 2: Code: PassRefPtr<Document> DocumentWriter::createDocument(const KURL& url) { if (!m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader()->client()->shouldUsePluginDocument(m_mimeType)) return PluginDocument::create(m_frame, url); if (!m_frame->loader()->client()->hasHTMLView()) return PlaceholderDocument::create(m_frame, url); return DOMImplementation::createDocument(m_mimeType, m_frame, url, m_frame->inViewSourceMode()); } 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 udf_translate_to_linux(uint8_t *newName, uint8_t *udfName, int udfLen, uint8_t *fidName, int fidNameLen) { int index, newIndex = 0, needsCRC = 0; int extIndex = 0, newExtIndex = 0, hasExt = 0; unsigned short valueCRC; uint8_t curr; if (udfName[0] == '.' && (udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) { needsCRC = 1; newIndex = udfLen; memcpy(newName, udfName, udfLen); } else { for (index = 0; index < udfLen; index++) { curr = udfName[index]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (index + 1 < udfLen && (udfName[index + 1] == '/' || udfName[index + 1] == 0)) index++; } if (curr == EXT_MARK && (udfLen - index - 1) <= EXT_SIZE) { if (udfLen == index + 1) hasExt = 0; else { hasExt = 1; extIndex = index; newExtIndex = newIndex; } } if (newIndex < 256) newName[newIndex++] = curr; else needsCRC = 1; } } if (needsCRC) { uint8_t ext[EXT_SIZE]; int localExtIndex = 0; if (hasExt) { int maxFilenameLen; for (index = 0; index < EXT_SIZE && extIndex + index + 1 < udfLen; index++) { curr = udfName[extIndex + index + 1]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (extIndex + index + 2 < udfLen && (index + 1 < EXT_SIZE && (udfName[extIndex + index + 2] == '/' || udfName[extIndex + index + 2] == 0))) index++; } ext[localExtIndex++] = curr; } maxFilenameLen = 250 - localExtIndex; if (newIndex > maxFilenameLen) newIndex = maxFilenameLen; else newIndex = newExtIndex; } else if (newIndex > 250) newIndex = 250; newName[newIndex++] = CRC_MARK; valueCRC = crc_itu_t(0, fidName, fidNameLen); newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_hi(valueCRC); newName[newIndex++] = hex_asc_upper_lo(valueCRC); if (hasExt) { newName[newIndex++] = EXT_MARK; for (index = 0; index < localExtIndex; index++) newName[newIndex++] = ext[index]; } } return newIndex; } CWE ID: CWE-17 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 NTSTATUS fd_open_atomic(struct connection_struct *conn, files_struct *fsp, int flags, mode_t mode, bool *file_created) { NTSTATUS status = NT_STATUS_UNSUCCESSFUL; bool file_existed = VALID_STAT(fsp->fsp_name->st); *file_created = false; * We're not creating the file, just pass through. */ return fd_open(conn, fsp, flags, mode); } CWE ID: CWE-835 Target: 1 Example 2: Code: CameraSourceListener::~CameraSourceListener() { } 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: virtual InputMethodDescriptor current_input_method() const { if (current_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return current_input_method_; } 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 MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } CWE ID: CWE-834 Target: 1 Example 2: Code: static inline double clip01(double x) { return (x < 0) ? 0 : (x > 1) ? 1 : x; } 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: void BrowserView::ExecuteExtensionCommand( const extensions::Extension* extension, const extensions::Command& command) { extension_keybinding_registry_->ExecuteCommand(extension->id(), command.accelerator()); } 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 kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) { int start = 0; u32 prev_legacy, cur_legacy; mutex_lock(&kvm->arch.vpit->pit_state.lock); prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY; cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY; if (!prev_legacy && cur_legacy) start = 1; memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels, sizeof(kvm->arch.vpit->pit_state.channels)); kvm->arch.vpit->pit_state.flags = ps->flags; kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start); mutex_unlock(&kvm->arch.vpit->pit_state.lock); return 0; } CWE ID: Target: 1 Example 2: Code: static void unhash_openowner_locked(struct nfs4_openowner *oo) { struct nfs4_client *clp = oo->oo_owner.so_client; lockdep_assert_held(&clp->cl_lock); list_del_init(&oo->oo_owner.so_strhash); list_del_init(&oo->oo_perclient); } CWE ID: CWE-404 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: xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, int normalize) { xmlChar limit = 0; const xmlChar *in = NULL, *start, *end, *last; xmlChar *ret = NULL; GROW; in = (xmlChar *) CUR_PTR; if (*in != '"' && *in != '\'') { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return (NULL); } ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; /* * try to handle in this routine the most common case where no * allocation of a new string is required and where content is * pure ASCII. */ limit = *in++; end = ctxt->input->end; start = in; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; } if (normalize) { /* * Skip any leading spaces */ while ((in < end) && (*in != limit) && ((*in == 0x20) || (*in == 0x9) || (*in == 0xA) || (*in == 0xD))) { in++; start = in; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; } } while ((in < end) && (*in != limit) && (*in >= 0x20) && (*in <= 0x7f) && (*in != '&') && (*in != '<')) { if ((*in++ == 0x20) && (*in == 0x20)) break; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; } } last = in; /* * skip the trailing blanks */ while ((last[-1] == 0x20) && (last > start)) last--; while ((in < end) && (*in != limit) && ((*in == 0x20) || (*in == 0x9) || (*in == 0xA) || (*in == 0xD))) { in++; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; last = last + delta; } end = ctxt->input->end; } } if (*in != limit) goto need_complex; } else { while ((in < end) && (*in != limit) && (*in >= 0x20) && (*in <= 0x7f) && (*in != '&') && (*in != '<')) { in++; if (in >= end) { const xmlChar *oldbase = ctxt->input->base; GROW; if (oldbase != ctxt->input->base) { long delta = ctxt->input->base - oldbase; start = start + delta; in = in + delta; } end = ctxt->input->end; } } last = in; if (*in != limit) goto need_complex; } in++; if (len != NULL) { *len = last - start; ret = (xmlChar *) start; } else { if (alloc) *alloc = 1; ret = xmlStrndup(start, last - start); } CUR_PTR = in; if (alloc) *alloc = 0; return ret; need_complex: if (alloc) *alloc = 1; return xmlParseAttValueComplex(ctxt, len, normalize); } 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: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case SEQ_DISPLAY_EXT_ID: impeg2d_dec_seq_disp_ext(ps_dec); break; case SEQ_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_peek_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; } CWE ID: CWE-254 Target: 1 Example 2: Code: struct trace_entry *trace_find_next_entry(struct trace_iterator *iter, int *ent_cpu, u64 *ent_ts) { return __find_next_entry(iter, ent_cpu, NULL, ent_ts); } 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: static void vmxnet3_fill_stats(VMXNET3State *s) { int i; PCIDevice *d = PCI_DEVICE(s); if (!s->device_active) return; for (i = 0; i < s->txq_num; i++) { pci_dma_write(d, s->txq_descr[i].tx_stats_pa, &s->txq_descr[i].txq_stats, sizeof(s->txq_descr[i].txq_stats)); } for (i = 0; i < s->rxq_num; i++) { pci_dma_write(d, s->rxq_descr[i].rx_stats_pa, &s->rxq_descr[i].rxq_stats, sizeof(s->rxq_descr[i].rxq_stats)); } } CWE ID: CWE-200 Output:
0