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: bool DataReductionProxySettings::IsDataReductionProxyManaged() { return spdy_proxy_auth_enabled_.IsManaged(); } CWE ID: CWE-119 Target: 1 Example 2: Code: png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent) { png_debug1(1, "in %s storage function", "sRGB"); if (png_ptr == NULL || info_ptr == NULL) return; info_ptr->srgb_intent = (png_byte)intent; info_ptr->valid |= PNG_INFO_sRGB; } 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: gdImagePtr gdImageScaleTwoPass(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const unsigned int new_width, const unsigned int new_height) { gdImagePtr tmp_im; gdImagePtr dst; tmp_im = gdImageCreateTrueColor(new_width, src_height); if (tmp_im == NULL) { return NULL; } gdImageSetInterpolationMethod(tmp_im, src->interpolation_id); _gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height); dst = gdImageCreateTrueColor(new_width, new_height); if (dst == NULL) { gdFree(tmp_im); return NULL; } gdImageSetInterpolationMethod(dst, src->interpolation_id); _gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height); gdFree(tmp_im); return dst; } 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: void ProcessHeap::Init() { total_allocated_space_ = 0; total_allocated_object_size_ = 0; total_marked_object_size_ = 0; GCInfoTable::Init(); base::SamplingHeapProfiler::SetHooksInstallCallback([]() { HeapAllocHooks::SetAllocationHook(&BlinkGCAllocHook); HeapAllocHooks::SetFreeHook(&BlinkGCFreeHook); }); } CWE ID: CWE-362 Target: 1 Example 2: Code: static int set_file_offset(stb_vorbis *f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif } 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: ExtensionTtsController::~ExtensionTtsController() { FinishCurrentUtterance(); ClearUtteranceQueue(); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) { DTLS1_RECORD_DATA *rdata; pitem *item; /* Limit the size of the queue to prevent DOS attacks */ if (pqueue_size(queue->q) >= 100) return 0; rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA)); item = pitem_new(priority, rdata); if (rdata == NULL || item == NULL) { if (rdata != NULL) OPENSSL_free(rdata); if (item != NULL) pitem_free(item); SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); return(0); } rdata->packet = s->packet; rdata->packet_length = s->packet_length; memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER)); memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD)); item->data = rdata; #ifndef OPENSSL_NO_SCTP /* Store bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && (s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) { BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif s->packet = NULL; s->packet_length = 0; memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER)); memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD)); if (!ssl3_setup_buffers(s)) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); OPENSSL_free(rdata); pitem_free(item); return(0); } /* insert should not fail, since duplicates are dropped */ if (pqueue_insert(queue->q, item) == NULL) { SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); OPENSSL_free(rdata); pitem_free(item); return(0); } return(1); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool ExecuteScriptWithoutUserGestureAndExtractDouble( const ToRenderFrameHost& adapter, const std::string& script, double* result) { DCHECK(result); std::unique_ptr<base::Value> value; return ExecuteScriptHelper(adapter.render_frame_host(), script, false, &value) && value && value->GetAsDouble(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: static int ceph_x_encrypt_buflen(int ilen) { return sizeof(struct ceph_x_encrypt_header) + ilen + 16 + sizeof(u32); } 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: GpuChannelHost* BrowserGpuChannelHostFactory::EstablishGpuChannelSync( CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kLost) gpu_channel_ = NULL; else return gpu_channel_.get(); } GpuDataManagerImpl::GetInstance(); EstablishRequest request; GetIOLoopProxy()->PostTask( FROM_HERE, base::Bind( &BrowserGpuChannelHostFactory::EstablishGpuChannelOnIO, base::Unretained(this), &request, cause_for_gpu_launch)); request.event.Wait(); if (request.channel_handle.name.empty() || request.gpu_process_handle == base::kNullProcessHandle) return NULL; base::ProcessHandle browser_process_for_gpu; #if defined(OS_WIN) DuplicateHandle(base::GetCurrentProcessHandle(), base::GetCurrentProcessHandle(), request.gpu_process_handle, &browser_process_for_gpu, PROCESS_DUP_HANDLE, FALSE, 0); #else browser_process_for_gpu = base::GetCurrentProcessHandle(); #endif gpu_channel_ = new GpuChannelHost(this, gpu_host_id_, gpu_client_id_); gpu_channel_->set_gpu_info(request.gpu_info); content::GetContentClient()->SetGpuInfo(request.gpu_info); gpu_channel_->Connect(request.channel_handle, browser_process_for_gpu); return gpu_channel_.get(); } CWE ID: Target: 1 Example 2: Code: static int vcpu_stat_get(void *_offset, u64 *val) { unsigned offset = (long)_offset; struct kvm *kvm; struct kvm_vcpu *vcpu; int i; *val = 0; raw_spin_lock(&kvm_lock); list_for_each_entry(kvm, &vm_list, vm_list) kvm_for_each_vcpu(i, vcpu, kvm) *val += *(u32 *)((void *)vcpu + offset); raw_spin_unlock(&kvm_lock); 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: ConfirmInfoBar::ConfirmInfoBar(std::unique_ptr<ConfirmInfoBarDelegate> delegate) : InfoBarView(std::move(delegate)) { auto* delegate_ptr = GetDelegate(); label_ = CreateLabel(delegate_ptr->GetMessageText()); AddChildView(label_); const auto buttons = delegate_ptr->GetButtons(); if (buttons & ConfirmInfoBarDelegate::BUTTON_OK) { ok_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_OK); ok_button_->SetProminent(true); if (delegate_ptr->OKButtonTriggersUACPrompt()) { elevation_icon_setter_.reset(new ElevationIconSetter( ok_button_, base::BindOnce(&ConfirmInfoBar::Layout, base::Unretained(this)))); } } if (buttons & ConfirmInfoBarDelegate::BUTTON_CANCEL) { cancel_button_ = CreateButton(ConfirmInfoBarDelegate::BUTTON_CANCEL); if (buttons == ConfirmInfoBarDelegate::BUTTON_CANCEL) cancel_button_->SetProminent(true); } link_ = CreateLink(delegate_ptr->GetLinkText(), this); AddChildView(link_); } 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: long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); for(search = fs_searchpaths; search; search = search->next) { len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } } CWE ID: CWE-269 Target: 1 Example 2: Code: void reds_on_char_device_state_destroy(SpiceCharDeviceState *dev) { reds_char_device_remove_state(dev); } 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 _convert_job_mem(slurm_msg_t *msg) { prolog_launch_msg_t *req = (prolog_launch_msg_t *)msg->data; slurm_cred_arg_t arg; hostset_t j_hset = NULL; int rc, hi, host_index, job_cpus; int i, i_first_bit = 0, i_last_bit = 0; rc = slurm_cred_verify(conf->vctx, req->cred, &arg, msg->protocol_version); if (rc < 0) { error("%s: slurm_cred_verify failed: %m", __func__); req->nnodes = 1; /* best guess */ return; } req->nnodes = arg.job_nhosts; if (arg.job_mem_limit == 0) goto fini; if ((arg.job_mem_limit & MEM_PER_CPU) == 0) { req->job_mem_limit = arg.job_mem_limit; goto fini; } /* Assume 1 CPU on error */ req->job_mem_limit = arg.job_mem_limit & (~MEM_PER_CPU); if (!(j_hset = hostset_create(arg.job_hostlist))) { error("%s: Unable to parse credential hostlist: `%s'", __func__, arg.step_hostlist); goto fini; } host_index = hostset_find(j_hset, conf->node_name); hostset_destroy(j_hset); hi = host_index + 1; /* change from 0-origin to 1-origin */ for (i = 0; hi; i++) { if (hi > arg.sock_core_rep_count[i]) { i_first_bit += arg.sockets_per_node[i] * arg.cores_per_socket[i] * arg.sock_core_rep_count[i]; i_last_bit = i_first_bit + arg.sockets_per_node[i] * arg.cores_per_socket[i] * arg.sock_core_rep_count[i]; hi -= arg.sock_core_rep_count[i]; } else { i_first_bit += arg.sockets_per_node[i] * arg.cores_per_socket[i] * (hi - 1); i_last_bit = i_first_bit + arg.sockets_per_node[i] * arg.cores_per_socket[i]; break; } } /* Now count the allocated processors on this node */ job_cpus = 0; for (i = i_first_bit; i < i_last_bit; i++) { if (bit_test(arg.job_core_bitmap, i)) job_cpus++; } /* NOTE: alloc_lps is the count of allocated resources * (typically cores). Convert to CPU count as needed */ if (i_last_bit > i_first_bit) { i = conf->cpus / (i_last_bit - i_first_bit); if (i > 1) job_cpus *= i; } req->job_mem_limit *= job_cpus; fini: slurm_cred_free_args(&arg); } 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: DrawingBuffer::ScopedStateRestorer::~ScopedStateRestorer() { DCHECK_EQ(drawing_buffer_->state_restorer_, this); drawing_buffer_->state_restorer_ = previous_state_restorer_; Client* client = drawing_buffer_->client_; if (!client) return; if (clear_state_dirty_) { client->DrawingBufferClientRestoreScissorTest(); client->DrawingBufferClientRestoreMaskAndClearValues(); } if (pixel_pack_alignment_dirty_) client->DrawingBufferClientRestorePixelPackAlignment(); if (texture_binding_dirty_) client->DrawingBufferClientRestoreTexture2DBinding(); if (renderbuffer_binding_dirty_) client->DrawingBufferClientRestoreRenderbufferBinding(); if (framebuffer_binding_dirty_) client->DrawingBufferClientRestoreFramebufferBinding(); if (pixel_unpack_buffer_binding_dirty_) client->DrawingBufferClientRestorePixelUnpackBufferBinding(); } CWE ID: CWE-119 Target: 1 Example 2: Code: void mptsas_reply(MPTSASState *s, MPIDefaultReply *reply) { if (s->doorbell_state == DOORBELL_WRITE) { /* The reply is sent out in 16 bit chunks, while the size * in the reply is in 32 bit units. */ s->doorbell_state = DOORBELL_READ; s->doorbell_reply_idx = 0; s->doorbell_reply_size = reply->MsgLength * 2; memcpy(s->doorbell_reply, reply, s->doorbell_reply_size * 2); s->intr_status |= MPI_HIS_DOORBELL_INTERRUPT; mptsas_update_interrupt(s); } else { mptsas_post_reply(s, reply); } } 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: isoent_cmp_key(const struct archive_rb_node *n, const void *key) { const struct isoent *e = (const struct isoent *)n; return (strcmp(e->file->basename.s, (const char *)key)); } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ExpectCanDiscardFalseTrivial(const LifecycleUnit* lifecycle_unit, DiscardReason discard_reason) { DecisionDetails decision_details; EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details)); EXPECT_FALSE(decision_details.IsPositive()); EXPECT_TRUE(decision_details.reasons().empty()); } CWE ID: Target: 1 Example 2: Code: display_clean_read(struct display *dp) { if (dp->read_pp != NULL) png_destroy_read_struct(&dp->read_pp, &dp->read_ip, 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: status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); header->nFilledLen = 0; header->nOffset = 0; header->nFlags = 0; status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput); if (res != OK) { CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd)); return res; } { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.add(header); CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd))); } OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header); if (err != OMX_ErrorNone) { CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd)); Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(header); } return StatusFromOMXError(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: struct snd_seq_client_port *snd_seq_create_port(struct snd_seq_client *client, int port) { unsigned long flags; struct snd_seq_client_port *new_port, *p; int num = -1; /* sanity check */ if (snd_BUG_ON(!client)) return NULL; if (client->num_ports >= SNDRV_SEQ_MAX_PORTS) { pr_warn("ALSA: seq: too many ports for client %d\n", client->number); return NULL; } /* create a new port */ new_port = kzalloc(sizeof(*new_port), GFP_KERNEL); if (!new_port) return NULL; /* failure, out of memory */ /* init port data */ new_port->addr.client = client->number; new_port->addr.port = -1; new_port->owner = THIS_MODULE; sprintf(new_port->name, "port-%d", num); snd_use_lock_init(&new_port->use_lock); port_subs_info_init(&new_port->c_src); port_subs_info_init(&new_port->c_dest); num = port >= 0 ? port : 0; mutex_lock(&client->ports_mutex); write_lock_irqsave(&client->ports_lock, flags); list_for_each_entry(p, &client->ports_list_head, list) { if (p->addr.port > num) break; if (port < 0) /* auto-probe mode */ num = p->addr.port + 1; } /* insert the new port */ list_add_tail(&new_port->list, &p->list); client->num_ports++; new_port->addr.port = num; /* store the port number in the port */ write_unlock_irqrestore(&client->ports_lock, flags); mutex_unlock(&client->ports_mutex); sprintf(new_port->name, "port-%d", num); return new_port; } CWE ID: CWE-416 Target: 1 Example 2: Code: static void remove_user_radios(u32 portid) { struct mac80211_hwsim_data *entry, *tmp; spin_lock_bh(&hwsim_radio_lock); list_for_each_entry_safe(entry, tmp, &hwsim_radios, list) { if (entry->destroy_on_close && entry->portid == portid) { list_del(&entry->list); rhashtable_remove_fast(&hwsim_radios_rht, &entry->rht, hwsim_rht_params); INIT_WORK(&entry->destroy_work, destroy_radio); schedule_work(&entry->destroy_work); } } spin_unlock_bh(&hwsim_radio_lock); } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) { String8 name(packageName); String8 myName(mClientPackageName); if (op != AppOpsManager::OP_CAMERA) { ALOGW("Unexpected app ops notification received: %d", op); return; } int32_t res; res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA, mClientUid, mClientPackageName); ALOGV("checkOp returns: %d, %s ", res, res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" : res == AppOpsManager::MODE_IGNORED ? "IGNORED" : res == AppOpsManager::MODE_ERRORED ? "ERRORED" : "UNKNOWN"); if (res != AppOpsManager::MODE_ALLOWED) { ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId, myName.string()); mClientPid = getCallingPid(); notifyError(); disconnect(); } } 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 do_session_handshake (lua_State *L, int status, lua_KContext ctx) { int rc; struct ssh_userdata *sshu = NULL; assert(lua_gettop(L) == 4); sshu = (struct ssh_userdata *) nseU_checkudata(L, 3, SSH2_UDATA, "ssh2"); while ((rc = libssh2_session_handshake(sshu->session, sshu->sp[0])) == LIBSSH2_ERROR_EAGAIN) { luaL_getmetafield(L, 3, "filter"); lua_pushvalue(L, 3); assert(lua_status(L) == LUA_OK); lua_callk(L, 1, 0, 0, do_session_handshake); } if (rc) { libssh2_session_free(sshu->session); return luaL_error(L, "Unable to complete libssh2 handshake."); } lua_settop(L, 3); return 1; } CWE ID: CWE-415 Target: 1 Example 2: Code: static void pmcraid_cancel_all(struct pmcraid_cmd *cmd, u32 sense) { struct scsi_cmnd *scsi_cmd = cmd->scsi_cmd; struct pmcraid_ioarcb *ioarcb = &cmd->ioa_cb->ioarcb; struct pmcraid_resource_entry *res = scsi_cmd->device->hostdata; void (*cmd_done) (struct pmcraid_cmd *) = sense ? pmcraid_erp_done : pmcraid_request_sense; memset(ioarcb->cdb, 0, PMCRAID_MAX_CDB_LEN); ioarcb->request_flags0 = SYNC_OVERRIDE; ioarcb->request_type = REQ_TYPE_IOACMD; ioarcb->cdb[0] = PMCRAID_CANCEL_ALL_REQUESTS; if (RES_IS_GSCSI(res->cfg_entry)) ioarcb->cdb[1] = PMCRAID_SYNC_COMPLETE_AFTER_CANCEL; ioarcb->ioadl_bus_addr = 0; ioarcb->ioadl_length = 0; ioarcb->data_transfer_length = 0; ioarcb->ioarcb_bus_addr &= (~0x1FULL); /* writing to IOARRIN must be protected by host_lock, as mid-layer * schedule queuecommand while we are doing this */ pmcraid_send_cmd(cmd, cmd_done, PMCRAID_REQUEST_SENSE_TIMEOUT, pmcraid_timeout_handler); } 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 vrend_renderer_context_create_internal(uint32_t handle, uint32_t nlen, const char *debug_name) { struct vrend_decode_ctx *dctx; if (handle >= VREND_MAX_CTX) return; dctx = malloc(sizeof(struct vrend_decode_ctx)); if (!dctx) return; return; } 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 Frame* ReuseExistingWindow(LocalFrame& active_frame, LocalFrame& lookup_frame, const AtomicString& frame_name, NavigationPolicy policy, const KURL& destination_url) { if (!frame_name.IsEmpty() && !EqualIgnoringASCIICase(frame_name, "_blank") && policy == kNavigationPolicyIgnore) { if (Frame* frame = lookup_frame.FindFrameForNavigation( frame_name, active_frame, destination_url)) { if (!EqualIgnoringASCIICase(frame_name, "_self")) { if (Page* page = frame->GetPage()) { if (page == active_frame.GetPage()) page->GetFocusController().SetFocusedFrame(frame); else page->GetChromeClient().Focus(); } } return frame; } } return nullptr; } CWE ID: Target: 1 Example 2: Code: static int phar_zip_process_extra(php_stream *fp, phar_entry_info *entry, php_uint16 len) /* {{{ */ { union { phar_zip_extra_field_header header; phar_zip_unix3 unix3; } h; int read; do { if (sizeof(h.header) != php_stream_read(fp, (char *) &h.header, sizeof(h.header))) { return FAILURE; } if (h.header.tag[0] != 'n' || h.header.tag[1] != 'u') { /* skip to next header */ php_stream_seek(fp, PHAR_GET_16(h.header.size), SEEK_CUR); len -= PHAR_GET_16(h.header.size) + 4; continue; } /* unix3 header found */ read = php_stream_read(fp, (char *) &(h.unix3.crc32), sizeof(h.unix3) - sizeof(h.header)); len -= read + 4; if (sizeof(h.unix3) - sizeof(h.header) != read) { return FAILURE; } if (PHAR_GET_16(h.unix3.size) > sizeof(h.unix3) - 4) { /* skip symlink filename - we may add this support in later */ php_stream_seek(fp, PHAR_GET_16(h.unix3.size) - sizeof(h.unix3.size), SEEK_CUR); } /* set permissions */ entry->flags &= PHAR_ENT_COMPRESSION_MASK; if (entry->is_dir) { entry->flags |= PHAR_GET_16(h.unix3.perms) & PHAR_ENT_PERM_MASK; } else { entry->flags |= PHAR_GET_16(h.unix3.perms) & PHAR_ENT_PERM_MASK; } } while (len); return SUCCESS; } /* }}} */ 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 libxsmm_sparse_csr_reader( libxsmm_generated_code* io_generated_code, const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_INPUT ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC data-structure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * ((size_t)(*o_row_count) + 1)); memset(*o_column_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int) * (*o_row_count)); /* init column idx */ for ( l_i = 0; l_i <= *o_row_count; ++l_i ) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_DESC ); fclose( l_csr_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csr_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_READ_ELEMS ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_row_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSR_LEN ); return; } if ( l_row_idx_id != NULL ) { /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ free( l_row_idx_id ); } } 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 l2cap_connect_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_conn_rsp *rsp = (struct l2cap_conn_rsp *) data; u16 scid, dcid, result, status; struct sock *sk; u8 req[128]; scid = __le16_to_cpu(rsp->scid); dcid = __le16_to_cpu(rsp->dcid); result = __le16_to_cpu(rsp->result); status = __le16_to_cpu(rsp->status); BT_DBG("dcid 0x%4.4x scid 0x%4.4x result 0x%2.2x status 0x%2.2x", dcid, scid, result, status); if (scid) { sk = l2cap_get_chan_by_scid(&conn->chan_list, scid); if (!sk) return 0; } else { sk = l2cap_get_chan_by_ident(&conn->chan_list, cmd->ident); if (!sk) return 0; } switch (result) { case L2CAP_CR_SUCCESS: sk->sk_state = BT_CONFIG; l2cap_pi(sk)->ident = 0; l2cap_pi(sk)->dcid = dcid; l2cap_pi(sk)->conf_state |= L2CAP_CONF_REQ_SENT; l2cap_pi(sk)->conf_state &= ~L2CAP_CONF_CONNECT_PEND; l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(sk, req), req); break; case L2CAP_CR_PEND: l2cap_pi(sk)->conf_state |= L2CAP_CONF_CONNECT_PEND; break; default: l2cap_chan_del(sk, ECONNREFUSED); break; } bh_unlock_sock(sk); return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoDisableVertexAttribArray(GLuint index) { if (state_.vertex_attrib_manager->Enable(index, false)) { if (index != 0 || gl_version_info().BehavesLikeGLES()) { state_.vertex_attrib_manager->SetDriverVertexAttribEnabled(index, false); } } else { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, "glDisableVertexAttribArray", "index out of range"); } } 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: pgoff_t get_next_page_offset(struct dnode_of_data *dn, pgoff_t pgofs) { const long direct_index = ADDRS_PER_INODE(dn->inode); const long direct_blks = ADDRS_PER_BLOCK; const long indirect_blks = ADDRS_PER_BLOCK * NIDS_PER_BLOCK; unsigned int skipped_unit = ADDRS_PER_BLOCK; int cur_level = dn->cur_level; int max_level = dn->max_level; pgoff_t base = 0; if (!dn->max_level) return pgofs + 1; while (max_level-- > cur_level) skipped_unit *= NIDS_PER_BLOCK; switch (dn->max_level) { case 3: base += 2 * indirect_blks; case 2: base += 2 * direct_blks; case 1: base += direct_index; break; default: f2fs_bug_on(F2FS_I_SB(dn->inode), 1); } return ((pgofs - base) / skipped_unit + 1) * skipped_unit + base; } 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: sctp_disposition_t sctp_sf_do_asconf_ack(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *asconf_ack = arg; struct sctp_chunk *last_asconf = asoc->addip_last_asconf; struct sctp_chunk *abort; struct sctp_paramhdr *err_param = NULL; sctp_addiphdr_t *addip_hdr; __u32 sent_serial, rcvd_serial; if (!sctp_vtag_verify(asconf_ack, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* ADD-IP, Section 4.1.2: * This chunk MUST be sent in an authenticated way by using * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk * is received unauthenticated it MUST be silently discarded as * described in [I-D.ietf-tsvwg-sctp-auth]. */ if (!net->sctp.addip_noauth && !asconf_ack->auth) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); /* Make sure that the ADDIP chunk has a valid length. */ if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data; rcvd_serial = ntohl(addip_hdr->serial); /* Verify the ASCONF-ACK chunk before processing it. */ if (!sctp_verify_asconf(asoc, (sctp_paramhdr_t *)addip_hdr->params, (void *)asconf_ack->chunk_end, &err_param)) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, (void *)err_param, commands); if (last_asconf) { addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr; sent_serial = ntohl(addip_hdr->serial); } else { sent_serial = asoc->addip_serial - 1; } /* D0) If an endpoint receives an ASCONF-ACK that is greater than or * equal to the next serial number to be used but no ASCONF chunk is * outstanding the endpoint MUST ABORT the association. Note that a * sequence number is greater than if it is no more than 2^^31-1 * larger than the current sequence number (using serial arithmetic). */ if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) && !(asoc->addip_last_asconf)) { abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); if (!sctp_process_asconf_ack((struct sctp_association *)asoc, asconf_ack)) { /* Successfully processed ASCONF_ACK. We can * release the next asconf if we have one. */ sctp_add_cmd_sf(commands, SCTP_CMD_SEND_NEXT_ASCONF, SCTP_NULL()); return SCTP_DISPOSITION_CONSUME; } abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } return SCTP_DISPOSITION_DISCARD; } CWE ID: CWE-399 Target: 1 Example 2: Code: static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir, unsigned int flags, bool *need_lookup) { struct dentry *dentry; int error; *need_lookup = false; dentry = d_lookup(dir, name); if (dentry) { if (dentry->d_flags & DCACHE_OP_REVALIDATE) { error = d_revalidate(dentry, flags); if (unlikely(error <= 0)) { if (error < 0) { dput(dentry); return ERR_PTR(error); } else if (!d_invalidate(dentry)) { dput(dentry); dentry = NULL; } } } } if (!dentry) { dentry = d_alloc(dir, name); if (unlikely(!dentry)) return ERR_PTR(-ENOMEM); *need_lookup = true; } return dentry; } CWE ID: CWE-59 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 build_l4proto_dccp(const struct nf_conntrack *ct, struct nethdr *n) { ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); if (!nfct_attr_is_set(ct, ATTR_DCCP_STATE)) return; ct_build_u8(ct, ATTR_DCCP_STATE, n, NTA_DCCP_STATE); ct_build_u8(ct, ATTR_DCCP_ROLE, n, NTA_DCCP_ROLE); } 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: HistogramBase* Histogram::Factory::Build() { HistogramBase* histogram = StatisticsRecorder::FindHistogram(name_); if (!histogram) { const BucketRanges* created_ranges = CreateRanges(); const BucketRanges* registered_ranges = StatisticsRecorder::RegisterOrDeleteDuplicateRanges(created_ranges); if (bucket_count_ == 0) { bucket_count_ = static_cast<uint32_t>(registered_ranges->bucket_count()); minimum_ = registered_ranges->range(1); maximum_ = registered_ranges->range(bucket_count_ - 1); } PersistentHistogramAllocator::Reference histogram_ref = 0; std::unique_ptr<HistogramBase> tentative_histogram; PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get(); if (allocator) { tentative_histogram = allocator->AllocateHistogram( histogram_type_, name_, minimum_, maximum_, registered_ranges, flags_, &histogram_ref); } if (!tentative_histogram) { DCHECK(!histogram_ref); // Should never have been set. DCHECK(!allocator); // Shouldn't have failed. flags_ &= ~HistogramBase::kIsPersistent; tentative_histogram = HeapAlloc(registered_ranges); tentative_histogram->SetFlags(flags_); } FillHistogram(tentative_histogram.get()); const void* tentative_histogram_ptr = tentative_histogram.get(); histogram = StatisticsRecorder::RegisterOrDeleteDuplicate( tentative_histogram.release()); if (histogram_ref) { allocator->FinalizeHistogram(histogram_ref, histogram == tentative_histogram_ptr); } ReportHistogramActivity(*histogram, HISTOGRAM_CREATED); } else { ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP); } DCHECK_EQ(histogram_type_, histogram->GetHistogramType()) << name_; if (bucket_count_ != 0 && !histogram->HasConstructionArguments(minimum_, maximum_, bucket_count_)) { DLOG(ERROR) << "Histogram " << name_ << " has bad construction arguments"; return nullptr; } return histogram; } CWE ID: CWE-476 Target: 1 Example 2: Code: static ssize_t proc_fault_inject_read(struct file * file, char __user * buf, size_t count, loff_t *ppos) { struct task_struct *task = get_proc_task(file_inode(file)); char buffer[PROC_NUMBUF]; size_t len; int make_it_fail; if (!task) return -ESRCH; make_it_fail = task->make_it_fail; put_task_struct(task); len = snprintf(buffer, sizeof(buffer), "%i\n", make_it_fail); return simple_read_from_buffer(buf, count, ppos, buffer, len); } 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: static int nfs4_xdr_dec_locku(struct rpc_rqst *rqstp, __be32 *p, struct nfs_locku_res *res) { struct xdr_stream xdr; struct compound_hdr hdr; int status; xdr_init_decode(&xdr, &rqstp->rq_rcv_buf, p); status = decode_compound_hdr(&xdr, &hdr); if (status) goto out; status = decode_putfh(&xdr); if (status) goto out; status = decode_locku(&xdr, res); out: return status; } 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: virtual void TearDown() { delete[] src_; delete[] ref_; libvpx_test::ClearSystemState(); } CWE ID: CWE-119 Target: 1 Example 2: Code: MagickExport MagickBooleanType SetImageChannels(Image *image, const size_t channels) { image->channels=channels; return(MagickTrue); } CWE ID: CWE-617 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 update_from_utee_param(struct tee_ta_param *p, const struct utee_params *up) { size_t n; for (n = 0; n < TEE_NUM_PARAMS; n++) { switch (TEE_PARAM_TYPE_GET(p->types, n)) { case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: /* See comment for struct utee_params in utee_types.h */ p->u[n].mem.size = up->vals[n * 2 + 1]; break; case TEE_PARAM_TYPE_VALUE_OUTPUT: case TEE_PARAM_TYPE_VALUE_INOUT: /* See comment for struct utee_params in utee_types.h */ p->u[n].val.a = up->vals[n * 2]; p->u[n].val.b = up->vals[n * 2 + 1]; break; default: break; } } } 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: void SetUp() { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); SyncCredentials credentials; credentials.email = "[email protected]"; credentials.sync_token = "sometoken"; sync_notifier_mock_ = new StrictMock<SyncNotifierMock>(); EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)). WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver)); EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_)); EXPECT_CALL(*sync_notifier_mock_, SetState("")); EXPECT_CALL(*sync_notifier_mock_, UpdateCredentials(credentials.email, credentials.sync_token)); EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)). Times(AtLeast(1)). WillRepeatedly( Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes)); EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)). WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver)); sync_manager_.AddObserver(&observer_); EXPECT_CALL(observer_, OnInitializationComplete(_, _)). WillOnce(SaveArg<0>(&js_backend_)); EXPECT_FALSE(sync_notifier_observer_); EXPECT_FALSE(js_backend_.IsInitialized()); sync_manager_.Init(temp_dir_.path(), WeakHandle<JsEventHandler>(), "bogus", 0, false, base::MessageLoopProxy::current(), new TestHttpPostProviderFactory(), this, &extensions_activity_monitor_, this, "bogus", credentials, false /* enable_sync_tabs_for_other_clients */, sync_notifier_mock_, "", sync_api::SyncManager::TEST_IN_MEMORY, &encryptor_, &handler_, NULL); EXPECT_TRUE(sync_notifier_observer_); EXPECT_TRUE(js_backend_.IsInitialized()); EXPECT_EQ(1, update_enabled_types_call_count_); ModelSafeRoutingInfo routes; GetModelSafeRoutingInfo(&routes); for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end(); ++i) { type_roots_[i->first] = MakeServerNodeForType( sync_manager_.GetUserShare(), i->first); } PumpLoop(); } CWE ID: CWE-362 Target: 1 Example 2: Code: static int dcbnl_setpfccfg(struct net_device *netdev, struct nlmsghdr *nlh, u32 seq, struct nlattr **tb, struct sk_buff *skb) { struct nlattr *data[DCB_PFC_UP_ATTR_MAX + 1]; int i; int ret; u8 value; if (!tb[DCB_ATTR_PFC_CFG]) return -EINVAL; if (!netdev->dcbnl_ops->setpfccfg) return -EOPNOTSUPP; ret = nla_parse_nested(data, DCB_PFC_UP_ATTR_MAX, tb[DCB_ATTR_PFC_CFG], dcbnl_pfc_up_nest); if (ret) return ret; for (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) { if (data[i] == NULL) continue; value = nla_get_u8(data[i]); netdev->dcbnl_ops->setpfccfg(netdev, data[i]->nla_type - DCB_PFC_UP_ATTR_0, value); } return nla_put_u8(skb, DCB_ATTR_PFC_CFG, 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: extra_last_record(struct isoent *isoent) { if (isoent->extr_rec_list.first == NULL) return (NULL); return ((struct extr_rec *)(void *) ((char *)(isoent->extr_rec_list.last) - offsetof(struct extr_rec, next))); } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ContextImpl::CreateFrame( fidl::InterfaceHandle<chromium::web::FrameObserver> observer, fidl::InterfaceRequest<chromium::web::Frame> frame_request) { auto web_contents = content::WebContents::Create( content::WebContents::CreateParams(browser_context_, nullptr)); frame_bindings_.AddBinding( std::make_unique<FrameImpl>(std::move(web_contents), observer.Bind()), std::move(frame_request)); } CWE ID: CWE-264 Target: 1 Example 2: Code: CStarter::Hold( void ) { bool jobRunning = false; UserProc *job; dprintf( D_ALWAYS, "Hold all jobs\n" ); if ( this->deferral_tid != -1 ) { this->removeDeferredJobs(); } m_job_list.Rewind(); while( (job = m_job_list.Next()) != NULL ) { if( job->Hold() ) { m_job_list.DeleteCurrent(); delete job; } else { jobRunning = true; } } ShuttingDown = TRUE; return ( !jobRunning ); } CWE ID: CWE-134 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void snd_msndmidi_input_read(void *mpuv) { unsigned long flags; struct snd_msndmidi *mpu = mpuv; void *pwMIDQData = mpu->dev->mappedbase + MIDQ_DATA_BUFF; spin_lock_irqsave(&mpu->input_lock, flags); while (readw(mpu->dev->MIDQ + JQS_wTail) != readw(mpu->dev->MIDQ + JQS_wHead)) { u16 wTmp, val; val = readw(pwMIDQData + 2 * readw(mpu->dev->MIDQ + JQS_wHead)); if (test_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER, &mpu->mode)) snd_rawmidi_receive(mpu->substream_input, (unsigned char *)&val, 1); wTmp = readw(mpu->dev->MIDQ + JQS_wHead) + 1; if (wTmp > readw(mpu->dev->MIDQ + JQS_wSize)) writew(0, mpu->dev->MIDQ + JQS_wHead); else writew(wTmp, mpu->dev->MIDQ + JQS_wHead); } spin_unlock_irqrestore(&mpu->input_lock, flags); } 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: String TextCodecUTF8::Decode(const char* bytes, wtf_size_t length, FlushBehavior flush, bool stop_on_error, bool& saw_error) { const bool do_flush = flush != FlushBehavior::kDoNotFlush; StringBuffer<LChar> buffer(partial_sequence_size_ + length); const uint8_t* source = reinterpret_cast<const uint8_t*>(bytes); const uint8_t* end = source + length; const uint8_t* aligned_end = AlignToMachineWord(end); LChar* destination = buffer.Characters(); do { if (partial_sequence_size_) { LChar* destination_for_handle_partial_sequence = destination; const uint8_t* source_for_handle_partial_sequence = source; if (HandlePartialSequence(destination_for_handle_partial_sequence, source_for_handle_partial_sequence, end, do_flush, stop_on_error, saw_error)) { source = source_for_handle_partial_sequence; goto upConvertTo16Bit; } destination = destination_for_handle_partial_sequence; source = source_for_handle_partial_sequence; if (partial_sequence_size_) break; } while (source < end) { if (IsASCII(*source)) { if (IsAlignedToMachineWord(source)) { while (source < aligned_end) { MachineWord chunk = *reinterpret_cast_ptr<const MachineWord*>(source); if (!IsAllASCII<LChar>(chunk)) break; CopyASCIIMachineWord(destination, source); source += sizeof(MachineWord); destination += sizeof(MachineWord); } if (source == end) break; if (!IsASCII(*source)) continue; } *destination++ = *source++; continue; } int count = NonASCIISequenceLength(*source); int character; if (count == 0) { character = kNonCharacter1; } else { if (count > end - source) { SECURITY_DCHECK(end - source < static_cast<ptrdiff_t>(sizeof(partial_sequence_))); DCHECK(!partial_sequence_size_); partial_sequence_size_ = static_cast<wtf_size_t>(end - source); memcpy(partial_sequence_, source, partial_sequence_size_); source = end; break; } character = DecodeNonASCIISequence(source, count); } if (IsNonCharacter(character)) { saw_error = true; if (stop_on_error) break; goto upConvertTo16Bit; } if (character > 0xff) goto upConvertTo16Bit; source += count; *destination++ = static_cast<LChar>(character); } } while (do_flush && partial_sequence_size_); buffer.Shrink(static_cast<wtf_size_t>(destination - buffer.Characters())); return String::Adopt(buffer); upConvertTo16Bit: StringBuffer<UChar> buffer16(partial_sequence_size_ + length); UChar* destination16 = buffer16.Characters(); for (LChar* converted8 = buffer.Characters(); converted8 < destination;) *destination16++ = *converted8++; do { if (partial_sequence_size_) { UChar* destination_for_handle_partial_sequence = destination16; const uint8_t* source_for_handle_partial_sequence = source; HandlePartialSequence(destination_for_handle_partial_sequence, source_for_handle_partial_sequence, end, do_flush, stop_on_error, saw_error); destination16 = destination_for_handle_partial_sequence; source = source_for_handle_partial_sequence; if (partial_sequence_size_) break; } while (source < end) { if (IsASCII(*source)) { if (IsAlignedToMachineWord(source)) { while (source < aligned_end) { MachineWord chunk = *reinterpret_cast_ptr<const MachineWord*>(source); if (!IsAllASCII<LChar>(chunk)) break; CopyASCIIMachineWord(destination16, source); source += sizeof(MachineWord); destination16 += sizeof(MachineWord); } if (source == end) break; if (!IsASCII(*source)) continue; } *destination16++ = *source++; continue; } int count = NonASCIISequenceLength(*source); int character; if (count == 0) { character = kNonCharacter1; } else { if (count > end - source) { SECURITY_DCHECK(end - source < static_cast<ptrdiff_t>(sizeof(partial_sequence_))); DCHECK(!partial_sequence_size_); partial_sequence_size_ = static_cast<wtf_size_t>(end - source); memcpy(partial_sequence_, source, partial_sequence_size_); source = end; break; } character = DecodeNonASCIISequence(source, count); } if (IsNonCharacter(character)) { saw_error = true; if (stop_on_error) break; *destination16++ = kReplacementCharacter; source -= character; continue; } source += count; destination16 = AppendCharacter(destination16, character); } } while (do_flush && partial_sequence_size_); buffer16.Shrink( static_cast<wtf_size_t>(destination16 - buffer16.Characters())); return String::Adopt(buffer16); } CWE ID: CWE-190 Target: 1 Example 2: Code: explicit MigrationTest(TestType test_type) : SyncTest(test_type) {} 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: static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len, RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value, const RBinDwarfCompUnitHdr *hdr, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf; const ut8 *buf_end = obuf + obuf_len; size_t j; if (!spec || !value || !hdr || !obuf || obuf_len < 1) { return NULL; } value->form = spec->attr_form; value->name = spec->attr_name; value->encoding.block.data = NULL; value->encoding.str_struct.string = NULL; value->encoding.str_struct.offset = 0; switch (spec->attr_form) { case DW_FORM_addr: switch (hdr->pointer_size) { case 1: value->encoding.address = READ (buf, ut8); break; case 2: value->encoding.address = READ (buf, ut16); break; case 4: value->encoding.address = READ (buf, ut32); break; case 8: value->encoding.address = READ (buf, ut64); break; default: eprintf ("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size); return NULL; } break; case DW_FORM_block2: value->encoding.block.length = READ (buf, ut16); if (value->encoding.block.length > 0) { value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length); for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_block4: value->encoding.block.length = READ (buf, ut32); if (value->encoding.block.length > 0) { ut8 *data = calloc (sizeof (ut8), value->encoding.block.length); if (data) { for (j = 0; j < value->encoding.block.length; j++) { data[j] = READ (buf, ut8); } } value->encoding.block.data = data; } break; #if 0 case DW_FORM_data2: value->encoding.data = READ (buf, ut16); break; case DW_FORM_data4: value->encoding.data = READ (buf, ut32); break; case DW_FORM_data8: value->encoding.data = READ (buf, ut64); break; #endif case DW_FORM_string: value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL; buf += (strlen ((const char*)buf) + 1); break; case DW_FORM_block: buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length); if (!buf) { return NULL; } value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length); if (value->encoding.block.data) { for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_block1: value->encoding.block.length = READ (buf, ut8); value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1); if (value->encoding.block.data) { for (j = 0; j < value->encoding.block.length; j++) { value->encoding.block.data[j] = READ (buf, ut8); } } break; case DW_FORM_flag: value->encoding.flag = READ (buf, ut8); break; case DW_FORM_sdata: buf = r_leb128 (buf, &value->encoding.sdata); break; case DW_FORM_strp: value->encoding.str_struct.offset = READ (buf, ut32); if (debug_str && value->encoding.str_struct.offset < debug_str_len) { value->encoding.str_struct.string = strdup ( (const char *)(debug_str + value->encoding.str_struct.offset)); } else { value->encoding.str_struct.string = NULL; } break; case DW_FORM_udata: { ut64 ndata = 0; const ut8 *data = (const ut8*)&ndata; buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata); memcpy (&value->encoding.data, data, sizeof (value->encoding.data)); value->encoding.str_struct.string = NULL; } break; case DW_FORM_ref_addr: value->encoding.reference = READ (buf, ut64); // addr size of machine break; case DW_FORM_ref1: value->encoding.reference = READ (buf, ut8); break; case DW_FORM_ref2: value->encoding.reference = READ (buf, ut16); break; case DW_FORM_ref4: value->encoding.reference = READ (buf, ut32); break; case DW_FORM_ref8: value->encoding.reference = READ (buf, ut64); break; case DW_FORM_data1: value->encoding.data = READ (buf, ut8); break; default: eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form); value->encoding.data = 0; return NULL; } return buf; } 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: mkvparser::IMkvReader::~IMkvReader() { //// Disable MSVC warnings that suggest making code non-portable. } CWE ID: CWE-119 Target: 1 Example 2: Code: const Vector<double>& BaseRenderingContext2D::getLineDash() const { return GetState().LineDash(); } 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: opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; } 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: static bool check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; } CWE ID: CWE-476 Target: 1 Example 2: Code: ScopedMessagePipeHandle Core::ExtractMessagePipeFromInvitation( const std::string& name) { RequestContext request_context; ports::PortRef port0, port1; GetNodeController()->node()->CreatePortPair(&port0, &port1); MojoHandle handle = AddDispatcher(new MessagePipeDispatcher( GetNodeController(), port0, kUnknownPipeIdForDebug, 1)); GetNodeController()->MergePortIntoParent(name, port1); return ScopedMessagePipeHandle(MessagePipeHandle(handle)); } 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: PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp, struct mount *source_mnt, struct hlist_head *tree_list) { struct mount *m, *n; int ret = 0; /* * we don't want to bother passing tons of arguments to * propagate_one(); everything is serialized by namespace_sem, * so globals will do just fine. */ user_ns = current->nsproxy->mnt_ns->user_ns; last_dest = dest_mnt; last_source = source_mnt; mp = dest_mp; list = tree_list; dest_master = dest_mnt->mnt_master; /* all peers of dest_mnt, except dest_mnt itself */ for (n = next_peer(dest_mnt); n != dest_mnt; n = next_peer(n)) { ret = propagate_one(n); if (ret) goto out; } /* all slave groups */ for (m = next_group(dest_mnt, dest_mnt); m; m = next_group(m, dest_mnt)) { /* everything in that slave group */ n = m; do { ret = propagate_one(n); if (ret) goto out; n = next_peer(n); } while (n != m); } out: read_seqlock_excl(&mount_lock); hlist_for_each_entry(n, tree_list, mnt_hash) { m = n->mnt_parent; if (m->mnt_master != dest_mnt->mnt_master) CLEAR_MNT_MARK(m->mnt_master); } read_sequnlock_excl(&mount_lock); return ret; } CWE ID: Target: 1 Example 2: Code: static bool NeedsEffect(const LayoutObject& object) { const ComputedStyle& style = object.StyleRef(); const bool is_css_isolated_group = object.IsBoxModelObject() && style.IsStackingContext(); if (!is_css_isolated_group && !object.IsSVG()) return false; if (object.IsSVG()) { if (object.IsSVGRoot() && is_css_isolated_group && object.HasNonIsolatedBlendingDescendants()) return true; if (SVGLayoutSupport::IsIsolationRequired(&object)) return true; if (SVGResources* resources = SVGResourcesCache::CachedResourcesForLayoutObject(object)) { if (resources->Masker()) { return true; } } } else if (object.IsBoxModelObject()) { if (PaintLayer* layer = ToLayoutBoxModelObject(object).Layer()) { if (layer->HasNonIsolatedDescendantWithBlendMode()) return true; } } SkBlendMode blend_mode = object.IsBlendingAllowed() ? WebCoreCompositeToSkiaComposite( kCompositeSourceOver, style.GetBlendMode()) : SkBlendMode::kSrcOver; if (blend_mode != SkBlendMode::kSrcOver) return true; float opacity = style.Opacity(); if (opacity != 1.0f) return true; if (CompositingReasonFinder::RequiresCompositingForOpacityAnimation(style)) return true; if (object.StyleRef().HasMask()) return true; if (object.HasLayer() && ToLayoutBoxModelObject(object).Layer()->GetCompositedLayerMapping() && ToLayoutBoxModelObject(object) .Layer() ->GetCompositedLayerMapping() ->MaskLayer()) { return true; } if (object.StyleRef().ClipPath() && object.FirstFragment().ClipPathBoundingBox() && !object.FirstFragment().ClipPathPath()) { return true; } return 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: static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } 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 Image *ReadUYVYImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; ssize_t y; unsigned char u, v, y1, y2; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if ((image->columns % 2) != 0) image->columns++; (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); image->depth=8; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Accumulate UYVY, then unpack into two pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) (image->columns >> 1); x++) { u=(unsigned char) ReadBlobByte(image); y1=(unsigned char) ReadBlobByte(image); v=(unsigned char) ReadBlobByte(image); y2=(unsigned char) ReadBlobByte(image); SetPixelRed(q,ScaleCharToQuantum(y1)); SetPixelGreen(q,ScaleCharToQuantum(u)); SetPixelBlue(q,ScaleCharToQuantum(v)); q++; SetPixelRed(q,ScaleCharToQuantum(y2)); SetPixelGreen(q,ScaleCharToQuantum(u)); SetPixelBlue(q,ScaleCharToQuantum(v)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetImageColorspace(image,YCbCrColorspace); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard) { return smartInsertDeleteEnabled() && pasteboard->canSmartReplace(); } 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 nfs_lseek(struct device_d *dev, FILE *file, loff_t pos) { struct file_priv *priv = file->priv; kfifo_reset(priv->fifo); return 0; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_get_mmx_rowbytes_threshold (png_structp png_ptr) { /* Obsolete, to be removed from libpng-1.4.0 */ return (png_ptr? 0L: 0L); } CWE ID: CWE-119 Target: 1 Example 2: Code: input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt) { Authctxt *authctxt = ctxt; Key *key = NULL; Identity *id = NULL; Buffer b; int pktype, sent = 0; u_int alen, blen; char *pkalg, *fp; u_char *pkblob; if (authctxt == NULL) fatal("input_userauth_pk_ok: no authentication context"); if (datafellows & SSH_BUG_PKOK) { /* this is similar to SSH_BUG_PKAUTH */ debug2("input_userauth_pk_ok: SSH_BUG_PKOK"); pkblob = packet_get_string(&blen); buffer_init(&b); buffer_append(&b, pkblob, blen); pkalg = buffer_get_string(&b, &alen); buffer_free(&b); } else { pkalg = packet_get_string(&alen); pkblob = packet_get_string(&blen); } packet_check_eom(); debug("Server accepts key: pkalg %s blen %u", pkalg, blen); if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) { debug("unknown pkalg %s", pkalg); goto done; } if ((key = key_from_blob(pkblob, blen)) == NULL) { debug("no key from blob. pkalg %s", pkalg); goto done; } if (key->type != pktype) { error("input_userauth_pk_ok: type mismatch " "for decoded key (received %d, expected %d)", key->type, pktype); goto done; } if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) goto done; debug2("input_userauth_pk_ok: fp %s", fp); free(fp); /* * search keys in the reverse order, because last candidate has been * moved to the end of the queue. this also avoids confusion by * duplicate keys */ TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) { if (key_equal(key, id->key)) { sent = sign_and_send_pubkey(authctxt, id); break; } } done: if (key != NULL) key_free(key); free(pkalg); free(pkblob); /* try another method if we did not send a packet */ if (sent == 0) userauth(authctxt, NULL); return 0; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BlockEntry::Kind Track::EOSBlock::GetKind() const { return kBlockEOS; } 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: image_transform_png_set_rgb_to_gray_ini(PNG_CONST image_transform *this, transform_display *that) { png_modifier *pm = that->pm; PNG_CONST color_encoding *e = pm->current_encoding; UNUSED(this) /* Since we check the encoding this flag must be set: */ pm->test_uses_encoding = 1; /* If 'e' is not NULL chromaticity information is present and either a cHRM * or an sRGB chunk will be inserted. */ if (e != 0) { /* Coefficients come from the encoding, but may need to be normalized to a * white point Y of 1.0 */ PNG_CONST double whiteY = e->red.Y + e->green.Y + e->blue.Y; data.red_coefficient = e->red.Y; data.green_coefficient = e->green.Y; data.blue_coefficient = e->blue.Y; if (whiteY != 1) { data.red_coefficient /= whiteY; data.green_coefficient /= whiteY; data.blue_coefficient /= whiteY; } } else { /* The default (built in) coeffcients, as above: */ data.red_coefficient = 6968 / 32768.; data.green_coefficient = 23434 / 32768.; data.blue_coefficient = 2366 / 32768.; } data.gamma = pm->current_gamma; /* If not set then the calculations assume linear encoding (implicitly): */ if (data.gamma == 0) data.gamma = 1; /* The arguments to png_set_rgb_to_gray can override the coefficients implied * by the color space encoding. If doing exhaustive checks do the override * in each case, otherwise do it randomly. */ if (pm->test_exhaustive) { /* First time in coefficients_overridden is 0, the following sets it to 1, * so repeat if it is set. If a test fails this may mean we subsequently * skip a non-override test, ignore that. */ data.coefficients_overridden = !data.coefficients_overridden; pm->repeat = data.coefficients_overridden != 0; } else data.coefficients_overridden = random_choice(); if (data.coefficients_overridden) { /* These values override the color encoding defaults, simply use random * numbers. */ png_uint_32 ru; double total; RANDOMIZE(ru); data.green_coefficient = total = (ru & 0xffff) / 65535.; ru >>= 16; data.red_coefficient = (1 - total) * (ru & 0xffff) / 65535.; total += data.red_coefficient; data.blue_coefficient = 1 - total; # ifdef PNG_FLOATING_POINT_SUPPORTED data.red_to_set = data.red_coefficient; data.green_to_set = data.green_coefficient; # else data.red_to_set = fix(data.red_coefficient); data.green_to_set = fix(data.green_coefficient); # endif /* The following just changes the error messages: */ pm->encoding_ignored = 1; } else { data.red_to_set = -1; data.green_to_set = -1; } /* Adjust the error limit in the png_modifier because of the larger errors * produced in the digitization during the gamma handling. */ if (data.gamma != 1) /* Use gamma tables */ { if (that->this.bit_depth == 16 || pm->assume_16_bit_calculations) { /* The computations have the form: * * r * rc + g * gc + b * bc * * Each component of which is +/-1/65535 from the gamma_to_1 table * lookup, resulting in a base error of +/-6. The gamma_from_1 * conversion adds another +/-2 in the 16-bit case and * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case. */ that->pm->limit += pow( # if PNG_MAX_GAMMA_8 < 14 (that->this.bit_depth == 16 ? 8. : 6. + (1<<(15-PNG_MAX_GAMMA_8))) # else 8. # endif /65535, data.gamma); } else { /* Rounding to 8 bits in the linear space causes massive errors which * will trigger the error check in transform_range_check. Fix that * here by taking the gamma encoding into account. * * When DIGITIZE is set because a pre-1.7 version of libpng is being * tested allow a bigger slack. * * NOTE: this magic number was determined by experiment to be 1.1 (when * using fixed point arithmetic). There's no great merit to the value * below, however it only affects the limit used for checking for * internal calculation errors, not the actual limit imposed by * pngvalid on the output errors. */ that->pm->limit += pow( # if DIGITIZE 1.1 # else 1. # endif /255, data.gamma); } } else { /* With no gamma correction a large error comes from the truncation of the * calculation in the 8 bit case, allow for that here. */ if (that->this.bit_depth != 16 && !pm->assume_16_bit_calculations) that->pm->limit += 4E-3; } } CWE ID: Target: 1 Example 2: Code: status_t getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]) { switch (numChannels) { case 1: map[0] = OMX_AUDIO_ChannelCF; break; case 2: map[0] = OMX_AUDIO_ChannelLF; map[1] = OMX_AUDIO_ChannelRF; break; case 3: map[0] = OMX_AUDIO_ChannelLF; map[1] = OMX_AUDIO_ChannelRF; map[2] = OMX_AUDIO_ChannelCF; break; case 4: map[0] = OMX_AUDIO_ChannelLF; map[1] = OMX_AUDIO_ChannelRF; map[2] = OMX_AUDIO_ChannelLR; map[3] = OMX_AUDIO_ChannelRR; break; case 5: map[0] = OMX_AUDIO_ChannelLF; map[1] = OMX_AUDIO_ChannelRF; map[2] = OMX_AUDIO_ChannelCF; map[3] = OMX_AUDIO_ChannelLR; map[4] = OMX_AUDIO_ChannelRR; break; case 6: map[0] = OMX_AUDIO_ChannelLF; map[1] = OMX_AUDIO_ChannelRF; map[2] = OMX_AUDIO_ChannelCF; map[3] = OMX_AUDIO_ChannelLFE; map[4] = OMX_AUDIO_ChannelLR; map[5] = OMX_AUDIO_ChannelRR; break; case 7: map[0] = OMX_AUDIO_ChannelLF; map[1] = OMX_AUDIO_ChannelRF; map[2] = OMX_AUDIO_ChannelCF; map[3] = OMX_AUDIO_ChannelLFE; map[4] = OMX_AUDIO_ChannelLR; map[5] = OMX_AUDIO_ChannelRR; map[6] = OMX_AUDIO_ChannelCS; break; case 8: map[0] = OMX_AUDIO_ChannelLF; map[1] = OMX_AUDIO_ChannelRF; map[2] = OMX_AUDIO_ChannelCF; map[3] = OMX_AUDIO_ChannelLFE; map[4] = OMX_AUDIO_ChannelLR; map[5] = OMX_AUDIO_ChannelRR; map[6] = OMX_AUDIO_ChannelLS; map[7] = OMX_AUDIO_ChannelRS; break; default: return -EINVAL; } return OK; } 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: static int vp7_decode_block_coeffs_internal(VP56RangeCoder *r, int16_t block[16], uint8_t probs[16][3][NUM_DCT_TOKENS - 1], int i, uint8_t *token_prob, int16_t qmul[2], const uint8_t scan[16]) { return decode_block_coeffs_internal(r, block, probs, i, token_prob, qmul, scan, IS_VP7); } 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 read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } CWE ID: CWE-125 Target: 1 Example 2: Code: void OxideQQuickWebView::dropEvent(QDropEvent* event) { Q_D(OxideQQuickWebView); QQuickItem::dropEvent(event); d->contents_view_->handleDropEvent(event); } 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: perform_gamma_composition_tests(png_modifier *pm, int do_background, int expand_16) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Skip the non-alpha cases - there is no setting of a transparency colour at * present. */ while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0) { unsigned int i, j; /* Don't skip the i==j case here - it's relevant. */ for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j) { gamma_composition_test(pm, colour_type, bit_depth, palette_number, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], pm->use_input_precision, do_background, expand_16); if (fail(pm)) return; } } } 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: SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() { return syslogs_lib_.GetDefaultImpl(use_stub_impl_); } CWE ID: CWE-189 Target: 1 Example 2: Code: grabPartialWakeLock() { if (s_callbacks.version >= 13) { int ret; ret = pthread_mutex_lock(&s_wakeLockCountMutex); assert(ret == 0); acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME); UserCallbackInfo *p_info = internalRequestTimedCallback(wakeTimeoutCallback, NULL, &TIMEVAL_WAKE_TIMEOUT); if (p_info == NULL) { release_wake_lock(ANDROID_WAKE_LOCK_NAME); } else { s_wakelock_count++; if (s_last_wake_timeout_info != NULL) { s_last_wake_timeout_info->userParam = (void *)1; } s_last_wake_timeout_info = p_info; } ret = pthread_mutex_unlock(&s_wakeLockCountMutex); assert(ret == 0); } else { acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME); } } 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: int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout) { struct urb *urb; struct usb_host_endpoint *ep; ep = usb_pipe_endpoint(usb_dev, pipe); if (!ep || len < 0) return -EINVAL; urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) return -ENOMEM; if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT) { pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30); usb_fill_int_urb(urb, usb_dev, pipe, data, len, usb_api_blocking_completion, NULL, ep->desc.bInterval); } else usb_fill_bulk_urb(urb, usb_dev, pipe, data, len, usb_api_blocking_completion, NULL); return usb_start_wait_urb(urb, timeout, actual_length); } 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 __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc) { xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc; __GLXconfig *config; __GLXscreen *pGlxScreen; int err; if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) return err; if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err)) config, pGlxScreen, req->isDirect); } CWE ID: CWE-20 Target: 1 Example 2: Code: static ssize_t validate_store(struct kmem_cache *s, const char *buf, size_t length) { int ret = -EINVAL; if (buf[0] == '1') { ret = validate_slab_cache(s); if (ret >= 0) ret = length; } return ret; } 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 AudioRendererHost::OnPlayStream(int stream_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); AudioOutputDelegate* delegate = LookupById(stream_id); if (!delegate) { SendErrorMessage(stream_id); return; } delegate->OnPlayStream(); } 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 int can_open_cached(struct nfs4_state *state, int mode) { int ret = 0; switch (mode & (FMODE_READ|FMODE_WRITE|O_EXCL)) { case FMODE_READ: ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0; break; case FMODE_WRITE: ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0; break; case FMODE_READ|FMODE_WRITE: ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0; } return ret; } CWE ID: Target: 1 Example 2: Code: void vrend_clear(struct vrend_context *ctx, unsigned buffers, const union pipe_color_union *color, double depth, unsigned stencil) { GLbitfield bits = 0; if (ctx->in_error) return; if (ctx->ctx_switch_pending) vrend_finish_context_switch(ctx); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->sub->fb_id); vrend_update_frontface_state(ctx); if (ctx->sub->stencil_state_dirty) vrend_update_stencil_state(ctx); if (ctx->sub->scissor_state_dirty) vrend_update_scissor_state(ctx); if (ctx->sub->viewport_state_dirty) vrend_update_viewport_state(ctx); vrend_use_program(ctx, 0); if (buffers & PIPE_CLEAR_COLOR) { if (ctx->sub->nr_cbufs && ctx->sub->surf[0] && vrend_format_is_emulated_alpha(ctx->sub->surf[0]->format)) { glClearColor(color->f[3], 0.0, 0.0, 0.0); } else { glClearColor(color->f[0], color->f[1], color->f[2], color->f[3]); } } if (buffers & PIPE_CLEAR_DEPTH) { /* gallium clears don't respect depth mask */ glDepthMask(GL_TRUE); glClearDepth(depth); } if (buffers & PIPE_CLEAR_STENCIL) glClearStencil(stencil); if (buffers & PIPE_CLEAR_COLOR) { uint32_t mask = 0; int i; for (i = 0; i < ctx->sub->nr_cbufs; i++) { if (ctx->sub->surf[i]) mask |= (1 << i); } if (mask != (buffers >> 2)) { mask = buffers >> 2; while (mask) { i = u_bit_scan(&mask); if (util_format_is_pure_uint(ctx->sub->surf[i]->format)) glClearBufferuiv(GL_COLOR, i, (GLuint *)color); else if (util_format_is_pure_sint(ctx->sub->surf[i]->format)) glClearBufferiv(GL_COLOR, i, (GLint *)color); else glClearBufferfv(GL_COLOR, i, (GLfloat *)color); } } else bits |= GL_COLOR_BUFFER_BIT; } if (buffers & PIPE_CLEAR_DEPTH) bits |= GL_DEPTH_BUFFER_BIT; if (buffers & PIPE_CLEAR_STENCIL) bits |= GL_STENCIL_BUFFER_BIT; if (bits) glClear(bits); if (buffers & PIPE_CLEAR_DEPTH) if (!ctx->sub->dsa_state.depth.writemask) glDepthMask(GL_FALSE); } 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 pcd_init_units(void) { struct pcd_unit *cd; int unit; pcd_drive_count = 0; for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { struct gendisk *disk = alloc_disk(1); if (!disk) continue; disk->queue = blk_mq_init_sq_queue(&cd->tag_set, &pcd_mq_ops, 1, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disk->queue)) { disk->queue = NULL; continue; } INIT_LIST_HEAD(&cd->rq_list); disk->queue->queuedata = cd; blk_queue_bounce_limit(disk->queue, BLK_BOUNCE_HIGH); cd->disk = disk; cd->pi = &cd->pia; cd->present = 0; cd->last_sense = 0; cd->changed = 1; cd->drive = (*drives[unit])[D_SLV]; if ((*drives[unit])[D_PRT]) pcd_drive_count++; cd->name = &cd->info.name[0]; snprintf(cd->name, sizeof(cd->info.name), "%s%d", name, unit); cd->info.ops = &pcd_dops; cd->info.handle = cd; cd->info.speed = 0; cd->info.capacity = 1; cd->info.mask = 0; disk->major = major; disk->first_minor = unit; strcpy(disk->disk_name, cd->name); /* umm... */ disk->fops = &pcd_bdops; disk->flags = GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE; } } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount, struct vm_area_struct *vma, struct page *check_page) { struct mm_struct *mm = vma->vm_mm; pmd_t *pmd; pte_t *pte; pte_t pteval; spinlock_t *ptl; struct page *page; unsigned long address; unsigned long mmun_start; /* For mmu_notifiers */ unsigned long mmun_end; /* For mmu_notifiers */ unsigned long end; int ret = SWAP_AGAIN; int locked_vma = 0; address = (vma->vm_start + cursor) & CLUSTER_MASK; end = address + CLUSTER_SIZE; if (address < vma->vm_start) address = vma->vm_start; if (end > vma->vm_end) end = vma->vm_end; pmd = mm_find_pmd(mm, address); if (!pmd) return ret; mmun_start = address; mmun_end = end; mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); /* * If we can acquire the mmap_sem for read, and vma is VM_LOCKED, * keep the sem while scanning the cluster for mlocking pages. */ if (down_read_trylock(&vma->vm_mm->mmap_sem)) { locked_vma = (vma->vm_flags & VM_LOCKED); if (!locked_vma) up_read(&vma->vm_mm->mmap_sem); /* don't need it */ } pte = pte_offset_map_lock(mm, pmd, address, &ptl); /* Update high watermark before we lower rss */ update_hiwater_rss(mm); for (; address < end; pte++, address += PAGE_SIZE) { if (!pte_present(*pte)) continue; page = vm_normal_page(vma, address, *pte); BUG_ON(!page || PageAnon(page)); if (locked_vma) { mlock_vma_page(page); /* no-op if already mlocked */ if (page == check_page) ret = SWAP_MLOCK; continue; /* don't unmap */ } if (ptep_clear_flush_young_notify(vma, address, pte)) continue; /* Nuke the page table entry. */ flush_cache_page(vma, address, pte_pfn(*pte)); pteval = ptep_clear_flush(vma, address, pte); /* If nonlinear, store the file page offset in the pte. */ if (page->index != linear_page_index(vma, address)) { pte_t ptfile = pgoff_to_pte(page->index); if (pte_soft_dirty(pteval)) pte_file_mksoft_dirty(ptfile); set_pte_at(mm, address, pte, ptfile); } /* Move the dirty bit to the physical page now the pte is gone. */ if (pte_dirty(pteval)) set_page_dirty(page); page_remove_rmap(page); page_cache_release(page); dec_mm_counter(mm, MM_FILEPAGES); (*mapcount)--; } pte_unmap_unlock(pte - 1, ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); if (locked_vma) up_read(&vma->vm_mm->mmap_sem); return ret; } CWE ID: CWE-264 Target: 1 Example 2: Code: wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se) { s64 gran, vdiff = curr->vruntime - se->vruntime; if (vdiff <= 0) return -1; gran = wakeup_gran(se); if (vdiff > gran) return 1; return 0; } CWE ID: CWE-400 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: _archive_write_data(struct archive *_a, const void *buff, size_t s) { struct archive_write *a = (struct archive_write *)_a; archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, ARCHIVE_STATE_DATA, "archive_write_data"); archive_clear_error(&a->archive); return ((a->format_write_data)(a, buff, s)); } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BrowserWindowGtk::UpdateDevToolsForContents(WebContents* contents) { TRACE_EVENT0("ui::gtk", "BrowserWindowGtk::UpdateDevToolsForContents"); DevToolsWindow* new_devtools_window = contents ? DevToolsWindow::GetDockedInstanceForInspectedTab(contents) : NULL; if (devtools_window_ == new_devtools_window && (!new_devtools_window || new_devtools_window->dock_side() == devtools_dock_side_)) return; if (devtools_window_ != new_devtools_window) { if (devtools_window_) devtools_container_->DetachTab(devtools_window_->tab_contents()); devtools_container_->SetTab( new_devtools_window ? new_devtools_window->tab_contents() : NULL); if (new_devtools_window) { new_devtools_window->tab_contents()->web_contents()->WasShown(); } } if (devtools_window_) { GtkAllocation contents_rect; gtk_widget_get_allocation(contents_vsplit_, &contents_rect); if (devtools_dock_side_ == DEVTOOLS_DOCK_SIDE_RIGHT) { devtools_window_->SetWidth( contents_rect.width - gtk_paned_get_position(GTK_PANED(contents_hsplit_))); } else { devtools_window_->SetHeight( contents_rect.height - gtk_paned_get_position(GTK_PANED(contents_vsplit_))); } } bool should_hide = devtools_window_ && (!new_devtools_window || devtools_dock_side_ != new_devtools_window->dock_side()); bool should_show = new_devtools_window && (!devtools_window_ || should_hide); if (should_hide) HideDevToolsContainer(); devtools_window_ = new_devtools_window; if (should_show) { devtools_dock_side_ = new_devtools_window->dock_side(); ShowDevToolsContainer(); } else if (new_devtools_window) { UpdateDevToolsSplitPosition(); } } CWE ID: CWE-20 Target: 1 Example 2: Code: PHP_FUNCTION(gethostname) { char buf[HOST_NAME_MAX]; if (zend_parse_parameters_none() == FAILURE) { return; } if (gethostname(buf, sizeof(buf) - 1)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to fetch host [%d]: %s", errno, strerror(errno)); RETURN_FALSE; } RETURN_STRING(buf, 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: main(void) { fwrite(signature, sizeof signature, 1, stdout); put_chunk(IHDR, sizeof IHDR); for(;;) put_chunk(unknown, sizeof unknown); } 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 nfs4_close_sync(struct path *path, struct nfs4_state *state, mode_t mode) { __nfs4_close(path, state, mode, 1); } CWE ID: Target: 1 Example 2: Code: void BlinkMediaTestSuite::Initialize() { base::TestSuite::Initialize(); #if defined(OS_ANDROID) JNIEnv* env = base::android::AttachCurrentThread(); ui::gl::android::RegisterJni(env); media::RegisterJni(env); #endif media::InitializeMediaLibrary(); #ifdef V8_USE_EXTERNAL_STARTUP_DATA gin::V8Initializer::LoadV8Snapshot(); gin::V8Initializer::LoadV8Natives(); #endif scoped_ptr<base::MessageLoop> message_loop; if (!base::MessageLoop::current()) message_loop.reset(new base::MessageLoop()); blink::initialize(blink_platform_support_.get()); } CWE ID: CWE-310 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 SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != 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; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new uint32_t[mTimeToSampleCount * 2]; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline void sem_putref(struct sem_array *sma) { ipc_lock_by_ptr(&sma->sem_perm); ipc_rcu_putref(sma); ipc_unlock(&(sma)->sem_perm); } CWE ID: CWE-189 Target: 1 Example 2: Code: static int ext4_ext_rm_idx(handle_t *handle, struct inode *inode, struct ext4_ext_path *path) { int err; ext4_fsblk_t leaf; /* free index block */ path--; leaf = idx_pblock(path->p_idx); BUG_ON(path->p_hdr->eh_entries == 0); err = ext4_ext_get_access(handle, inode, path); if (err) return err; le16_add_cpu(&path->p_hdr->eh_entries, -1); err = ext4_ext_dirty(handle, inode, path); if (err) return err; ext_debug("index is empty, remove it, free block %llu\n", leaf); ext4_free_blocks(handle, inode, 0, leaf, 1, EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET); return err; } 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 DateTimeChooserImpl::writeDocument(SharedBuffer* data) { String stepString = String::number(m_parameters.step); String stepBaseString = String::number(m_parameters.stepBase, 11, WTF::TruncateTrailingZeros); IntRect anchorRectInScreen = m_chromeClient->rootViewToScreen(m_parameters.anchorRectInRootView); String todayLabelString; String otherDateLabelString; if (m_parameters.type == InputTypeNames::month) { todayLabelString = locale().queryString(WebLocalizedString::ThisMonthButtonLabel); otherDateLabelString = locale().queryString(WebLocalizedString::OtherMonthLabel); } else if (m_parameters.type == InputTypeNames::week) { todayLabelString = locale().queryString(WebLocalizedString::ThisWeekButtonLabel); otherDateLabelString = locale().queryString(WebLocalizedString::OtherWeekLabel); } else { todayLabelString = locale().queryString(WebLocalizedString::CalendarToday); otherDateLabelString = locale().queryString(WebLocalizedString::OtherDateLabel); } addString("<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", data); data->append(Platform::current()->loadResource("pickerCommon.css")); data->append(Platform::current()->loadResource("pickerButton.css")); data->append(Platform::current()->loadResource("suggestionPicker.css")); data->append(Platform::current()->loadResource("calendarPicker.css")); addString("</style></head><body><div id=main>Loading...</div><script>\n" "window.dialogArguments = {\n", data); addProperty("anchorRectInScreen", anchorRectInScreen, data); addProperty("min", valueToDateTimeString(m_parameters.minimum, m_parameters.type), data); addProperty("max", valueToDateTimeString(m_parameters.maximum, m_parameters.type), data); addProperty("step", stepString, data); addProperty("stepBase", stepBaseString, data); addProperty("required", m_parameters.required, data); addProperty("currentValue", valueToDateTimeString(m_parameters.doubleValue, m_parameters.type), data); addProperty("locale", m_parameters.locale.string(), data); addProperty("todayLabel", todayLabelString, data); addProperty("clearLabel", locale().queryString(WebLocalizedString::CalendarClear), data); addProperty("weekLabel", locale().queryString(WebLocalizedString::WeekNumberLabel), data); addProperty("weekStartDay", m_locale->firstDayOfWeek(), data); addProperty("shortMonthLabels", m_locale->shortMonthLabels(), data); addProperty("dayLabels", m_locale->weekDayShortLabels(), data); addProperty("isLocaleRTL", m_locale->isRTL(), data); addProperty("isRTL", m_parameters.isAnchorElementRTL, data); addProperty("mode", m_parameters.type.string(), data); if (m_parameters.suggestions.size()) { Vector<String> suggestionValues; Vector<String> localizedSuggestionValues; Vector<String> suggestionLabels; for (unsigned i = 0; i < m_parameters.suggestions.size(); i++) { suggestionValues.append(valueToDateTimeString(m_parameters.suggestions[i].value, m_parameters.type)); localizedSuggestionValues.append(m_parameters.suggestions[i].localizedValue); suggestionLabels.append(m_parameters.suggestions[i].label); } addProperty("suggestionValues", suggestionValues, data); addProperty("localizedSuggestionValues", localizedSuggestionValues, data); addProperty("suggestionLabels", suggestionLabels, data); addProperty("inputWidth", static_cast<unsigned>(m_parameters.anchorRectInRootView.width()), data); addProperty("showOtherDateEntry", RenderTheme::theme().supportsCalendarPicker(m_parameters.type), data); addProperty("otherDateLabel", otherDateLabelString, data); addProperty("suggestionHighlightColor", RenderTheme::theme().activeListBoxSelectionBackgroundColor().serialized(), data); addProperty("suggestionHighlightTextColor", RenderTheme::theme().activeListBoxSelectionForegroundColor().serialized(), data); } addString("}\n", data); data->append(Platform::current()->loadResource("pickerCommon.js")); data->append(Platform::current()->loadResource("suggestionPicker.js")); data->append(Platform::current()->loadResource("calendarPicker.js")); addString("</script></body>\n", data); } CWE ID: CWE-22 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: ProcRenderSetPictureFilter(ClientPtr client) { REQUEST(xRenderSetPictureFilterReq); PicturePtr pPicture; int result; xFixed *params; int nparams; char *name; REQUEST_AT_LEAST_SIZE(xRenderSetPictureFilterReq); VERIFY_PICTURE(pPicture, stuff->picture, client, DixSetAttrAccess); name = (char *) (stuff + 1); params = (xFixed *) (name + pad_to_int32(stuff->nbytes)); nparams = ((xFixed *) stuff + client->req_len) - params; result = SetPictureFilter(pPicture, name, stuff->nbytes, params, nparams); return result; } CWE ID: CWE-20 Target: 1 Example 2: Code: oftable_destroy(struct oftable *table) { ovs_assert(classifier_is_empty(&table->cls)); ovs_mutex_lock(&ofproto_mutex); oftable_configure_eviction(table, 0, NULL, 0); ovs_mutex_unlock(&ofproto_mutex); hmap_destroy(&table->eviction_groups_by_id); heap_destroy(&table->eviction_groups_by_size); classifier_destroy(&table->cls); free(table->name); } CWE ID: CWE-617 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 virtio_gpu_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq) { VirtIOGPU *g = VIRTIO_GPU(vdev); struct virtio_gpu_ctrl_command *cmd; if (!virtio_queue_ready(vq)) { return; } #ifdef CONFIG_VIRGL if (!g->renderer_inited && g->use_virgl_renderer) { virtio_gpu_virgl_init(g); g->renderer_inited = true; } #endif cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command)); while (cmd) { cmd->vq = vq; cmd->error = 0; cmd->finished = false; cmd->waiting = false; QTAILQ_INSERT_TAIL(&g->cmdq, cmd, next); cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command)); } virtio_gpu_process_cmdq(g); #ifdef CONFIG_VIRGL if (g->use_virgl_renderer) { virtio_gpu_virgl_fence_poll(g); } #endif } CWE ID: CWE-772 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; BIGNUM local_r0, local_d, local_p; BIGNUM *pr0, *d, *p; int bitsp, bitsq, ok = -1, n = 0; BN_CTX *ctx = NULL; unsigned long error = 0; /* * When generating ridiculously small keys, we can get stuck * continually regenerating the same prime values. */ if (bits < 16) { ok = 0; /* we set our own err */ RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL); goto err; } ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); r3 = BN_CTX_get(ctx); if (r3 == NULL) goto err; bitsp = (bits + 1) / 2; bitsq = bits - bitsp; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_new()) == NULL)) goto err; if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_new()) == NULL)) goto err; if (!rsa->q && ((rsa->q = BN_new()) == NULL)) goto err; if (!rsa->dmp1 && ((rsa->dmp1 = BN_new()) == NULL)) goto err; if (!rsa->dmq1 && ((rsa->dmq1 = BN_new()) == NULL)) goto err; if (!rsa->iqmp && ((rsa->iqmp = BN_new()) == NULL)) goto err; if (BN_copy(rsa->e, e_value) == NULL) goto err; BN_set_flags(r2, BN_FLG_CONSTTIME); /* generate p and q */ for (;;) { if (!BN_sub(r2, rsa->p, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 0)) goto err; for (;;) { do { if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb)) goto err; } while (BN_cmp(rsa->p, rsa->q) == 0); if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 1)) goto err; if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* calculate n */ if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* calculate d */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* p-1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* q-1 */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* (p-1)(q-1) */ if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) { pr0 = &local_r0; BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); } else pr0 = r0; if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) goto err; /* d */ /* set up d for correct BN_FLG_CONSTTIME flag */ if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) { d = &local_d; BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); } else d = rsa->d; /* calculate d mod (p-1) */ if (!BN_mod(rsa->dmp1, d, r1, ctx)) goto err; /* calculate d mod (q-1) */ if (!BN_mod(rsa->dmq1, d, r2, ctx)) goto err; /* calculate inverse of q mod p */ if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) { p = &local_p; BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME); } else p = rsa->p; if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) goto err; ok = 1; err: if (ok == -1) { RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN); ok = 0; } if (ctx != NULL) { BN_CTX_end(ctx); BN_CTX_free(ctx); } return ok; } CWE ID: CWE-327 Target: 1 Example 2: Code: static void tcp_get_info_chrono_stats(const struct tcp_sock *tp, struct tcp_info *info) { u64 stats[__TCP_CHRONO_MAX], total = 0; enum tcp_chrono i; for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) { stats[i] = tp->chrono_stat[i - 1]; if (i == tp->chrono_type) stats[i] += tcp_time_stamp - tp->chrono_start; stats[i] *= USEC_PER_SEC / HZ; total += stats[i]; } info->tcpi_busy_time = total; info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED]; info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED]; } CWE ID: CWE-369 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SVGImage::setContainerSize(const IntSize& size) { if (!m_page || !usesContainerSize()) return; LocalFrame* frame = m_page->mainFrame(); SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement(); if (!rootElement) return; RenderSVGRoot* renderer = toRenderSVGRoot(rootElement->renderer()); if (!renderer) return; FrameView* view = frameView(); view->resize(this->containerSize()); renderer->setContainerSize(size); } 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: Blob::~Blob() { ThreadableBlobRegistry::unregisterBlobURL(m_internalURL); } CWE ID: Target: 1 Example 2: Code: Document::~Document() { ASSERT(!layoutView()); ASSERT(!parentTreeScope()); ASSERT(!m_axObjectCache); #if !ENABLE(OILPAN) ASSERT(m_ranges.isEmpty()); ASSERT(!hasGuardRefCount()); ASSERT(!m_importsController); ASSERT(m_visibilityObservers.isEmpty()); if (m_templateDocument) m_templateDocument->m_templateDocumentHost = nullptr; // balanced in ensureTemplateDocument(). m_scriptRunner.clear(); removeAllEventListenersRecursively(); ASSERT(!m_parser || m_parser->refCount() == 1); detachParser(); if (m_styleSheetList) m_styleSheetList->detachFromDocument(); m_timeline->detachFromDocument(); m_styleEngine->detachFromDocument(); if (m_elemSheet) m_elemSheet->clearOwnerNode(); if (hasRareData()) clearRareData(); ASSERT(m_listsInvalidatedAtDocument.isEmpty()); for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListCounts); ++i) ASSERT(!m_nodeListCounts[i]); liveDocumentSet().remove(this); #endif InstanceCounters::decrementCounter(InstanceCounters::DocumentCounter); } 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: sctp_disposition_t sctp_sf_do_prm_requestheartbeat( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { if (SCTP_DISPOSITION_NOMEM == sctp_sf_heartbeat(ep, asoc, type, (struct sctp_transport *)arg, commands)) return SCTP_DISPOSITION_NOMEM; /* * RFC 2960 (bis), section 8.3 * * D) Request an on-demand HEARTBEAT on a specific destination * transport address of a given association. * * The endpoint should increment the respective error counter of * the destination transport address each time a HEARTBEAT is sent * to that address and not acknowledged within one RTO. * */ sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT, SCTP_TRANSPORT(arg)); return SCTP_DISPOSITION_CONSUME; } 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 int bmp_getint32(jas_stream_t *in, int_fast32_t *val) { int n; uint_fast32_t v; int c; for (n = 4, v = 0;;) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } v |= (c << 24); if (--n <= 0) { break; } v >>= 8; } if (val) { *val = v; } return 0; } CWE ID: CWE-476 Target: 1 Example 2: Code: char *ap_response_code_string(request_rec *r, int error_index) { core_dir_config *dirconf; core_request_config *reqconf = ap_get_core_module_config(r->request_config); const char *err; const char *response; ap_expr_info_t *expr; /* check for string registered via ap_custom_response() first */ if (reqconf->response_code_strings != NULL && reqconf->response_code_strings[error_index] != NULL) { return reqconf->response_code_strings[error_index]; } /* check for string specified via ErrorDocument */ dirconf = ap_get_core_module_config(r->per_dir_config); if (!dirconf->response_code_exprs) { return NULL; } expr = apr_hash_get(dirconf->response_code_exprs, &error_index, sizeof(error_index)); if (!expr) { return NULL; } /* special token to indicate revert back to default */ if ((char *) expr == &errordocument_default) { return NULL; } err = NULL; response = ap_expr_str_exec(r, expr, &err); if (err) { ap_log_rerror( APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02841) "core: ErrorDocument: can't " "evaluate require expression: %s", err); return NULL; } /* alas, duplication required as we return not-const */ return apr_pstrdup(r->pool, response); } 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 __sys_sendmsg(struct socket *sock, struct msghdr __user *msg, struct msghdr *msg_sys, unsigned flags, struct used_address *used_address) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct sockaddr_storage address; struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; unsigned char ctl[sizeof(struct cmsghdr) + 20] __attribute__ ((aligned(sizeof(__kernel_size_t)))); /* 20 is size of ipv6_pktinfo */ unsigned char *ctl_buf = ctl; int err, ctl_len, iov_size, total_len; err = -EFAULT; if (MSG_CMSG_COMPAT & flags) { if (get_compat_msghdr(msg_sys, msg_compat)) return -EFAULT; } else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr))) return -EFAULT; /* do not move before msg_sys is valid */ err = -EMSGSIZE; if (msg_sys->msg_iovlen > UIO_MAXIOV) goto out; /* Check whether to allocate the iovec area */ err = -ENOMEM; iov_size = msg_sys->msg_iovlen * sizeof(struct iovec); if (msg_sys->msg_iovlen > UIO_FASTIOV) { iov = sock_kmalloc(sock->sk, iov_size, GFP_KERNEL); if (!iov) goto out; } /* This will also move the address data into kernel space */ if (MSG_CMSG_COMPAT & flags) { err = verify_compat_iovec(msg_sys, iov, (struct sockaddr *)&address, VERIFY_READ); } else err = verify_iovec(msg_sys, iov, (struct sockaddr *)&address, VERIFY_READ); if (err < 0) goto out_freeiov; total_len = err; err = -ENOBUFS; if (msg_sys->msg_controllen > INT_MAX) goto out_freeiov; ctl_len = msg_sys->msg_controllen; if ((MSG_CMSG_COMPAT & flags) && ctl_len) { err = cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl, sizeof(ctl)); if (err) goto out_freeiov; ctl_buf = msg_sys->msg_control; ctl_len = msg_sys->msg_controllen; } else if (ctl_len) { if (ctl_len > sizeof(ctl)) { ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL); if (ctl_buf == NULL) goto out_freeiov; } err = -EFAULT; /* * Careful! Before this, msg_sys->msg_control contains a user pointer. * Afterwards, it will be a kernel pointer. Thus the compiler-assisted * checking falls down on this. */ if (copy_from_user(ctl_buf, (void __user __force *)msg_sys->msg_control, ctl_len)) goto out_freectl; msg_sys->msg_control = ctl_buf; } msg_sys->msg_flags = flags; if (sock->file->f_flags & O_NONBLOCK) msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. * used_address->name_len is initialized to UINT_MAX so that the first * destination address never matches. */ if (used_address && used_address->name_len == msg_sys->msg_namelen && !memcmp(&used_address->name, msg->msg_name, used_address->name_len)) { err = sock_sendmsg_nosec(sock, msg_sys, total_len); goto out_freectl; } err = sock_sendmsg(sock, msg_sys, total_len); /* * If this is sendmmsg() and sending to current destination address was * successful, remember it. */ if (used_address && err >= 0) { used_address->name_len = msg_sys->msg_namelen; memcpy(&used_address->name, msg->msg_name, used_address->name_len); } out_freectl: if (ctl_buf != ctl) sock_kfree_s(sock->sk, ctl_buf, ctl_len); out_freeiov: if (iov != iovstack) sock_kfree_s(sock->sk, iov, iov_size); out: return err; } 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: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[аысԁеԍһіюјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8( "[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋпԥกח] > n; œ > ce;" "[ŧтҭԏ七丅丆丁] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;" "[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;" "[ҫင] > c; [ұ丫] > y; [χҳӽӿ乂] > x;" "[ԃძ] > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;" "[०০੦૦ଠ୦೦] > o;" "[৭੧૧] > q;" "[บບ] > u;" "[θ] > 0;" "[२২੨੨૨೩೭շ] > 2;" "[зҙӡउওਤ੩૩౩ဒვპ] > 3;" "[੫丩ㄐ] > 4;" "[ճ] > 6;" "[৪੪୫] > 8;" "[૭୨౨] > 9;" "[—一―⸺⸻] > \\-;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } CWE ID: Target: 1 Example 2: Code: vmxnet3_setup_tx_offloads(VMXNET3State *s) { switch (s->offload_mode) { case VMXNET3_OM_NONE: net_tx_pkt_build_vheader(s->tx_pkt, false, false, 0); break; case VMXNET3_OM_CSUM: net_tx_pkt_build_vheader(s->tx_pkt, false, true, 0); VMW_PKPRN("L4 CSO requested\n"); break; case VMXNET3_OM_TSO: net_tx_pkt_build_vheader(s->tx_pkt, true, true, s->cso_or_gso_size); net_tx_pkt_update_ip_checksums(s->tx_pkt); VMW_PKPRN("GSO offload requested."); break; default: g_assert_not_reached(); return false; } return true; } 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: int use_env() { int indent; size_t flags = 0; json_t *json; json_error_t error; #ifdef _WIN32 /* On Windows, set stdout and stderr to binary mode to avoid outputting DOS line terminators */ _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stderr), _O_BINARY); #endif indent = getenv_int("JSON_INDENT"); if(indent < 0 || indent > 255) { fprintf(stderr, "invalid value for JSON_INDENT: %d\n", indent); return 2; } if(indent > 0) flags |= JSON_INDENT(indent); if(getenv_int("JSON_COMPACT") > 0) flags |= JSON_COMPACT; if(getenv_int("JSON_ENSURE_ASCII")) flags |= JSON_ENSURE_ASCII; if(getenv_int("JSON_PRESERVE_ORDER")) flags |= JSON_PRESERVE_ORDER; if(getenv_int("JSON_SORT_KEYS")) flags |= JSON_SORT_KEYS; if(getenv_int("STRIP")) { /* Load to memory, strip leading and trailing whitespace */ size_t size = 0, used = 0; char *buffer = NULL; while(1) { size_t count; size = (size == 0 ? 128 : size * 2); buffer = realloc(buffer, size); if(!buffer) { fprintf(stderr, "Unable to allocate %d bytes\n", (int)size); return 1; } count = fread(buffer + used, 1, size - used, stdin); if(count < size - used) { buffer[used + count] = '\0'; break; } used += count; } json = json_loads(strip(buffer), 0, &error); free(buffer); } else json = json_loadf(stdin, 0, &error); if(!json) { fprintf(stderr, "%d %d %d\n%s\n", error.line, error.column, error.position, error.text); return 1; } json_dumpf(json, stdout, flags); json_decref(json); return 0; } CWE ID: CWE-310 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 InspectorNetworkAgent::WillSendRequestInternal( ExecutionContext* execution_context, unsigned long identifier, DocumentLoader* loader, const ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo& initiator_info) { String request_id = IdentifiersFactory::RequestId(identifier); String loader_id = loader ? IdentifiersFactory::LoaderId(loader) : ""; resources_data_->ResourceCreated(request_id, loader_id, request.Url()); InspectorPageAgent::ResourceType type = InspectorPageAgent::kOtherResource; if (initiator_info.name == FetchInitiatorTypeNames::xmlhttprequest) { type = InspectorPageAgent::kXHRResource; resources_data_->SetResourceType(request_id, type); } else if (initiator_info.name == FetchInitiatorTypeNames::document) { type = InspectorPageAgent::kDocumentResource; resources_data_->SetResourceType(request_id, type); } String frame_id = loader && loader->GetFrame() ? IdentifiersFactory::FrameId(loader->GetFrame()) : ""; std::unique_ptr<protocol::Network::Initiator> initiator_object = BuildInitiatorObject(loader && loader->GetFrame() ? loader->GetFrame()->GetDocument() : nullptr, initiator_info); if (initiator_info.name == FetchInitiatorTypeNames::document) { FrameNavigationInitiatorMap::iterator it = frame_navigation_initiator_map_.find(frame_id); if (it != frame_navigation_initiator_map_.end()) initiator_object = it->value->clone(); } std::unique_ptr<protocol::Network::Request> request_info( BuildObjectForResourceRequest(request)); if (loader) { request_info->setMixedContentType(MixedContentTypeForContextType( MixedContentChecker::ContextTypeForInspector(loader->GetFrame(), request))); } request_info->setReferrerPolicy( GetReferrerPolicy(request.GetReferrerPolicy())); if (initiator_info.is_link_preload) request_info->setIsLinkPreload(true); String resource_type = InspectorPageAgent::ResourceTypeJson(type); String documentURL = loader ? UrlWithoutFragment(loader->Url()).GetString() : UrlWithoutFragment(execution_context->Url()).GetString(); Maybe<String> maybe_frame_id; if (!frame_id.IsEmpty()) maybe_frame_id = frame_id; GetFrontend()->requestWillBeSent( request_id, loader_id, documentURL, std::move(request_info), MonotonicallyIncreasingTime(), CurrentTime(), std::move(initiator_object), BuildObjectForResourceResponse(redirect_response), resource_type, std::move(maybe_frame_id)); if (pending_xhr_replay_data_ && !pending_xhr_replay_data_->Async()) GetFrontend()->flush(); } CWE ID: CWE-119 Target: 1 Example 2: Code: piv_decipher(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, piv_validate_general_authentication(card, data, datalen, out, outlen)); } 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 bool get_build_id( Backtrace* backtrace, uintptr_t base_addr, uint8_t* e_ident, std::string* build_id) { HdrType hdr; memcpy(&hdr.e_ident[0], e_ident, EI_NIDENT); if (backtrace->Read(base_addr + EI_NIDENT, reinterpret_cast<uint8_t*>(&hdr) + EI_NIDENT, sizeof(HdrType) - EI_NIDENT) != sizeof(HdrType) - EI_NIDENT) { return false; } for (size_t i = 0; i < hdr.e_phnum; i++) { PhdrType phdr; if (backtrace->Read(base_addr + hdr.e_phoff + i * hdr.e_phentsize, reinterpret_cast<uint8_t*>(&phdr), sizeof(phdr)) != sizeof(phdr)) { return false; } if (phdr.p_type == PT_NOTE) { size_t hdr_size = phdr.p_filesz; uintptr_t addr = base_addr + phdr.p_offset; while (hdr_size >= sizeof(NhdrType)) { NhdrType nhdr; if (backtrace->Read(addr, reinterpret_cast<uint8_t*>(&nhdr), sizeof(nhdr)) != sizeof(nhdr)) { return false; } addr += sizeof(nhdr); if (nhdr.n_type == NT_GNU_BUILD_ID) { addr += NOTE_ALIGN(nhdr.n_namesz); uint8_t build_id_data[128]; if (nhdr.n_namesz > sizeof(build_id_data)) { ALOGE("Possible corrupted note, name size value is too large: %u", nhdr.n_namesz); return false; } if (backtrace->Read(addr, build_id_data, nhdr.n_descsz) != nhdr.n_descsz) { return false; } build_id->clear(); for (size_t bytes = 0; bytes < nhdr.n_descsz; bytes++) { *build_id += android::base::StringPrintf("%02x", build_id_data[bytes]); } return true; } else { hdr_size -= sizeof(nhdr); size_t skip_bytes = NOTE_ALIGN(nhdr.n_namesz) + NOTE_ALIGN(nhdr.n_descsz); addr += skip_bytes; if (hdr_size < skip_bytes) { break; } hdr_size -= skip_bytes; } } } } return false; } 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: bool ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter, param_type* r) { const char *data; int data_size = 0; bool result = m->ReadData(iter, &data, &data_size); if (result && data_size == sizeof(LOGFONT)) { memcpy(r, data, sizeof(LOGFONT)); } else { result = false; NOTREACHED(); } return result; } CWE ID: CWE-20 Target: 1 Example 2: Code: static struct net_device_stats *airo_get_stats(struct net_device *dev) { struct airo_info *local = dev->ml_priv; if (!test_bit(JOB_STATS, &local->jobs)) { /* Get stats out of the card if available */ if (down_trylock(&local->sem) != 0) { set_bit(JOB_STATS, &local->jobs); wake_up_interruptible(&local->thr_wait); } else airo_read_stats(dev); } return &dev->stats; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void set_checkpoint_signal(void) { } 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: long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); int status; len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) //error or underflow return status; if (status > 0) //interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) //we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; } CWE ID: CWE-119 Target: 1 Example 2: Code: circuit_resume_edge_reading_helper(edge_connection_t *first_conn, circuit_t *circ, crypt_path_t *layer_hint) { edge_connection_t *conn; int n_packaging_streams, n_streams_left; int packaged_this_round; int cells_on_queue; int cells_per_conn; edge_connection_t *chosen_stream = NULL; int max_to_package; if (first_conn == NULL) { /* Don't bother to try to do the rest of this if there are no connections * to resume. */ return 0; } /* How many cells do we have space for? It will be the minimum of * the number needed to exhaust the package window, and the minimum * needed to fill the cell queue. */ max_to_package = circ->package_window; if (CIRCUIT_IS_ORIGIN(circ)) { cells_on_queue = circ->n_chan_cells.n; } else { or_circuit_t *or_circ = TO_OR_CIRCUIT(circ); cells_on_queue = or_circ->p_chan_cells.n; } if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package) max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue; /* Once we used to start listening on the streams in the order they * appeared in the linked list. That leads to starvation on the * streams that appeared later on the list, since the first streams * would always get to read first. Instead, we just pick a random * stream on the list, and enable reading for streams starting at that * point (and wrapping around as if the list were circular). It would * probably be better to actually remember which streams we've * serviced in the past, but this is simple and effective. */ /* Select a stream uniformly at random from the linked list. We * don't need cryptographic randomness here. */ { int num_streams = 0; for (conn = first_conn; conn; conn = conn->next_stream) { num_streams++; if (tor_weak_random_one_in_n(&stream_choice_rng, num_streams)) { chosen_stream = conn; } /* Invariant: chosen_stream has been chosen uniformly at random from * among the first num_streams streams on first_conn. * * (Note that we iterate over every stream on the circuit, so that after * we've considered the first stream, we've chosen it with P=1; and * after we consider the second stream, we've switched to it with P=1/2 * and stayed with the first stream with P=1/2; and after we've * considered the third stream, we've switched to it with P=1/3 and * remained with one of the first two streams with P=(2/3), giving each * one P=(1/2)(2/3) )=(1/3).) */ } } /* Count how many non-marked streams there are that have anything on * their inbuf, and enable reading on all of the connections. */ n_packaging_streams = 0; /* Activate reading starting from the chosen stream */ for (conn=chosen_stream; conn; conn = conn->next_stream) { /* Start reading for the streams starting from here */ if (conn->base_.marked_for_close || conn->package_window <= 0) continue; if (!layer_hint || conn->cpath_layer == layer_hint) { connection_start_reading(TO_CONN(conn)); if (connection_get_inbuf_len(TO_CONN(conn)) > 0) ++n_packaging_streams; } } /* Go back and do the ones we skipped, circular-style */ for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) { if (conn->base_.marked_for_close || conn->package_window <= 0) continue; if (!layer_hint || conn->cpath_layer == layer_hint) { connection_start_reading(TO_CONN(conn)); if (connection_get_inbuf_len(TO_CONN(conn)) > 0) ++n_packaging_streams; } } if (n_packaging_streams == 0) /* avoid divide-by-zero */ return 0; again: cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams); packaged_this_round = 0; n_streams_left = 0; /* Iterate over all connections. Package up to cells_per_conn cells on * each. Update packaged_this_round with the total number of cells * packaged, and n_streams_left with the number that still have data to * package. */ for (conn=first_conn; conn; conn=conn->next_stream) { if (conn->base_.marked_for_close || conn->package_window <= 0) continue; if (!layer_hint || conn->cpath_layer == layer_hint) { int n = cells_per_conn, r; /* handle whatever might still be on the inbuf */ r = connection_edge_package_raw_inbuf(conn, 1, &n); /* Note how many we packaged */ packaged_this_round += (cells_per_conn-n); if (r<0) { /* Problem while packaging. (We already sent an end cell if * possible) */ connection_mark_for_close(TO_CONN(conn)); continue; } /* If there's still data to read, we'll be coming back to this stream. */ if (connection_get_inbuf_len(TO_CONN(conn))) ++n_streams_left; /* If the circuit won't accept any more data, return without looking * at any more of the streams. Any connections that should be stopped * have already been stopped by connection_edge_package_raw_inbuf. */ if (circuit_consider_stop_edge_reading(circ, layer_hint)) return -1; /* XXXX should we also stop immediately if we fill up the cell queue? * Probably. */ } } /* If we made progress, and we are willing to package more, and there are * any streams left that want to package stuff... try again! */ if (packaged_this_round && packaged_this_round < max_to_package && n_streams_left) { max_to_package -= packaged_this_round; n_packaging_streams = n_streams_left; goto again; } return 0; } CWE ID: CWE-617 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 CWebServer::Cmd_GetNewHistory(WebEmSession & session, const request& req, Json::Value &root) { root["status"] = "OK"; root["title"] = "GetNewHistory"; std::string historyfile; int nValue; m_sql.GetPreferencesVar("ReleaseChannel", nValue); bool bIsBetaChannel = (nValue != 0); std::string szHistoryURL = "https://www.domoticz.com/download.php?channel=stable&type=history"; if (bIsBetaChannel) { utsname my_uname; if (uname(&my_uname) < 0) return; std::string systemname = my_uname.sysname; std::string machine = my_uname.machine; std::transform(systemname.begin(), systemname.end(), systemname.begin(), ::tolower); if (machine == "armv6l") { machine = "armv7l"; } if (((machine != "armv6l") && (machine != "armv7l") && (systemname != "windows") && (machine != "x86_64") && (machine != "aarch64")) || (strstr(my_uname.release, "ARCH+") != NULL)) szHistoryURL = "https://www.domoticz.com/download.php?channel=beta&type=history"; else szHistoryURL = "https://www.domoticz.com/download.php?channel=beta&type=history&system=" + systemname + "&machine=" + machine; } if (!HTTPClient::GET(szHistoryURL, historyfile)) { historyfile = "Unable to get Online History document !!"; } std::istringstream stream(historyfile); std::string sLine; int ii = 0; while (std::getline(stream, sLine)) { root["LastLogTime"] = ""; if (sLine.find("Version ") == 0) root["result"][ii]["level"] = 1; else root["result"][ii]["level"] = 0; root["result"][ii]["message"] = sLine; ii++; } } CWE ID: CWE-89 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 nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx, struct nfs4_state *state) { struct nfs4_opendata *opendata; opendata = nfs4_opendata_alloc(&ctx->path, state->owner, 0, NULL); if (opendata == NULL) return ERR_PTR(-ENOMEM); opendata->state = state; atomic_inc(&state->count); return opendata; } CWE ID: Target: 1 Example 2: Code: PHP_FUNCTION(snmp2_set) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_2c); } 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 struct ip_mc_list *igmp_mc_get_next(struct seq_file *seq, struct ip_mc_list *im) { struct igmp_mc_iter_state *state = igmp_mc_seq_private(seq); im = rcu_dereference(im->next_rcu); while (!im) { state->dev = next_net_device_rcu(state->dev); if (!state->dev) { state->in_dev = NULL; break; } state->in_dev = __in_dev_get_rcu(state->dev); if (!state->in_dev) continue; im = rcu_dereference(state->in_dev->mc_list); } return im; } 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 FolderHeaderView::ContentsChanged(views::Textfield* sender, const base::string16& new_contents) { if (!folder_item_) return; folder_item_->RemoveObserver(this); std::string name = base::UTF16ToUTF8(folder_name_view_->text()); delegate_->SetItemName(folder_item_, name); folder_item_->AddObserver(this); Layout(); } CWE ID: CWE-399 Target: 1 Example 2: Code: sp<MetaData> OggExtractor::getMetaData() { return mImpl->getFileMetaData(); } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void show_object(struct object *obj, struct strbuf *path, const char *last, void *data) { char *name = path_name(path, last); add_preferred_base_object(name); add_object_entry(obj->oid.hash, obj->type, name, 0); obj->flags |= OBJECT_ADDED; /* * We will have generated the hash from the name, * but not saved a pointer to it - we can free it */ free((char *)name); } 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 ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *isk = inet_sk(sk); int family = sk->sk_family; struct sockaddr_in *sin; struct sockaddr_in6 *sin6; struct sk_buff *skb; int copied, err; pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num); err = -EOPNOTSUPP; if (flags & MSG_OOB) goto out; if (addr_len) { if (family == AF_INET) *addr_len = sizeof(*sin); else if (family == AF_INET6 && addr_len) *addr_len = sizeof(*sin6); } if (flags & MSG_ERRQUEUE) { if (family == AF_INET) { return ip_recv_error(sk, msg, len); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { return pingv6_ops.ipv6_recv_error(sk, msg, len); #endif } } skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* Don't bother checking the checksum */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address and add cmsg data. */ if (family == AF_INET) { sin = (struct sockaddr_in *) msg->msg_name; sin->sin_family = AF_INET; sin->sin_port = 0 /* skb->h.uh->source */; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); if (isk->cmsg_flags) ip_cmsg_recv(msg, skb); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6hdr *ip6 = ipv6_hdr(skb); sin6 = (struct sockaddr_in6 *) msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ip6->saddr; sin6->sin6_flowinfo = 0; if (np->sndflow) sin6->sin6_flowinfo = ip6_flowinfo(ip6); sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); if (inet6_sk(sk)->rxopt.all) pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb); #endif } else { BUG(); } err = copied; done: skb_free_datagram(sk, skb); out: pr_debug("ping_recvmsg -> %d\n", err); return err; } CWE ID: CWE-200 Target: 1 Example 2: Code: static noinline size_t if_nlmsg_size(const struct net_device *dev, u32 ext_filter_mask) { return NLMSG_ALIGN(sizeof(struct ifinfomsg)) + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */ + nla_total_size(IFALIASZ) /* IFLA_IFALIAS */ + nla_total_size(IFNAMSIZ) /* IFLA_QDISC */ + nla_total_size(sizeof(struct rtnl_link_ifmap)) + nla_total_size(sizeof(struct rtnl_link_stats)) + nla_total_size(sizeof(struct rtnl_link_stats64)) + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */ + nla_total_size(MAX_ADDR_LEN) /* IFLA_BROADCAST */ + nla_total_size(4) /* IFLA_TXQLEN */ + nla_total_size(4) /* IFLA_WEIGHT */ + nla_total_size(4) /* IFLA_MTU */ + nla_total_size(4) /* IFLA_LINK */ + nla_total_size(4) /* IFLA_MASTER */ + nla_total_size(1) /* IFLA_CARRIER */ + nla_total_size(4) /* IFLA_PROMISCUITY */ + nla_total_size(4) /* IFLA_NUM_TX_QUEUES */ + nla_total_size(4) /* IFLA_NUM_RX_QUEUES */ + nla_total_size(1) /* IFLA_OPERSTATE */ + nla_total_size(1) /* IFLA_LINKMODE */ + nla_total_size(ext_filter_mask & RTEXT_FILTER_VF ? 4 : 0) /* IFLA_NUM_VF */ + rtnl_vfinfo_size(dev, ext_filter_mask) /* IFLA_VFINFO_LIST */ + rtnl_port_size(dev) /* IFLA_VF_PORTS + IFLA_PORT_SELF */ + rtnl_link_get_size(dev) /* IFLA_LINKINFO */ + rtnl_link_get_af_size(dev); /* IFLA_AF_SPEC */ } 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 ldb_dn_escape_internal(char *dst, const char *src, int len) { char c; char *d; int i; d = dst; for (i = 0; i < len; i++){ c = src[i]; switch (c) { case ' ': if (i == 0 || i == len - 1) { /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = c; } else { /* otherwise don't escape */ *d++ = c; } break; case '#': /* despite the RFC, windows escapes a # anywhere in the string */ case ',': case '+': case '"': case '\\': case '<': case '>': case '?': /* these must be escaped using \c form */ *d++ = '\\'; *d++ = c; break; case ';': case '\r': case '\n': case '=': case '\0': { /* any others get \XX form */ unsigned char v; const char *hexbytes = "0123456789ABCDEF"; v = (const unsigned char)c; *d++ = '\\'; *d++ = hexbytes[v>>4]; *d++ = hexbytes[v&0xF]; break; } default: *d++ = c; } } /* return the length of the resulting string */ return (d - dst); } 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: ChromeGeolocationPermissionContext::ChromeGeolocationPermissionContext( Profile* profile) : profile_(profile), ALLOW_THIS_IN_INITIALIZER_LIST(geolocation_infobar_queue_controller_( new GeolocationInfoBarQueueController( base::Bind( &ChromeGeolocationPermissionContext::NotifyPermissionSet, this), profile))) { } CWE ID: Target: 1 Example 2: Code: MagickExport MagickBooleanType CloneImageProperties(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); if (clone_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", clone_image->filename); (void) CopyMagickString(image->filename,clone_image->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,clone_image->magick_filename, MagickPathExtent); image->compression=clone_image->compression; image->quality=clone_image->quality; image->depth=clone_image->depth; image->alpha_color=clone_image->alpha_color; image->background_color=clone_image->background_color; image->border_color=clone_image->border_color; image->transparent_color=clone_image->transparent_color; image->gamma=clone_image->gamma; image->chromaticity=clone_image->chromaticity; image->rendering_intent=clone_image->rendering_intent; image->black_point_compensation=clone_image->black_point_compensation; image->units=clone_image->units; image->montage=(char *) NULL; image->directory=(char *) NULL; (void) CloneString(&image->geometry,clone_image->geometry); image->offset=clone_image->offset; image->resolution.x=clone_image->resolution.x; image->resolution.y=clone_image->resolution.y; image->page=clone_image->page; image->tile_offset=clone_image->tile_offset; image->extract_info=clone_image->extract_info; image->filter=clone_image->filter; image->fuzz=clone_image->fuzz; image->intensity=clone_image->intensity; image->interlace=clone_image->interlace; image->interpolate=clone_image->interpolate; image->endian=clone_image->endian; image->gravity=clone_image->gravity; image->compose=clone_image->compose; image->orientation=clone_image->orientation; image->scene=clone_image->scene; image->dispose=clone_image->dispose; image->delay=clone_image->delay; image->ticks_per_second=clone_image->ticks_per_second; image->iterations=clone_image->iterations; image->total_colors=clone_image->total_colors; image->taint=clone_image->taint; image->progress_monitor=clone_image->progress_monitor; image->client_data=clone_image->client_data; image->start_loop=clone_image->start_loop; image->error=clone_image->error; image->signature=clone_image->signature; if (clone_image->properties != (void *) NULL) { if (image->properties != (void *) NULL) DestroyImageProperties(image); image->properties=CloneSplayTree((SplayTreeInfo *) clone_image->properties,(void *(*)(void *)) ConstantString, (void *(*)(void *)) ConstantString); } return(MagickTrue); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Document::open(Document* entered_document, ExceptionState& exception_state) { if (ImportLoader()) { exception_state.ThrowDOMException( kInvalidStateError, "Imported document doesn't support open()."); return; } if (!IsHTMLDocument()) { exception_state.ThrowDOMException(kInvalidStateError, "Only HTML documents support open()."); return; } if (throw_on_dynamic_markup_insertion_count_) { exception_state.ThrowDOMException( kInvalidStateError, "Custom Element constructor should not use open()."); return; } if (entered_document) { if (!GetSecurityOrigin()->IsSameSchemeHostPortAndSuborigin( entered_document->GetSecurityOrigin())) { exception_state.ThrowSecurityError( "Can only call open() on same-origin documents."); return; } SetSecurityOrigin(entered_document->GetSecurityOrigin()); if (this != entered_document) { KURL new_url = entered_document->Url(); new_url.SetFragmentIdentifier(String()); SetURL(new_url); } cookie_url_ = entered_document->CookieURL(); } open(); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int SSL_library_init(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_cbc()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); #if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__)) EVP_add_cipher(EVP_rc4_hmac_md5()); #endif #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_cbc()); /* Not actually used for SSL/TLS but this makes PKCS#12 work * if an application only calls SSL_library_init(). */ EVP_add_cipher(EVP_rc2_40_cbc()); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_128_gcm()); EVP_add_cipher(EVP_aes_256_gcm()); #if 0 /* Disabled because of timing side-channel leaks. */ #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); #endif #endif #endif #ifndef OPENSSL_NO_CAMELLIA #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_256_cbc()); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_cbc()); #endif #ifndef OPENSSL_NO_MD5 EVP_add_digest(EVP_md5()); EVP_add_digest_alias(SN_md5,"ssl2-md5"); EVP_add_digest_alias(SN_md5,"ssl3-md5"); #endif #ifndef OPENSSL_NO_SHA EVP_add_digest(EVP_sha1()); /* RSA with sha1 */ EVP_add_digest_alias(SN_sha1,"ssl3-sha1"); EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA); #endif #ifndef OPENSSL_NO_SHA256 EVP_add_digest(EVP_sha224()); EVP_add_digest(EVP_sha256()); #endif #ifndef OPENSSL_NO_SHA512 EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); #endif #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA) EVP_add_digest(EVP_dss1()); /* DSA with sha1 */ EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2); EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1"); EVP_add_digest_alias(SN_dsaWithSHA1,"dss1"); #endif #ifndef OPENSSL_NO_ECDSA EVP_add_digest(EVP_ecdsa()); #endif /* If you want support for phased out ciphers, add the following */ #if 0 EVP_add_digest(EVP_sha()); EVP_add_digest(EVP_dss()); #endif #ifndef OPENSSL_NO_COMP /* This will initialise the built-in compression algorithms. The value returned is a STACK_OF(SSL_COMP), but that can be discarded safely */ (void)SSL_COMP_get_compression_methods(); #endif /* initialize cipher/digest methods table */ ssl_load_ciphers(); return(1); } CWE ID: CWE-310 Target: 1 Example 2: Code: static enum TIFFReadDirEntryErr TIFFReadDirEntryByteArray(TIFF* tif, TIFFDirEntry* direntry, uint8** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; uint8* data; switch (direntry->tdir_type) { case TIFF_ASCII: case TIFF_UNDEFINED: case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,1,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_ASCII: case TIFF_UNDEFINED: case TIFF_BYTE: *value=(uint8*)origdata; return(TIFFReadDirEntryErrOk); case TIFF_SBYTE: { int8* m; uint32 n; m=(int8*)origdata; for (n=0; n<count; n++) { err=TIFFReadDirEntryCheckRangeByteSbyte(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(uint8*)origdata; return(TIFFReadDirEntryErrOk); } } data=(uint8*)_TIFFmalloc(count); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_SHORT: { uint16* ma; uint8* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); err=TIFFReadDirEntryCheckRangeByteShort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; uint8* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); err=TIFFReadDirEntryCheckRangeByteSshort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_LONG: { uint32* ma; uint8* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); err=TIFFReadDirEntryCheckRangeByteLong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_SLONG: { int32* ma; uint8* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); err=TIFFReadDirEntryCheckRangeByteSlong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; uint8* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); err=TIFFReadDirEntryCheckRangeByteLong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_SLONG8: { int64* ma; uint8* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); err=TIFFReadDirEntryCheckRangeByteSlong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3) { if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) { kvm_mmu_sync_roots(vcpu); kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu); return 0; } if (is_long_mode(vcpu)) { if (cr3 & CR3_L_MODE_RESERVED_BITS) return 1; } else if (is_pae(vcpu) && is_paging(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) return 1; vcpu->arch.cr3 = cr3; __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail); kvm_mmu_new_cr3(vcpu); return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BrowserContextDestroyer::DestroyContext(BrowserContext* context) { CHECK(context->IsOffTheRecord() || !context->HasOffTheRecordContext()); content::BrowserContext::NotifyWillBeDestroyed(context); std::set<content::RenderProcessHost*> hosts; for (content::RenderProcessHost::iterator it = content::RenderProcessHost::AllHostsIterator(); !it.IsAtEnd(); it.Advance()) { content::RenderProcessHost* host = it.GetCurrentValue(); if (host->GetBrowserContext() != context) { continue; } hosts.insert(host); //// static } if (hosts.empty()) { delete context; } else { new BrowserContextDestroyer(context, hosts); } } CWE ID: CWE-20 Target: 1 Example 2: Code: int load_abrt_conf_file(const char *file, map_string_t *settings) { static const char *const base_directories[] = { DEFAULT_CONF_DIR, CONF_DIR, NULL }; return load_conf_file_from_dirs(file, base_directories, settings, /*skip key w/o values:*/ false); } 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: AviaryScheddPlugin::processJob(const char *key, const char *, int ) { PROC_ID id; ClassAd *jobAd; if (!IS_JOB(key)) return false; id = getProcByString(key); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Failed to parse key: %s - skipping\n", key); return false; } if (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) { dprintf(D_ALWAYS, "NOTICE: Failed to lookup ad for %s - maybe deleted\n", key); return false; } MyString submissionName; if (GetAttributeString(id.cluster, id.proc, ATTR_JOB_SUBMISSION, submissionName) < 0) { PROC_ID dagman; if (GetAttributeInt(id.cluster, id.proc, ATTR_DAGMAN_JOB_ID, &dagman.cluster) >= 0) { dagman.proc = 0; if (GetAttributeString(dagman.cluster, dagman.proc, ATTR_JOB_SUBMISSION, submissionName) < 0) { submissionName.sprintf("%s#%d", Name, dagman.cluster); } } else { submissionName.sprintf("%s#%d", Name, id.cluster); } MyString tmp; tmp += "\""; tmp += submissionName; tmp += "\""; SetAttribute(id.cluster, id.proc, ATTR_JOB_SUBMISSION, tmp.Value()); } return true; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ext4_show_options(struct seq_file *seq, struct vfsmount *vfs) { int def_errors; unsigned long def_mount_opts; struct super_block *sb = vfs->mnt_sb; struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; def_mount_opts = le32_to_cpu(es->s_default_mount_opts); def_errors = le16_to_cpu(es->s_errors); if (sbi->s_sb_block != 1) seq_printf(seq, ",sb=%llu", sbi->s_sb_block); if (test_opt(sb, MINIX_DF)) seq_puts(seq, ",minixdf"); if (test_opt(sb, GRPID) && !(def_mount_opts & EXT4_DEFM_BSDGROUPS)) seq_puts(seq, ",grpid"); if (!test_opt(sb, GRPID) && (def_mount_opts & EXT4_DEFM_BSDGROUPS)) seq_puts(seq, ",nogrpid"); if (sbi->s_resuid != EXT4_DEF_RESUID || le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID) { seq_printf(seq, ",resuid=%u", sbi->s_resuid); } if (sbi->s_resgid != EXT4_DEF_RESGID || le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID) { seq_printf(seq, ",resgid=%u", sbi->s_resgid); } if (test_opt(sb, ERRORS_RO)) { if (def_errors == EXT4_ERRORS_PANIC || def_errors == EXT4_ERRORS_CONTINUE) { seq_puts(seq, ",errors=remount-ro"); } } if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE) seq_puts(seq, ",errors=continue"); if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC) seq_puts(seq, ",errors=panic"); if (test_opt(sb, NO_UID32) && !(def_mount_opts & EXT4_DEFM_UID16)) seq_puts(seq, ",nouid32"); if (test_opt(sb, DEBUG) && !(def_mount_opts & EXT4_DEFM_DEBUG)) seq_puts(seq, ",debug"); if (test_opt(sb, OLDALLOC)) seq_puts(seq, ",oldalloc"); #ifdef CONFIG_EXT4_FS_XATTR if (test_opt(sb, XATTR_USER) && !(def_mount_opts & EXT4_DEFM_XATTR_USER)) seq_puts(seq, ",user_xattr"); if (!test_opt(sb, XATTR_USER) && (def_mount_opts & EXT4_DEFM_XATTR_USER)) { seq_puts(seq, ",nouser_xattr"); } #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL if (test_opt(sb, POSIX_ACL) && !(def_mount_opts & EXT4_DEFM_ACL)) seq_puts(seq, ",acl"); if (!test_opt(sb, POSIX_ACL) && (def_mount_opts & EXT4_DEFM_ACL)) seq_puts(seq, ",noacl"); #endif if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) { seq_printf(seq, ",commit=%u", (unsigned) (sbi->s_commit_interval / HZ)); } if (sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME) { seq_printf(seq, ",min_batch_time=%u", (unsigned) sbi->s_min_batch_time); } if (sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME) { seq_printf(seq, ",max_batch_time=%u", (unsigned) sbi->s_min_batch_time); } /* * We're changing the default of barrier mount option, so * let's always display its mount state so it's clear what its * status is. */ seq_puts(seq, ",barrier="); seq_puts(seq, test_opt(sb, BARRIER) ? "1" : "0"); if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) seq_puts(seq, ",journal_async_commit"); if (test_opt(sb, NOBH)) seq_puts(seq, ",nobh"); if (test_opt(sb, I_VERSION)) seq_puts(seq, ",i_version"); if (!test_opt(sb, DELALLOC)) seq_puts(seq, ",nodelalloc"); if (sbi->s_stripe) seq_printf(seq, ",stripe=%lu", sbi->s_stripe); /* * journal mode get enabled in different ways * So just print the value even if we didn't specify it */ if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) seq_puts(seq, ",data=journal"); else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) seq_puts(seq, ",data=ordered"); else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA) seq_puts(seq, ",data=writeback"); if (sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS) seq_printf(seq, ",inode_readahead_blks=%u", sbi->s_inode_readahead_blks); if (test_opt(sb, DATA_ERR_ABORT)) seq_puts(seq, ",data_err=abort"); if (test_opt(sb, NO_AUTO_DA_ALLOC)) seq_puts(seq, ",noauto_da_alloc"); if (test_opt(sb, DISCARD)) seq_puts(seq, ",discard"); if (test_opt(sb, NOLOAD)) seq_puts(seq, ",norecovery"); ext4_show_quota_options(seq, sb); return 0; } CWE ID: Target: 1 Example 2: Code: event_create(void) { int evhdl = eventfd(0, EFD_CLOEXEC); int *ret; if (evhdl == -1) { /* Linux uses -1 on error, Windows NULL. */ /* However, Linux does not return 0 on success either. */ return 0; } ret = (int *)mg_malloc(sizeof(int)); if (ret) { *ret = evhdl; } else { (void)close(evhdl); } return (void *)ret; } 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: CameraDeviceClient::CameraDeviceClient(const sp<CameraService>& cameraService, const sp<ICameraDeviceCallbacks>& remoteCallback, const String16& clientPackageName, int cameraId, int cameraFacing, int clientPid, uid_t clientUid, int servicePid) : Camera2ClientBase(cameraService, remoteCallback, clientPackageName, cameraId, cameraFacing, clientPid, clientUid, servicePid), mRequestIdCounter(0) { ATRACE_CALL(); ALOGI("CameraDeviceClient %d: Opened", cameraId); } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ar6000_create_ap_interface(struct ar6_softc *ar, char *ap_ifname) { struct net_device *dev; struct ar_virtual_interface *arApDev; dev = alloc_etherdev(sizeof(struct ar_virtual_interface)); if (dev == NULL) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: can't alloc etherdev\n")); return A_ERROR; } ether_setup(dev); init_netdev(dev, ap_ifname); if (register_netdev(dev)) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: register_netdev failed\n")); return A_ERROR; } arApDev = netdev_priv(dev); arApDev->arDev = ar; arApDev->arNetDev = dev; arApDev->arStaNetDev = ar->arNetDev; ar->arApDev = arApDev; arApNetDev = dev; /* Copy the MAC address */ memcpy(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN); return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoAttachShader( GLuint program_client_id, GLint shader_client_id) { Program* program = GetProgramInfoNotShader( program_client_id, "glAttachShader"); if (!program) { return; } Shader* shader = GetShaderInfoNotProgram(shader_client_id, "glAttachShader"); if (!shader) { return; } if (!program->AttachShader(shader_manager(), shader)) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glAttachShader", "can not attach more than one shader of the same type."); return; } api()->glAttachShaderFn(program->service_id(), shader->service_id()); } 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 struct sock *unix_create1(struct net *net, struct socket *sock, int kern) { struct sock *sk = NULL; struct unix_sock *u; atomic_long_inc(&unix_nr_socks); if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files()) goto out; sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern); if (!sk) goto out; sock_init_data(sock, sk); lockdep_set_class(&sk->sk_receive_queue.lock, &af_unix_sk_receive_queue_lock_key); sk->sk_write_space = unix_write_space; sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen; sk->sk_destruct = unix_sock_destructor; u = unix_sk(sk); u->path.dentry = NULL; u->path.mnt = NULL; spin_lock_init(&u->lock); atomic_long_set(&u->inflight, 0); INIT_LIST_HEAD(&u->link); mutex_init(&u->readlock); /* single task reading lock */ init_waitqueue_head(&u->peer_wait); unix_insert_socket(unix_sockets_unbound(sk), sk); out: if (sk == NULL) atomic_long_dec(&unix_nr_socks); else { local_bh_disable(); sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); local_bh_enable(); } return sk; } 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: kg_unseal(minor_status, context_handle, input_token_buffer, message_buffer, conf_state, qop_state, toktype) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_buffer_t input_token_buffer; gss_buffer_t message_buffer; int *conf_state; gss_qop_t *qop_state; int toktype; { krb5_gss_ctx_id_rec *ctx; unsigned char *ptr; unsigned int bodysize; int err; int toktype2; int vfyflags = 0; OM_uint32 ret; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } /* parse the token, leave the data in message_buffer, setting conf_state */ /* verify the header */ ptr = (unsigned char *) input_token_buffer->value; err = g_verify_token_header(ctx->mech_used, &bodysize, &ptr, -1, input_token_buffer->length, vfyflags); if (err) { *minor_status = err; return GSS_S_DEFECTIVE_TOKEN; } if (bodysize < 2) { *minor_status = (OM_uint32)G_BAD_TOK_HEADER; return GSS_S_DEFECTIVE_TOKEN; } toktype2 = load_16_be(ptr); ptr += 2; bodysize -= 2; switch (toktype2) { case KG2_TOK_MIC_MSG: case KG2_TOK_WRAP_MSG: case KG2_TOK_DEL_CTX: ret = gss_krb5int_unseal_token_v3(&ctx->k5_context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype); break; case KG_TOK_MIC_MSG: case KG_TOK_WRAP_MSG: case KG_TOK_DEL_CTX: ret = kg_unseal_v1(ctx->k5_context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype); break; default: *minor_status = (OM_uint32)G_BAD_TOK_HEADER; ret = GSS_S_DEFECTIVE_TOKEN; break; } if (ret != 0) save_error_info (*minor_status, ctx->k5_context); return ret; } CWE ID: Target: 1 Example 2: Code: static void esp_lower_irq(ESPState *s) { if (s->rregs[ESP_RSTAT] & STAT_INT) { s->rregs[ESP_RSTAT] &= ~STAT_INT; qemu_irq_lower(s->irq); trace_esp_lower_irq(); } } 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: gpc_unpc(Pixel *out, const Pixel *in, const Background *back) { (void)back; if (in->a <= 128) { out->r = out->g = out->b = 255; out->a = 0; } else { out->r = sRGB((double)in->r / in->a); out->g = sRGB((double)in->g / in->a); out->b = sRGB((double)in->b / in->a); out->a = u8d(in->a / 257.); } } 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 int misaligned_store(struct pt_regs *regs, __u32 opcode, int displacement_not_indexed, int width_shift) { /* Return -1 for a fault, 0 for OK */ int error; int srcreg; __u64 address; error = generate_and_check_address(regs, opcode, displacement_not_indexed, width_shift, &address); if (error < 0) { return error; } perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, address); srcreg = (opcode >> 4) & 0x3f; if (user_mode(regs)) { __u64 buffer; if (!access_ok(VERIFY_WRITE, (unsigned long) address, 1UL<<width_shift)) { return -1; } switch (width_shift) { case 1: *(__u16 *) &buffer = (__u16) regs->regs[srcreg]; break; case 2: *(__u32 *) &buffer = (__u32) regs->regs[srcreg]; break; case 3: buffer = regs->regs[srcreg]; break; default: printk("Unexpected width_shift %d in misaligned_store, PC=%08lx\n", width_shift, (unsigned long) regs->pc); break; } if (__copy_user((void *)(int)address, &buffer, (1 << width_shift)) > 0) { return -1; /* fault */ } } else { /* kernel mode - we can take short cuts since if we fault, it's a genuine bug */ __u64 val = regs->regs[srcreg]; switch (width_shift) { case 1: misaligned_kernel_word_store(address, val); break; case 2: asm ("stlo.l %1, 0, %0" : : "r" (val), "r" (address)); asm ("sthi.l %1, 3, %0" : : "r" (val), "r" (address)); break; case 3: asm ("stlo.q %1, 0, %0" : : "r" (val), "r" (address)); asm ("sthi.q %1, 7, %0" : : "r" (val), "r" (address)); break; default: printk("Unexpected width_shift %d in misaligned_store, PC=%08lx\n", width_shift, (unsigned long) regs->pc); break; } } return 0; } CWE ID: CWE-399 Target: 1 Example 2: Code: static int ln_cmp(const ASN1_OBJECT * const *a, const unsigned int *b) { return(strcmp((*a)->ln,nid_objs[*b].ln)); } 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: save_expand_strings(uschar **save_expand_nstring, int *save_expand_nlength) { int i; for (i = 0; i <= expand_nmax; i++) { save_expand_nstring[i] = expand_nstring[i]; save_expand_nlength[i] = expand_nlength[i]; } return expand_nmax; } 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: png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length) { png_alloc_size_t limit = PNG_UINT_31_MAX; # ifdef PNG_SET_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_malloc_max > 0 && png_ptr->user_chunk_malloc_max < limit) limit = png_ptr->user_chunk_malloc_max; # elif PNG_USER_CHUNK_MALLOC_MAX > 0 if (PNG_USER_CHUNK_MALLOC_MAX < limit) limit = PNG_USER_CHUNK_MALLOC_MAX; # endif if (png_ptr->chunk_name == png_IDAT) { png_alloc_size_t idat_limit = PNG_UINT_31_MAX; size_t row_factor = (png_ptr->width * png_ptr->channels * (png_ptr->bit_depth > 8? 2: 1) + 1 + (png_ptr->interlaced? 6: 0)); if (png_ptr->height > PNG_UINT_32_MAX/row_factor) idat_limit=PNG_UINT_31_MAX; else idat_limit = png_ptr->height * row_factor; row_factor = row_factor > 32566? 32566 : row_factor; idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */ idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX; limit = limit < idat_limit? idat_limit : limit; } if (length > limit) { png_debug2(0," length = %lu, limit = %lu", (unsigned long)length,(unsigned long)limit); png_chunk_error(png_ptr, "chunk data is too large"); } } CWE ID: CWE-190 Target: 1 Example 2: Code: static struct hlist_head *unix_sockets_unbound(void *addr) { unsigned long hash = (unsigned long)addr; hash ^= hash >> 16; hash ^= hash >> 8; hash %= UNIX_HASH_SIZE; return &unix_socket_table[UNIX_HASH_SIZE + hash]; } CWE ID: CWE-287 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebRuntimeFeatures::EnableMediaCapture(bool enable) { RuntimeEnabledFeatures::SetMediaCaptureEnabled(enable); } CWE ID: CWE-254 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 DoCanonicalizePathURL(const URLComponentSource<CHAR>& source, const Parsed& parsed, CanonOutput* output, Parsed* new_parsed) { bool success = CanonicalizeScheme(source.scheme, parsed.scheme, output, &new_parsed->scheme); new_parsed->username.reset(); new_parsed->password.reset(); new_parsed->host.reset(); new_parsed->port.reset(); success &= DoCanonicalizePathComponent<CHAR, UCHAR>( source.path, parsed.path, '\0', output, &new_parsed->path); success &= DoCanonicalizePathComponent<CHAR, UCHAR>( source.query, parsed.query, '?', output, &new_parsed->query); success &= DoCanonicalizePathComponent<CHAR, UCHAR>( source.ref, parsed.ref, '#', output, &new_parsed->ref); return success; } CWE ID: CWE-20 Target: 1 Example 2: Code: bool JSTestNamedConstructorOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor) { JSTestNamedConstructor* jsTestNamedConstructor = jsCast<JSTestNamedConstructor*>(handle.get().asCell()); if (jsTestNamedConstructor->impl()->hasPendingActivity()) return true; if (!isObservable(jsTestNamedConstructor)) return false; UNUSED_PARAM(visitor); return false; } 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: IntRect RenderLayerScrollableArea::rectForHorizontalScrollbar(const IntRect& borderBoxRect) const { if (!m_hBar) return IntRect(); const IntRect& scrollCorner = scrollCornerRect(); return IntRect(horizontalScrollbarStart(borderBoxRect.x()), borderBoxRect.maxY() - box().borderBottom() - m_hBar->height(), borderBoxRect.width() - (box().borderLeft() + box().borderRight()) - scrollCorner.width(), m_hBar->height()); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ide_dma_cb(void *opaque, int ret) { IDEState *s = opaque; int n; int64_t sector_num; bool stay_active = false; if (ret == -ECANCELED) { return; } if (ret < 0) { int op = IDE_RETRY_DMA; if (s->dma_cmd == IDE_DMA_READ) op |= IDE_RETRY_READ; else if (s->dma_cmd == IDE_DMA_TRIM) op |= IDE_RETRY_TRIM; if (ide_handle_rw_error(s, -ret, op)) { return; } } n = s->io_buffer_size >> 9; if (n > s->nsector) { /* The PRDs were longer than needed for this request. Shorten them so * we don't get a negative remainder. The Active bit must remain set * after the request completes. */ n = s->nsector; stay_active = true; } sector_num = ide_get_sector(s); if (n > 0) { assert(s->io_buffer_size == s->sg.size); dma_buf_commit(s, s->io_buffer_size); sector_num += n; ide_set_sector(s, sector_num); s->nsector -= n; } /* end of transfer ? */ if (s->nsector == 0) { s->status = READY_STAT | SEEK_STAT; ide_set_irq(s->bus); goto eot; } /* launch next transfer */ n = s->nsector; s->io_buffer_index = 0; s->io_buffer_size = n * 512; if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) == 0) { /* The PRDs were too short. Reset the Active bit, but don't raise an * interrupt. */ s->status = READY_STAT | SEEK_STAT; goto eot; } printf("ide_dma_cb: sector_num=%" PRId64 " n=%d, cmd_cmd=%d\n", sector_num, n, s->dma_cmd); #endif if ((s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) && !ide_sect_range_ok(s, sector_num, n)) { ide_dma_error(s); return; } switch (s->dma_cmd) { case IDE_DMA_READ: s->bus->dma->aiocb = dma_blk_read(s->blk, &s->sg, sector_num, ide_dma_cb, s); break; case IDE_DMA_WRITE: s->bus->dma->aiocb = dma_blk_write(s->blk, &s->sg, sector_num, ide_dma_cb, s); break; case IDE_DMA_TRIM: s->bus->dma->aiocb = dma_blk_io(s->blk, &s->sg, sector_num, ide_issue_trim, ide_dma_cb, s, DMA_DIRECTION_TO_DEVICE); break; } return; eot: if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) { block_acct_done(blk_get_stats(s->blk), &s->acct); } ide_set_inactive(s, stay_active); } CWE ID: CWE-399 Target: 1 Example 2: Code: void AutofillPopupViewViews::DrawAutofillEntry(gfx::Canvas* canvas, int index, const gfx::Rect& entry_rect) { canvas->FillRect( entry_rect, GetNativeTheme()->GetSystemColor( controller_->GetBackgroundColorIDForRow(index))); const bool is_rtl = controller_->IsRTL(); const int text_align = is_rtl ? gfx::Canvas::TEXT_ALIGN_RIGHT : gfx::Canvas::TEXT_ALIGN_LEFT; gfx::Rect value_rect = entry_rect; value_rect.Inset(AutofillPopupLayoutModel::kEndPadding, 0); bool icon_on_the_right = !is_rtl; int x_align_left = icon_on_the_right ? value_rect.right() : value_rect.x(); int row_height = controller_->layout_model().GetRowBounds(index).height(); const gfx::ImageSkia image = controller_->layout_model().GetIconImage(index); if (!image.isNull()) { int icon_y = entry_rect.y() + (row_height - image.height()) / 2; int icon_x_align_left = icon_on_the_right ? x_align_left - image.width() : x_align_left; canvas->DrawImageInt(image, icon_x_align_left, icon_y); x_align_left = icon_x_align_left + (is_rtl ? image.width() + AutofillPopupLayoutModel::kIconPadding : -AutofillPopupLayoutModel::kIconPadding); } const int value_width = gfx::GetStringWidth( controller_->GetElidedValueAt(index), controller_->layout_model().GetValueFontListForRow(index)); int value_x_align_left = is_rtl ? value_rect.right() - value_width : value_rect.x(); canvas->DrawStringRectWithFlags( controller_->GetElidedValueAt(index), controller_->layout_model().GetValueFontListForRow(index), GetNativeTheme()->GetSystemColor( controller_->layout_model().GetValueFontColorIDForRow(index)), gfx::Rect(value_x_align_left, value_rect.y(), value_width, value_rect.height()), text_align); if (!controller_->GetSuggestionAt(index).label.empty()) { const int label_width = gfx::GetStringWidth( controller_->GetElidedLabelAt(index), controller_->layout_model().GetLabelFontListForRow(index)); int label_x_align_left = x_align_left + (is_rtl ? 0 : -label_width); canvas->DrawStringRectWithFlags( controller_->GetElidedLabelAt(index), controller_->layout_model().GetLabelFontListForRow(index), GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_ResultsTableDimmedText), gfx::Rect(label_x_align_left, entry_rect.y(), label_width, entry_rect.height()), text_align); } } 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 ssize_t aio_setup_vectored_rw(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t *len, struct iovec **iovec, bool compat) { ssize_t ret; *nr_segs = *len; #ifdef CONFIG_COMPAT if (compat) ret = compat_rw_copy_check_uvector(rw, (struct compat_iovec __user *)buf, *nr_segs, UIO_FASTIOV, *iovec, iovec); else #endif ret = rw_copy_check_uvector(rw, (struct iovec __user *)buf, *nr_segs, UIO_FASTIOV, *iovec, iovec); if (ret < 0) return ret; /* len now reflect bytes instead of segs */ *len = ret; return 0; } 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 multipath_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct multipath *m = (struct multipath *) ti->private; struct block_device *bdev = NULL; fmode_t mode = 0; unsigned long flags; int r = 0; spin_lock_irqsave(&m->lock, flags); if (!m->current_pgpath) __choose_pgpath(m, 0); if (m->current_pgpath) { bdev = m->current_pgpath->path.dev->bdev; mode = m->current_pgpath->path.dev->mode; } if (m->queue_io) r = -EAGAIN; else if (!bdev) r = -EIO; spin_unlock_irqrestore(&m->lock, flags); return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg); } CWE ID: CWE-264 Target: 1 Example 2: Code: static void voidMethodDefaultNullStringStringArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::voidMethodDefaultNullStringStringArgMethod(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: void EC_GROUP_clear_free(EC_GROUP *group) { if (!group) return; if (group->meth->group_clear_finish != 0) group->meth->group_clear_finish(group); else if (group->meth->group_finish != 0) group->meth->group_finish(group); EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_POINT_clear_free(group->generator); BN_clear_free(&group->order); OPENSSL_cleanse(group, sizeof *group); OPENSSL_free(group); } CWE ID: CWE-320 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 process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops) { while (elements-- > 0) { zval *key, *data, **old_data; ALLOC_INIT_ZVAL(key); if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); return 0; } if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) { zval_dtor(key); FREE_ZVAL(key); return 0; } ALLOC_INIT_ZVAL(data); if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); zval_dtor(data); FREE_ZVAL(data); return 0; } if (!objprops) { switch (Z_TYPE_P(key)) { case IS_LONG: if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL); break; case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL); break; } } else { /* object properties should include no integers */ convert_to_string(key); zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof data, NULL); } if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } } CWE ID: Target: 1 Example 2: Code: static ssize_t k90_store_macro_mode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; struct usb_interface *usbif = to_usb_interface(dev->parent); struct usb_device *usbdev = interface_to_usbdev(usbif); __u16 value; if (strncmp(buf, "SW", 2) == 0) value = K90_MACRO_MODE_SW; else if (strncmp(buf, "HW", 2) == 0) value = K90_MACRO_MODE_HW; else return -EINVAL; ret = usb_control_msg(usbdev, usb_sndctrlpipe(usbdev, 0), K90_REQUEST_MACRO_MODE, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, value, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (ret != 0) { dev_warn(dev, "Failed to set macro mode.\n"); return ret; } return count; } 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: selftest_sign_2048 (gcry_sexp_t pkey, gcry_sexp_t skey) { static const char sample_data[] = "(data (flags pkcs1)" " (hash sha256 #11223344556677889900aabbccddeeff" /**/ "102030405060708090a0b0c0d0f01121#))"; static const char sample_data_bad[] = "(data (flags pkcs1)" " (hash sha256 #11223344556677889900aabbccddeeff" /**/ "802030405060708090a0b0c0d0f01121#))"; const char *errtxt = NULL; gcry_error_t err; gcry_sexp_t data = NULL; gcry_sexp_t data_bad = NULL; gcry_sexp_t sig = NULL; /* raw signature data reference */ const char ref_data[] = "6252a19a11e1d5155ed9376036277193d644fa239397fff03e9b92d6f86415d6" "d30da9273775f290e580d038295ff8ff89522becccfa6ae870bf76b76df402a8" "54f69347e3db3de8e1e7d4dada281ec556810c7a8ecd0b5f51f9b1c0e7aa7557" "61aa2b8ba5f811304acc6af0eca41fe49baf33bf34eddaf44e21e036ac7f0b68" "03cdef1c60021fb7b5b97ebacdd88ab755ce29af568dbc5728cc6e6eff42618d" "62a0386ca8beed46402bdeeef29b6a3feded906bace411a06a39192bf516ae10" "67e4320fa8ea113968525f4574d022a3ceeaafdc41079efe1f22cc94bf59d8d3" "328085da9674857db56de5978a62394aab48aa3b72e23a1b16260cfd9daafe65"; gcry_mpi_t ref_mpi = NULL; gcry_mpi_t sig_mpi = NULL; err = sexp_sscan (&data, NULL, sample_data, strlen (sample_data)); if (!err) err = sexp_sscan (&data_bad, NULL, sample_data_bad, strlen (sample_data_bad)); if (err) { errtxt = "converting data failed"; goto leave; } err = _gcry_pk_sign (&sig, data, skey); if (err) { errtxt = "signing failed"; goto leave; } err = _gcry_mpi_scan(&ref_mpi, GCRYMPI_FMT_HEX, ref_data, 0, NULL); if (err) { errtxt = "converting ref_data to mpi failed"; goto leave; } err = _gcry_sexp_extract_param(sig, "sig-val!rsa", "s", &sig_mpi, NULL); if (err) { errtxt = "extracting signature data failed"; goto leave; } if (mpi_cmp (sig_mpi, ref_mpi)) { errtxt = "signature does not match reference data"; goto leave; } err = _gcry_pk_verify (sig, data, pkey); if (err) { errtxt = "verify failed"; goto leave; } err = _gcry_pk_verify (sig, data_bad, pkey); if (gcry_err_code (err) != GPG_ERR_BAD_SIGNATURE) { errtxt = "bad signature not detected"; goto leave; } leave: sexp_release (sig); sexp_release (data_bad); sexp_release (data); _gcry_mpi_release (ref_mpi); _gcry_mpi_release (sig_mpi); return errtxt; } 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: virtual InputMethodDescriptors* GetActiveInputMethods() { return GetInputMethodDescriptorsForTesting(); } CWE ID: CWE-399 Target: 1 Example 2: Code: rpc_xdr_buf_init(struct xdr_buf *buf, void *start, size_t len) { buf->head[0].iov_base = start; buf->head[0].iov_len = len; buf->tail[0].iov_len = 0; buf->page_len = 0; buf->flags = 0; buf->len = 0; buf->buflen = len; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool omx_venc::dev_free_buf(void *buf_addr,unsigned port) { return handle->venc_free_buf(buf_addr,port); } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL ) ); } CWE ID: CWE-200 Target: 1 Example 2: Code: JsVar *jswrap_graphics_createSDL(int width, int height) { if (width<=0 || height<=0 || width>32767 || height>32767) { jsExceptionHere(JSET_ERROR, "Invalid Size"); return 0; } JsVar *parent = jspNewObject(0, "Graphics"); if (!parent) return 0; // low memory JsGraphics gfx; graphicsStructInit(&gfx); gfx.data.type = JSGRAPHICSTYPE_SDL; gfx.graphicsVar = parent; gfx.data.width = (unsigned short)width; gfx.data.height = (unsigned short)height; gfx.data.bpp = 32; lcdInit_SDL(&gfx); graphicsSetVar(&gfx); return parent; } 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: rpl_print(netdissect_options *ndo, const struct icmp6_hdr *hdr, const u_char *bp, u_int length) { int secured = hdr->icmp6_code & 0x80; int basecode= hdr->icmp6_code & 0x7f; if(secured) { ND_PRINT((ndo, ", (SEC) [worktodo]")); /* XXX * the next header pointer needs to move forward to * skip the secure part. */ return; } else { ND_PRINT((ndo, ", (CLR)")); } switch(basecode) { case ND_RPL_DAG_IS: ND_PRINT((ndo, "DODAG Information Solicitation")); if(ndo->ndo_vflag) { } break; case ND_RPL_DAG_IO: ND_PRINT((ndo, "DODAG Information Object")); if(ndo->ndo_vflag) { rpl_dio_print(ndo, bp, length); } break; case ND_RPL_DAO: ND_PRINT((ndo, "Destination Advertisement Object")); if(ndo->ndo_vflag) { rpl_dao_print(ndo, bp, length); } break; case ND_RPL_DAO_ACK: ND_PRINT((ndo, "Destination Advertisement Object Ack")); if(ndo->ndo_vflag) { rpl_daoack_print(ndo, bp, length); } break; default: ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code)); break; } return; #if 0 trunc: ND_PRINT((ndo," [|truncated]")); return; #endif } 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 FindBarController::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { FindManager* find_manager = tab_contents_->GetFindManager(); if (type == NotificationType::FIND_RESULT_AVAILABLE) { if (Source<TabContents>(source).ptr() == tab_contents_->tab_contents()) { UpdateFindBarForCurrentResult(); if (find_manager->find_result().final_update() && find_manager->find_result().number_of_matches() == 0) { const string16& last_search = find_manager->previous_find_text(); const string16& current_search = find_manager->find_text(); if (last_search.find(current_search) != 0) find_bar_->AudibleAlert(); } } } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { NavigationController* source_controller = Source<NavigationController>(source).ptr(); if (source_controller == &tab_contents_->controller()) { NavigationController::LoadCommittedDetails* commit_details = Details<NavigationController::LoadCommittedDetails>(details).ptr(); PageTransition::Type transition_type = commit_details->entry->transition_type(); if (find_bar_->IsFindBarVisible()) { if (PageTransition::StripQualifier(transition_type) != PageTransition::RELOAD) { EndFindSession(kKeepSelection); } else { find_manager->set_find_op_aborted(true); } } } } } CWE ID: CWE-20 Target: 1 Example 2: Code: bt_status_t btif_dut_mode_configure(uint8_t enable) { BTIF_TRACE_DEBUG("%s", __FUNCTION__); if (!stack_manager_get_interface()->get_stack_is_running()) { BTIF_TRACE_ERROR("btif_dut_mode_configure : Bluetooth not enabled"); return BT_STATUS_NOT_READY; } btif_dut_mode = enable; if (enable == 1) { BTA_EnableTestMode(); } else { BTA_DisableTestMode(); } return BT_STATUS_SUCCESS; } 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: static ssize_t fuse_fill_write_pages(struct fuse_req *req, struct address_space *mapping, struct iov_iter *ii, loff_t pos) { struct fuse_conn *fc = get_fuse_conn(mapping->host); unsigned offset = pos & (PAGE_CACHE_SIZE - 1); size_t count = 0; int err; req->in.argpages = 1; req->page_descs[0].offset = offset; do { size_t tmp; struct page *page; pgoff_t index = pos >> PAGE_CACHE_SHIFT; size_t bytes = min_t(size_t, PAGE_CACHE_SIZE - offset, iov_iter_count(ii)); bytes = min_t(size_t, bytes, fc->max_write - count); again: err = -EFAULT; if (iov_iter_fault_in_readable(ii, bytes)) break; err = -ENOMEM; page = grab_cache_page_write_begin(mapping, index, 0); if (!page) break; if (mapping_writably_mapped(mapping)) flush_dcache_page(page); tmp = iov_iter_copy_from_user_atomic(page, ii, offset, bytes); flush_dcache_page(page); if (!tmp) { unlock_page(page); page_cache_release(page); bytes = min(bytes, iov_iter_single_seg_count(ii)); goto again; } err = 0; req->pages[req->num_pages] = page; req->page_descs[req->num_pages].length = tmp; req->num_pages++; iov_iter_advance(ii, tmp); count += tmp; pos += tmp; offset += tmp; if (offset == PAGE_CACHE_SIZE) offset = 0; if (!fc->big_writes) break; } while (iov_iter_count(ii) && count < fc->max_write && req->num_pages < req->max_pages && offset == 0); return count > 0 ? count : err; } 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 pdf_load_pages_kids(FILE *fp, pdf_t *pdf) { int i, id, dummy; char *buf, *c; long start, sz; start = ftell(fp); /* Load all kids for all xref tables (versions) */ for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].version && (pdf->xrefs[i].end != 0)) { fseek(fp, pdf->xrefs[i].start, SEEK_SET); while (SAFE_F(fp, (fgetc(fp) != 't'))) ; /* Iterate to trailer */ /* Get root catalog */ sz = pdf->xrefs[i].end - ftell(fp); buf = malloc(sz + 1); SAFE_E(fread(buf, 1, sz, fp), sz, "Failed to load /Root.\n"); buf[sz] = '\0'; if (!(c = strstr(buf, "/Root"))) { free(buf); continue; } /* Jump to catalog (root) */ id = atoi(c + strlen("/Root") + 1); free(buf); buf = get_object(fp, id, &pdf->xrefs[i], NULL, &dummy); if (!buf || !(c = strstr(buf, "/Pages"))) { free(buf); continue; } /* Start at the first Pages obj and get kids */ id = atoi(c + strlen("/Pages") + 1); load_kids(fp, id, &pdf->xrefs[i]); free(buf); } } fseek(fp, start, SEEK_SET); } CWE ID: CWE-787 Target: 1 Example 2: Code: kex_from_blob(struct sshbuf *m, struct kex **kexp) { struct kex *kex; int r; if ((kex = calloc(1, sizeof(struct kex))) == NULL || (kex->my = sshbuf_new()) == NULL || (kex->peer = sshbuf_new()) == NULL) { r = SSH_ERR_ALLOC_FAIL; goto out; } if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 || (r = sshbuf_get_u32(m, &kex->we_need)) != 0 || (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 || (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 || (r = sshbuf_get_stringb(m, kex->my)) != 0 || (r = sshbuf_get_stringb(m, kex->peer)) != 0 || (r = sshbuf_get_u32(m, &kex->flags)) != 0 || (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 || (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0) goto out; kex->server = 1; kex->done = 1; r = 0; out: if (r != 0 || kexp == NULL) { if (kex != NULL) { if (kex->my != NULL) sshbuf_free(kex->my); if (kex->peer != NULL) sshbuf_free(kex->peer); free(kex); } if (kexp != NULL) *kexp = NULL; } else { *kexp = kex; } return r; } 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 HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { if (name == nameAttr) { removeFromRadioButtonGroup(); m_name = value; addToRadioButtonGroup(); HTMLTextFormControlElement::parseAttribute(name, value); } else if (name == autocompleteAttr) { if (equalIgnoringCase(value, "off")) m_autocomplete = Off; else { if (value.isEmpty()) m_autocomplete = Uninitialized; else m_autocomplete = On; } } else if (name == typeAttr) updateType(); else if (name == valueAttr) { if (!hasDirtyValue()) { updatePlaceholderVisibility(false); setNeedsStyleRecalc(); } setFormControlValueMatchesRenderer(false); setNeedsValidityCheck(); m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress; m_inputType->valueAttributeChanged(); } else if (name == checkedAttr) { if (!m_parsingInProgress && m_reflectsCheckedAttribute) { setChecked(!value.isNull()); m_reflectsCheckedAttribute = true; } } else if (name == maxlengthAttr) parseMaxLengthAttribute(value); else if (name == sizeAttr) { int oldSize = m_size; int valueAsInteger = value.toInt(); m_size = valueAsInteger > 0 ? valueAsInteger : defaultSize; if (m_size != oldSize && renderer()) renderer()->setNeedsLayoutAndPrefWidthsRecalc(); } else if (name == altAttr) m_inputType->altAttributeChanged(); else if (name == srcAttr) m_inputType->srcAttributeChanged(); else if (name == usemapAttr || name == accesskeyAttr) { } else if (name == onsearchAttr) { setAttributeEventListener(eventNames().searchEvent, createAttributeEventListener(this, name, value)); } else if (name == resultsAttr) { int oldResults = m_maxResults; m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1; if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0)) lazyReattachIfAttached(); setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::ResultsAttribute); } else if (name == incrementalAttr) { setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::IncrementalAttribute); } else if (name == minAttr) { m_inputType->minOrMaxAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::MinAttribute); } else if (name == maxAttr) { m_inputType->minOrMaxAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::MaxAttribute); } else if (name == multipleAttr) { m_inputType->multipleAttributeChanged(); setNeedsValidityCheck(); } else if (name == stepAttr) { m_inputType->stepAttributeChanged(); setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::StepAttribute); } else if (name == patternAttr) { setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::PatternAttribute); } else if (name == precisionAttr) { setNeedsValidityCheck(); UseCounter::count(document(), UseCounter::PrecisionAttribute); } else if (name == disabledAttr) { HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->disabledAttributeChanged(); } else if (name == readonlyAttr) { HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->readonlyAttributeChanged(); } else if (name == listAttr) { m_hasNonEmptyList = !value.isEmpty(); if (m_hasNonEmptyList) { resetListAttributeTargetObserver(); listAttributeTargetChanged(); } UseCounter::count(document(), UseCounter::ListAttribute); } #if ENABLE(INPUT_SPEECH) else if (name == webkitspeechAttr) { if (renderer()) { detach(); m_inputType->destroyShadowSubtree(); m_inputType->createShadowSubtree(); if (!attached()) attach(); } else { m_inputType->destroyShadowSubtree(); m_inputType->createShadowSubtree(); } setFormControlValueMatchesRenderer(false); setNeedsStyleRecalc(); UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute); } else if (name == onwebkitspeechchangeAttr) setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value)); #endif else if (name == webkitdirectoryAttr) { HTMLTextFormControlElement::parseAttribute(name, value); UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute); } else HTMLTextFormControlElement::parseAttribute(name, value); m_inputType->attributeChanged(); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void copyStereo16( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i]; *dst++ = src[1][i]; } } CWE ID: CWE-119 Target: 1 Example 2: Code: void WebGL2RenderingContextBase::framebufferTextureLayer(GLenum target, GLenum attachment, WebGLTexture* texture, GLint level, GLint layer) { if (isContextLost() || !ValidateFramebufferFuncParameters( "framebufferTextureLayer", target, attachment)) return; if (texture && !texture->Validate(ContextGroup(), this)) { SynthesizeGLError(GL_INVALID_VALUE, "framebufferTextureLayer", "no texture or texture not from this context"); return; } GLenum textarget = texture ? texture->GetTarget() : 0; if (texture) { if (textarget != GL_TEXTURE_3D && textarget != GL_TEXTURE_2D_ARRAY) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "invalid texture type"); return; } if (!ValidateTexFuncLayer("framebufferTextureLayer", textarget, layer)) return; if (!ValidateTexFuncLevel("framebufferTextureLayer", textarget, level)) return; } WebGLFramebuffer* framebuffer_binding = GetFramebufferBinding(target); if (!framebuffer_binding || !framebuffer_binding->Object()) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "no framebuffer bound"); return; } if (framebuffer_binding && framebuffer_binding->Opaque()) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "opaque framebuffer bound"); return; } framebuffer_binding->SetAttachmentForBoundFramebuffer( target, attachment, textarget, texture, level, layer); ApplyStencilTest(); } 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: user_update_local_account_property (User *user, gboolean local) { accounts_user_set_local_account (ACCOUNTS_USER (user), local); } CWE ID: CWE-22 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 MagickBooleanType CheckMemoryOverflow(const size_t count, const size_t quantum) { size_t size; size=count*quantum; if ((count == 0) || (quantum != (size/count))) { errno=ENOMEM; return(MagickTrue); } return(MagickFalse); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void ux500_hash_shutdown(struct platform_device *pdev) { struct resource *res = NULL; struct hash_device_data *device_data; device_data = platform_get_drvdata(pdev); if (!device_data) { dev_err(&pdev->dev, "%s: platform_get_drvdata() failed!\n", __func__); return; } /* Check that the device is free */ spin_lock(&device_data->ctx_lock); /* current_ctx allocates a device, NULL = unallocated */ if (!device_data->current_ctx) { if (down_trylock(&driver_data.device_allocation)) dev_dbg(&pdev->dev, "%s: Cryp still in use! Shutting down anyway...\n", __func__); /** * (Allocate the device) * Need to set this to non-null (dummy) value, * to avoid usage if context switching. */ device_data->current_ctx++; } spin_unlock(&device_data->ctx_lock); /* Remove the device from the list */ if (klist_node_attached(&device_data->list_node)) klist_remove(&device_data->list_node); /* If this was the last device, remove the services */ if (list_empty(&driver_data.device_list.k_list)) ahash_algs_unregister_all(device_data); iounmap(device_data->base); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (res) release_mem_region(res->start, resource_size(res)); if (hash_disable_power(device_data, false)) dev_err(&pdev->dev, "%s: hash_disable_power() failed\n", __func__); } 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 LoginHtmlDialog::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type.value == NotificationType::LOAD_COMPLETED_MAIN_FRAME); if (bubble_frame_view_) bubble_frame_view_->StopThrobber(); } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int propagate_one(struct mount *m) { struct mount *child; int type; /* skip ones added by this propagate_mnt() */ if (IS_MNT_NEW(m)) return 0; /* skip if mountpoint isn't covered by it */ if (!is_subdir(mp->m_dentry, m->mnt.mnt_root)) return 0; if (peers(m, last_dest)) { type = CL_MAKE_SHARED; } else { struct mount *n, *p; for (n = m; ; n = p) { p = n->mnt_master; if (p == dest_master || IS_MNT_MARKED(p)) { while (last_dest->mnt_master != p) { last_source = last_source->mnt_master; last_dest = last_source->mnt_parent; } if (!peers(n, last_dest)) { last_source = last_source->mnt_master; last_dest = last_source->mnt_parent; } break; } } type = CL_SLAVE; /* beginning of peer group among the slaves? */ if (IS_MNT_SHARED(m)) type |= CL_MAKE_SHARED; } /* Notice when we are propagating across user namespaces */ if (m->mnt_ns->user_ns != user_ns) type |= CL_UNPRIVILEGED; child = copy_tree(last_source, last_source->mnt.mnt_root, type); if (IS_ERR(child)) return PTR_ERR(child); child->mnt.mnt_flags &= ~MNT_LOCKED; mnt_set_mountpoint(m, mp, child); last_dest = m; last_source = child; if (m->mnt_master != dest_master) { read_seqlock_excl(&mount_lock); SET_MNT_MARK(m->mnt_master); read_sequnlock_excl(&mount_lock); } hlist_add_head(&child->mnt_hash, list); return 0; } CWE ID: Target: 1 Example 2: Code: void GLES2DecoderImpl::DoVertexAttrib2f(GLuint index, GLfloat v0, GLfloat v1) { VertexAttribManager::VertexAttribInfo* info = vertex_attrib_manager_->GetVertexAttribInfo(index); if (!info) { SetGLError(GL_INVALID_VALUE, "glVertexAttrib2f: index out of range"); return; } VertexAttribManager::VertexAttribInfo::Vec4 value; value.v[0] = v0; value.v[1] = v1; value.v[2] = 0.0f; value.v[3] = 1.0f; info->set_value(value); glVertexAttrib2f(index, v0, v1); } 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 WebMediaPlayerImpl::DidGetOpaqueResponseFromServiceWorker() const { if (data_source_) return data_source_->DidGetOpaqueResponseViaServiceWorker(); return false; } 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: my_object_error_get_type (void) { static GType etype = 0; if (etype == 0) { static const GEnumValue values[] = { ENUM_ENTRY (MY_OBJECT_ERROR_FOO, "Foo"), ENUM_ENTRY (MY_OBJECT_ERROR_BAR, "Bar"), { 0, 0, 0 } }; etype = g_enum_register_static ("MyObjectError", values); } return etype; } CWE ID: CWE-264 Target: 1 Example 2: Code: void DownloadController::AcquireFileAccessPermission( WebContents* web_contents, const DownloadControllerBase::AcquireFileAccessPermissionCallback& cb) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(web_contents); ui::ViewAndroid* view_android = ViewAndroidHelper::FromWebContents(web_contents)->GetViewAndroid(); if (!view_android) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(cb, false)); return; } ui::WindowAndroid* window_android = view_android->GetWindowAndroid(); if (window_android && HasFileAccessPermission(window_android)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(cb, true)); return; } intptr_t callback_id = reinterpret_cast<intptr_t>( new DownloadControllerBase::AcquireFileAccessPermissionCallback(cb)); ChromeDownloadDelegate::FromWebContents(web_contents)-> RequestFileAccess(callback_id); } 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: String referrerPolicy(net::URLRequest::ReferrerPolicy referrer_policy) { switch (referrer_policy) { case net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE: return Network::Request::ReferrerPolicyEnum::NoReferrerWhenDowngrade; case net::URLRequest:: REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN: return Network::Request::ReferrerPolicyEnum::StrictOriginWhenCrossOrigin; case net::URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN: return Network::Request::ReferrerPolicyEnum::OriginWhenCrossOrigin; case net::URLRequest::NEVER_CLEAR_REFERRER: return Network::Request::ReferrerPolicyEnum::Origin; case net::URLRequest::ORIGIN: return Network::Request::ReferrerPolicyEnum::Origin; case net::URLRequest::NO_REFERRER: return Network::Request::ReferrerPolicyEnum::NoReferrer; default: break; } NOTREACHED(); return Network::Request::ReferrerPolicyEnum::NoReferrerWhenDowngrade; } 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 CreateTwoTabs(bool focus_tab_strip, LifecycleUnit** first_lifecycle_unit, LifecycleUnit** second_lifecycle_unit) { if (focus_tab_strip) source_->SetFocusedTabStripModelForTesting(tab_strip_model_.get()); task_runner_->FastForwardBy(kShortDelay); auto time_before_first_tab = NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)) .WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *first_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_TRUE(IsFocused(*first_lifecycle_unit)); } else { EXPECT_EQ(time_before_first_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); } })); std::unique_ptr<content::WebContents> first_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_first_web_contents = first_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(first_web_contents), true); testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_first_web_contents)); task_runner_->FastForwardBy(kShortDelay); auto time_before_second_tab = NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)) .WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *second_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_EQ(time_before_second_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); EXPECT_TRUE(IsFocused(*second_lifecycle_unit)); } else { EXPECT_EQ(time_before_first_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); EXPECT_EQ(time_before_second_tab, (*second_lifecycle_unit)->GetLastFocusedTime()); } })); std::unique_ptr<content::WebContents> second_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_second_web_contents = second_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(second_web_contents), true); testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_second_web_contents)); raw_first_web_contents->WasHidden(); } CWE ID: Target: 1 Example 2: Code: static size_t in_get_buffer_size(const struct audio_stream *stream) { UNUSED(stream); FNLOG(); return 320; } 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: m_authenticate(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *agent_p = NULL; struct Client *saslserv_p = NULL; /* They really should use CAP for their own sake. */ if(!IsCapable(source_p, CLICAP_SASL)) return 0; if (strlen(client_p->id) == 3) { exit_client(client_p, client_p, client_p, "Mixing client and server protocol"); return 0; } saslserv_p = find_named_client(ConfigFileEntry.sasl_service); if (saslserv_p == NULL || !IsService(saslserv_p)) { sendto_one(source_p, form_str(ERR_SASLABORTED), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(source_p->localClient->sasl_complete) { *source_p->localClient->sasl_agent = '\0'; source_p->localClient->sasl_complete = 0; } if(strlen(parv[1]) > 400) { sendto_one(source_p, form_str(ERR_SASLTOOLONG), me.name, EmptyString(source_p->name) ? "*" : source_p->name); return 0; } if(!*source_p->id) { /* Allocate a UID. */ strcpy(source_p->id, generate_uid()); add_to_id_hash(source_p->id, source_p); } if(*source_p->localClient->sasl_agent) agent_p = find_id(source_p->localClient->sasl_agent); if(agent_p == NULL) { sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s H %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, source_p->host, source_p->sockhost); if (!strcmp(parv[1], "EXTERNAL") && source_p->certfp != NULL) sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1], source_p->certfp); else sendto_one(saslserv_p, ":%s ENCAP %s SASL %s %s S %s", me.id, saslserv_p->servptr->name, source_p->id, saslserv_p->id, parv[1]); rb_strlcpy(source_p->localClient->sasl_agent, saslserv_p->id, IDLEN); } else sendto_one(agent_p, ":%s ENCAP %s SASL %s %s C %s", me.id, agent_p->servptr->name, source_p->id, agent_p->id, parv[1]); source_p->localClient->sasl_out++; return 0; } CWE ID: CWE-285 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 macvlan_common_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; dev->netdev_ops = &macvlan_netdev_ops; dev->destructor = free_netdev; dev->header_ops = &macvlan_hard_header_ops, dev->ethtool_ops = &macvlan_ethtool_ops; } CWE ID: CWE-264 Target: 1 Example 2: Code: SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, struct smb2_file_full_ea_info *buf, int len) { return send_set_info(xid, tcon, persistent_fid, volatile_fid, current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE, 0, 1, (void **)&buf, &len); } 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: GDataEntry* GDataDirectory::FromDocumentEntry( GDataDirectory* parent, DocumentEntry* doc, GDataDirectoryService* directory_service) { DCHECK(doc->is_folder()); GDataDirectory* dir = new GDataDirectory(parent, directory_service); dir->title_ = UTF16ToUTF8(doc->title()); dir->SetBaseNameFromTitle(); dir->file_info_.last_modified = doc->updated_time(); dir->file_info_.last_accessed = doc->updated_time(); dir->file_info_.creation_time = doc->published_time(); dir->resource_id_ = doc->resource_id(); dir->content_url_ = doc->content_url(); dir->deleted_ = doc->deleted(); const Link* edit_link = doc->GetLinkByType(Link::EDIT); DCHECK(edit_link) << "No edit link for dir " << dir->title_; if (edit_link) dir->edit_url_ = edit_link->href(); const Link* parent_link = doc->GetLinkByType(Link::PARENT); if (parent_link) dir->parent_resource_id_ = ExtractResourceId(parent_link->href()); const Link* upload_link = doc->GetLinkByType(Link::RESUMABLE_CREATE_MEDIA); if (upload_link) dir->upload_url_ = upload_link->href(); return dir; } 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: OMX_ERRORTYPE SoftAACEncoder2::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = (OMX_AUDIO_AACPROFILETYPE) mAACProfile; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; switch (mSBRMode) { case 1: // sbr on switch (mSBRRatio) { case 0: aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; case 1: aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 2: aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; default: ALOGE("invalid SBR ratio %d", mSBRRatio); TRESPASS(); } break; case 0: // sbr off case -1: // sbr undefined aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; default: ALOGE("invalid SBR mode %d", mSBRMode); TRESPASS(); } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { 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 = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int in_standby(struct audio_stream *stream) { struct stream_in *in = (struct stream_in *)stream; struct audio_device *adev = in->dev; int status; ALOGV("%s: enter", __func__); pthread_mutex_lock(&adev->lock_inputs); status = in_standby_l(in); pthread_mutex_unlock(&adev->lock_inputs); ALOGV("%s: exit: status(%d)", __func__, status); return status; } 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: bool semaphore_try_wait(semaphore_t *semaphore) { assert(semaphore != NULL); assert(semaphore->fd != INVALID_FD); int flags = fcntl(semaphore->fd, F_GETFL); if (flags == -1) { LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno)); return false; } if (fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK) == -1) { LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno)); return false; } eventfd_t value; if (eventfd_read(semaphore->fd, &value) == -1) return false; if (fcntl(semaphore->fd, F_SETFL, flags) == -1) LOG_ERROR("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno)); return true; } 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: static void show_object(struct object *object, struct strbuf *path, const char *last, void *data) { struct bitmap *base = data; bitmap_set(base, find_object_pos(object->oid.hash)); mark_as_seen(object); } CWE ID: CWE-119 Target: 1 Example 2: Code: void WallpaperManagerBase::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kUsersWallpaperInfo); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void VoidMethodDOMStringOrArrayBufferOrArrayBufferViewArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodDOMStringOrArrayBufferOrArrayBufferViewArg"); TestObject* impl = V8TestObject::ToImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } StringOrArrayBufferOrArrayBufferView arg; V8StringOrArrayBufferOrArrayBufferView::ToImpl(info.GetIsolate(), info[0], arg, UnionTypeConversionMode::kNotNullable, exception_state); if (exception_state.HadException()) return; impl->voidMethodDOMStringOrArrayBufferOrArrayBufferViewArg(arg); } 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: BOOL rdp_decrypt(rdpRdp* rdp, STREAM* s, int length, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; if (stream_get_left(s) < 12) return FALSE; stream_read_UINT16(s, len); /* 0x10 */ stream_read_BYTE(s, version); /* 0x1 */ stream_read_BYTE(s, pad); sig = s->p; stream_seek(s, 8); /* signature */ length -= 12; if (!security_fips_decrypt(s->p, length, rdp)) { printf("FATAL: cannot decrypt\n"); return FALSE; /* TODO */ } if (!security_fips_check_signature(s->p, length - pad, sig, rdp)) { printf("FATAL: invalid packet signature\n"); return FALSE; /* TODO */ } /* is this what needs adjusting? */ s->size -= pad; return TRUE; } if (stream_get_left(s) < 8) return FALSE; stream_read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); security_decrypt(s->p, length, rdp); if (securityFlags & SEC_SECURE_CHECKSUM) security_salted_mac_signature(rdp, s->p, length, FALSE, cmac); else security_mac_signature(rdp, s->p, length, cmac); if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { printf("WARNING: invalid packet signature\n"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ } return TRUE; } CWE ID: CWE-476 Target: 1 Example 2: Code: static void xhci_stall_ep(XHCITransfer *xfer) { XHCIState *xhci = xfer->xhci; XHCISlot *slot = &xhci->slots[xfer->slotid-1]; XHCIEPContext *epctx = slot->eps[xfer->epid-1]; uint32_t err; XHCIStreamContext *sctx; if (epctx->nr_pstreams) { sctx = xhci_find_stream(epctx, xfer->streamid, &err); if (sctx == NULL) { return; } sctx->ring.dequeue = xfer->trbs[0].addr; sctx->ring.ccs = xfer->trbs[0].ccs; xhci_set_ep_state(xhci, epctx, sctx, EP_HALTED); } else { epctx->ring.dequeue = xfer->trbs[0].addr; epctx->ring.ccs = xfer->trbs[0].ccs; xhci_set_ep_state(xhci, epctx, NULL, EP_HALTED); } } 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 __ext4_error(struct super_block *sb, const char *function, unsigned int line, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: comm %s: %pV\n", sb->s_id, function, line, current->comm, &vaf); va_end(args); ext4_handle_error(sb); } 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: void btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) { UNUSED(p_org_set); BTIF_TRACE_DEBUG("entering %s",__FUNCTION__); for (const list_node_t *node = list_begin(soc_queue); node != list_end(soc_queue); node = list_next(node)) { btif_hl_soc_cb_t *p_scb = list_node(node); if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) { if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) { BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ"); btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx, p_scb->mcl_idx, p_scb->mdl_idx); assert(p_dcb != NULL); if (p_dcb->p_tx_pkt) { BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been" " sent tx_size=%d", p_dcb->tx_size); btif_hl_free_buf((void **) &p_dcb->p_tx_pkt); } p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu); if (p_dcb) { int r = (int)recv(p_scb->socket_id[1], p_dcb->p_tx_pkt, p_dcb->mtu, MSG_DONTWAIT); if (r > 0) { BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r); p_dcb->tx_size = r; BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size ); BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size); } else { BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r); BTA_HlDchClose(p_dcb->mdl_handle); } } } } } if (list_is_empty(soc_queue)) BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty"); BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__); } CWE ID: CWE-284 Target: 1 Example 2: Code: static uint16_t *plist_utf8_to_utf16(char *unistr, long size, long *items_read, long *items_written) { uint16_t *outbuf = (uint16_t*)malloc(((size*2)+1)*sizeof(uint16_t)); int p = 0; long i = 0; unsigned char c0; unsigned char c1; unsigned char c2; unsigned char c3; uint32_t w; while (i < size) { c0 = unistr[i]; c1 = (i < size-1) ? unistr[i+1] : 0; c2 = (i < size-2) ? unistr[i+2] : 0; c3 = (i < size-3) ? unistr[i+3] : 0; if ((c0 >= 0xF0) && (i < size-3) && (c1 >= 0x80) && (c2 >= 0x80) && (c3 >= 0x80)) { w = ((((c0 & 7) << 18) + ((c1 & 0x3F) << 12) + ((c2 & 0x3F) << 6) + (c3 & 0x3F)) & 0x1FFFFF) - 0x010000; outbuf[p++] = 0xD800 + (w >> 10); outbuf[p++] = 0xDC00 + (w & 0x3FF); i+=4; } else if ((c0 >= 0xE0) && (i < size-2) && (c1 >= 0x80) && (c2 >= 0x80)) { outbuf[p++] = ((c2 & 0x3F) + ((c1 & 3) << 6)) + (((c1 >> 2) & 15) << 8) + ((c0 & 15) << 12); i+=3; } else if ((c0 >= 0xC0) && (i < size-1) && (c1 >= 0x80)) { outbuf[p++] = ((c1 & 0x3F) + ((c0 & 3) << 6)) + (((c0 >> 2) & 7) << 8); i+=2; } else if (c0 < 0x80) { outbuf[p++] = c0; i+=1; } else { PLIST_BIN_ERR("%s: invalid utf8 sequence in string at index %lu\n", __func__, i); break; } } if (items_read) { *items_read = i; } if (items_written) { *items_written = p; } outbuf[p] = 0; return outbuf; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int udp_v6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; struct udphdr *uh; struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct flowi6 *fl6 = &inet->cork.fl.u.ip6; int err = 0; int is_udplite = IS_UDPLITE(sk); __wsum csum = 0; /* Grab the skbuff where UDP header space exists. */ if ((skb = skb_peek(&sk->sk_write_queue)) == NULL) goto out; /* * Create a UDP header */ uh = udp_hdr(skb); uh->source = fl6->fl6_sport; uh->dest = fl6->fl6_dport; uh->len = htons(up->len); uh->check = 0; if (is_udplite) csum = udplite_csum_outgoing(sk, skb); else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr, up->len); goto send; } else csum = udp_csum_outgoing(sk, skb); /* add protocol-dependent pseudo-header */ uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr, up->len, fl6->flowi6_proto, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; send: err = ip6_push_pending_frames(sk); if (err) { if (err == -ENOBUFS && !inet6_sk(sk)->recverr) { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); err = 0; } } else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_OUTDATAGRAMS, is_udplite); out: up->len = 0; up->pending = 0; return err; } 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 nfs4_return_incompatible_delegation(struct inode *inode, mode_t open_flags) { struct nfs_delegation *delegation; rcu_read_lock(); delegation = rcu_dereference(NFS_I(inode)->delegation); if (delegation == NULL || (delegation->type & open_flags) == open_flags) { rcu_read_unlock(); return; } rcu_read_unlock(); nfs_inode_return_delegation(inode); } CWE ID: Target: 1 Example 2: Code: static int snd_compr_next_track(struct snd_compr_stream *stream) { int retval; /* only a running stream can transition to next track */ if (stream->runtime->state != SNDRV_PCM_STATE_RUNNING) return -EPERM; /* you can signal next track isf this is intended to be a gapless stream * and current track metadata is set */ if (stream->metadata_set == false) return -EPERM; retval = stream->ops->trigger(stream, SND_COMPR_TRIGGER_NEXT_TRACK); if (retval != 0) return retval; stream->metadata_set = false; stream->next_track = true; 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: void PrintPreviewDialogController::SaveInitiatorTitle( WebContents* preview_dialog) { WebContents* initiator = GetInitiator(preview_dialog); if (initiator && preview_dialog->GetWebUI()) { PrintPreviewUI* print_preview_ui = static_cast<PrintPreviewUI*>( preview_dialog->GetWebUI()->GetController()); print_preview_ui->SetInitiatorTitle( PrintViewManager::FromWebContents(initiator)->RenderSourceName()); } } CWE ID: CWE-254 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 DevToolsDomainHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) {} CWE ID: CWE-20 Target: 1 Example 2: Code: static int ext4_load_journal(struct super_block *sb, struct ext4_super_block *es, unsigned long journal_devnum) { journal_t *journal; unsigned int journal_inum = le32_to_cpu(es->s_journal_inum); dev_t journal_dev; int err = 0; int really_read_only; BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)); if (journal_devnum && journal_devnum != le32_to_cpu(es->s_journal_dev)) { ext4_msg(sb, KERN_INFO, "external journal device major/minor " "numbers have changed"); journal_dev = new_decode_dev(journal_devnum); } else journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev)); really_read_only = bdev_read_only(sb->s_bdev); /* * Are we loading a blank journal or performing recovery after a * crash? For recovery, we need to check in advance whether we * can get read-write access to the device. */ if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { if (sb->s_flags & MS_RDONLY) { ext4_msg(sb, KERN_INFO, "INFO: recovery " "required on readonly filesystem"); if (really_read_only) { ext4_msg(sb, KERN_ERR, "write access " "unavailable, cannot proceed"); return -EROFS; } ext4_msg(sb, KERN_INFO, "write access will " "be enabled during recovery"); } } if (journal_inum && journal_dev) { ext4_msg(sb, KERN_ERR, "filesystem has both journal " "and inode journals!"); return -EINVAL; } if (journal_inum) { if (!(journal = ext4_get_journal(sb, journal_inum))) return -EINVAL; } else { if (!(journal = ext4_get_dev_journal(sb, journal_dev))) return -EINVAL; } if (!(journal->j_flags & JBD2_BARRIER)) ext4_msg(sb, KERN_INFO, "barriers disabled"); if (!really_read_only && test_opt(sb, UPDATE_JOURNAL)) { err = jbd2_journal_update_format(journal); if (err) { ext4_msg(sb, KERN_ERR, "error updating journal"); jbd2_journal_destroy(journal); return err; } } if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) err = jbd2_journal_wipe(journal, !really_read_only); if (!err) err = jbd2_journal_load(journal); if (err) { ext4_msg(sb, KERN_ERR, "error loading journal"); jbd2_journal_destroy(journal); return err; } EXT4_SB(sb)->s_journal = journal; ext4_clear_journal_err(sb, es); if (journal_devnum && journal_devnum != le32_to_cpu(es->s_journal_dev)) { es->s_journal_dev = cpu_to_le32(journal_devnum); /* Make sure we flush the recovery flag to disk. */ ext4_commit_super(sb, 1); } return 0; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int uvesafb_helper_start(void) { char *envp[] = { "HOME=/", "PATH=/sbin:/bin", NULL, }; char *argv[] = { v86d_path, NULL, }; return call_usermodehelper(v86d_path, argv, envp, UMH_WAIT_PROC); } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void TIFFGetProperties(TIFF *tiff,Image *image,ExceptionInfo *exception) { char message[MagickPathExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text,exception); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text,exception); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text,exception); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text,exception); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text,exception); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text,exception); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text,exception); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text,exception); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message,exception); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text,exception); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text,exception); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message,exception); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MagickPathExtent) count=MagickPathExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message,exception); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE", exception); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE",exception); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK",exception); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MagickPathExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message,exception); } } CWE ID: CWE-476 Target: 1 Example 2: Code: int perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); perf_event_enable(event); return 0; } 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 pin_remove(struct fs_pin *pin) { spin_lock(&pin_lock); hlist_del(&pin->m_list); hlist_del(&pin->s_list); spin_unlock(&pin_lock); spin_lock_irq(&pin->wait.lock); pin->done = 1; wake_up_locked(&pin->wait); spin_unlock_irq(&pin->wait.lock); } 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 __be32 nfsacld_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd_attrstat *resp) { struct inode *inode; svc_fh *fh; __be32 nfserr = 0; int error; dprintk("nfsd: SETACL(2acl) %s\n", SVCFH_fmt(&argp->fh)); fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (nfserr) goto out; inode = d_inode(fh->fh_dentry); if (!IS_POSIXACL(inode) || !inode->i_op->set_acl) { error = -EOPNOTSUPP; goto out_errno; } error = fh_want_write(fh); if (error) goto out_errno; error = inode->i_op->set_acl(inode, argp->acl_access, ACL_TYPE_ACCESS); if (error) goto out_drop_write; error = inode->i_op->set_acl(inode, argp->acl_default, ACL_TYPE_DEFAULT); if (error) goto out_drop_write; fh_drop_write(fh); nfserr = fh_getattr(fh, &resp->stat); out: /* argp->acl_{access,default} may have been allocated in nfssvc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); return nfserr; out_drop_write: fh_drop_write(fh); out_errno: nfserr = nfserrno(error); goto out; } CWE ID: CWE-284 Target: 1 Example 2: Code: GLuint GetVertexArrayServiceID(GLuint client_id, ClientServiceMap<GLuint, GLuint>* id_map) { return id_map->GetServiceIDOrInvalid(client_id); } 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 bool blit_is_unsafe(struct CirrusVGAState *s) { /* should be the case, see cirrus_bitblt_start */ assert(s->cirrus_blt_width > 0); assert(s->cirrus_blt_height > 0); if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch, s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) { return true; } return false; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() { DCHECK(main_message_loop_proxy_->BelongsToCurrentThread()); RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL; } CWE ID: CWE-399 Target: 1 Example 2: Code: void Browser::OnWindowDidShow() { if (window_has_shown_) return; window_has_shown_ = true; startup_metric_utils::RecordBrowserWindowDisplay(base::TimeTicks::Now()); if (!is_type_tabbed() || window_->IsMinimized()) return; GlobalErrorService* service = GlobalErrorServiceFactory::GetForProfile(profile()); GlobalError* error = service->GetFirstGlobalErrorWithBubbleView(); if (error) error->ShowBubbleView(this); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __unqueue_futex(struct futex_q *q) { struct futex_hash_bucket *hb; if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr)) || WARN_ON(plist_node_empty(&q->list))) return; hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock); plist_del(&q->list, &hb->chain); } 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 CoordinatorImpl::RegisterClientProcess( mojom::ClientProcessPtr client_process_ptr, mojom::ProcessType process_type) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); mojom::ClientProcess* client_process = client_process_ptr.get(); client_process_ptr.set_connection_error_handler( base::BindOnce(&CoordinatorImpl::UnregisterClientProcess, base::Unretained(this), client_process)); auto identity = GetClientIdentityForCurrentRequest(); auto client_info = std::make_unique<ClientInfo>( std::move(identity), std::move(client_process_ptr), process_type); auto iterator_and_inserted = clients_.emplace(client_process, std::move(client_info)); DCHECK(iterator_and_inserted.second); } CWE ID: CWE-416 Target: 1 Example 2: Code: static int mp_startup(struct sb_uart_state *state, int init_hw) { struct sb_uart_info *info = state->info; struct sb_uart_port *port = state->port; unsigned long page; int retval = 0; if (info->flags & UIF_INITIALIZED) return 0; if (info->tty) set_bit(TTY_IO_ERROR, &info->tty->flags); if (port->type == PORT_UNKNOWN) return 0; if (!info->xmit.buf) { page = get_zeroed_page(GFP_KERNEL); if (!page) return -ENOMEM; info->xmit.buf = (unsigned char *) page; uart_circ_clear(&info->xmit); } retval = port->ops->startup(port); if (retval == 0) { if (init_hw) { mp_change_speed(state, NULL); if (info->tty->termios.c_cflag & CBAUD) uart_set_mctrl(port, TIOCM_RTS | TIOCM_DTR); } info->flags |= UIF_INITIALIZED; clear_bit(TTY_IO_ERROR, &info->tty->flags); } if (retval && capable(CAP_SYS_ADMIN)) retval = 0; return retval; } 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 WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host, const base::string16& message, const base::string16& default_prompt, const GURL& frame_url, JavaScriptDialogType dialog_type, IPC::Message* reply_msg) { bool suppress_this_message = ShowingInterstitialPage() || !delegate_ || delegate_->ShouldSuppressDialogs(this) || !delegate_->GetJavaScriptDialogManager(this); if (!suppress_this_message) { is_showing_javascript_dialog_ = true; dialog_manager_ = delegate_->GetJavaScriptDialogManager(this); dialog_manager_->RunJavaScriptDialog( this, frame_url, dialog_type, message, default_prompt, base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, false), &suppress_this_message); } if (suppress_this_message) { OnDialogClosed(render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, true, false, base::string16()); } } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen) { uint8_t optlen, i; ND_TCHECK(*option); if (*option >= 32) { ND_TCHECK(*(option+1)); optlen = *(option +1); if (optlen < 2) { if (*option >= 128) ND_PRINT((ndo, "CCID option %u optlen too short", *option)); else ND_PRINT((ndo, "%s optlen too short", tok2str(dccp_option_values, "Option %u", *option))); return 0; } } else optlen = 1; if (hlen < optlen) { if (*option >= 128) ND_PRINT((ndo, "CCID option %u optlen goes past header length", *option)); else ND_PRINT((ndo, "%s optlen goes past header length", tok2str(dccp_option_values, "Option %u", *option))); return 0; } ND_TCHECK2(*option, optlen); if (*option >= 128) { ND_PRINT((ndo, "CCID option %d", *option)); switch (optlen) { case 4: ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2))); break; case 6: ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2))); break; default: break; } } else { ND_PRINT((ndo, "%s", tok2str(dccp_option_values, "Option %u", *option))); switch (*option) { case 32: case 33: case 34: case 35: if (optlen < 3) { ND_PRINT((ndo, " optlen too short")); return optlen; } if (*(option + 2) < 10){ ND_PRINT((ndo, " %s", dccp_feature_nums[*(option + 2)])); for (i = 0; i < optlen - 3; i++) ND_PRINT((ndo, " %d", *(option + 3 + i))); } break; case 36: if (optlen > 2) { ND_PRINT((ndo, " 0x")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; case 37: for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, " %d", *(option + 2 + i))); break; case 38: if (optlen > 2) { ND_PRINT((ndo, " 0x")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; case 39: if (optlen > 2) { ND_PRINT((ndo, " 0x")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; case 40: if (optlen > 2) { ND_PRINT((ndo, " 0x")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; case 41: if (optlen == 4) ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2))); else ND_PRINT((ndo, " optlen != 4")); break; case 42: if (optlen == 4) ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2))); else ND_PRINT((ndo, " optlen != 4")); break; case 43: if (optlen == 6) ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2))); else if (optlen == 4) ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2))); else ND_PRINT((ndo, " optlen != 4 or 6")); break; case 44: if (optlen > 2) { ND_PRINT((ndo, " ")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; } } return optlen; trunc: ND_PRINT((ndo, "%s", tstr)); return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: size_t get_camera_metadata_data_capacity(const camera_metadata_t *metadata) { return metadata->data_capacity; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual status_t configureVideoTunnelMode( node_id node, OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync, native_handle_t **sidebandHandle ) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeInt32(portIndex); data.writeInt32((int32_t)tunneled); data.writeInt32(audioHwSync); remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply); status_t err = reply.readInt32(); if (sidebandHandle) { *sidebandHandle = (native_handle_t *)reply.readNativeHandle(); } 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: long long VideoTrack::GetWidth() const { return m_width; } CWE ID: CWE-119 Target: 1 Example 2: Code: int SpdyProxyClientSocket::DoLoop(int last_io_result) { DCHECK_NE(next_state_, STATE_DISCONNECTED); int rv = last_io_result; do { State state = next_state_; next_state_ = STATE_DISCONNECTED; switch (state) { case STATE_GENERATE_AUTH_TOKEN: DCHECK_EQ(OK, rv); rv = DoGenerateAuthToken(); break; case STATE_GENERATE_AUTH_TOKEN_COMPLETE: rv = DoGenerateAuthTokenComplete(rv); break; case STATE_SEND_REQUEST: DCHECK_EQ(OK, rv); net_log_.BeginEvent(NetLog::TYPE_HTTP_TRANSACTION_TUNNEL_SEND_REQUEST); rv = DoSendRequest(); break; case STATE_SEND_REQUEST_COMPLETE: net_log_.EndEventWithNetErrorCode( NetLog::TYPE_HTTP_TRANSACTION_TUNNEL_SEND_REQUEST, rv); rv = DoSendRequestComplete(rv); if (rv >= 0 || rv == ERR_IO_PENDING) { net_log_.BeginEvent( NetLog::TYPE_HTTP_TRANSACTION_TUNNEL_READ_HEADERS); } break; case STATE_READ_REPLY_COMPLETE: rv = DoReadReplyComplete(rv); net_log_.EndEventWithNetErrorCode( NetLog::TYPE_HTTP_TRANSACTION_TUNNEL_READ_HEADERS, rv); break; default: NOTREACHED() << "bad state"; rv = ERR_UNEXPECTED; break; } } while (rv != ERR_IO_PENDING && next_state_ != STATE_DISCONNECTED && next_state_ != STATE_OPEN); return rv; } 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: static int compat_table_info(const struct ebt_table_info *info, struct compat_ebt_replace *newinfo) { unsigned int size = info->entries_size; const void *entries = info->entries; newinfo->entries_size = size; xt_compat_init_offsets(NFPROTO_BRIDGE, info->nentries); return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info, entries, newinfo); } CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height) { const int w = 8; const int ix = ox >> (16 + shift); const int iy = oy >> (16 + shift); const int oxs = ox >> 4; const int oys = oy >> 4; const int dxxs = dxx >> 4; const int dxys = dxy >> 4; const int dyxs = dyx >> 4; const int dyys = dyy >> 4; const uint16_t r4[4] = { r, r, r, r }; const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys }; const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys }; const uint64_t shift2 = 2 * shift; #define MAX_STRIDE 4096U #define MAX_H 8U uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE]; int x, y; const int dxw = (dxx - (1 << (16 + shift))) * (w - 1); const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); const int dxh = dxy * (h - 1); const int dyw = dyx * (w - 1); int need_emu = (unsigned) ix >= width - w || (unsigned) iy >= height - h; if ( // non-constant fullpel offset (3% of blocks) ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) || (dxx | dxy | dyx | dyy) & 15 || (need_emu && (h > MAX_H || stride > MAX_STRIDE))) { ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy * stride; if (need_emu) { ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height); src = edge_buf; } __asm__ volatile ( "movd %0, %%mm6 \n\t" "pxor %%mm7, %%mm7 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" :: "r" (1 << shift)); for (x = 0; x < w; x += 4) { uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0), oxs - dxys + dxxs * (x + 1), oxs - dxys + dxxs * (x + 2), oxs - dxys + dxxs * (x + 3) }; uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0), oys - dyys + dyxs * (x + 1), oys - dyys + dyxs * (x + 2), oys - dyys + dyxs * (x + 3) }; for (y = 0; y < h; y++) { __asm__ volatile ( "movq %0, %%mm4 \n\t" "movq %1, %%mm5 \n\t" "paddw %2, %%mm4 \n\t" "paddw %3, %%mm5 \n\t" "movq %%mm4, %0 \n\t" "movq %%mm5, %1 \n\t" "psrlw $12, %%mm4 \n\t" "psrlw $12, %%mm5 \n\t" : "+m" (*dx4), "+m" (*dy4) : "m" (*dxy4), "m" (*dyy4)); __asm__ volatile ( "movq %%mm6, %%mm2 \n\t" "movq %%mm6, %%mm1 \n\t" "psubw %%mm4, %%mm2 \n\t" "psubw %%mm5, %%mm1 \n\t" "movq %%mm2, %%mm0 \n\t" "movq %%mm4, %%mm3 \n\t" "pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy) "pmullw %%mm5, %%mm3 \n\t" // dx * dy "pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy "pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy) "movd %4, %%mm5 \n\t" "movd %3, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy "pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy "movd %2, %%mm5 \n\t" "movd %1, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy) "pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy) "paddw %5, %%mm1 \n\t" "paddw %%mm3, %%mm2 \n\t" "paddw %%mm1, %%mm0 \n\t" "paddw %%mm2, %%mm0 \n\t" "psrlw %6, %%mm0 \n\t" "packuswb %%mm0, %%mm0 \n\t" "movd %%mm0, %0 \n\t" : "=m" (dst[x + y * stride]) : "m" (src[0]), "m" (src[1]), "m" (src[stride]), "m" (src[stride + 1]), "m" (*r4), "m" (shift2)); src += stride; } src += 4 - h * stride; } } CWE ID: CWE-125 Target: 1 Example 2: Code: ProcXvShmPutImage(ClientPtr client) { return BadImplementation; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int tls1_set_server_sigalgs(SSL *s) { int al; size_t i; /* Clear any shared sigtnature algorithms */ if (s->cert->shared_sigalgs) { OPENSSL_free(s->cert->shared_sigalgs); s->cert->shared_sigalgs = NULL; } /* Clear certificate digests and validity flags */ for (i = 0; i < SSL_PKEY_NUM; i++) { s->cert->pkeys[i].valid_flags = 0; } /* If sigalgs received process it. */ if (s->cert->peer_sigalgs) { if (!tls1_process_sigalgs(s)) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE); al = SSL_AD_INTERNAL_ERROR; goto err; } /* Fatal error is no shared signature algorithms */ if (!s->cert->shared_sigalgs) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, SSL_R_NO_SHARED_SIGATURE_ALGORITHMS); al = SSL_AD_ILLEGAL_PARAMETER; goto err; } } else ssl_cert_set_default_md(s->cert); return 1; err: ssl3_send_alert(s, SSL3_AL_FATAL, al); return 0; } 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 aac_sync(uint64_t state, AACAC3ParseContext *hdr_info, int *need_next_header, int *new_frame_start) { GetBitContext bits; AACADTSHeaderInfo hdr; int size; union { uint64_t u64; uint8_t u8[8]; } tmp; tmp.u64 = av_be2ne64(state); init_get_bits(&bits, tmp.u8+8-AAC_ADTS_HEADER_SIZE, AAC_ADTS_HEADER_SIZE * 8); if ((size = avpriv_aac_parse_header(&bits, &hdr)) < 0) return 0; *need_next_header = 0; *new_frame_start = 1; hdr_info->sample_rate = hdr.sample_rate; hdr_info->channels = ff_mpeg4audio_channels[hdr.chan_config]; hdr_info->samples = hdr.samples; hdr_info->bit_rate = hdr.bit_rate; return size; } CWE ID: CWE-125 Target: 1 Example 2: Code: hook_command_build_completion (struct t_hook_command *hook_command) { int i, j, k, length, num_items; struct t_weelist *list; char *pos_completion, *pos_double_pipe, *pos_start, *pos_end; char **items, *last_space, *ptr_template; /* split templates using "||" as separator */ hook_command->cplt_num_templates = 1; pos_completion = hook_command->completion; while ((pos_double_pipe = strstr (pos_completion, "||")) != NULL) { hook_command->cplt_num_templates++; pos_completion = pos_double_pipe + 2; } hook_command->cplt_templates = malloc (hook_command->cplt_num_templates * sizeof (*hook_command->cplt_templates)); for (i = 0; i < hook_command->cplt_num_templates; i++) { hook_command->cplt_templates[i] = NULL; } pos_completion = hook_command->completion; i = 0; while (pos_completion) { pos_double_pipe = strstr (pos_completion, "||"); if (!pos_double_pipe) pos_double_pipe = pos_completion + strlen (pos_completion); pos_start = pos_completion; pos_end = pos_double_pipe - 1; if (pos_end < pos_start) { hook_command->cplt_templates[i] = strdup (""); } else { while (pos_start[0] == ' ') { pos_start++; } pos_end = pos_double_pipe - 1; while ((pos_end > pos_start) && (pos_end[0] == ' ')) { pos_end--; } hook_command->cplt_templates[i] = string_strndup (pos_start, pos_end - pos_start + 1); } i++; if (!pos_double_pipe[0]) pos_completion = NULL; else pos_completion = pos_double_pipe + 2; } /* for each template, split/count args */ hook_command->cplt_templates_static = malloc (hook_command->cplt_num_templates * sizeof (*hook_command->cplt_templates_static)); hook_command->cplt_template_num_args = malloc (hook_command->cplt_num_templates * sizeof (*hook_command->cplt_template_num_args)); hook_command->cplt_template_args = malloc (hook_command->cplt_num_templates * sizeof (*hook_command->cplt_template_args)); hook_command->cplt_template_num_args_concat = 0; for (i = 0; i < hook_command->cplt_num_templates; i++) { /* * build static part of template: it's first argument(s) which does not * contain "%" or "|" */ last_space = NULL; ptr_template = hook_command->cplt_templates[i]; while (ptr_template && ptr_template[0]) { if (ptr_template[0] == ' ') { last_space = ptr_template; break; } else if ((ptr_template[0] == '%') || (ptr_template[0] == '|')) break; ptr_template = utf8_next_char (ptr_template); } if (last_space) { last_space--; while (last_space > hook_command->cplt_templates[i]) { if (last_space[0] != ' ') break; } if (last_space < hook_command->cplt_templates[i]) last_space = NULL; else last_space++; } if (last_space) hook_command->cplt_templates_static[i] = string_strndup (hook_command->cplt_templates[i], last_space - hook_command->cplt_templates[i]); else hook_command->cplt_templates_static[i] = strdup (hook_command->cplt_templates[i]); /* build arguments for each template */ hook_command->cplt_template_args[i] = string_split (hook_command->cplt_templates[i], " ", 0, 0, &(hook_command->cplt_template_num_args[i])); if (hook_command->cplt_template_num_args[i] > hook_command->cplt_template_num_args_concat) hook_command->cplt_template_num_args_concat = hook_command->cplt_template_num_args[i]; } /* * build strings with concatentaion of items from different templates * for each argument: these strings will be used when completing argument * if we can't find which template to use (for example for first argument) */ if (hook_command->cplt_template_num_args_concat == 0) hook_command->cplt_template_args_concat = NULL; else { hook_command->cplt_template_args_concat = malloc (hook_command->cplt_template_num_args_concat * sizeof (*hook_command->cplt_template_args_concat)); list = weelist_new (); for (i = 0; i < hook_command->cplt_template_num_args_concat; i++) { /* first compute length */ length = 1; for (j = 0; j < hook_command->cplt_num_templates; j++) { if (i < hook_command->cplt_template_num_args[j]) length += strlen (hook_command->cplt_template_args[j][i]) + 1; } /* alloc memory */ hook_command->cplt_template_args_concat[i] = malloc (length); if (hook_command->cplt_template_args_concat[i]) { /* concatene items with "|" as separator */ weelist_remove_all (list); hook_command->cplt_template_args_concat[i][0] = '\0'; for (j = 0; j < hook_command->cplt_num_templates; j++) { if (i < hook_command->cplt_template_num_args[j]) { items = string_split (hook_command->cplt_template_args[j][i], "|", 0, 0, &num_items); for (k = 0; k < num_items; k++) { if (!weelist_search (list, items[k])) { if (hook_command->cplt_template_args_concat[i][0]) strcat (hook_command->cplt_template_args_concat[i], "|"); strcat (hook_command->cplt_template_args_concat[i], items[k]); weelist_add (list, items[k], WEECHAT_LIST_POS_END, NULL); } } string_free_split (items); } } } } weelist_free (list); } } 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: Shader* CreateShader( GLuint client_id, GLuint service_id, GLenum shader_type) { return shader_manager()->CreateShader( client_id, service_id, shader_type); } 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 rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) return -EMSGSIZE; return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: static uint64_t ahci_mem_read_32(void *opaque, hwaddr addr) { AHCIState *s = opaque; uint32_t val = 0; if (addr < AHCI_GENERIC_HOST_CONTROL_REGS_MAX_ADDR) { switch (addr) { case HOST_CAP: val = s->control_regs.cap; break; case HOST_CTL: val = s->control_regs.ghc; break; case HOST_IRQ_STAT: val = s->control_regs.irqstatus; break; case HOST_PORTS_IMPL: val = s->control_regs.impl; break; case HOST_VERSION: val = s->control_regs.version; break; } DPRINTF(-1, "(addr 0x%08X), val 0x%08X\n", (unsigned) addr, val); } else if ((addr >= AHCI_PORT_REGS_START_ADDR) && (addr < (AHCI_PORT_REGS_START_ADDR + (s->ports * AHCI_PORT_ADDR_OFFSET_LEN)))) { val = ahci_port_read(s, (addr - AHCI_PORT_REGS_START_ADDR) >> 7, addr & AHCI_PORT_ADDR_OFFSET_MASK); } return val; } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int _mkp_stage_30(struct plugin *p, struct client_session *cs, struct session_request *sr) { mk_ptr_t referer; (void) p; (void) cs; PLUGIN_TRACE("[FD %i] Mandril validating URL", cs->socket); if (mk_security_check_url(sr->uri) < 0) { PLUGIN_TRACE("[FD %i] Close connection, blocked URL", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } PLUGIN_TRACE("[FD %d] Mandril validating hotlinking", cs->socket); referer = mk_api->header_get(&sr->headers_toc, "Referer", strlen("Referer")); if (mk_security_check_hotlink(sr->uri_processed, sr->host, referer) < 0) { PLUGIN_TRACE("[FD %i] Close connection, deny hotlinking.", cs->socket); mk_api->header_set_http_status(sr, MK_CLIENT_FORBIDDEN); return MK_PLUGIN_RET_CLOSE_CONX; } return MK_PLUGIN_RET_NOT_ME; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Verify_MakeGroupObsolete() { EXPECT_TRUE(delegate()->obsoleted_success_); EXPECT_EQ(group_.get(), delegate()->obsoleted_group_.get()); EXPECT_TRUE(group_->is_obsolete()); EXPECT_TRUE(storage()->usage_map_.empty()); AppCacheDatabase::GroupRecord group_record; AppCacheDatabase::CacheRecord cache_record; EXPECT_FALSE(database()->FindGroup(1, &group_record)); EXPECT_FALSE(database()->FindCache(1, &cache_record)); std::vector<AppCacheDatabase::EntryRecord> entry_records; database()->FindEntriesForCache(1, &entry_records); EXPECT_TRUE(entry_records.empty()); std::vector<AppCacheDatabase::NamespaceRecord> intercept_records; std::vector<AppCacheDatabase::NamespaceRecord> fallback_records; database()->FindNamespacesForCache(1, &intercept_records, &fallback_records); EXPECT_TRUE(fallback_records.empty()); std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelist_records; database()->FindOnlineWhiteListForCache(1, &whitelist_records); EXPECT_TRUE(whitelist_records.empty()); EXPECT_TRUE(storage()->usage_map_.empty()); EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_); EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_); EXPECT_EQ(-kDefaultEntrySize, mock_quota_manager_proxy_->last_delta_); TestFinished(); } CWE ID: CWE-200 Target: 1 Example 2: Code: void Resource::OnMemoryDump(WebMemoryDumpLevelOfDetail level_of_detail, WebProcessMemoryDump* memory_dump) const { static const size_t kMaxURLReportLength = 128; static const int kMaxResourceClientToShowInMemoryInfra = 10; const String dump_name = GetMemoryDumpName(); WebMemoryAllocatorDump* dump = memory_dump->CreateMemoryAllocatorDump(dump_name); dump->AddScalar("encoded_size", "bytes", encoded_size_memory_usage_); if (HasClientsOrObservers()) dump->AddScalar("live_size", "bytes", encoded_size_memory_usage_); else dump->AddScalar("dead_size", "bytes", encoded_size_memory_usage_); if (data_) data_->OnMemoryDump(dump_name, memory_dump); if (level_of_detail == WebMemoryDumpLevelOfDetail::kDetailed) { String url_to_report = Url().GetString(); if (url_to_report.length() > kMaxURLReportLength) { url_to_report.Truncate(kMaxURLReportLength); url_to_report = url_to_report + "..."; } dump->AddString("url", "", url_to_report); dump->AddString("reason_not_deletable", "", ReasonNotDeletable()); Vector<String> client_names; ResourceClientWalker<ResourceClient> walker(clients_); while (ResourceClient* client = walker.Next()) client_names.push_back(client->DebugName()); ResourceClientWalker<ResourceClient> walker2(clients_awaiting_callback_); while (ResourceClient* client = walker2.Next()) client_names.push_back("(awaiting) " + client->DebugName()); ResourceClientWalker<ResourceClient> walker3(finished_clients_); while (ResourceClient* client = walker3.Next()) client_names.push_back("(finished) " + client->DebugName()); std::sort(client_names.begin(), client_names.end(), WTF::CodePointCompareLessThan); StringBuilder builder; for (size_t i = 0; i < client_names.size() && i < kMaxResourceClientToShowInMemoryInfra; ++i) { if (i > 0) builder.Append(" / "); builder.Append(client_names[i]); } if (client_names.size() > kMaxResourceClientToShowInMemoryInfra) { builder.Append(" / and "); builder.AppendNumber(client_names.size() - kMaxResourceClientToShowInMemoryInfra); builder.Append(" more"); } dump->AddString("ResourceClient", "", builder.ToString()); } const String overhead_name = dump_name + "/metadata"; WebMemoryAllocatorDump* overhead_dump = memory_dump->CreateMemoryAllocatorDump(overhead_name); overhead_dump->AddScalar("size", "bytes", OverheadSize()); memory_dump->AddSuballocation( overhead_dump->Guid(), String(WTF::Partitions::kAllocatedObjectPoolName)); } 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 PaintArtifactCompositor::PendingLayer::Merge(const PendingLayer& guest) { DCHECK(!requires_own_layer && !guest.requires_own_layer); paint_chunk_indices.AppendVector(guest.paint_chunk_indices); FloatClipRect guest_bounds_in_home(guest.bounds); GeometryMapper::LocalToAncestorVisualRect( guest.property_tree_state, property_tree_state, guest_bounds_in_home); bounds.Unite(guest_bounds_in_home.Rect()); } 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: int sas_discover_sata(struct domain_device *dev) { int res; if (dev->dev_type == SAS_SATA_PM) return -ENODEV; dev->sata_dev.class = sas_get_ata_command_set(dev); sas_fill_in_rphy(dev, dev->rphy); res = sas_notify_lldd_dev_found(dev); if (res) return res; sas_discover_event(dev->port, DISCE_PROBE); return 0; } CWE ID: Target: 1 Example 2: Code: nautilus_mime_types_group_get_name (gint group_index) { g_return_val_if_fail (group_index < G_N_ELEMENTS (mimetype_groups), NULL); return gettext (mimetype_groups[group_index].name); } 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 nbd_send_option_request(QIOChannel *ioc, uint32_t opt, uint32_t len, const char *data, Error **errp) { nbd_option req; QEMU_BUILD_BUG_ON(sizeof(req) != 16); if (len == -1) { req.length = len = strlen(data); } TRACE("Sending option request %" PRIu32", len %" PRIu32, opt, len); stq_be_p(&req.magic, NBD_OPTS_MAGIC); stl_be_p(&req.option, opt); stl_be_p(&req.length, len); if (write_sync(ioc, &req, sizeof(req)) != sizeof(req)) { error_setg(errp, "Failed to send option request header"); return -1; } if (len && write_sync(ioc, (char *) data, len) != len) { error_setg(errp, "Failed to send option request data"); return -1; } return 0; } 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 devmem_is_allowed(unsigned long pagenr) { if (pagenr < 256) return 1; if (iomem_is_exclusive(pagenr << PAGE_SHIFT)) return 0; if (!page_is_ram(pagenr)) return 1; return 0; } CWE ID: CWE-732 Target: 1 Example 2: Code: static void rmd256_transform(u32 *state, const __le32 *in) { u32 aa, bb, cc, dd, aaa, bbb, ccc, ddd, tmp; /* Initialize left lane */ aa = state[0]; bb = state[1]; cc = state[2]; dd = state[3]; /* Initialize right lane */ aaa = state[4]; bbb = state[5]; ccc = state[6]; ddd = state[7]; /* round 1: left lane */ ROUND(aa, bb, cc, dd, F1, K1, in[0], 11); ROUND(dd, aa, bb, cc, F1, K1, in[1], 14); ROUND(cc, dd, aa, bb, F1, K1, in[2], 15); ROUND(bb, cc, dd, aa, F1, K1, in[3], 12); ROUND(aa, bb, cc, dd, F1, K1, in[4], 5); ROUND(dd, aa, bb, cc, F1, K1, in[5], 8); ROUND(cc, dd, aa, bb, F1, K1, in[6], 7); ROUND(bb, cc, dd, aa, F1, K1, in[7], 9); ROUND(aa, bb, cc, dd, F1, K1, in[8], 11); ROUND(dd, aa, bb, cc, F1, K1, in[9], 13); ROUND(cc, dd, aa, bb, F1, K1, in[10], 14); ROUND(bb, cc, dd, aa, F1, K1, in[11], 15); ROUND(aa, bb, cc, dd, F1, K1, in[12], 6); ROUND(dd, aa, bb, cc, F1, K1, in[13], 7); ROUND(cc, dd, aa, bb, F1, K1, in[14], 9); ROUND(bb, cc, dd, aa, F1, K1, in[15], 8); /* round 1: right lane */ ROUND(aaa, bbb, ccc, ddd, F4, KK1, in[5], 8); ROUND(ddd, aaa, bbb, ccc, F4, KK1, in[14], 9); ROUND(ccc, ddd, aaa, bbb, F4, KK1, in[7], 9); ROUND(bbb, ccc, ddd, aaa, F4, KK1, in[0], 11); ROUND(aaa, bbb, ccc, ddd, F4, KK1, in[9], 13); ROUND(ddd, aaa, bbb, ccc, F4, KK1, in[2], 15); ROUND(ccc, ddd, aaa, bbb, F4, KK1, in[11], 15); ROUND(bbb, ccc, ddd, aaa, F4, KK1, in[4], 5); ROUND(aaa, bbb, ccc, ddd, F4, KK1, in[13], 7); ROUND(ddd, aaa, bbb, ccc, F4, KK1, in[6], 7); ROUND(ccc, ddd, aaa, bbb, F4, KK1, in[15], 8); ROUND(bbb, ccc, ddd, aaa, F4, KK1, in[8], 11); ROUND(aaa, bbb, ccc, ddd, F4, KK1, in[1], 14); ROUND(ddd, aaa, bbb, ccc, F4, KK1, in[10], 14); ROUND(ccc, ddd, aaa, bbb, F4, KK1, in[3], 12); ROUND(bbb, ccc, ddd, aaa, F4, KK1, in[12], 6); /* Swap contents of "a" registers */ tmp = aa; aa = aaa; aaa = tmp; /* round 2: left lane */ ROUND(aa, bb, cc, dd, F2, K2, in[7], 7); ROUND(dd, aa, bb, cc, F2, K2, in[4], 6); ROUND(cc, dd, aa, bb, F2, K2, in[13], 8); ROUND(bb, cc, dd, aa, F2, K2, in[1], 13); ROUND(aa, bb, cc, dd, F2, K2, in[10], 11); ROUND(dd, aa, bb, cc, F2, K2, in[6], 9); ROUND(cc, dd, aa, bb, F2, K2, in[15], 7); ROUND(bb, cc, dd, aa, F2, K2, in[3], 15); ROUND(aa, bb, cc, dd, F2, K2, in[12], 7); ROUND(dd, aa, bb, cc, F2, K2, in[0], 12); ROUND(cc, dd, aa, bb, F2, K2, in[9], 15); ROUND(bb, cc, dd, aa, F2, K2, in[5], 9); ROUND(aa, bb, cc, dd, F2, K2, in[2], 11); ROUND(dd, aa, bb, cc, F2, K2, in[14], 7); ROUND(cc, dd, aa, bb, F2, K2, in[11], 13); ROUND(bb, cc, dd, aa, F2, K2, in[8], 12); /* round 2: right lane */ ROUND(aaa, bbb, ccc, ddd, F3, KK2, in[6], 9); ROUND(ddd, aaa, bbb, ccc, F3, KK2, in[11], 13); ROUND(ccc, ddd, aaa, bbb, F3, KK2, in[3], 15); ROUND(bbb, ccc, ddd, aaa, F3, KK2, in[7], 7); ROUND(aaa, bbb, ccc, ddd, F3, KK2, in[0], 12); ROUND(ddd, aaa, bbb, ccc, F3, KK2, in[13], 8); ROUND(ccc, ddd, aaa, bbb, F3, KK2, in[5], 9); ROUND(bbb, ccc, ddd, aaa, F3, KK2, in[10], 11); ROUND(aaa, bbb, ccc, ddd, F3, KK2, in[14], 7); ROUND(ddd, aaa, bbb, ccc, F3, KK2, in[15], 7); ROUND(ccc, ddd, aaa, bbb, F3, KK2, in[8], 12); ROUND(bbb, ccc, ddd, aaa, F3, KK2, in[12], 7); ROUND(aaa, bbb, ccc, ddd, F3, KK2, in[4], 6); ROUND(ddd, aaa, bbb, ccc, F3, KK2, in[9], 15); ROUND(ccc, ddd, aaa, bbb, F3, KK2, in[1], 13); ROUND(bbb, ccc, ddd, aaa, F3, KK2, in[2], 11); /* Swap contents of "b" registers */ tmp = bb; bb = bbb; bbb = tmp; /* round 3: left lane */ ROUND(aa, bb, cc, dd, F3, K3, in[3], 11); ROUND(dd, aa, bb, cc, F3, K3, in[10], 13); ROUND(cc, dd, aa, bb, F3, K3, in[14], 6); ROUND(bb, cc, dd, aa, F3, K3, in[4], 7); ROUND(aa, bb, cc, dd, F3, K3, in[9], 14); ROUND(dd, aa, bb, cc, F3, K3, in[15], 9); ROUND(cc, dd, aa, bb, F3, K3, in[8], 13); ROUND(bb, cc, dd, aa, F3, K3, in[1], 15); ROUND(aa, bb, cc, dd, F3, K3, in[2], 14); ROUND(dd, aa, bb, cc, F3, K3, in[7], 8); ROUND(cc, dd, aa, bb, F3, K3, in[0], 13); ROUND(bb, cc, dd, aa, F3, K3, in[6], 6); ROUND(aa, bb, cc, dd, F3, K3, in[13], 5); ROUND(dd, aa, bb, cc, F3, K3, in[11], 12); ROUND(cc, dd, aa, bb, F3, K3, in[5], 7); ROUND(bb, cc, dd, aa, F3, K3, in[12], 5); /* round 3: right lane */ ROUND(aaa, bbb, ccc, ddd, F2, KK3, in[15], 9); ROUND(ddd, aaa, bbb, ccc, F2, KK3, in[5], 7); ROUND(ccc, ddd, aaa, bbb, F2, KK3, in[1], 15); ROUND(bbb, ccc, ddd, aaa, F2, KK3, in[3], 11); ROUND(aaa, bbb, ccc, ddd, F2, KK3, in[7], 8); ROUND(ddd, aaa, bbb, ccc, F2, KK3, in[14], 6); ROUND(ccc, ddd, aaa, bbb, F2, KK3, in[6], 6); ROUND(bbb, ccc, ddd, aaa, F2, KK3, in[9], 14); ROUND(aaa, bbb, ccc, ddd, F2, KK3, in[11], 12); ROUND(ddd, aaa, bbb, ccc, F2, KK3, in[8], 13); ROUND(ccc, ddd, aaa, bbb, F2, KK3, in[12], 5); ROUND(bbb, ccc, ddd, aaa, F2, KK3, in[2], 14); ROUND(aaa, bbb, ccc, ddd, F2, KK3, in[10], 13); ROUND(ddd, aaa, bbb, ccc, F2, KK3, in[0], 13); ROUND(ccc, ddd, aaa, bbb, F2, KK3, in[4], 7); ROUND(bbb, ccc, ddd, aaa, F2, KK3, in[13], 5); /* Swap contents of "c" registers */ tmp = cc; cc = ccc; ccc = tmp; /* round 4: left lane */ ROUND(aa, bb, cc, dd, F4, K4, in[1], 11); ROUND(dd, aa, bb, cc, F4, K4, in[9], 12); ROUND(cc, dd, aa, bb, F4, K4, in[11], 14); ROUND(bb, cc, dd, aa, F4, K4, in[10], 15); ROUND(aa, bb, cc, dd, F4, K4, in[0], 14); ROUND(dd, aa, bb, cc, F4, K4, in[8], 15); ROUND(cc, dd, aa, bb, F4, K4, in[12], 9); ROUND(bb, cc, dd, aa, F4, K4, in[4], 8); ROUND(aa, bb, cc, dd, F4, K4, in[13], 9); ROUND(dd, aa, bb, cc, F4, K4, in[3], 14); ROUND(cc, dd, aa, bb, F4, K4, in[7], 5); ROUND(bb, cc, dd, aa, F4, K4, in[15], 6); ROUND(aa, bb, cc, dd, F4, K4, in[14], 8); ROUND(dd, aa, bb, cc, F4, K4, in[5], 6); ROUND(cc, dd, aa, bb, F4, K4, in[6], 5); ROUND(bb, cc, dd, aa, F4, K4, in[2], 12); /* round 4: right lane */ ROUND(aaa, bbb, ccc, ddd, F1, KK4, in[8], 15); ROUND(ddd, aaa, bbb, ccc, F1, KK4, in[6], 5); ROUND(ccc, ddd, aaa, bbb, F1, KK4, in[4], 8); ROUND(bbb, ccc, ddd, aaa, F1, KK4, in[1], 11); ROUND(aaa, bbb, ccc, ddd, F1, KK4, in[3], 14); ROUND(ddd, aaa, bbb, ccc, F1, KK4, in[11], 14); ROUND(ccc, ddd, aaa, bbb, F1, KK4, in[15], 6); ROUND(bbb, ccc, ddd, aaa, F1, KK4, in[0], 14); ROUND(aaa, bbb, ccc, ddd, F1, KK4, in[5], 6); ROUND(ddd, aaa, bbb, ccc, F1, KK4, in[12], 9); ROUND(ccc, ddd, aaa, bbb, F1, KK4, in[2], 12); ROUND(bbb, ccc, ddd, aaa, F1, KK4, in[13], 9); ROUND(aaa, bbb, ccc, ddd, F1, KK4, in[9], 12); ROUND(ddd, aaa, bbb, ccc, F1, KK4, in[7], 5); ROUND(ccc, ddd, aaa, bbb, F1, KK4, in[10], 15); ROUND(bbb, ccc, ddd, aaa, F1, KK4, in[14], 8); /* Swap contents of "d" registers */ tmp = dd; dd = ddd; ddd = tmp; /* combine results */ state[0] += aa; state[1] += bb; state[2] += cc; state[3] += dd; state[4] += aaa; state[5] += bbb; state[6] += ccc; state[7] += ddd; return; } 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 int assigned_device_enable_host_intx(struct kvm *kvm, struct kvm_assigned_dev_kernel *dev) { dev->host_irq = dev->dev->irq; /* Even though this is PCI, we don't want to use shared * interrupts. Sharing host devices with guest-assigned devices * on the same interrupt line is not a happy situation: there * are going to be long delays in accepting, acking, etc. */ if (request_threaded_irq(dev->host_irq, NULL, kvm_assigned_dev_thread, IRQF_ONESHOT, dev->irq_name, (void *)dev)) return -EIO; return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int encrypted_update(struct key *key, struct key_preparsed_payload *prep) { struct encrypted_key_payload *epayload = key->payload.data[0]; struct encrypted_key_payload *new_epayload; char *buf; char *new_master_desc = NULL; const char *format = NULL; size_t datalen = prep->datalen; int ret = 0; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; buf = kmalloc(datalen + 1, GFP_KERNEL); if (!buf) return -ENOMEM; buf[datalen] = 0; memcpy(buf, prep->data, datalen); ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL); if (ret < 0) goto out; ret = valid_master_desc(new_master_desc, epayload->master_desc); if (ret < 0) goto out; new_epayload = encrypted_key_alloc(key, epayload->format, new_master_desc, epayload->datalen); if (IS_ERR(new_epayload)) { ret = PTR_ERR(new_epayload); goto out; } __ekey_init(new_epayload, epayload->format, new_master_desc, epayload->datalen); memcpy(new_epayload->iv, epayload->iv, ivsize); memcpy(new_epayload->payload_data, epayload->payload_data, epayload->payload_datalen); rcu_assign_keypointer(key, new_epayload); call_rcu(&epayload->rcu, encrypted_rcu_free); out: kfree(buf); return ret; } CWE ID: CWE-264 Target: 1 Example 2: Code: void HTMLMediaElement::RejectScheduledPlayPromises() { DCHECK(play_promise_error_code_ == kAbortError || play_promise_error_code_ == kNotSupportedError); if (play_promise_error_code_ == kAbortError) { RecordPlayPromiseRejected(PlayPromiseRejectReason::kInterruptedByPause); RejectPlayPromisesInternal(kAbortError, "The play() request was interrupted by a call " "to pause(). https://goo.gl/LdLk22"); } else { RecordPlayPromiseRejected(PlayPromiseRejectReason::kNoSupportedSources); RejectPlayPromisesInternal( kNotSupportedError, "Failed to load because no supported source was found."); } } 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: bool HasProvider() const { return test_data_providers.size() == 1U; } CWE ID: CWE-732 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 RenderWidgetHostViewAura::AdjustSurfaceProtection() { bool surface_is_protected = current_surface_ || !host_->is_hidden() || (current_surface_is_protected_ && (pending_thumbnail_tasks_ > 0 || current_surface_in_use_by_compositor_)); if (current_surface_is_protected_ == surface_is_protected) return; current_surface_is_protected_ = surface_is_protected; ++protection_state_id_; if (!surface_route_id_ || !shared_surface_handle_.parent_gpu_process_id) return; RenderWidgetHostImpl::SendFrontSurfaceIsProtected( surface_is_protected, protection_state_id_, surface_route_id_, shared_surface_handle_.parent_gpu_process_id); } CWE ID: Target: 1 Example 2: Code: static rsRetVal parseSubscriptions(char* subscribes, sublist** subList){ char* tok = strtok(subscribes, ","); sublist* currentSub; sublist* head; DEFiRet; /* create empty list */ CHKmalloc(*subList = (sublist*)MALLOC(sizeof(sublist))); head = *subList; head->next = NULL; head->subscribe=NULL; currentSub=head; if(tok) { head->subscribe=strdup(tok); for(tok=strtok(NULL, ","); tok!=NULL;tok=strtok(NULL, ",")) { CHKmalloc(currentSub->next = (sublist*)MALLOC(sizeof(sublist))); currentSub=currentSub->next; currentSub->subscribe=strdup(tok); currentSub->next=NULL; } } else { /* make empty subscription ie subscribe="" */ head->subscribe=strdup(""); } /* TODO: temporary logging */ currentSub = head; DBGPRINTF("imzmq3: Subscriptions:"); for(currentSub = head; currentSub != NULL; currentSub=currentSub->next) { DBGPRINTF("'%s'", currentSub->subscribe); } DBGPRINTF("\n"); finalize_it: RETiRet; } CWE ID: CWE-134 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } } 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: int gs_lib_ctx_init( gs_memory_t *mem ) { gs_lib_ctx_t *pio = 0; /* Check the non gc allocator is being passed in */ if (mem == 0 || mem != mem->non_gc_memory) return_error(gs_error_Fatal); #ifndef GS_THREADSAFE mem_err_print = mem; #endif if (mem->gs_lib_ctx) /* one time initialization */ return 0; pio = (gs_lib_ctx_t*)gs_alloc_bytes_immovable(mem, sizeof(gs_lib_ctx_t), "gs_lib_ctx_init"); if( pio == 0 ) return -1; /* Wholesale blanking is cheaper than retail, and scales better when new * fields are added. */ memset(pio, 0, sizeof(*pio)); /* Now set the non zero/false/NULL things */ pio->memory = mem; gs_lib_ctx_get_real_stdio(&pio->fstdin, &pio->fstdout, &pio->fstderr ); pio->stdin_is_interactive = true; /* id's 1 through 4 are reserved for Device color spaces; see gscspace.h */ pio->gs_next_id = 5; /* this implies that each thread has its own complete state */ /* Need to set this before calling gs_lib_ctx_set_icc_directory. */ mem->gs_lib_ctx = pio; /* Initialize our default ICCProfilesDir */ pio->profiledir = NULL; pio->profiledir_len = 0; gs_lib_ctx_set_icc_directory(mem, DEFAULT_DIR_ICC, strlen(DEFAULT_DIR_ICC)); if (gs_lib_ctx_set_default_device_list(mem, gs_dev_defaults, strlen(gs_dev_defaults)) < 0) { gs_free_object(mem, pio, "gs_lib_ctx_init"); mem->gs_lib_ctx = NULL; } /* Initialise the underlying CMS. */ if (gscms_create(mem)) { Failure: gs_free_object(mem, mem->gs_lib_ctx->default_device_list, "gs_lib_ctx_fin"); gs_free_object(mem, pio, "gs_lib_ctx_init"); mem->gs_lib_ctx = NULL; return -1; } /* Initialise any lock required for the jpx codec */ if (sjpxd_create(mem)) { gscms_destroy(mem); goto Failure; } gp_get_realtime(pio->real_time_0); /* Set scanconverter to 1 (default) */ pio->scanconverter = GS_SCANCONVERTER_DEFAULT; return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: Mutex* CameraService::Client::getClientLockFromCookie(void* user) { return gCameraService->getClientLockById((int) user); } 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 ACodec::FlushingState::onInputBufferFilled(const sp<AMessage> &msg) { BaseState::onInputBufferFilled(msg); changeStateIfWeOwnAllBuffers(); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void mntput_no_expire(struct mount *mnt) { rcu_read_lock(); mnt_add_count(mnt, -1); if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */ rcu_read_unlock(); return; } lock_mount_hash(); if (mnt_get_count(mnt)) { rcu_read_unlock(); unlock_mount_hash(); return; } if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) { rcu_read_unlock(); unlock_mount_hash(); return; } mnt->mnt.mnt_flags |= MNT_DOOMED; rcu_read_unlock(); list_del(&mnt->mnt_instance); unlock_mount_hash(); if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) { struct task_struct *task = current; if (likely(!(task->flags & PF_KTHREAD))) { init_task_work(&mnt->mnt_rcu, __cleanup_mnt); if (!task_work_add(task, &mnt->mnt_rcu, true)) return; } if (llist_add(&mnt->mnt_llist, &delayed_mntput_list)) schedule_delayed_work(&delayed_mntput_work, 1); return; } cleanup_mnt(mnt); } CWE ID: CWE-284 Target: 1 Example 2: Code: static uint32_t NumberOfElementsImpl(JSObject* receiver, FixedArrayBase* backing_store) { uint32_t max_index = Subclass::GetMaxIndex(receiver, backing_store); if (IsFastPackedElementsKind(Subclass::kind())) return max_index; Isolate* isolate = receiver->GetIsolate(); uint32_t count = 0; for (uint32_t i = 0; i < max_index; i++) { if (Subclass::HasEntryImpl(isolate, backing_store, i)) count++; } return count; } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: AutocompleteLog::AutocompleteLog( const string16& text, bool just_deleted_text, AutocompleteInput::Type input_type, size_t selected_index, SessionID::id_type tab_id, metrics::OmniboxEventProto::PageClassification current_page_classification, base::TimeDelta elapsed_time_since_user_first_modified_omnibox, size_t inline_autocompleted_length, const AutocompleteResult& result) : text(text), just_deleted_text(just_deleted_text), input_type(input_type), selected_index(selected_index), tab_id(tab_id), current_page_classification(current_page_classification), elapsed_time_since_user_first_modified_omnibox( elapsed_time_since_user_first_modified_omnibox), inline_autocompleted_length(inline_autocompleted_length), result(result) { } 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 WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 nInterpolatedSample; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pOutputBuffer = pWTIntFrame->pAudioBuffer; phaseInc = pWTIntFrame->frame.phaseIncrement; /* get last two samples generated */ /*lint -e{704} <avoid divide for performance>*/ tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18; /*lint -e{704} <avoid divide for performance>*/ tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18; /* generate a buffer of noise */ while (numSamples--) { nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac)); nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac); *pOutputBuffer++ = (EAS_PCM) nInterpolatedSample; /* update PRNG */ pWTVoice->phaseFrac += (EAS_U32) phaseInc; if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) { tmp0 = tmp1; pWTVoice->phaseAccum = pWTVoice->loopEnd; pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1); tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18; pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac); } } } CWE ID: CWE-119 Target: 1 Example 2: Code: bool NavigationControllerImpl::CanGoBack() const { return entries_.size() > 1 && GetCurrentEntryIndex() > 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: print_dns_label(netdissect_options *ndo, const u_char *cp, u_int max_length, int print) { u_int length = 0; while (length < max_length) { u_int lab_length = cp[length++]; if (lab_length == 0) return (int)length; if (length > 1 && print) safeputchar(ndo, '.'); if (length+lab_length > max_length) { if (print) safeputs(ndo, cp+length, max_length-length); break; } if (print) safeputs(ndo, cp+length, lab_length); length += lab_length; } if (print) ND_PRINT((ndo, "[|DNS]")); return -1; } 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: void set_scl(int state) { qrio_set_opendrain_gpio(DEBLOCK_PORT1, DEBLOCK_SCL1, state); } CWE ID: CWE-787 Target: 1 Example 2: Code: xmlFatalErrMsgInt(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, int val) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, NULL, NULL, NULL, val, 0, msg, val); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } CWE ID: CWE-835 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst) { switch (ctxt->op_bytes) { case 2: ctxt->_eip = (u16)dst; break; case 4: ctxt->_eip = (u32)dst; break; case 8: ctxt->_eip = dst; break; default: WARN(1, "unsupported eip assignment size\n"); } } 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: psf_close (SF_PRIVATE *psf) { uint32_t k ; int error = 0 ; if (psf->codec_close) { error = psf->codec_close (psf) ; /* To prevent it being called in psf->container_close(). */ psf->codec_close = NULL ; } ; if (psf->container_close) error = psf->container_close (psf) ; error = psf_fclose (psf) ; psf_close_rsrc (psf) ; /* For an ISO C compliant implementation it is ok to free a NULL pointer. */ free (psf->container_data) ; free (psf->codec_data) ; free (psf->interleave) ; free (psf->dither) ; free (psf->peak_info) ; free (psf->broadcast_16k) ; free (psf->loop_info) ; free (psf->instrument) ; free (psf->cues) ; free (psf->channel_map) ; free (psf->format_desc) ; free (psf->strings.storage) ; if (psf->wchunks.chunks) for (k = 0 ; k < psf->wchunks.used ; k++) free (psf->wchunks.chunks [k].data) ; free (psf->rchunks.chunks) ; free (psf->wchunks.chunks) ; free (psf->iterator) ; free (psf->cart_16k) ; memset (psf, 0, sizeof (SF_PRIVATE)) ; free (psf) ; return error ; } /* psf_close */ CWE ID: CWE-119 Target: 1 Example 2: Code: void jslInit(JsVar *var) { lex->sourceVar = jsvLockAgain(var); lex->tk = 0; lex->tokenStart.it.var = 0; lex->tokenStart.currCh = 0; lex->tokenLastStart = 0; lex->tokenl = 0; lex->tokenValue = 0; lex->lineNumberOffset = 0; jsvStringIteratorNew(&lex->it, lex->sourceVar, 0); jsvUnLock(lex->it.var); // see jslGetNextCh jslPreload(); } 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 ftrace_dump(enum ftrace_dump_mode oops_dump_mode) { /* use static because iter can be a bit big for the stack */ static struct trace_iterator iter; static atomic_t dump_running; struct trace_array *tr = &global_trace; unsigned int old_userobj; unsigned long flags; int cnt = 0, cpu; /* Only allow one dump user at a time. */ if (atomic_inc_return(&dump_running) != 1) { atomic_dec(&dump_running); return; } /* * Always turn off tracing when we dump. * We don't need to show trace output of what happens * between multiple crashes. * * If the user does a sysrq-z, then they can re-enable * tracing with echo 1 > tracing_on. */ tracing_off(); local_irq_save(flags); printk_nmi_direct_enter(); /* Simulate the iterator */ trace_init_global_iter(&iter); for_each_tracing_cpu(cpu) { atomic_inc(&per_cpu_ptr(iter.trace_buffer->data, cpu)->disabled); } old_userobj = tr->trace_flags & TRACE_ITER_SYM_USEROBJ; /* don't look at user memory in panic mode */ tr->trace_flags &= ~TRACE_ITER_SYM_USEROBJ; switch (oops_dump_mode) { case DUMP_ALL: iter.cpu_file = RING_BUFFER_ALL_CPUS; break; case DUMP_ORIG: iter.cpu_file = raw_smp_processor_id(); break; case DUMP_NONE: goto out_enable; default: printk(KERN_TRACE "Bad dumping mode, switching to all CPUs dump\n"); iter.cpu_file = RING_BUFFER_ALL_CPUS; } printk(KERN_TRACE "Dumping ftrace buffer:\n"); /* Did function tracer already get disabled? */ if (ftrace_is_dead()) { printk("# WARNING: FUNCTION TRACING IS CORRUPTED\n"); printk("# MAY BE MISSING FUNCTION EVENTS\n"); } /* * We need to stop all tracing on all CPUS to read the * the next buffer. This is a bit expensive, but is * not done often. We fill all what we can read, * and then release the locks again. */ while (!trace_empty(&iter)) { if (!cnt) printk(KERN_TRACE "---------------------------------\n"); cnt++; /* reset all but tr, trace, and overruns */ memset(&iter.seq, 0, sizeof(struct trace_iterator) - offsetof(struct trace_iterator, seq)); iter.iter_flags |= TRACE_FILE_LAT_FMT; iter.pos = -1; if (trace_find_next_entry_inc(&iter) != NULL) { int ret; ret = print_trace_line(&iter); if (ret != TRACE_TYPE_NO_CONSUME) trace_consume(&iter); } touch_nmi_watchdog(); trace_printk_seq(&iter.seq); } if (!cnt) printk(KERN_TRACE " (ftrace buffer empty)\n"); else printk(KERN_TRACE "---------------------------------\n"); out_enable: tr->trace_flags |= old_userobj; for_each_tracing_cpu(cpu) { atomic_dec(&per_cpu_ptr(iter.trace_buffer->data, cpu)->disabled); } atomic_dec(&dump_running); printk_nmi_direct_exit(); local_irq_restore(flags); } 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 void sctp_generate_timeout_event(struct sctp_association *asoc, sctp_event_timeout_t timeout_type) { struct net *net = sock_net(asoc->base.sk); int error = 0; bh_lock_sock(asoc->base.sk); if (sock_owned_by_user(asoc->base.sk)) { pr_debug("%s: sock is busy: timer %d\n", __func__, timeout_type); /* Try again later. */ if (!mod_timer(&asoc->timers[timeout_type], jiffies + (HZ/20))) sctp_association_hold(asoc); goto out_unlock; } /* Is this association really dead and just waiting around for * the timer to let go of the reference? */ if (asoc->base.dead) goto out_unlock; /* Run through the state machine. */ error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT, SCTP_ST_TIMEOUT(timeout_type), asoc->state, asoc->ep, asoc, (void *)timeout_type, GFP_ATOMIC); if (error) asoc->base.sk->sk_err = -error; out_unlock: bh_unlock_sock(asoc->base.sk); sctp_association_put(asoc); } CWE ID: CWE-362 Target: 1 Example 2: Code: void NavigationControllerImpl::SetTransientEntry( std::unique_ptr<NavigationEntry> entry) { int index = 0; if (last_committed_entry_index_ != -1) index = last_committed_entry_index_ + 1; DiscardTransientEntry(); entries_.insert(entries_.begin() + index, NavigationEntryImpl::FromNavigationEntry(std::move(entry))); transient_entry_index_ = index; delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char make[12], model[15]; } table[] = { { 0x00, "PENTAX", "Optio 33WR" }, { 0x03, "NIKON", "E3200" }, { 0x32, "NIKON", "E3700" }, { 0x33, "OLYMPUS", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < (int) sizeof table / (int) sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].make ); strcpy (model, table[i].model); } } 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: ~CreateFileResult() { } CWE ID: CWE-119 Target: 1 Example 2: Code: void ShowLoginWizardFinish( chromeos::OobeScreen first_screen, const chromeos::StartupCustomizationDocument* startup_manifest) { TRACE_EVENT0("chromeos", "ShowLoginWizard::ShowLoginWizardFinish"); chromeos::LoginDisplayHost* display_host = nullptr; if (chromeos::LoginDisplayHost::default_host()) { display_host = chromeos::LoginDisplayHost::default_host(); } else if (ash::features::IsViewsLoginEnabled() && ShouldShowSigninScreen(first_screen)) { display_host = new chromeos::LoginDisplayHostMojo(); } else { display_host = new chromeos::LoginDisplayHostWebUI(); } std::string timezone; if (chromeos::system::PerUserTimezoneEnabled()) { timezone = g_browser_process->local_state()->GetString( prefs::kSigninScreenTimezone); } if (ShouldShowSigninScreen(first_screen)) { display_host->StartSignInScreen(chromeos::LoginScreenContext()); } else { display_host->StartWizard(first_screen); const std::string customization_timezone = startup_manifest->initial_timezone(); VLOG(1) << "Initial time zone: " << customization_timezone; if (!customization_timezone.empty()) timezone = customization_timezone; } if (!timezone.empty()) { chromeos::system::SetSystemAndSigninScreenTimezone(timezone); } } 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 reflectedCustomStringAttrAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; TestObjectV8Internal::reflectedCustomStringAttrAttributeSetter(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: static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg) { u8 cpl = ctxt->ops->cpl(ctxt); return __load_segment_descriptor(ctxt, selector, seg, cpl, false); } CWE ID: CWE-264 Target: 1 Example 2: Code: static bool path_connected(const struct path *path) { struct vfsmount *mnt = path->mnt; /* Only bind mounts can have disconnected paths */ if (mnt->mnt_root == mnt->mnt_sb->s_root) return true; return is_subdir(path->dentry, mnt->mnt_root); } 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 blk_rq_unprep_clone(struct request *rq) { struct bio *bio; while ((bio = rq->bio) != NULL) { rq->bio = bio->bi_next; bio_put(bio); } } 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 snd_timer_user_tselect(struct file *file, struct snd_timer_select __user *_tselect) { struct snd_timer_user *tu; struct snd_timer_select tselect; char str[32]; int err = 0; tu = file->private_data; if (tu->timeri) { snd_timer_close(tu->timeri); tu->timeri = NULL; } if (copy_from_user(&tselect, _tselect, sizeof(tselect))) { err = -EFAULT; goto __err; } sprintf(str, "application %i", current->pid); if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE) tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION; err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid); if (err < 0) goto __err; kfree(tu->queue); tu->queue = NULL; kfree(tu->tqueue); tu->tqueue = NULL; if (tu->tread) { tu->tqueue = kmalloc(tu->queue_size * sizeof(struct snd_timer_tread), GFP_KERNEL); if (tu->tqueue == NULL) err = -ENOMEM; } else { tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read), GFP_KERNEL); if (tu->queue == NULL) err = -ENOMEM; } if (err < 0) { snd_timer_close(tu->timeri); tu->timeri = NULL; } else { tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST; tu->timeri->callback = tu->tread ? snd_timer_user_tinterrupt : snd_timer_user_interrupt; tu->timeri->ccallback = snd_timer_user_ccallback; tu->timeri->callback_data = (void *)tu; tu->timeri->disconnect = snd_timer_user_disconnect; } __err: return err; } CWE ID: CWE-200 Target: 1 Example 2: Code: static void rpc_release_resources_task(struct rpc_task *task) { if (task->tk_rqstp) xprt_release(task); if (task->tk_msg.rpc_cred) { put_rpccred(task->tk_msg.rpc_cred); task->tk_msg.rpc_cred = NULL; } rpc_task_release_client(task); } 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: SWFInput_input_seek(SWFInput input, long offset, int whence) { if ( whence == SEEK_CUR ) { if ( offset >= 0 ) input->offset = min(input->length, input->offset + offset); else input->offset = max(0, input->offset + offset); } else if ( whence == SEEK_END ) input->offset = max(0, input->length - offset); else if ( whence == SEEK_SET ) input->offset = min(input->length, offset); } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SProcXFixesChangeSaveSet(ClientPtr client) { REQUEST(xXFixesChangeSaveSetReq); swaps(&stuff->length); swapl(&stuff->window); } CWE ID: CWE-20 Target: 1 Example 2: Code: void SharedWorkerDevToolsAgentHost::DispatchProtocolMessage( DevToolsSession* session, const std::string& message) { session->DispatchProtocolMessage(message); } 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 Textfield::UseDefaultTextColor() { use_default_text_color_ = true; SetColor(GetTextColor()); } 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 int su3000_power_ctrl(struct dvb_usb_device *d, int i) { struct dw2102_state *state = (struct dw2102_state *)d->priv; u8 obuf[] = {0xde, 0}; info("%s: %d, initialized %d", __func__, i, state->initialized); if (i && !state->initialized) { state->initialized = 1; /* reset board */ return dvb_usb_generic_rw(d, obuf, 2, NULL, 0, 0); } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: void FrameSelection::DidSetSelectionDeprecated( const SetSelectionData& options) { const Document& current_document = GetDocument(); if (!GetSelectionInDOMTree().IsNone() && !options.DoNotSetFocus()) { SetFocusedNodeIfNeeded(); if (!IsAvailable() || GetDocument() != current_document) { NOTREACHED(); return; } } frame_caret_->StopCaretBlinkTimer(); UpdateAppearance(); x_pos_for_vertical_arrow_navigation_ = NoXPosForVerticalArrowNavigation(); if (!options.DoNotSetFocus()) { SelectFrameElementInParentIfFullySelected(); if (!IsAvailable() || GetDocument() != current_document) { return; } } const SetSelectionBy set_selection_by = options.GetSetSelectionBy(); NotifyTextControlOfSelectionChange(set_selection_by); if (set_selection_by == SetSelectionBy::kUser) { const CursorAlignOnScroll align = options.GetCursorAlignOnScroll(); ScrollAlignment alignment; if (frame_->GetEditor() .Behavior() .ShouldCenterAlignWhenSelectionIsRevealed()) alignment = (align == CursorAlignOnScroll::kAlways) ? ScrollAlignment::kAlignCenterAlways : ScrollAlignment::kAlignCenterIfNeeded; else alignment = (align == CursorAlignOnScroll::kAlways) ? ScrollAlignment::kAlignTopAlways : ScrollAlignment::kAlignToEdgeIfNeeded; RevealSelection(alignment, kRevealExtent); } NotifyAccessibilityForSelectionChange(); NotifyCompositorForSelectionChange(); NotifyEventHandlerForSelectionChange(); frame_->DomWindow()->EnqueueDocumentEvent( Event::Create(EventTypeNames::selectionchange)); } 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: check_interlace_type(int PNG_CONST interlace_type) { if (interlace_type != PNG_INTERLACE_NONE) { /* This is an internal error - --interlace tests should be skipped, not * attempted. */ fprintf(stderr, "pngvalid: no interlace support\n"); exit(99); } } 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 AutofillPopupBaseView::DoShow() { const bool initialize_widget = !GetWidget(); if (initialize_widget) { if (parent_widget_) parent_widget_->AddObserver(this); views::Widget* widget = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.delegate = this; params.parent = parent_widget_ ? parent_widget_->GetNativeView() : delegate_->container_view(); AddExtraInitParams(&params); widget->Init(params); std::unique_ptr<views::View> wrapper = CreateWrapperView(); if (wrapper) widget->SetContentsView(wrapper.release()); widget->AddObserver(this); widget->SetVisibilityAnimationTransition(views::Widget::ANIMATE_HIDE); show_time_ = base::Time::Now(); } GetWidget()->GetRootView()->SetBorder(CreateBorder()); DoUpdateBoundsAndRedrawPopup(); GetWidget()->Show(); if (initialize_widget) views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this); } CWE ID: CWE-416 Target: 1 Example 2: Code: static int hid_uevent(struct device *dev, struct kobj_uevent_env *env) { struct hid_device *hdev = to_hid_device(dev); if (add_uevent_var(env, "HID_ID=%04X:%08X:%08X", hdev->bus, hdev->vendor, hdev->product)) return -ENOMEM; if (add_uevent_var(env, "HID_NAME=%s", hdev->name)) return -ENOMEM; if (add_uevent_var(env, "HID_PHYS=%s", hdev->phys)) return -ENOMEM; if (add_uevent_var(env, "HID_UNIQ=%s", hdev->uniq)) return -ENOMEM; if (add_uevent_var(env, "MODALIAS=hid:b%04Xg%04Xv%08Xp%08X", hdev->bus, hdev->group, hdev->vendor, hdev->product)) return -ENOMEM; return 0; } 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 int rfcomm_sock_debugfs_show(struct seq_file *f, void *p) { struct sock *sk; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, &rfcomm_sk_list.head) { seq_printf(f, "%pMR %pMR %d %d\n", &bt_sk(sk)->src, &bt_sk(sk)->dst, sk->sk_state, rfcomm_pi(sk)->channel); } read_unlock(&rfcomm_sk_list.lock); return 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: testing::AssertionResult ScriptAllowedExclusivelyOnTab( const Extension* extension, const std::set<GURL>& allowed_urls, int tab_id) { std::vector<std::string> errors; for (const GURL& url : urls_) { bool allowed = IsAllowedScript(extension, url, tab_id); if (allowed && !allowed_urls.count(url)) errors.push_back("Script unexpectedly disallowed on " + url.spec()); else if (!allowed && allowed_urls.count(url)) errors.push_back("Script unexpectedly allowed on " + url.spec()); } if (!errors.empty()) return testing::AssertionFailure() << base::JoinString(errors, "\n"); return testing::AssertionSuccess(); } CWE ID: CWE-20 Target: 1 Example 2: Code: entry_guards_update_confirmed(guard_selection_t *gs) { smartlist_clear(gs->confirmed_entry_guards); SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) { if (guard->confirmed_idx >= 0) smartlist_add(gs->confirmed_entry_guards, guard); } SMARTLIST_FOREACH_END(guard); smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx); int any_changed = 0; SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) { if (guard->confirmed_idx != guard_sl_idx) { any_changed = 1; guard->confirmed_idx = guard_sl_idx; } } SMARTLIST_FOREACH_END(guard); gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards); if (any_changed) { entry_guards_changed_for_guard_selection(gs); } } 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: int sctp_verify_asconf(const struct sctp_association *asoc, struct sctp_paramhdr *param_hdr, void *chunk_end, struct sctp_paramhdr **errp) { sctp_addip_param_t *asconf_param; union sctp_params param; int length, plen; param.v = (sctp_paramhdr_t *) param_hdr; while (param.v <= chunk_end - sizeof(sctp_paramhdr_t)) { length = ntohs(param.p->length); *errp = param.p; if (param.v > chunk_end - length || length < sizeof(sctp_paramhdr_t)) return 0; switch (param.p->type) { case SCTP_PARAM_ADD_IP: case SCTP_PARAM_DEL_IP: case SCTP_PARAM_SET_PRIMARY: asconf_param = (sctp_addip_param_t *)param.v; plen = ntohs(asconf_param->param_hdr.length); if (plen < sizeof(sctp_addip_param_t) + sizeof(sctp_paramhdr_t)) return 0; break; case SCTP_PARAM_SUCCESS_REPORT: case SCTP_PARAM_ADAPTATION_LAYER_IND: if (length != sizeof(sctp_addip_param_t)) return 0; break; default: break; } param.v += WORD_ROUND(length); } if (param.v != chunk_end) return 0; return 1; } 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 DownloadItemImpl::OnDownloadRenamedToFinalName( DownloadFileManager* file_manager, const FilePath& full_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); VLOG(20) << __FUNCTION__ << "()" << " full_path = \"" << full_path.value() << "\"" << " needed rename = " << NeedsRename() << " " << DebugString(false); DCHECK(NeedsRename()); if (!full_path.empty()) { target_path_ = full_path; SetFullPath(full_path); delegate_->DownloadRenamedToFinalName(this); if (delegate_->ShouldOpenDownload(this)) Completed(); else delegate_delayed_complete_ = true; BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::CompleteDownload, file_manager, GetGlobalId())); } } CWE ID: CWE-119 Target: 1 Example 2: Code: void OmniboxEditModel::SetSuggestionToPrefetch( const InstantSuggestion& suggestion) { delegate_->SetSuggestionToPrefetch(suggestion); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void V8TestObject::RuntimeCallStatsCounterMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE(info.GetIsolate(), RuntimeCallStats::CounterId::kRuntimeCallStatsCounterMethod); test_object_v8_internal::RuntimeCallStatsCounterMethodMethod(info); } 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 int ohci_bus_start(OHCIState *ohci) { ohci->eof_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ohci_frame_boundary, ohci); if (ohci->eof_timer == NULL) { trace_usb_ohci_bus_eof_timer_failed(ohci->name); ohci_die(ohci); return 0; } trace_usb_ohci_start(ohci->name); /* Delay the first SOF event by one frame time as if (ohci->eof_timer == NULL) { trace_usb_ohci_bus_eof_timer_failed(ohci->name); ohci_die(ohci); return 0; } trace_usb_ohci_start(ohci->name); /* Delay the first SOF event by one frame time as static void ohci_bus_stop(OHCIState *ohci) { trace_usb_ohci_stop(ohci->name); if (ohci->eof_timer) { timer_del(ohci->eof_timer); timer_free(ohci->eof_timer); } ohci->eof_timer = NULL; } /* Sets a flag in a port status register but only set it if the port is } CWE ID: Target: 1 Example 2: Code: lou_translateString(const char *tableList, const widechar *inbufx, int *inlen, widechar *outbuf, int *outlen, formtype *typeform, char *spacing, int mode) { return lou_translate(tableList, inbufx, inlen, outbuf, outlen, typeform, spacing, NULL, NULL, NULL, mode); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SynchronousCompositorOutputSurface::InvokeComposite( const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, gfx::Transform transform_for_tile_priority, bool hardware_draw) { DCHECK(!frame_holder_.get()); gfx::Transform adjusted_transform = transform; adjusted_transform.matrix().postTranslate(-viewport.x(), -viewport.y(), 0); SetExternalDrawConstraints(adjusted_transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority, !hardware_draw); if (!hardware_draw || next_hardware_draw_needs_damage_) { next_hardware_draw_needs_damage_ = false; SetNeedsRedrawRect(gfx::Rect(viewport.size())); } client_->OnDraw(); if (hardware_draw) { cached_hw_transform_ = adjusted_transform; cached_hw_viewport_ = viewport; cached_hw_clip_ = clip; cached_hw_viewport_rect_for_tile_priority_ = viewport_rect_for_tile_priority; cached_hw_transform_for_tile_priority_ = transform_for_tile_priority; } else { bool resourceless_software_draw = false; SetExternalDrawConstraints(cached_hw_transform_, cached_hw_viewport_, cached_hw_clip_, cached_hw_viewport_rect_for_tile_priority_, cached_hw_transform_for_tile_priority_, resourceless_software_draw); next_hardware_draw_needs_damage_ = true; } if (frame_holder_.get()) client_->DidSwapBuffersComplete(); } 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: OMX_ERRORTYPE omx_video::allocate_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) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes); if (!m_out_mem_ptr) { int nBufHdrSize = 0; DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sOutPortDef.nBufferSize, (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); #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 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; } if (m_out_mem_ptr && m_pOutput_pmem) { bufHdr = 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->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i]; 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: calloc() failed for m_out_mem_ptr/m_pOutput_pmem"); eRet = OMX_ErrorInsufficientResources; } } DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i); break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { #ifdef USE_ION #ifdef _MSM8974_ align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096; 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, ION_FLAG_CACHED); #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 in o/p alloc buffer"); close (m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); native_handle_t *handle = native_handle_create(1, 0); handle->data[0] = m_pOutput_pmem[i].fd; char *data = (char*) m_pOutput_pmem[i].buffer; OMX_U32 type = 1; memcpy(data, &type, sizeof(OMX_U32)); memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*)); } *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); 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; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call" "for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual); } } return eRet; } CWE ID: CWE-119 Target: 1 Example 2: Code: void CL_NextDownload( void ) { char *s; char *remoteName, *localName; qboolean useCURL = qfalse; if( *clc.downloadName ) { char *zippath = FS_BuildOSPath(Cvar_VariableString("fs_homepath"), clc.downloadName, ""); zippath[strlen(zippath)-1] = '\0'; if(!FS_CompareZipChecksum(zippath)) Com_Error(ERR_DROP, "Incorrect checksum for file: %s", clc.downloadName); } *clc.downloadTempName = *clc.downloadName = 0; Cvar_Set("cl_downloadName", ""); if ( *clc.downloadList ) { s = clc.downloadList; if ( *s == '@' ) { s++; } remoteName = s; if ( ( s = strchr( s, '@' ) ) == NULL ) { CL_DownloadsComplete(); return; } *s++ = 0; localName = s; if ( ( s = strchr( s, '@' ) ) != NULL ) { *s++ = 0; } else { s = localName + strlen( localName ); // point at the nul byte } #ifdef USE_CURL if(!(cl_allowDownload->integer & DLF_NO_REDIRECT)) { if(clc.sv_allowDownload & DLF_NO_REDIRECT) { Com_Printf("WARNING: server does not " "allow download redirection " "(sv_allowDownload is %d)\n", clc.sv_allowDownload); } else if(!*clc.sv_dlURL) { Com_Printf("WARNING: server allows " "download redirection, but does not " "have sv_dlURL set\n"); } else if(!CL_cURL_Init()) { Com_Printf("WARNING: could not load " "cURL library\n"); } else { CL_cURL_BeginDownload(localName, va("%s/%s", clc.sv_dlURL, remoteName)); useCURL = qtrue; } } else if(!(clc.sv_allowDownload & DLF_NO_REDIRECT)) { Com_Printf("WARNING: server allows download " "redirection, but it disabled by client " "configuration (cl_allowDownload is %d)\n", cl_allowDownload->integer); } #endif /* USE_CURL */ if(!useCURL) { if((cl_allowDownload->integer & DLF_NO_UDP)) { Com_Error(ERR_DROP, "UDP Downloads are " "disabled on your client. " "(cl_allowDownload is %d)", cl_allowDownload->integer); return; } else { CL_BeginDownload( localName, remoteName ); } } clc.downloadRestart = qtrue; memmove( clc.downloadList, s, strlen( s ) + 1 ); return; } CL_DownloadsComplete(); } CWE ID: CWE-269 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 sctp_getsockopt_local_addrs_old(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_bind_addr *bp; struct sctp_association *asoc; struct list_head *pos; int cnt = 0; struct sctp_getaddrs_old getaddrs; struct sctp_sockaddr_entry *addr; void __user *to; union sctp_addr temp; struct sctp_sock *sp = sctp_sk(sk); int addrlen; rwlock_t *addr_lock; int err = 0; if (len != sizeof(struct sctp_getaddrs_old)) return -EINVAL; if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs_old))) return -EFAULT; if (getaddrs.addr_num <= 0) return -EINVAL; /* * For UDP-style sockets, id specifies the association to query. * If the id field is set to the value '0' then the locally bound * addresses are returned without regard to any particular * association. */ if (0 == getaddrs.assoc_id) { bp = &sctp_sk(sk)->ep->base.bind_addr; addr_lock = &sctp_sk(sk)->ep->base.addr_lock; } else { asoc = sctp_id2assoc(sk, getaddrs.assoc_id); if (!asoc) return -EINVAL; bp = &asoc->base.bind_addr; addr_lock = &asoc->base.addr_lock; } to = getaddrs.addrs; sctp_read_lock(addr_lock); /* If the endpoint is bound to 0.0.0.0 or ::0, get the valid * addresses from the global local address list. */ if (sctp_list_single_entry(&bp->address_list)) { addr = list_entry(bp->address_list.next, struct sctp_sockaddr_entry, list); if (sctp_is_any(&addr->a)) { cnt = sctp_copy_laddrs_to_user_old(sk, bp->port, getaddrs.addr_num, to); if (cnt < 0) { err = cnt; goto unlock; } goto copy_getaddrs; } } list_for_each(pos, &bp->address_list) { addr = list_entry(pos, struct sctp_sockaddr_entry, list); memcpy(&temp, &addr->a, sizeof(temp)); sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp); addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len; if (copy_to_user(to, &temp, addrlen)) { err = -EFAULT; goto unlock; } to += addrlen; cnt ++; if (cnt >= getaddrs.addr_num) break; } copy_getaddrs: getaddrs.addr_num = cnt; if (copy_to_user(optval, &getaddrs, sizeof(struct sctp_getaddrs_old))) err = -EFAULT; unlock: sctp_read_unlock(addr_lock); return err; } CWE ID: Output:
0