prompt
stringlengths
799
20.4k
output
int64
0
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void IndexedDBTransaction::Abort(const IndexedDBDatabaseError& error) { IDB_TRACE1("IndexedDBTransaction::Abort", "txn.id", id()); DCHECK(!processing_event_queue_); if (state_ == FINISHED) return; UMA_HISTOGRAM_ENUMERATION("WebCore.IndexedDB.TransactionAbortReason", ExceptionCodeToUmaEnum(error.code()), UmaIDBExceptionExclusiveMaxValue); timeout_timer_.Stop(); state_ = FINISHED; should_process_queue_ = false; if (backing_store_transaction_begun_) transaction_->Rollback(); while (!abort_task_stack_.empty()) abort_task_stack_.pop().Run(); preemptive_task_queue_.clear(); pending_preemptive_events_ = 0; task_queue_.clear(); CloseOpenCursors(); transaction_->Reset(); database_->transaction_coordinator().DidFinishTransaction(this); #ifndef NDEBUG DCHECK(!database_->transaction_coordinator().IsActive(this)); #endif if (callbacks_.get()) callbacks_->OnAbort(*this, error); database_->TransactionFinished(this, false); connection_->RemoveTransaction(id_); } CWE ID: Target: 1 Example 2: Code: void V8TestObject::UnsignedLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_unsignedLongAttribute_Getter"); test_object_v8_internal::UnsignedLongAttributeAttributeGetter(info); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: R_API bool r_config_save_char(RConfigHold *h, ...) { va_list ap; char *key; if (!h->list_char) { h->list_char = r_list_newf ((RListFree) free); if (!h->list_char) { return false; } } va_start (ap, h); while ((key = va_arg (ap, char *))) { RConfigHoldChar *hc = R_NEW0 (RConfigHoldChar); if (!hc) { continue; } hc->key = key; hc->value = r_config_get (h->cfg, key); r_list_append (h->list_char, hc); } va_end (ap); return true; } 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: _handle_carbons(xmpp_stanza_t *const stanza) { xmpp_stanza_t *carbons = xmpp_stanza_get_child_by_ns(stanza, STANZA_NS_CARBONS); if (!carbons) { return FALSE; } const char *name = xmpp_stanza_get_name(carbons); if (!name) { log_error("Unable to retrieve stanza name for Carbon"); return TRUE; } if (g_strcmp0(name, "private") == 0) { log_info("Carbon received with private element."); return FALSE; } if ((g_strcmp0(name, "received") != 0) && (g_strcmp0(name, "sent") != 0)) { log_warning("Carbon received with unrecognised stanza name: %s", name); return TRUE; } xmpp_stanza_t *forwarded = xmpp_stanza_get_child_by_ns(carbons, STANZA_NS_FORWARD); if (!forwarded) { log_warning("Carbon received with no forwarded element"); return TRUE; } xmpp_stanza_t *message = xmpp_stanza_get_child_by_name(forwarded, STANZA_NAME_MESSAGE); if (!message) { log_warning("Carbon received with no message element"); return TRUE; } char *message_txt = xmpp_message_get_body(message); if (!message_txt) { log_warning("Carbon received with no message."); return TRUE; } const gchar *to = xmpp_stanza_get_to(message); const gchar *from = xmpp_stanza_get_from(message); if (!to) to = from; Jid *jid_from = jid_create(from); Jid *jid_to = jid_create(to); Jid *my_jid = jid_create(connection_get_fulljid()); char *enc_message = NULL; xmpp_stanza_t *x = xmpp_stanza_get_child_by_ns(message, STANZA_NS_ENCRYPTED); if (x) { enc_message = xmpp_stanza_get_text(x); } if (g_strcmp0(my_jid->barejid, jid_to->barejid) == 0) { sv_ev_incoming_carbon(jid_from->barejid, jid_from->resourcepart, message_txt, enc_message); } else { sv_ev_outgoing_carbon(jid_to->barejid, message_txt, enc_message); } xmpp_ctx_t *ctx = connection_get_ctx(); xmpp_free(ctx, message_txt); xmpp_free(ctx, enc_message); jid_destroy(jid_from); jid_destroy(jid_to); jid_destroy(my_jid); return TRUE; } CWE ID: CWE-346 Target: 1 Example 2: Code: monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit) { while (ent->f != NULL) { if (ent->type == type) { ent->flags &= ~MON_PERMIT; ent->flags |= permit ? MON_PERMIT : 0; return; } ent++; } } 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: Image *AutoResizeImage(const Image *image,const char *option, MagickOffsetType *count,ExceptionInfo *exception) { #define MAX_SIZES 16 char *q; const char *p; Image *resized, *images; register ssize_t i; size_t sizes[MAX_SIZES]={256,192,128,96,64,48,40,32,24,16}; images=NULL; *count=0; i=0; p=option; while (*p != '\0' && i < MAX_SIZES) { size_t size; while ((isspace((int) ((unsigned char) *p)) != 0)) p++; size=(size_t)strtol(p,&q,10); if (p == q || size < 16 || size > 256) return((Image *) NULL); p=q; sizes[i++]=size; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (i==0) i=10; *count=i; for (i=0; i < *count; i++) { resized=ResizeImage(image,sizes[i],sizes[i],image->filter,exception); if (resized == (Image *) NULL) return(DestroyImageList(images)); if (images == (Image *) NULL) images=resized; else AppendImageToList(&images,resized); } return(images); } 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 ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait, struct uffd_msg *msg) { ssize_t ret; DECLARE_WAITQUEUE(wait, current); struct userfaultfd_wait_queue *uwq; /* * Handling fork event requires sleeping operations, so * we drop the event_wqh lock, then do these ops, then * lock it back and wake up the waiter. While the lock is * dropped the ewq may go away so we keep track of it * carefully. */ LIST_HEAD(fork_event); struct userfaultfd_ctx *fork_nctx = NULL; /* always take the fd_wqh lock before the fault_pending_wqh lock */ spin_lock(&ctx->fd_wqh.lock); __add_wait_queue(&ctx->fd_wqh, &wait); for (;;) { set_current_state(TASK_INTERRUPTIBLE); spin_lock(&ctx->fault_pending_wqh.lock); uwq = find_userfault(ctx); if (uwq) { /* * Use a seqcount to repeat the lockless check * in wake_userfault() to avoid missing * wakeups because during the refile both * waitqueue could become empty if this is the * only userfault. */ write_seqcount_begin(&ctx->refile_seq); /* * The fault_pending_wqh.lock prevents the uwq * to disappear from under us. * * Refile this userfault from * fault_pending_wqh to fault_wqh, it's not * pending anymore after we read it. * * Use list_del() by hand (as * userfaultfd_wake_function also uses * list_del_init() by hand) to be sure nobody * changes __remove_wait_queue() to use * list_del_init() in turn breaking the * !list_empty_careful() check in * handle_userfault(). The uwq->wq.head list * must never be empty at any time during the * refile, or the waitqueue could disappear * from under us. The "wait_queue_head_t" * parameter of __remove_wait_queue() is unused * anyway. */ list_del(&uwq->wq.entry); __add_wait_queue(&ctx->fault_wqh, &uwq->wq); write_seqcount_end(&ctx->refile_seq); /* careful to always initialize msg if ret == 0 */ *msg = uwq->msg; spin_unlock(&ctx->fault_pending_wqh.lock); ret = 0; break; } spin_unlock(&ctx->fault_pending_wqh.lock); spin_lock(&ctx->event_wqh.lock); uwq = find_userfault_evt(ctx); if (uwq) { *msg = uwq->msg; if (uwq->msg.event == UFFD_EVENT_FORK) { fork_nctx = (struct userfaultfd_ctx *) (unsigned long) uwq->msg.arg.reserved.reserved1; list_move(&uwq->wq.entry, &fork_event); spin_unlock(&ctx->event_wqh.lock); ret = 0; break; } userfaultfd_event_complete(ctx, uwq); spin_unlock(&ctx->event_wqh.lock); ret = 0; break; } spin_unlock(&ctx->event_wqh.lock); if (signal_pending(current)) { ret = -ERESTARTSYS; break; } if (no_wait) { ret = -EAGAIN; break; } spin_unlock(&ctx->fd_wqh.lock); schedule(); spin_lock(&ctx->fd_wqh.lock); } __remove_wait_queue(&ctx->fd_wqh, &wait); __set_current_state(TASK_RUNNING); spin_unlock(&ctx->fd_wqh.lock); if (!ret && msg->event == UFFD_EVENT_FORK) { ret = resolve_userfault_fork(ctx, fork_nctx, msg); if (!ret) { spin_lock(&ctx->event_wqh.lock); if (!list_empty(&fork_event)) { uwq = list_first_entry(&fork_event, typeof(*uwq), wq.entry); list_del(&uwq->wq.entry); __add_wait_queue(&ctx->event_wqh, &uwq->wq); userfaultfd_event_complete(ctx, uwq); } spin_unlock(&ctx->event_wqh.lock); } } return ret; } CWE ID: CWE-416 Target: 1 Example 2: Code: void HTMLCanvasElement::UpdateMemoryUsage() { int non_gpu_buffer_count = 0; int gpu_buffer_count = 0; if (!Is2d() && !Is3d()) return; if (ResourceProvider()) { non_gpu_buffer_count++; if (IsAccelerated()) { gpu_buffer_count += 2; } } if (Is3d()) non_gpu_buffer_count += context_->ExternallyAllocatedBufferCountPerPixel(); const int bytes_per_pixel = ColorParams().BytesPerPixel(); if (gpu_buffer_count && !gpu_memory_usage_) { base::CheckedNumeric<intptr_t> checked_usage = gpu_buffer_count * bytes_per_pixel; checked_usage *= width(); checked_usage *= height(); intptr_t gpu_memory_usage = checked_usage.ValueOrDefault(std::numeric_limits<intptr_t>::max()); global_gpu_memory_usage_ += (gpu_memory_usage - gpu_memory_usage_); gpu_memory_usage_ = gpu_memory_usage; global_accelerated_context_count_++; } else if (!gpu_buffer_count && gpu_memory_usage_) { DCHECK_GT(global_accelerated_context_count_, 0u); global_accelerated_context_count_--; global_gpu_memory_usage_ -= gpu_memory_usage_; gpu_memory_usage_ = 0; } base::CheckedNumeric<intptr_t> checked_usage = non_gpu_buffer_count * bytes_per_pixel; checked_usage *= width(); checked_usage *= height(); checked_usage += gpu_memory_usage_; intptr_t externally_allocated_memory = checked_usage.ValueOrDefault(std::numeric_limits<intptr_t>::max()); v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory( externally_allocated_memory - externally_allocated_memory_); externally_allocated_memory_ = externally_allocated_memory; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ExtensionSettingsHandler::MultiFilesSelected( const std::vector<FilePath>& files, void* params) { NOTREACHED(); } 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 b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1) - 1; defaultoptions(&h); lua_settop(L, 2); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); luaL_checkstack(L, 1, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); break; } case 'c': { if (size == 0) { if (!lua_isnumber(L, -1)) luaL_error(L, "format `c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); return lua_gettop(L) - 2; } CWE ID: CWE-190 Target: 1 Example 2: Code: SoftRaw::SoftRaw( const char *name, const OMX_CALLBACKTYPE *callbacks, OMX_PTR appData, OMX_COMPONENTTYPE **component) : SimpleSoftOMXComponent(name, callbacks, appData, component), mSignalledError(false), mChannelCount(2), mSampleRate(44100) { initPorts(); CHECK_EQ(initDecoder(), (status_t)OK); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int simulate_rdhwr(struct pt_regs *regs, unsigned int opcode) { struct thread_info *ti = task_thread_info(current); if ((opcode & OPCODE) == SPEC3 && (opcode & FUNC) == RDHWR) { int rd = (opcode & RD) >> 11; int rt = (opcode & RT) >> 16; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); switch (rd) { case 0: /* CPU number */ regs->regs[rt] = smp_processor_id(); return 0; case 1: /* SYNCI length */ regs->regs[rt] = min(current_cpu_data.dcache.linesz, current_cpu_data.icache.linesz); return 0; case 2: /* Read count register */ regs->regs[rt] = read_c0_count(); return 0; case 3: /* Count register resolution */ switch (current_cpu_data.cputype) { case CPU_20KC: case CPU_25KF: regs->regs[rt] = 1; break; default: regs->regs[rt] = 2; } return 0; case 29: regs->regs[rt] = ti->tp_value; return 0; default: return -1; } } /* Not ours. */ 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: static unsigned int seedsize(struct crypto_alg *alg) { struct rng_alg *ralg = container_of(alg, struct rng_alg, base); return alg->cra_rng.rng_make_random ? alg->cra_rng.seedsize : ralg->seedsize; } CWE ID: CWE-476 Target: 1 Example 2: Code: string16 FindPrepopulateText(TabContents* contents) { return FindBarState::GetLastPrepopulateText(contents->profile()); } 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 SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) { return; } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); if (mHeadersDecoded) { drainAllOutputBuffers(false /* eos */); } H264SwDecRet ret = H264SWDEC_PIC_RDY; bool portWillReset = false; while ((mEOSStatus != INPUT_DATA_AVAILABLE || !inQueue.empty()) && outQueue.size() == kNumOutputBuffers) { if (mEOSStatus == INPUT_EOS_SEEN) { drainAllOutputBuffers(true /* eos */); return; } BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; ++mPicId; OMX_BUFFERHEADERTYPE *header = new OMX_BUFFERHEADERTYPE; memset(header, 0, sizeof(OMX_BUFFERHEADERTYPE)); header->nTimeStamp = inHeader->nTimeStamp; header->nFlags = inHeader->nFlags; if (header->nFlags & OMX_BUFFERFLAG_EOS) { mEOSStatus = INPUT_EOS_SEEN; } mPicToHeaderMap.add(mPicId, header); inQueue.erase(inQueue.begin()); H264SwDecInput inPicture; H264SwDecOutput outPicture; memset(&inPicture, 0, sizeof(inPicture)); inPicture.dataLen = inHeader->nFilledLen; inPicture.pStream = inHeader->pBuffer + inHeader->nOffset; inPicture.picId = mPicId; inPicture.intraConcealmentMethod = 1; H264SwDecPicture decodedPicture; while (inPicture.dataLen > 0) { ret = H264SwDecDecode(mHandle, &inPicture, &outPicture); if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY || ret == H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY) { inPicture.dataLen -= (u32)(outPicture.pStrmCurrPos - inPicture.pStream); inPicture.pStream = outPicture.pStrmCurrPos; if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY) { mHeadersDecoded = true; H264SwDecInfo decoderInfo; CHECK(H264SwDecGetInfo(mHandle, &decoderInfo) == H264SWDEC_OK); SoftVideoDecoderOMXComponent::CropSettingsMode cropSettingsMode = handleCropParams(decoderInfo); handlePortSettingsChange( &portWillReset, decoderInfo.picWidth, decoderInfo.picHeight, cropSettingsMode); } } else { if (portWillReset) { if (H264SwDecNextPicture(mHandle, &decodedPicture, 0) == H264SWDEC_PIC_RDY) { saveFirstOutputBuffer( decodedPicture.picId, (uint8_t *)decodedPicture.pOutputPicture); } } inPicture.dataLen = 0; if (ret < 0) { ALOGE("Decoder failed: %d", ret); notify(OMX_EventError, OMX_ErrorUndefined, ERROR_MALFORMED, NULL); mSignalledError = true; return; } } } inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); if (portWillReset) { return; } if (mFirstPicture && !outQueue.empty()) { drainOneOutputBuffer(mFirstPictureId, mFirstPicture); delete[] mFirstPicture; mFirstPicture = NULL; mFirstPictureId = -1; } drainAllOutputBuffers(false /* eos */); } } 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 Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile"); length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file); length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\000\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite("\001\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file); length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file); length=fwrite("\021\001\003\000\001\000\000\000",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite("\022\001\003\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file); length=fwrite("\026\001\004\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite("\032\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\033\001\005\000\001\000\000\000",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file); length=fwrite("\000\000\000\000",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); for (length=0; (c=ReadBlobByte(image)) != EOF; length++) (void) fputc(c,file); offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,"GROUP4",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); return(image); } CWE ID: CWE-20 Target: 1 Example 2: Code: UsbConnectionFunction::UsbConnectionFunction() { } 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: int uipc_start_main_server_thread(void) { uipc_main.running = 1; if (pthread_create(&uipc_main.tid, (const pthread_attr_t *) NULL, (void*)uipc_read_task, NULL) < 0) { BTIF_TRACE_ERROR("uipc_thread_create pthread_create failed:%d", errno); return -1; } return 0; } 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: verify_client_san(krb5_context context, pkinit_kdc_context plgctx, pkinit_kdc_req_context reqctx, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_const_principal client, int *valid_san) { krb5_error_code retval; krb5_principal *princs = NULL; krb5_principal *upns = NULL; int i; #ifdef DEBUG_SAN_INFO char *client_string = NULL, *san_string; #endif *valid_san = 0; retval = crypto_retrieve_cert_sans(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &princs, plgctx->opts->allow_upn ? &upns : NULL, NULL); if (retval == ENOENT) { TRACE_PKINIT_SERVER_NO_SAN(context); goto out; } else if (retval) { pkiDebug("%s: error from retrieve_certificate_sans()\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } /* XXX Verify this is consistent with client side XXX */ #if 0 retval = call_san_checking_plugins(context, plgctx, reqctx, princs, upns, NULL, &plugin_decision, &ignore); pkiDebug("%s: call_san_checking_plugins() returned retval %d\n", __FUNCTION__); if (retval) { retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto cleanup; } pkiDebug("%s: call_san_checking_plugins() returned decision %d\n", __FUNCTION__, plugin_decision); if (plugin_decision != NO_DECISION) { retval = plugin_decision; goto out; } #endif #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, client, &client_string); #endif pkiDebug("%s: Checking pkinit sans\n", __FUNCTION__); for (i = 0; princs != NULL && princs[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, princs[i], &san_string); pkiDebug("%s: Comparing client '%s' to pkinit san value '%s'\n", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, princs[i])) { TRACE_PKINIT_SERVER_MATCHING_SAN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug("%s: no pkinit san match found\n", __FUNCTION__); /* * XXX if cert has names but none match, should we * be returning KRB5KDC_ERR_CLIENT_NAME_MISMATCH here? */ if (upns == NULL) { pkiDebug("%s: no upn sans (or we wouldn't accept them anyway)\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } pkiDebug("%s: Checking upn sans\n", __FUNCTION__); for (i = 0; upns[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, upns[i], &san_string); pkiDebug("%s: Comparing client '%s' to upn san value '%s'\n", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, upns[i])) { TRACE_PKINIT_SERVER_MATCHING_UPN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug("%s: no upn san match found\n", __FUNCTION__); /* We found no match */ if (princs != NULL || upns != NULL) { *valid_san = 0; /* XXX ??? If there was one or more name in the cert, but * none matched the client name, then return mismatch? */ retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; } retval = 0; out: if (princs != NULL) { for (i = 0; princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); } if (upns != NULL) { for (i = 0; upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); } #ifdef DEBUG_SAN_INFO if (client_string != NULL) krb5_free_unparsed_name(context, client_string); #endif pkiDebug("%s: returning retval %d, valid_san %d\n", __FUNCTION__, retval, *valid_san); return retval; } CWE ID: CWE-287 Target: 1 Example 2: Code: void RenderFrameImpl::OnSwapOut( int proxy_routing_id, bool is_loading, const FrameReplicationState& replicated_frame_state) { TRACE_EVENT1("navigation,rail", "RenderFrameImpl::OnSwapOut", "id", routing_id_); SendUpdateState(); CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE); RenderFrameProxy* proxy = RenderFrameProxy::CreateProxyToReplaceFrame( this, proxy_routing_id, replicated_frame_state.scope); if (is_main_frame_) { render_view_->GetWidget()->SetIsFrozen(true); } RenderViewImpl* render_view = render_view_; bool is_main_frame = is_main_frame_; int routing_id = GetRoutingID(); scoped_refptr<base::SingleThreadTaskRunner> task_runner = GetTaskRunner(blink::TaskType::kPostedMessage); bool success = frame_->Swap(proxy->web_frame()); if (is_main_frame) { DCHECK(success); CHECK(!render_view->main_render_frame_); } if (!success) { proxy->FrameDetached(blink::WebRemoteFrameClient::DetachType::kSwap); return; } if (is_loading) proxy->OnDidStartLoading(); proxy->SetReplicatedState(replicated_frame_state); auto send_swapout_ack = base::BindOnce( [](int routing_id, bool is_main_frame) { RenderThread::Get()->Send(new FrameHostMsg_SwapOut_ACK(routing_id)); }, routing_id, is_main_frame); task_runner->PostTask(FROM_HERE, std::move(send_swapout_ack)); } 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 TraceQuadraticBezier(FT_Vector *control,FT_Vector *to, DrawInfo *draw_info) { AffineMatrix affine; char path[MagickPathExtent]; affine=draw_info->affine; (void) FormatLocaleString(path,MagickPathExtent,"Q%g,%g %g,%g",affine.tx+ control->x/64.0,affine.ty-control->y/64.0,affine.tx+to->x/64.0,affine.ty- to->y/64.0); (void) ConcatenateString(&draw_info->primitive,path); return(0); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RTCPeerConnection::setLocalDescription(PassRefPtr<RTCSessionDescription> prpSessionDescription, PassRefPtr<VoidCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback, ExceptionCode& ec) { if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) { ec = INVALID_STATE_ERR; return; } RefPtr<RTCSessionDescription> sessionDescription = prpSessionDescription; if (!sessionDescription) { ec = TYPE_MISMATCH_ERR; return; } RefPtr<RTCVoidRequestImpl> request = RTCVoidRequestImpl::create(scriptExecutionContext(), successCallback, errorCallback); m_peerHandler->setLocalDescription(request.release(), sessionDescription->descriptor()); } CWE ID: CWE-20 Target: 1 Example 2: Code: xfs_get_blocks_direct( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { return __xfs_get_blocks(inode, iblock, bh_result, create, true, false); } 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 igmp_send_report(struct in_device *in_dev, struct ip_mc_list *pmc, int type) { struct sk_buff *skb; struct iphdr *iph; struct igmphdr *ih; struct rtable *rt; struct net_device *dev = in_dev->dev; struct net *net = dev_net(dev); __be32 group = pmc ? pmc->multiaddr : 0; struct flowi4 fl4; __be32 dst; int hlen, tlen; if (type == IGMPV3_HOST_MEMBERSHIP_REPORT) return igmpv3_send_report(in_dev, pmc); else if (type == IGMP_HOST_LEAVE_MESSAGE) dst = IGMP_ALL_ROUTER; else dst = group; rt = ip_route_output_ports(net, &fl4, NULL, dst, 0, 0, 0, IPPROTO_IGMP, 0, dev->ifindex); if (IS_ERR(rt)) return -1; hlen = LL_RESERVED_SPACE(dev); tlen = dev->needed_tailroom; skb = alloc_skb(IGMP_SIZE + hlen + tlen, GFP_ATOMIC); if (skb == NULL) { ip_rt_put(rt); return -1; } skb_dst_set(skb, &rt->dst); skb_reserve(skb, hlen); skb_reset_network_header(skb); iph = ip_hdr(skb); skb_put(skb, sizeof(struct iphdr) + 4); iph->version = 4; iph->ihl = (sizeof(struct iphdr)+4)>>2; iph->tos = 0xc0; iph->frag_off = htons(IP_DF); iph->ttl = 1; iph->daddr = dst; iph->saddr = fl4.saddr; iph->protocol = IPPROTO_IGMP; ip_select_ident(iph, &rt->dst, NULL); ((u8*)&iph[1])[0] = IPOPT_RA; ((u8*)&iph[1])[1] = 4; ((u8*)&iph[1])[2] = 0; ((u8*)&iph[1])[3] = 0; ih = (struct igmphdr *)skb_put(skb, sizeof(struct igmphdr)); ih->type = type; ih->code = 0; ih->csum = 0; ih->group = group; ih->csum = ip_compute_csum((void *)ih, sizeof(struct igmphdr)); return ip_local_out(skb); } 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: int main(int argc, char **argv) { FILE *infile = NULL; VpxVideoWriter *writer = NULL; vpx_codec_ctx_t codec; vpx_codec_enc_cfg_t cfg; vpx_image_t raw; vpx_codec_err_t res; vpx_fixed_buf_t stats = {0}; VpxVideoInfo info = {0}; const VpxInterface *encoder = NULL; int pass; const int fps = 30; // TODO(dkovalev) add command line argument const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument const char *const codec_arg = argv[1]; const char *const width_arg = argv[2]; const char *const height_arg = argv[3]; const char *const infile_arg = argv[4]; const char *const outfile_arg = argv[5]; exec_name = argv[0]; if (argc != 6) die("Invalid number of arguments."); encoder = get_vpx_encoder_by_name(codec_arg); if (!encoder) die("Unsupported codec."); info.codec_fourcc = encoder->fourcc; info.time_base.numerator = 1; info.time_base.denominator = fps; info.frame_width = strtol(width_arg, NULL, 0); info.frame_height = strtol(height_arg, NULL, 0); if (info.frame_width <= 0 || info.frame_height <= 0 || (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) { die("Invalid frame size: %dx%d", info.frame_width, info.frame_height); } if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width, info.frame_height, 1)) { die("Failed to allocate image", info.frame_width, info.frame_height); } writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info); if (!writer) die("Failed to open %s for writing", outfile_arg); printf("Using %s\n", vpx_codec_iface_name(encoder->interface())); res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0); if (res) die_codec(&codec, "Failed to get default codec config."); cfg.g_w = info.frame_width; cfg.g_h = info.frame_height; cfg.g_timebase.num = info.time_base.numerator; cfg.g_timebase.den = info.time_base.denominator; cfg.rc_target_bitrate = bitrate; for (pass = 0; pass < 2; ++pass) { int frame_count = 0; if (pass == 0) { cfg.g_pass = VPX_RC_FIRST_PASS; } else { cfg.g_pass = VPX_RC_LAST_PASS; cfg.rc_twopass_stats_in = stats; } if (!(infile = fopen(infile_arg, "rb"))) die("Failed to open %s for reading", infile_arg); if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); while (vpx_img_read(&raw, infile)) { ++frame_count; if (pass == 0) { get_frame_stats(&codec, &raw, frame_count, 1, 0, VPX_DL_BEST_QUALITY, &stats); } else { encode_frame(&codec, &raw, frame_count, 1, 0, VPX_DL_BEST_QUALITY, writer); } } if (pass == 0) { get_frame_stats(&codec, NULL, frame_count, 1, 0, VPX_DL_BEST_QUALITY, &stats); } else { printf("\n"); } fclose(infile); printf("Pass %d complete. Processed %d frames.\n", pass + 1, frame_count); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); } vpx_img_free(&raw); free(stats.buf); vpx_video_writer_close(writer); return EXIT_SUCCESS; } CWE ID: CWE-119 Target: 1 Example 2: Code: ssize_t tpm_show_enabled(struct device * dev, struct device_attribute * attr, char *buf) { cap_t cap; ssize_t rc; rc = tpm_getcap(dev, TPM_CAP_FLAG_PERM, &cap, "attempting to determine the permanent enabled state"); if (rc) return 0; rc = sprintf(buf, "%d\n", !cap.perm_flags.disable); return rc; } 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 ssize_t ucma_query_gid(struct ucma_context *ctx, void __user *response, int out_len) { struct rdma_ucm_query_addr_resp resp; struct sockaddr_ib *addr; int ret = 0; if (out_len < sizeof(resp)) return -ENOSPC; memset(&resp, 0, sizeof resp); ucma_query_device_addr(ctx->cm_id, &resp); addr = (struct sockaddr_ib *) &resp.src_addr; resp.src_size = sizeof(*addr); if (ctx->cm_id->route.addr.src_addr.ss_family == AF_IB) { memcpy(addr, &ctx->cm_id->route.addr.src_addr, resp.src_size); } else { addr->sib_family = AF_IB; addr->sib_pkey = (__force __be16) resp.pkey; rdma_read_gids(ctx->cm_id, (union ib_gid *)&addr->sib_addr, NULL); addr->sib_sid = rdma_get_service_id(ctx->cm_id, (struct sockaddr *) &ctx->cm_id->route.addr.src_addr); } addr = (struct sockaddr_ib *) &resp.dst_addr; resp.dst_size = sizeof(*addr); if (ctx->cm_id->route.addr.dst_addr.ss_family == AF_IB) { memcpy(addr, &ctx->cm_id->route.addr.dst_addr, resp.dst_size); } else { addr->sib_family = AF_IB; addr->sib_pkey = (__force __be16) resp.pkey; rdma_read_gids(ctx->cm_id, NULL, (union ib_gid *)&addr->sib_addr); addr->sib_sid = rdma_get_service_id(ctx->cm_id, (struct sockaddr *) &ctx->cm_id->route.addr.dst_addr); } if (copy_to_user(response, &resp, sizeof(resp))) ret = -EFAULT; return ret; } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void perf_log_throttle(struct perf_event *event, int enable) { struct perf_output_handle handle; struct perf_sample_data sample; int ret; struct { struct perf_event_header header; u64 time; u64 id; u64 stream_id; } throttle_event = { .header = { .type = PERF_RECORD_THROTTLE, .misc = 0, .size = sizeof(throttle_event), }, .time = perf_clock(), .id = primary_event_id(event), .stream_id = event->id, }; if (enable) throttle_event.header.type = PERF_RECORD_UNTHROTTLE; perf_event_header__init_id(&throttle_event.header, &sample, event); ret = perf_output_begin(&handle, event, throttle_event.header.size, 1, 0); if (ret) return; perf_output_put(&handle, throttle_event); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } CWE ID: CWE-399 Target: 1 Example 2: Code: PanoramiXRenderCreatePicture (ClientPtr client) { REQUEST(xRenderCreatePictureReq); PanoramiXRes *refDraw, *newPict; int result, j; REQUEST_AT_LEAST_SIZE(xRenderCreatePictureReq); result = dixLookupResourceByClass((pointer *)&refDraw, stuff->drawable, XRC_DRAWABLE, client, DixWriteAccess); if (result != Success) return (result == BadValue) ? BadDrawable : result; if(!(newPict = (PanoramiXRes *) malloc(sizeof(PanoramiXRes)))) return BadAlloc; newPict->type = XRT_PICTURE; newPict->info[0].id = stuff->pid; if (refDraw->type == XRT_WINDOW && stuff->drawable == screenInfo.screens[0]->root->drawable.id) { newPict->u.pict.root = TRUE; } else newPict->u.pict.root = FALSE; for(j = 1; j < PanoramiXNumScreens; j++) newPict->info[j].id = FakeClientID(client->index); FOR_NSCREENS_BACKWARD(j) { stuff->pid = newPict->info[j].id; stuff->drawable = refDraw->info[j].id; result = (*PanoramiXSaveRenderVector[X_RenderCreatePicture]) (client); if(result != Success) break; } if (result == Success) AddResource(newPict->info[0].id, XRT_PICTURE, newPict); else free(newPict); return result; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderProcessHostImpl::WidgetRestored() { visible_widgets_++; UpdateProcessPriority(); } 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: int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int seof= -1,eof=0,rv= -1,ret=0,i,v,tmp,n,ln,exp_nl; unsigned char *d; n=ctx->num; d=ctx->enc_data; ln=ctx->line_num; exp_nl=ctx->expect_nl; /* last line of input. */ if ((inl == 0) || ((n == 0) && (conv_ascii2bin(in[0]) == B64_EOF))) { rv=0; goto end; } /* We parse the input data */ for (i=0; i<inl; i++) { /* If the current line is > 80 characters, scream alot */ if (ln >= 80) { rv= -1; goto end; } /* Get char and put it into the buffer */ tmp= *(in++); v=conv_ascii2bin(tmp); /* only save the good data :-) */ if (!B64_NOT_BASE64(v)) { OPENSSL_assert(n < (int)sizeof(ctx->enc_data)); d[n++]=tmp; ln++; } else if (v == B64_ERROR) { rv= -1; goto end; } /* have we seen a '=' which is 'definitly' the last * input line. seof will point to the character that * holds it. and eof will hold how many characters to * chop off. */ if (tmp == '=') { if (seof == -1) seof=n; eof++; } if (v == B64_CR) { ln = 0; if (exp_nl) continue; } /* eoln */ if (v == B64_EOLN) { ln=0; if (exp_nl) { exp_nl=0; continue; } } exp_nl=0; /* If we are at the end of input and it looks like a * line, process it. */ if (((i+1) == inl) && (((n&3) == 0) || eof)) { v=B64_EOF; /* In case things were given us in really small records (so two '=' were given in separate updates), eof may contain the incorrect number of ending bytes to skip, so let's redo the count */ eof = 0; if (d[n-1] == '=') eof++; if (d[n-2] == '=') eof++; /* There will never be more than two '=' */ } if ((v == B64_EOF && (n&3) == 0) || (n >= 64)) { /* This is needed to work correctly on 64 byte input * lines. We process the line and then need to * accept the '\n' */ if ((v != B64_EOF) && (n >= 64)) exp_nl=1; if (n > 0) { v=EVP_DecodeBlock(out,d,n); n=0; if (v < 0) { rv=0; goto end; } ret+=(v-eof); } else eof=1; v=0; } /* This is the case where we have had a short * but valid input line */ if ((v < ctx->length) && eof) { rv=0; goto end; } else ctx->length=v; if (seof >= 0) { rv=0; goto end; } out+=v; } } CWE ID: CWE-119 Target: 1 Example 2: Code: static PassRefPtr<CSSPrimitiveValue> fontWeightFromStyle(RenderStyle* style) { switch (style->fontDescription().weight()) { case FontWeight100: return cssValuePool().createIdentifierValue(CSSValue100); case FontWeight200: return cssValuePool().createIdentifierValue(CSSValue200); case FontWeight300: return cssValuePool().createIdentifierValue(CSSValue300); case FontWeightNormal: return cssValuePool().createIdentifierValue(CSSValueNormal); case FontWeight500: return cssValuePool().createIdentifierValue(CSSValue500); case FontWeight600: return cssValuePool().createIdentifierValue(CSSValue600); case FontWeightBold: return cssValuePool().createIdentifierValue(CSSValueBold); case FontWeight800: return cssValuePool().createIdentifierValue(CSSValue800); case FontWeight900: return cssValuePool().createIdentifierValue(CSSValue900); } ASSERT_NOT_REACHED(); return cssValuePool().createIdentifierValue(CSSValueNormal); } 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 BluetoothOptionsHandler::DeviceFound(const std::string& adapter_id, chromeos::BluetoothDevice* device) { VLOG(2) << "Device found on " << adapter_id; DCHECK(device); web_ui_->CallJavascriptFunction( "options.SystemOptions.addBluetoothDevice", device->AsDictionary()); } 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: MagickExport void RemoveDuplicateLayers(Image **images, ExceptionInfo *exception) { register Image *curr, *next; RectangleInfo bounds; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); curr=GetFirstImageInList(*images); for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next) { if ( curr->columns != next->columns || curr->rows != next->rows || curr->page.x != next->page.x || curr->page.y != next->page.y ) continue; bounds=CompareImageBounds(curr,next,CompareAnyLayer,exception); if ( bounds.x < 0 ) { /* the two images are the same, merge time delays and delete one. */ size_t time; time = curr->delay*1000/curr->ticks_per_second; time += next->delay*1000/next->ticks_per_second; next->ticks_per_second = 100L; next->delay = time*curr->ticks_per_second/1000; next->iterations = curr->iterations; *images = curr; (void) DeleteImageFromList(images); } } *images = GetFirstImageInList(*images); } CWE ID: CWE-369 Target: 1 Example 2: Code: AMediaCodec* AMediaCodec_createDecoderByType(const char *mime_type) { return createAMediaCodec(mime_type, true, 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: void WebMediaPlayerMS::OnIdleTimeout() {} 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: int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; } CWE ID: CWE-125 Target: 1 Example 2: Code: static void iwbmp_write_file_header(struct iwbmpwcontext *wctx) { iw_byte fileheader[14]; if(!wctx->include_file_header) return; iw_zeromem(fileheader,sizeof(fileheader)); fileheader[0] = 66; // 'B' fileheader[1] = 77; // 'M' iw_set_ui32le(&fileheader[ 2], (unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize+wctx->unc_bitssize)); // bfSize iw_set_ui32le(&fileheader[10],(unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize)); // bfOffBits iwbmp_write(wctx,fileheader,14); } 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: void pasp_del(GF_Box *s) { GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox*)s; if (ptr == NULL) return; gf_free(ptr); } 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 snd_usb_mixer_disconnect(struct usb_mixer_interface *mixer) { usb_kill_urb(mixer->urb); usb_kill_urb(mixer->rc_urb); } CWE ID: CWE-416 Target: 1 Example 2: Code: static void logi_dj_ll_stop(struct hid_device *hid) { dbg_hid("%s\n", __func__); } 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 locationReplaceableAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationReplaceable()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } 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 bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { int i; if (old->curframe != cur->curframe) return false; /* for states to be equal callsites have to be the same * and all frame states need to be equivalent */ for (i = 0; i <= old->curframe; i++) { if (old->frame[i]->callsite != cur->frame[i]->callsite) return false; if (!func_states_equal(old->frame[i], cur->frame[i])) return false; } return true; } CWE ID: CWE-189 Target: 1 Example 2: Code: void yr_re_print( RE_AST* re_ast) { _yr_re_print_node(re_ast->root_node); } 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 create_flush_cmd_control(struct f2fs_sb_info *sbi) { dev_t dev = sbi->sb->s_bdev->bd_dev; struct flush_cmd_control *fcc; int err = 0; if (SM_I(sbi)->fcc_info) { fcc = SM_I(sbi)->fcc_info; goto init_thread; } fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL); if (!fcc) return -ENOMEM; atomic_set(&fcc->issued_flush, 0); atomic_set(&fcc->issing_flush, 0); init_waitqueue_head(&fcc->flush_wait_queue); init_llist_head(&fcc->issue_list); SM_I(sbi)->fcc_info = fcc; init_thread: fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi, "f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev)); if (IS_ERR(fcc->f2fs_issue_flush)) { err = PTR_ERR(fcc->f2fs_issue_flush); kfree(fcc); SM_I(sbi)->fcc_info = NULL; return err; } return err; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitDecode( const scoped_refptr<H264Picture>& pic) { VLOGF(4) << "Decoding POC " << pic->pic_order_cnt; scoped_refptr<VaapiDecodeSurface> dec_surface = H264PictureToVaapiDecodeSurface(pic); return vaapi_dec_->DecodeSurface(dec_surface); } CWE ID: CWE-362 Target: 1 Example 2: Code: static void testInterfaceEmptyArrayAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectPythonV8Internal::testInterfaceEmptyArrayAttributeAttributeGetter(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: views::View* PasswordPopupSuggestionView::CreateSubtextLabel() { base::string16 text_to_use; if (!origin_.empty()) { text_to_use = origin_; } else if (GetLayoutType() == PopupItemLayoutType::kTwoLinesLeadingIcon) { text_to_use = masked_password_; } if (text_to_use.empty()) return nullptr; views::Label* label = CreateSecondaryLabel(text_to_use); label->SetElideBehavior(gfx::ELIDE_HEAD); return new ConstrainedWidthView(label, kAutofillPopupUsernameMaxWidth); } 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 walk_hugetlb_range(unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; struct hstate *h = hstate_vma(vma); unsigned long next; unsigned long hmask = huge_page_mask(h); unsigned long sz = huge_page_size(h); pte_t *pte; int err = 0; do { next = hugetlb_entry_end(h, addr, end); pte = huge_pte_offset(walk->mm, addr & hmask, sz); if (pte && walk->hugetlb_entry) err = walk->hugetlb_entry(pte, hmask, addr, next, walk); if (err) break; } while (addr = next, addr != end); return err; } CWE ID: CWE-200 Target: 1 Example 2: Code: heap_available() { long avail = 0; void *probes[max_malloc_probes]; uint n; for (n = 0; n < max_malloc_probes; n++) { if ((probes[n] = malloc(malloc_probe_size)) == 0) break; if_debug2('a', "[a]heap_available probe[%d]=0x%lx\n", n, (ulong) probes[n]); avail += malloc_probe_size; } while (n) free(probes[--n]); return avail; } 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: cifs_lookup(struct inode *parent_dir_inode, struct dentry *direntry, struct nameidata *nd) { int xid; int rc = 0; /* to get around spurious gcc warning, set to zero here */ __u32 oplock = enable_oplocks ? REQ_OPLOCK : 0; __u16 fileHandle = 0; bool posix_open = false; struct cifs_sb_info *cifs_sb; struct tcon_link *tlink; struct cifs_tcon *pTcon; struct cifsFileInfo *cfile; struct inode *newInode = NULL; char *full_path = NULL; struct file *filp; xid = GetXid(); cFYI(1, "parent inode = 0x%p name is: %s and dentry = 0x%p", parent_dir_inode, direntry->d_name.name, direntry); /* check whether path exists */ cifs_sb = CIFS_SB(parent_dir_inode->i_sb); tlink = cifs_sb_tlink(cifs_sb); if (IS_ERR(tlink)) { FreeXid(xid); return (struct dentry *)tlink; } pTcon = tlink_tcon(tlink); /* * Don't allow the separator character in a path component. * The VFS will not allow "/", but "\" is allowed by posix. */ if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)) { int i; for (i = 0; i < direntry->d_name.len; i++) if (direntry->d_name.name[i] == '\\') { cFYI(1, "Invalid file name"); rc = -EINVAL; goto lookup_out; } } /* * O_EXCL: optimize away the lookup, but don't hash the dentry. Let * the VFS handle the create. */ if (nd && (nd->flags & LOOKUP_EXCL)) { d_instantiate(direntry, NULL); rc = 0; goto lookup_out; } /* can not grab the rename sem here since it would deadlock in the cases (beginning of sys_rename itself) in which we already have the sb rename sem */ full_path = build_path_from_dentry(direntry); if (full_path == NULL) { rc = -ENOMEM; goto lookup_out; } if (direntry->d_inode != NULL) { cFYI(1, "non-NULL inode in lookup"); } else { cFYI(1, "NULL inode in lookup"); } cFYI(1, "Full path: %s inode = 0x%p", full_path, direntry->d_inode); /* Posix open is only called (at lookup time) for file create now. * For opens (rather than creates), because we do not know if it * is a file or directory yet, and current Samba no longer allows * us to do posix open on dirs, we could end up wasting an open call * on what turns out to be a dir. For file opens, we wait to call posix * open till cifs_open. It could be added here (lookup) in the future * but the performance tradeoff of the extra network request when EISDIR * or EACCES is returned would have to be weighed against the 50% * reduction in network traffic in the other paths. */ if (pTcon->unix_ext) { if (nd && !(nd->flags & LOOKUP_DIRECTORY) && (nd->flags & LOOKUP_OPEN) && !pTcon->broken_posix_open && (nd->intent.open.file->f_flags & O_CREAT)) { rc = cifs_posix_open(full_path, &newInode, parent_dir_inode->i_sb, nd->intent.open.create_mode, nd->intent.open.file->f_flags, &oplock, &fileHandle, xid); /* * The check below works around a bug in POSIX * open in samba versions 3.3.1 and earlier where * open could incorrectly fail with invalid parameter. * If either that or op not supported returned, follow * the normal lookup. */ if ((rc == 0) || (rc == -ENOENT)) posix_open = true; else if ((rc == -EINVAL) || (rc != -EOPNOTSUPP)) pTcon->broken_posix_open = true; } if (!posix_open) rc = cifs_get_inode_info_unix(&newInode, full_path, parent_dir_inode->i_sb, xid); } else rc = cifs_get_inode_info(&newInode, full_path, NULL, parent_dir_inode->i_sb, xid, NULL); if ((rc == 0) && (newInode != NULL)) { d_add(direntry, newInode); if (posix_open) { filp = lookup_instantiate_filp(nd, direntry, generic_file_open); if (IS_ERR(filp)) { rc = PTR_ERR(filp); CIFSSMBClose(xid, pTcon, fileHandle); goto lookup_out; } cfile = cifs_new_fileinfo(fileHandle, filp, tlink, oplock); if (cfile == NULL) { fput(filp); CIFSSMBClose(xid, pTcon, fileHandle); rc = -ENOMEM; goto lookup_out; } } /* since paths are not looked up by component - the parent directories are presumed to be good here */ renew_parental_timestamps(direntry); } else if (rc == -ENOENT) { rc = 0; direntry->d_time = jiffies; d_add(direntry, NULL); /* if it was once a directory (but how can we tell?) we could do shrink_dcache_parent(direntry); */ } else if (rc != -EACCES) { cERROR(1, "Unexpected lookup error %d", rc); /* We special case check for Access Denied - since that is a common return code */ } lookup_out: kfree(full_path); cifs_put_tlink(tlink); FreeXid(xid); return ERR_PTR(rc); } 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 DownloadResourceHandler::OnRequestRedirected( const net::RedirectInfo& redirect_info, network::ResourceResponse* response, std::unique_ptr<ResourceController> controller) { url::Origin new_origin(url::Origin::Create(redirect_info.new_url)); if (!follow_cross_origin_redirects_ && !first_origin_.IsSameOriginWith(new_origin)) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &NavigateOnUIThread, redirect_info.new_url, request()->url_chain(), Referrer(GURL(redirect_info.new_referrer), Referrer::NetReferrerPolicyToBlinkReferrerPolicy( redirect_info.new_referrer_policy)), GetRequestInfo()->HasUserGesture(), GetRequestInfo()->GetWebContentsGetterForRequest())); controller->Cancel(); return; } if (core_.OnRequestRedirected()) { controller->Resume(); } else { controller->Cancel(); } } CWE ID: CWE-284 Target: 1 Example 2: Code: void LayerTreeHost::SetPropertyTreesNeedRebuild() { property_trees_.needs_rebuild = true; SetNeedsUpdateLayers(); } 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 cp2112_i2c_write_read_req(void *buf, u8 slave_address, u8 *addr, int addr_length, int read_length) { struct cp2112_write_read_req_report *report = buf; if (read_length < 1 || read_length > 512 || addr_length > sizeof(report->target_address)) return -EINVAL; report->report = CP2112_DATA_WRITE_READ_REQUEST; report->slave_address = slave_address << 1; report->length = cpu_to_be16(read_length); report->target_address_length = addr_length; memcpy(report->target_address, addr, addr_length); return addr_length + 5; } CWE ID: CWE-388 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WebRTCSessionDescriptionDescriptor MockWebRTCPeerConnectionHandler::localDescription() { return m_localDescription; } CWE ID: CWE-20 Target: 1 Example 2: Code: PHP_FUNCTION(locale_get_display_language) { get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } 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 CCThreadProxy::obtainBeginFrameAndCommitTaskFromCCThread(CCCompletionEvent* completion, CCMainThread::Task** taskPtr) { OwnPtr<CCMainThread::Task> task = createBeginFrameAndCommitTaskOnCCThread(); *taskPtr = task.leakPtr(); completion->signal(); } 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: size_t OpenMP4SourceUDTA(char *filename) { mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object)); if (mp4 == NULL) return 0; memset(mp4, 0, sizeof(mp4object)); #ifdef _WINDOWS fopen_s(&mp4->mediafp, filename, "rb"); #else mp4->mediafp = fopen(filename, "rb"); #endif if (mp4->mediafp) { uint32_t qttag, qtsize32, len; int32_t nest = 0; uint64_t nestsize[MAX_NEST_LEVEL] = { 0 }; uint64_t lastsize = 0, qtsize; do { len = fread(&qtsize32, 1, 4, mp4->mediafp); len += fread(&qttag, 1, 4, mp4->mediafp); if (len == 8) { if (!GPMF_VALID_FOURCC(qttag)) { LONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR); NESTSIZE(lastsize - 8); continue; } qtsize32 = BYTESWAP32(qtsize32); if (qtsize32 == 1) // 64-bit Atom { fread(&qtsize, 1, 8, mp4->mediafp); qtsize = BYTESWAP64(qtsize) - 8; } else qtsize = qtsize32; nest++; if (qtsize < 8) break; if (nest >= MAX_NEST_LEVEL) break; nestsize[nest] = qtsize; lastsize = qtsize; if (qttag == MAKEID('m', 'd', 'a', 't') || qttag == MAKEID('f', 't', 'y', 'p')) { LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); continue; } if (qttag == MAKEID('G', 'P', 'M', 'F')) { mp4->videolength += 1.0; mp4->metadatalength += 1.0; mp4->indexcount = (int)mp4->metadatalength; mp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4); mp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8); mp4->metasizes[0] = (int)qtsize - 8; mp4->metaoffsets[0] = ftell(mp4->mediafp); mp4->metasize_count = 1; return (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second. } if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms qttag != MAKEID('u', 'd', 't', 'a')) { LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); continue; } else { NESTSIZE(8); } } } while (len > 0); } return (size_t)mp4; } CWE ID: CWE-787 Target: 1 Example 2: Code: int http_sync_req_state(struct session *s) { struct channel *chn = s->req; struct http_txn *txn = &s->txn; unsigned int old_flags = chn->flags; unsigned int old_state = txn->req.msg_state; if (unlikely(txn->req.msg_state < HTTP_MSG_BODY)) return 0; if (txn->req.msg_state == HTTP_MSG_DONE) { /* No need to read anymore, the request was completely parsed. * We can shut the read side unless we want to abort_on_close, * or we have a POST request. The issue with POST requests is * that some browsers still send a CRLF after the request, and * this CRLF must be read so that it does not remain in the kernel * buffers, otherwise a close could cause an RST on some systems * (eg: Linux). * Note that if we're using keep-alive on the client side, we'd * rather poll now and keep the polling enabled for the whole * session's life than enabling/disabling it between each * response and next request. */ if (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_SCL) && ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) && !(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST) channel_dont_read(chn); /* if the server closes the connection, we want to immediately react * and close the socket to save packets and syscalls. */ chn->cons->flags |= SI_FL_NOHALF; if (txn->rsp.msg_state == HTTP_MSG_ERROR) goto wait_other_side; if (txn->rsp.msg_state < HTTP_MSG_DONE) { /* The server has not finished to respond, so we * don't want to move in order not to upset it. */ goto wait_other_side; } if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) { /* if any side switches to tunnel mode, the other one does too */ channel_auto_read(chn); txn->req.msg_state = HTTP_MSG_TUNNEL; chn->flags |= CF_NEVER_WAIT; goto wait_other_side; } /* When we get here, it means that both the request and the * response have finished receiving. Depending on the connection * mode, we'll have to wait for the last bytes to leave in either * direction, and sometimes for a close to be effective. */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) { /* Server-close mode : queue a connection close to the server */ if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) channel_shutw_now(chn); } else if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) { /* Option forceclose is set, or either side wants to close, * let's enforce it now that we're not expecting any new * data to come. The caller knows the session is complete * once both states are CLOSED. */ if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) { channel_shutr_now(chn); channel_shutw_now(chn); } } else { /* The last possible modes are keep-alive and tunnel. Tunnel mode * will not have any analyser so it needs to poll for reads. */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) { channel_auto_read(chn); txn->req.msg_state = HTTP_MSG_TUNNEL; chn->flags |= CF_NEVER_WAIT; } } if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) { /* if we've just closed an output, let's switch */ chn->cons->flags |= SI_FL_NOLINGER; /* we want to close ASAP */ if (!channel_is_empty(chn)) { txn->req.msg_state = HTTP_MSG_CLOSING; goto http_msg_closing; } else { txn->req.msg_state = HTTP_MSG_CLOSED; goto http_msg_closed; } } goto wait_other_side; } if (txn->req.msg_state == HTTP_MSG_CLOSING) { http_msg_closing: /* nothing else to forward, just waiting for the output buffer * to be empty and for the shutw_now to take effect. */ if (channel_is_empty(chn)) { txn->req.msg_state = HTTP_MSG_CLOSED; goto http_msg_closed; } else if (chn->flags & CF_SHUTW) { txn->req.msg_state = HTTP_MSG_ERROR; goto wait_other_side; } } if (txn->req.msg_state == HTTP_MSG_CLOSED) { http_msg_closed: /* see above in MSG_DONE why we only do this in these states */ if (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_SCL) && ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) && !(s->be->options & PR_O_ABRT_CLOSE)) channel_dont_read(chn); goto wait_other_side; } wait_other_side: return txn->req.msg_state != old_state || chn->flags != old_flags; } 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 InspectorClientImpl::resetTraceEventCallback() { if (WebDevToolsAgentImpl* agent = devToolsAgent()) agent->resetTraceEventCallback(); } 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: status_t ACodec::setupAACCodec( bool encoder, int32_t numChannels, int32_t sampleRate, int32_t bitRate, int32_t aacProfile, bool isADTS, int32_t sbrMode, int32_t maxOutputChannelCount, const drcParams_t& drc, int32_t pcmLimiterEnable) { if (encoder && isADTS) { return -EINVAL; } status_t err = setupRawAudioFormat( encoder ? kPortIndexInput : kPortIndexOutput, sampleRate, numChannels); if (err != OK) { return err; } if (encoder) { err = selectAudioPortFormat(kPortIndexOutput, OMX_AUDIO_CodingAAC); if (err != OK) { return err; } OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = kPortIndexOutput; err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } def.format.audio.bFlagErrorConcealment = OMX_TRUE; def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; err = mOMX->setParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); if (err != OK) { return err; } OMX_AUDIO_PARAM_AACPROFILETYPE profile; InitOMXParams(&profile); profile.nPortIndex = kPortIndexOutput; err = mOMX->getParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } profile.nChannels = numChannels; profile.eChannelMode = (numChannels == 1) ? OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo; profile.nSampleRate = sampleRate; profile.nBitRate = bitRate; profile.nAudioBandWidth = 0; profile.nFrameLength = 0; profile.nAACtools = OMX_AUDIO_AACToolAll; profile.nAACERtools = OMX_AUDIO_AACERNone; profile.eAACProfile = (OMX_AUDIO_AACPROFILETYPE) aacProfile; profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; switch (sbrMode) { case 0: profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 1: profile.nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 2: profile.nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; case -1: profile.nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; profile.nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; default: return BAD_VALUE; } err = mOMX->setParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } return err; } OMX_AUDIO_PARAM_AACPROFILETYPE profile; InitOMXParams(&profile); profile.nPortIndex = kPortIndexInput; err = mOMX->getParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { return err; } profile.nChannels = numChannels; profile.nSampleRate = sampleRate; profile.eAACStreamFormat = isADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF; OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE presentation; presentation.nMaxOutputChannels = maxOutputChannelCount; presentation.nDrcCut = drc.drcCut; presentation.nDrcBoost = drc.drcBoost; presentation.nHeavyCompression = drc.heavyCompression; presentation.nTargetReferenceLevel = drc.targetRefLevel; presentation.nEncodedTargetLevel = drc.encodedTargetLevel; presentation.nPCMLimiterEnable = pcmLimiterEnable; status_t res = mOMX->setParameter(mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (res == OK) { mOMX->setParameter(mNode, (OMX_INDEXTYPE)OMX_IndexParamAudioAndroidAacPresentation, &presentation, sizeof(presentation)); } else { ALOGW("did not set AudioAndroidAacPresentation due to error %d when setting AudioAac", res); } return res; } CWE ID: CWE-119 Target: 1 Example 2: Code: gs_opendevice(gx_device *dev) { if (dev->is_open) return 0; check_device_separable(dev); gx_device_fill_in_procs(dev); { int code = (*dev_proc(dev, open_device))(dev); if (code < 0) return_error(code); dev->is_open = true; return 1; } } CWE ID: CWE-78 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 OnReadAllMetadata( const SessionStore::SessionInfo& session_info, SessionStore::FactoryCompletionCallback callback, std::unique_ptr<ModelTypeStore> store, std::unique_ptr<ModelTypeStore::RecordList> record_list, const base::Optional<syncer::ModelError>& error, std::unique_ptr<syncer::MetadataBatch> metadata_batch) { if (error) { std::move(callback).Run(error, /*store=*/nullptr, /*metadata_batch=*/nullptr); return; } std::map<std::string, sync_pb::SessionSpecifics> initial_data; for (ModelTypeStore::Record& record : *record_list) { const std::string& storage_key = record.id; SessionSpecifics specifics; if (storage_key.empty() || !specifics.ParseFromString(std::move(record.value))) { DVLOG(1) << "Ignoring corrupt database entry with key: " << storage_key; continue; } initial_data[storage_key].Swap(&specifics); } auto session_store = std::make_unique<SessionStore>( sessions_client_, session_info, std::move(store), std::move(initial_data), metadata_batch->GetAllMetadata(), restored_foreign_tab_callback_); std::move(callback).Run(/*error=*/base::nullopt, std::move(session_store), std::move(metadata_batch)); } 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 ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int ret = 0, size = 0; const char *name = NULL; char *value = NULL; struct iattr newattrs; umode_t new_mode = inode->i_mode, old_mode = inode->i_mode; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { ret = posix_acl_equiv_mode(acl, &new_mode); if (ret < 0) goto out; if (ret == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) { ret = acl ? -EINVAL : 0; goto out; } name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: ret = -EINVAL; goto out; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_NOFS); if (!value) { ret = -ENOMEM; goto out; } ret = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (ret < 0) goto out_free; } if (new_mode != old_mode) { newattrs.ia_mode = new_mode; newattrs.ia_valid = ATTR_MODE; ret = __ceph_setattr(inode, &newattrs); if (ret) goto out_free; } ret = __ceph_setxattr(inode, name, value, size, 0); if (ret) { if (new_mode != old_mode) { newattrs.ia_mode = old_mode; newattrs.ia_valid = ATTR_MODE; __ceph_setattr(inode, &newattrs); } goto out_free; } ceph_set_cached_acl(inode, type, acl); out_free: kfree(value); out: return ret; } CWE ID: CWE-285 Target: 1 Example 2: Code: static int encode_setclientid_confirm(struct xdr_stream *xdr, const struct nfs_client *client_state) { __be32 *p; RESERVE_SPACE(12 + NFS4_VERIFIER_SIZE); WRITE32(OP_SETCLIENTID_CONFIRM); WRITE64(client_state->cl_clientid); WRITEMEM(client_state->cl_confirm.data, NFS4_VERIFIER_SIZE); 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 void voidMethodVariadicTestInterfaceEmptyArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::voidMethodVariadicTestInterfaceEmptyArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PixelBufferRasterWorkerPool::ScheduleMoreTasks() { TRACE_EVENT0("cc", "PixelBufferRasterWorkerPool::ScheduleMoreTasks"); enum RasterTaskType { PREPAINT_TYPE = 0, REQUIRED_FOR_ACTIVATION_TYPE = 1, NUM_TYPES = 2 }; NodeVector tasks[NUM_TYPES]; unsigned priority = 2u; // 0-1 reserved for RasterFinished tasks. TaskGraph graph; size_t bytes_pending_upload = bytes_pending_upload_; bool did_throttle_raster_tasks = false; for (RasterTaskVector::const_iterator it = raster_tasks().begin(); it != raster_tasks().end(); ++it) { internal::RasterWorkerPoolTask* task = it->get(); TaskMap::iterator pixel_buffer_it = pixel_buffer_tasks_.find(task); if (pixel_buffer_it == pixel_buffer_tasks_.end()) continue; if (task->HasFinishedRunning()) { DCHECK(std::find(completed_tasks_.begin(), completed_tasks_.end(), task) != completed_tasks_.end()); continue; } size_t new_bytes_pending_upload = bytes_pending_upload; new_bytes_pending_upload += task->resource()->bytes(); if (new_bytes_pending_upload > max_bytes_pending_upload_) { did_throttle_raster_tasks = true; break; } internal::WorkerPoolTask* pixel_buffer_task = pixel_buffer_it->second.get(); if (pixel_buffer_task && pixel_buffer_task->HasCompleted()) { bytes_pending_upload = new_bytes_pending_upload; continue; } size_t scheduled_raster_task_count = tasks[PREPAINT_TYPE].container().size() + tasks[REQUIRED_FOR_ACTIVATION_TYPE].container().size(); if (scheduled_raster_task_count >= kMaxScheduledRasterTasks) { did_throttle_raster_tasks = true; break; } bytes_pending_upload = new_bytes_pending_upload; RasterTaskType type = IsRasterTaskRequiredForActivation(task) ? REQUIRED_FOR_ACTIVATION_TYPE : PREPAINT_TYPE; if (pixel_buffer_task) { tasks[type].container().push_back( CreateGraphNodeForRasterTask(pixel_buffer_task, task->dependencies(), priority++, &graph)); continue; } resource_provider()->AcquirePixelBuffer(task->resource()->id()); uint8* buffer = resource_provider()->MapPixelBuffer( task->resource()->id()); scoped_refptr<internal::WorkerPoolTask> new_pixel_buffer_task( new PixelBufferWorkerPoolTaskImpl( task, buffer, base::Bind(&PixelBufferRasterWorkerPool::OnRasterTaskCompleted, base::Unretained(this), make_scoped_refptr(task)))); pixel_buffer_tasks_[task] = new_pixel_buffer_task; tasks[type].container().push_back( CreateGraphNodeForRasterTask(new_pixel_buffer_task.get(), task->dependencies(), priority++, &graph)); } scoped_refptr<internal::WorkerPoolTask> new_raster_required_for_activation_finished_task; size_t scheduled_raster_task_required_for_activation_count = tasks[REQUIRED_FOR_ACTIVATION_TYPE].container().size(); DCHECK_LE(scheduled_raster_task_required_for_activation_count, tasks_required_for_activation_.size()); if (scheduled_raster_task_required_for_activation_count == tasks_required_for_activation_.size() && should_notify_client_if_no_tasks_required_for_activation_are_pending_) { new_raster_required_for_activation_finished_task = CreateRasterRequiredForActivationFinishedTask(); internal::GraphNode* raster_required_for_activation_finished_node = CreateGraphNodeForTask( new_raster_required_for_activation_finished_task.get(), 0u, // Priority 0 &graph); AddDependenciesToGraphNode( raster_required_for_activation_finished_node, tasks[REQUIRED_FOR_ACTIVATION_TYPE].container()); } scoped_refptr<internal::WorkerPoolTask> new_raster_finished_task; size_t scheduled_raster_task_count = tasks[PREPAINT_TYPE].container().size() + tasks[REQUIRED_FOR_ACTIVATION_TYPE].container().size(); DCHECK_LE(scheduled_raster_task_count, PendingRasterTaskCount()); if (!did_throttle_raster_tasks && should_notify_client_if_no_tasks_are_pending_) { new_raster_finished_task = CreateRasterFinishedTask(); internal::GraphNode* raster_finished_node = CreateGraphNodeForTask(new_raster_finished_task.get(), 1u, // Priority 1 &graph); for (unsigned type = 0; type < NUM_TYPES; ++type) { AddDependenciesToGraphNode( raster_finished_node, tasks[type].container()); } } SetTaskGraph(&graph); scheduled_raster_task_count_ = scheduled_raster_task_count; set_raster_finished_task(new_raster_finished_task); set_raster_required_for_activation_finished_task( new_raster_required_for_activation_finished_task); } CWE ID: CWE-20 Target: 1 Example 2: Code: mojom::ReportingMode PlatformSensorAndroid::GetReportingMode() { JNIEnv* env = AttachCurrentThread(); return static_cast<mojom::ReportingMode>( Java_PlatformSensor_getReportingMode(env, j_object_)); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int csum_len_for_type(int cst) { switch (cst) { case CSUM_NONE: return 1; case CSUM_ARCHAIC: return 2; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: return MD4_DIGEST_LEN; case CSUM_MD5: return MD5_DIGEST_LEN; } return 0; } CWE ID: CWE-354 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 xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct net *net = sock_net(cb->skb->sk); xfrm_policy_walk_done(walk, net); return 0; } CWE ID: CWE-416 Target: 1 Example 2: Code: compress_task_done (GObject *source_object, GAsyncResult *res, gpointer user_data) { CompressJob *compress_job = user_data; if (compress_job->done_callback) { compress_job->done_callback (compress_job->output_file, compress_job->success, compress_job->done_callback_data); } g_object_unref (compress_job->output_file); g_list_free_full (compress_job->source_files, g_object_unref); finalize_common ((CommonJob *) compress_job); nautilus_file_changes_consume_changes (TRUE); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int lxc_cgroupfs_get(const char *filename, char *value, size_t len, const char *name, const char *lxcpath) { char *subsystem = NULL, *p, *path; int ret = -1; subsystem = alloca(strlen(filename) + 1); strcpy(subsystem, filename); if ((p = strchr(subsystem, '.')) != NULL) *p = '\0'; path = lxc_cgroup_get_hierarchy_abs_path(subsystem, name, lxcpath); if (path) { ret = do_cgroup_get(path, filename, value, len); free(path); } return ret; } CWE ID: CWE-59 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WORD32 ihevcd_create(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { ihevcd_cxa_create_op_t *ps_create_op; WORD32 ret; codec_t *ps_codec; ps_create_op = (ihevcd_cxa_create_op_t *)pv_api_op; ps_create_op->s_ivd_create_op_t.u4_error_code = 0; ret = ihevcd_allocate_static_bufs(&ps_codec_obj, pv_api_ip, pv_api_op); /* If allocation of some buffer fails, then free buffers allocated till then */ if((IV_FAIL == ret) && (NULL != ps_codec_obj)) { ihevcd_free_static_bufs(ps_codec_obj); ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED; ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR; return IV_FAIL; } ps_codec = (codec_t *)ps_codec_obj->pv_codec_handle; ret = ihevcd_init(ps_codec); TRACE_INIT(NULL); STATS_INIT(); return ret; } CWE ID: CWE-770 Target: 1 Example 2: Code: void sgpd_del(GF_Box *a) { GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)a; while (gf_list_count(p->group_descriptions)) { void *ptr = gf_list_last(p->group_descriptions); sgpd_del_entry(p->grouping_type, ptr); gf_list_rem_last(p->group_descriptions); } gf_list_del(p->group_descriptions); gf_free(p); } 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 ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6, __u32 mark, struct ipv6_txoptions *opt, int tclass) { struct net *net = sock_net(sk); const struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *first_hop = &fl6->daddr; struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr; u8 proto = fl6->flowi6_proto; int seg_len = skb->len; int hlimit = -1; u32 mtu; if (opt) { unsigned int head_room; /* First: exthdrs may take lots of space (~8K for now) MAX_HEADER is not enough. */ head_room = opt->opt_nflen + opt->opt_flen; seg_len += head_room; head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev); if (skb_headroom(skb) < head_room) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room); if (!skb2) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return -ENOBUFS; } consume_skb(skb); skb = skb2; /* skb_set_owner_w() changes sk->sk_wmem_alloc atomically, * it is safe to call in our context (socket lock not held) */ skb_set_owner_w(skb, (struct sock *)sk); } if (opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop, &fl6->saddr); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); /* * Fill in the IPv6 header */ if (np) hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->payload_len = htons(seg_len); hdr->nexthdr = proto; hdr->hop_limit = hlimit; hdr->saddr = fl6->saddr; hdr->daddr = *first_hop; skb->protocol = htons(ETH_P_IPV6); skb->priority = sk->sk_priority; skb->mark = mark; mtu = dst_mtu(dst); if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) { IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUT, skb->len); /* if egress device is enslaved to an L3 master device pass the * skb to its handler for processing */ skb = l3mdev_ip6_out((struct sock *)sk, skb); if (unlikely(!skb)) return 0; /* hooks should never assume socket lock is held. * we promote our socket to non const */ return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, net, (struct sock *)sk, skb, NULL, dst->dev, dst_output); } skb->dev = dst->dev; /* ipv6_local_error() does not require socket lock, * we promote our socket to non const */ ipv6_local_error((struct sock *)sk, EMSGSIZE, fl6, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } 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 GDataFileSystem::OnGetDocumentEntry(const FilePath& cache_file_path, const GetFileFromCacheParams& params, GDataErrorCode status, scoped_ptr<base::Value> data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GDataFileError error = util::GDataToGDataFileError(status); scoped_ptr<GDataEntry> fresh_entry; if (error == GDATA_FILE_OK) { scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data)); if (doc_entry.get()) { fresh_entry.reset( GDataEntry::FromDocumentEntry(NULL, doc_entry.get(), directory_service_.get())); } if (!fresh_entry.get() || !fresh_entry->AsGDataFile()) { LOG(ERROR) << "Got invalid entry from server for " << params.resource_id; error = GDATA_FILE_ERROR_FAILED; } } if (error != GDATA_FILE_OK) { if (!params.get_file_callback.is_null()) { params.get_file_callback.Run(error, cache_file_path, params.mime_type, REGULAR_FILE); } return; } GURL content_url = fresh_entry->content_url(); int64 file_size = fresh_entry->file_info().size; DCHECK_EQ(params.resource_id, fresh_entry->resource_id()); scoped_ptr<GDataFile> fresh_entry_as_file( fresh_entry.release()->AsGDataFile()); directory_service_->RefreshFile(fresh_entry_as_file.Pass()); bool* has_enough_space = new bool(false); util::PostBlockingPoolSequencedTaskAndReply( FROM_HERE, blocking_task_runner_, base::Bind(&GDataCache::FreeDiskSpaceIfNeededFor, base::Unretained(cache_), file_size, has_enough_space), base::Bind(&GDataFileSystem::StartDownloadFileIfEnoughSpace, ui_weak_ptr_, params, content_url, cache_file_path, base::Owned(has_enough_space))); } CWE ID: CWE-399 Target: 1 Example 2: Code: bool Document::shouldScheduleLayout() { return (haveStylesheetsLoaded() && body()) || (documentElement() && !documentElement()->hasTagName(htmlTag)); } 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 SkiaOutputSurfaceImplTest::BlockMainThread() { wait_.Wait(); } CWE ID: CWE-704 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 AutocompleteEditModel::OpenMatch(const AutocompleteMatch& match, WindowOpenDisposition disposition, const GURL& alternate_nav_url, size_t index) { if (popup_->IsOpen()) { AutocompleteLog log( autocomplete_controller_->input().text(), just_deleted_text_, autocomplete_controller_->input().type(), popup_->selected_line(), -1, // don't yet know tab ID; set later if appropriate ClassifyPage(controller_->GetTabContentsWrapper()-> web_contents()->GetURL()), base::TimeTicks::Now() - time_user_first_modified_omnibox_, 0, // inline autocomplete length; possibly set later result()); DCHECK(user_input_in_progress_) << "We didn't get here through the " "expected series of calls. time_user_first_modified_omnibox_ is " "not set correctly and other things may be wrong."; if (index != AutocompletePopupModel::kNoMatch) log.selected_index = index; else if (!has_temporary_text_) log.inline_autocompleted_length = inline_autocomplete_text_.length(); if (disposition == CURRENT_TAB) { log.tab_id = controller_->GetTabContentsWrapper()-> restore_tab_helper()->session_id().id(); } content::NotificationService::current()->Notify( chrome::NOTIFICATION_OMNIBOX_OPENED_URL, content::Source<Profile>(profile_), content::Details<AutocompleteLog>(&log)); } TemplateURL* template_url = match.GetTemplateURL(profile_); if (template_url) { if (match.transition == content::PAGE_TRANSITION_KEYWORD) { if (template_url->IsExtensionKeyword()) { AutocompleteMatch current_match; GetInfoForCurrentText(&current_match, NULL); const AutocompleteMatch& match = (index == AutocompletePopupModel::kNoMatch) ? current_match : result().match_at(index); size_t prefix_length = match.keyword.length() + 1; extensions::ExtensionOmniboxEventRouter::OnInputEntered(profile_, template_url->GetExtensionId(), UTF16ToUTF8(match.fill_into_edit.substr(prefix_length))); view_->RevertAll(); return; } content::RecordAction(UserMetricsAction("AcceptedKeyword")); TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount( template_url); } else { DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition); } UMA_HISTOGRAM_ENUMERATION("Omnibox.SearchEngine", template_url->prepopulate_id(), TemplateURLPrepopulateData::kMaxPrepopulatedEngineID); } if (disposition != NEW_BACKGROUND_TAB) { in_revert_ = true; view_->RevertAll(); // Revert the box to its unedited state } if (match.type == AutocompleteMatch::EXTENSION_APP) { extensions::LaunchAppFromOmnibox(match, profile_, disposition); } else { controller_->OnAutocompleteAccept(match.destination_url, disposition, match.transition, alternate_nav_url); } if (match.starred) bookmark_utils::RecordBookmarkLaunch(bookmark_utils::LAUNCH_OMNIBOX); InstantController* instant = controller_->GetInstant(); if (instant && !popup_->IsOpen()) instant->DestroyPreviewContents(); in_revert_ = false; } CWE ID: Target: 1 Example 2: Code: static void hardware_disable_nolock(void *junk) { int cpu = raw_smp_processor_id(); if (!cpumask_test_cpu(cpu, cpus_hardware_enabled)) return; cpumask_clear_cpu(cpu, cpus_hardware_enabled); kvm_arch_hardware_disable(); } 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 DecodeIPV6RouteTest01 (void) { uint8_t raw_pkt1[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x2b, 0x40, 0x20, 0x01, 0xaa, 0xaa, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x20, 0x01, 0xaa, 0xaa, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb2, 0xed, 0x00, 0x50, 0x1b, 0xc7, 0x6a, 0xdf, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02, 0x20, 0x00, 0xfa, 0x87, 0x00, 0x00, }; Packet *p1 = PacketGetFromAlloc(); FAIL_IF(unlikely(p1 == NULL)); ThreadVars tv; DecodeThreadVars dtv; PacketQueue pq; FlowInitConfig(FLOW_QUIET); memset(&pq, 0, sizeof(PacketQueue)); memset(&tv, 0, sizeof(ThreadVars)); memset(&dtv, 0, sizeof(DecodeThreadVars)); PacketCopyData(p1, raw_pkt1, sizeof(raw_pkt1)); DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1), &pq); FAIL_IF (!(IPV6_EXTHDR_ISSET_RH(p1))); FAIL_IF (p1->ip6eh.rh_type != 0); PACKET_RECYCLE(p1); SCFree(p1); FlowShutdown(); PASS; } 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 RemoveActionCallback(const ActionCallback& callback) { DCHECK(g_task_runner.Get()); DCHECK(g_task_runner.Get()->BelongsToCurrentThread()); std::vector<ActionCallback>* callbacks = g_callbacks.Pointer(); for (size_t i = 0; i < callbacks->size(); ++i) { if ((*callbacks)[i].Equals(callback)) { callbacks->erase(callbacks->begin() + i); return; } } } CWE ID: CWE-20 Target: 1 Example 2: Code: static void erase_header(struct ctl_table_header *head) { struct ctl_table *entry; for (entry = head->ctl_table; entry->procname; entry++) erase_entry(head, entry); } 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 ImageResource::FlagAsUserAgentResource() { if (is_referenced_from_ua_stylesheet_) return; InstanceCounters::IncrementCounter(InstanceCounters::kUACSSResourceCounter); is_referenced_from_ua_stylesheet_ = true; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ResetState() { nav_handle1_.reset(); nav_handle2_.reset(); nav_handle3_.reset(); throttle1_.reset(); throttle2_.reset(); throttle3_.reset(); contents1_.reset(); contents2_.reset(); contents3_.reset(); } CWE ID: Target: 1 Example 2: Code: void WebGLRenderingContextBase::hint(GLenum target, GLenum mode) { if (isContextLost()) return; bool is_valid = false; switch (target) { case GL_GENERATE_MIPMAP_HINT: is_valid = true; break; case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: // OES_standard_derivatives if (ExtensionEnabled(kOESStandardDerivativesName) || IsWebGL2OrHigher()) is_valid = true; break; } if (!is_valid) { SynthesizeGLError(GL_INVALID_ENUM, "hint", "invalid target"); return; } ContextGL()->Hint(target, mode); } 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 UINT dvcman_receive_channel_data(drdynvcPlugin* drdynvc, IWTSVirtualChannelManager* pChannelMgr, UINT32 ChannelId, wStream* data) { UINT status = CHANNEL_RC_OK; DVCMAN_CHANNEL* channel; size_t dataSize = Stream_GetRemainingLength(data); channel = (DVCMAN_CHANNEL*) dvcman_find_channel_by_id(pChannelMgr, ChannelId); if (!channel) { /* Windows 8.1 tries to open channels not created. * Ignore cases like this. */ WLog_Print(drdynvc->log, WLOG_ERROR, "ChannelId %"PRIu32" not found!", ChannelId); return CHANNEL_RC_OK; } if (channel->dvc_data) { /* Fragmented data */ if (Stream_GetPosition(channel->dvc_data) + dataSize > (UINT32) Stream_Capacity( channel->dvc_data)) { WLog_Print(drdynvc->log, WLOG_ERROR, "data exceeding declared length!"); Stream_Release(channel->dvc_data); channel->dvc_data = NULL; return ERROR_INVALID_DATA; } Stream_Write(channel->dvc_data, Stream_Pointer(data), dataSize); if (Stream_GetPosition(channel->dvc_data) >= channel->dvc_data_length) { Stream_SealLength(channel->dvc_data); Stream_SetPosition(channel->dvc_data, 0); status = channel->channel_callback->OnDataReceived(channel->channel_callback, channel->dvc_data); Stream_Release(channel->dvc_data); channel->dvc_data = NULL; } } else { status = channel->channel_callback->OnDataReceived(channel->channel_callback, data); } return status; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MaybeStopInputMethodDaemon(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value) && enable_auto_ime_shutdown_) { StopInputMethodDaemon(); } } CWE ID: CWE-399 Target: 1 Example 2: Code: void curlfile_register_class(TSRMLS_D) { zend_class_entry ce; INIT_CLASS_ENTRY( ce, "CURLFile", curlfile_funcs ); curl_CURLFile_class = zend_register_internal_class(&ce TSRMLS_CC); zend_declare_property_string(curl_CURLFile_class, "name", sizeof("name")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_string(curl_CURLFile_class, "mime", sizeof("mime")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_string(curl_CURLFile_class, "postname", sizeof("postname")-1, "", ZEND_ACC_PUBLIC TSRMLS_CC); } 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: gfx::Point ShellSurface::GetSurfaceOrigin() const { gfx::Rect window_bounds = widget_->GetNativeWindow()->bounds(); if (!initial_bounds_.IsEmpty()) return initial_bounds_.origin() - window_bounds.OffsetFromOrigin(); gfx::Rect visible_bounds = GetVisibleBounds(); switch (resize_component_) { case HTCAPTION: return origin_ - visible_bounds.OffsetFromOrigin(); case HTBOTTOM: case HTRIGHT: case HTBOTTOMRIGHT: return gfx::Point() - visible_bounds.OffsetFromOrigin(); case HTTOP: case HTTOPRIGHT: return gfx::Point(0, window_bounds.height() - visible_bounds.height()) - visible_bounds.OffsetFromOrigin(); break; case HTLEFT: case HTBOTTOMLEFT: return gfx::Point(window_bounds.width() - visible_bounds.width(), 0) - visible_bounds.OffsetFromOrigin(); case HTTOPLEFT: return gfx::Point(window_bounds.width() - visible_bounds.width(), window_bounds.height() - visible_bounds.height()) - visible_bounds.OffsetFromOrigin(); default: NOTREACHED(); return gfx::Point(); } } 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 CrosLibrary::TestApi::SetMountLibrary( MountLibrary* library, bool own) { library_->mount_lib_.SetImpl(library, own); } CWE ID: CWE-189 Target: 1 Example 2: Code: static int futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2, union futex_key *key1, union futex_key *key2, struct futex_pi_state **ps, int set_waiters) { struct futex_q *top_waiter = NULL; u32 curval; int ret, vpid; if (get_futex_value_locked(&curval, pifutex)) return -EFAULT; /* * Find the top_waiter and determine if there are additional waiters. * If the caller intends to requeue more than 1 waiter to pifutex, * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now, * as we have means to handle the possible fault. If not, don't set * the bit unecessarily as it will force the subsequent unlock to enter * the kernel. */ top_waiter = futex_top_waiter(hb1, key1); /* There are no waiters, nothing for us to do. */ if (!top_waiter) return 0; /* Ensure we requeue to the expected futex. */ if (!match_futex(top_waiter->requeue_pi_key, key2)) return -EINVAL; /* * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in * the contended case or if set_waiters is 1. The pi_state is returned * in ps in contended cases. */ vpid = task_pid_vnr(top_waiter->task); ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task, set_waiters); if (ret == 1) { requeue_pi_wake_futex(top_waiter, key2, hb2); return vpid; } return ret; } 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 bool access_pmselr(struct kvm_vcpu *vcpu, struct sys_reg_params *p, const struct sys_reg_desc *r) { if (!kvm_arm_pmu_v3_ready(vcpu)) return trap_raz_wi(vcpu, p, r); if (pmu_access_event_counter_el0_disabled(vcpu)) return false; if (p->is_write) vcpu_sys_reg(vcpu, PMSELR_EL0) = p->regval; else /* return PMSELR.SEL field */ p->regval = vcpu_sys_reg(vcpu, PMSELR_EL0) & ARMV8_PMU_COUNTER_MASK; return true; } CWE ID: CWE-617 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 spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */ CWE ID: CWE-190 Target: 1 Example 2: Code: aspath_leftmost (struct aspath *aspath) { struct assegment *seg = aspath->segments; as_t leftmost = 0; if (seg && seg->length && seg->type == AS_SEQUENCE) leftmost = seg->as[0]; return leftmost; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __perf_event_header__init_id(struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event) { u64 sample_type = event->attr.sample_type; data->type = sample_type; header->size += event->id_header_size; if (sample_type & PERF_SAMPLE_TID) { /* namespace issues */ data->tid_entry.pid = perf_event_pid(event, current); data->tid_entry.tid = perf_event_tid(event, current); } if (sample_type & PERF_SAMPLE_TIME) data->time = perf_clock(); if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) data->id = primary_event_id(event); if (sample_type & PERF_SAMPLE_STREAM_ID) data->stream_id = event->id; if (sample_type & PERF_SAMPLE_CPU) { data->cpu_entry.cpu = raw_smp_processor_id(); data->cpu_entry.reserved = 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: bool ChromeContentBrowserClient::IsDataSaverEnabled( content::BrowserContext* browser_context) { data_reduction_proxy::DataReductionProxySettings* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( browser_context); return data_reduction_proxy_settings && data_reduction_proxy_settings->IsDataSaverEnabledByUser(); } CWE ID: CWE-119 Target: 1 Example 2: Code: void GetSanitizedEnabledFlagsForCurrentPlatform( PrefService* prefs, std::set<std::string>* result) { GetSanitizedEnabledFlags(prefs, result); std::set<std::string> platform_experiments; int current_platform = GetCurrentPlatform(); for (size_t i = 0; i < num_experiments; ++i) { if (experiments[i].supported_platforms & current_platform) AddInternalName(experiments[i], &platform_experiments); } std::set<std::string> new_enabled_experiments; std::set_intersection( platform_experiments.begin(), platform_experiments.end(), result->begin(), result->end(), std::inserter(new_enabled_experiments, new_enabled_experiments.begin())); result->swap(new_enabled_experiments); } 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 RenderViewTest::GoBack(const PageState& state) { GoToOffset(-1, state); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void l2tp_eth_dev_setup(struct net_device *dev) { ether_setup(dev); dev->netdev_ops = &l2tp_eth_netdev_ops; dev->destructor = free_netdev; } CWE ID: CWE-264 Target: 1 Example 2: Code: static int fill_psinfo(struct elf_prpsinfo *psinfo, struct task_struct *p, struct mm_struct *mm) { const struct cred *cred; unsigned int i, len; /* first copy the parameters from user space */ memset(psinfo, 0, sizeof(struct elf_prpsinfo)); len = mm->arg_end - mm->arg_start; if (len >= ELF_PRARGSZ) len = ELF_PRARGSZ-1; if (copy_from_user(&psinfo->pr_psargs, (const char __user *)mm->arg_start, len)) return -EFAULT; for(i = 0; i < len; i++) if (psinfo->pr_psargs[i] == 0) psinfo->pr_psargs[i] = ' '; psinfo->pr_psargs[len] = 0; rcu_read_lock(); psinfo->pr_ppid = task_pid_vnr(rcu_dereference(p->real_parent)); rcu_read_unlock(); psinfo->pr_pid = task_pid_vnr(p); psinfo->pr_pgrp = task_pgrp_vnr(p); psinfo->pr_sid = task_session_vnr(p); i = p->state ? ffz(~p->state) + 1 : 0; psinfo->pr_state = i; psinfo->pr_sname = (i > 5) ? '.' : "RSDTZW"[i]; psinfo->pr_zomb = psinfo->pr_sname == 'Z'; psinfo->pr_nice = task_nice(p); psinfo->pr_flag = p->flags; rcu_read_lock(); cred = __task_cred(p); SET_UID(psinfo->pr_uid, cred->uid); SET_GID(psinfo->pr_gid, cred->gid); rcu_read_unlock(); strncpy(psinfo->pr_fname, p->comm, sizeof(psinfo->pr_fname)); 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: int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, const mbedtls_ecp_point *G, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret; size_t n_size = ( grp->nbits + 7 ) / 8; #if defined(ECP_MONTGOMERY) if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY ) { /* [M225] page 5 */ size_t b; do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) ); } while( mbedtls_mpi_bitlen( d ) == 0); /* Make sure the most significant bit is nbits */ b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */ if( b > grp->nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) ); else MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) ); /* Make sure the last three bits are unset */ MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) ); } else #endif /* ECP_MONTGOMERY */ #if defined(ECP_SHORTWEIERSTRASS) if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS ) { /* SEC1 3.2.1: Generate d such that 1 <= n < N */ int count = 0; /* * Match the procedure given in RFC 6979 (deterministic ECDSA): * - use the same byte ordering; * - keep the leftmost nbits bits of the generated octet string; * - try until result is in the desired range. * This also avoids any biais, which is especially important for ECDSA. */ do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) ); /* * Each try has at worst a probability 1/2 of failing (the msb has * a probability 1/2 of being 0, and then the result will be < N), * so after 30 tries failure probability is a most 2**(-30). * * For most curves, 1 try is enough with overwhelming probability, * since N starts with a lot of 1s in binary, but some curves * such as secp224k1 are actually very close to the worst case. */ if( ++count > 30 ) return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); } while( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ); } else #endif /* ECP_SHORTWEIERSTRASS */ return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); cleanup: if( ret != 0 ) return( ret ); return( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) ); } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Cluster::CreateBlockGroup( long long start_offset, long long size, long long discard_padding) { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count >= 0); assert(m_entries_count < m_entries_size); IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = start_offset; const long long stop = start_offset + size; long long prev = 1; //nonce long long next = 0; //nonce long long duration = -1; //really, this is unsigned long long bpos = -1; long long bsize = -1; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume size if (id == 0x21) //Block ID { if (bpos < 0) //Block ID { bpos = pos; bsize = size; } } else if (id == 0x1B) //Duration ID { assert(size <= 8); duration = UnserializeUInt(pReader, pos, size); assert(duration >= 0); //TODO } else if (id == 0x7B) //ReferenceBlock { assert(size <= 8); const long size_ = static_cast<long>(size); long long time; long status = UnserializeInt(pReader, pos, size_, time); assert(status == 0); if (status != 0) return -1; if (time <= 0) //see note above prev = time; else //weird next = time; } pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); assert(bpos >= 0); assert(bsize >= 0); const long idx = m_entries_count; BlockEntry** const ppEntry = m_entries + idx; BlockEntry*& pEntry = *ppEntry; pEntry = new (std::nothrow) BlockGroup( this, idx, bpos, bsize, prev, next, duration, discard_padding); if (pEntry == NULL) return -1; //generic error BlockGroup* const p = static_cast<BlockGroup*>(pEntry); const long status = p->Parse(); if (status == 0) //success { ++m_entries_count; return 0; } delete pEntry; pEntry = 0; return status; } CWE ID: CWE-119 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoDisableVertexAttribArray( GLuint index) { api()->glDisableVertexAttribArrayFn(index); return error::kNoError; } 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: PlatformWebView::PlatformWebView(WKContextRef contextRef, WKPageGroupRef pageGroupRef) : m_view(new QQuickWebView(contextRef, pageGroupRef)) , m_window(new WrapperWindow(m_view)) , m_windowIsKey(true) , m_modalEventLoop(0) { QQuickWebViewExperimental experimental(m_view); experimental.setRenderToOffscreenBuffer(true); m_view->setAllowAnyHTTPSCertificateForLocalHost(true); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: std::unique_ptr<PrefService> CreatePrefService() { auto pref_registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); metrics::MetricsService::RegisterPrefs(pref_registry.get()); variations::VariationsService::RegisterPrefs(pref_registry.get()); AwBrowserProcess::RegisterNetworkContextLocalStatePrefs(pref_registry.get()); PrefServiceFactory pref_service_factory; std::set<std::string> persistent_prefs; for (const char* const pref_name : kPersistentPrefsWhitelist) persistent_prefs.insert(pref_name); pref_service_factory.set_user_prefs(base::MakeRefCounted<SegregatedPrefStore>( base::MakeRefCounted<InMemoryPrefStore>(), base::MakeRefCounted<JsonPrefStore>(GetPrefStorePath()), persistent_prefs, mojo::Remote<::prefs::mojom::TrackedPreferenceValidationDelegate>())); pref_service_factory.set_read_error_callback( base::BindRepeating(&HandleReadError)); return pref_service_factory.Create(pref_registry); } CWE ID: CWE-20 Target: 1 Example 2: Code: PanoramiXRenderSetPictureTransform (ClientPtr client) { REQUEST(xRenderSetPictureTransformReq); int result = Success, j; PanoramiXRes *pict; REQUEST_AT_LEAST_SIZE(xRenderSetPictureTransformReq); VERIFY_XIN_PICTURE(pict, stuff->picture, client, DixWriteAccess); FOR_NSCREENS_BACKWARD(j) { stuff->picture = pict->info[j].id; result = (*PanoramiXSaveRenderVector[X_RenderSetPictureTransform]) (client); if(result != Success) break; } return result; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WebRunnerBrowserContext::~WebRunnerBrowserContext() { if (resource_context_) { content::BrowserThread::DeleteSoon(content::BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } } 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 ChromeMockRenderThread::OnScriptedPrint( const PrintHostMsg_ScriptedPrint_Params& params, PrintMsg_PrintPages_Params* settings) { if (print_dialog_user_response_ && printer_.get()) { printer_->ScriptedPrint(params.cookie, params.expected_pages_count, params.has_selection, settings); } } CWE ID: CWE-200 Target: 1 Example 2: Code: XcursorImagesCreate (int size) { XcursorImages *images; images = malloc (sizeof (XcursorImages) + size * sizeof (XcursorImage *)); if (!images) return NULL; images->nimage = 0; images->images = (XcursorImage **) (images + 1); images->name = NULL; return images; } 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: std::unique_ptr<variations::SeedResponse> GetAndClearJavaSeed() { JNIEnv* env = base::android::AttachCurrentThread(); if (!Java_AwVariationsSeedBridge_haveSeed(env)) return nullptr; base::android::ScopedJavaLocalRef<jstring> j_signature = Java_AwVariationsSeedBridge_getSignature(env); base::android::ScopedJavaLocalRef<jstring> j_country = Java_AwVariationsSeedBridge_getCountry(env); jlong j_date = Java_AwVariationsSeedBridge_getDate(env); jboolean j_is_gzip_compressed = Java_AwVariationsSeedBridge_getIsGzipCompressed(env); base::android::ScopedJavaLocalRef<jbyteArray> j_data = Java_AwVariationsSeedBridge_getData(env); Java_AwVariationsSeedBridge_clearSeed(env); auto java_seed = std::make_unique<variations::SeedResponse>(); base::android::JavaByteArrayToString(env, j_data, &java_seed->data); java_seed->signature = base::android::ConvertJavaStringToUTF8(j_signature); java_seed->country = base::android::ConvertJavaStringToUTF8(j_country); java_seed->date = j_date; java_seed->is_gzip_compressed = static_cast<bool>(j_is_gzip_compressed); return java_seed; } 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 PrintViewManager::PrintPreviewDone() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_NE(NOT_PREVIEWING, print_preview_state_); if (print_preview_state_ == SCRIPTED_PREVIEW) { auto& map = g_scripted_print_preview_closure_map.Get(); auto it = map.find(scripted_print_preview_rph_); CHECK(it != map.end()); it->second.Run(); map.erase(it); scripted_print_preview_rph_ = nullptr; } print_preview_state_ = NOT_PREVIEWING; print_preview_rfh_ = nullptr; } CWE ID: CWE-125 Target: 1 Example 2: Code: void SVGDocumentExtensions::addElementReferencingTarget(SVGElement* referencingElement, SVGElement* referencedElement) { ASSERT(referencingElement); ASSERT(referencedElement); if (HashSet<SVGElement*>* elements = m_elementDependencies.get(referencedElement)) { elements->add(referencingElement); return; } OwnPtr<HashSet<SVGElement*> > elements = adoptPtr(new HashSet<SVGElement*>); elements->add(referencingElement); m_elementDependencies.set(referencedElement, elements.release()); } 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: ScriptValue WebGLRenderingContextBase::getProgramParameter( ScriptState* script_state, WebGLProgram* program, GLenum pname) { if (!ValidateWebGLProgramOrShader("getProgramParamter", program)) { return ScriptValue::CreateNull(script_state); } GLint value = 0; switch (pname) { case GL_DELETE_STATUS: return WebGLAny(script_state, program->MarkedForDeletion()); case GL_VALIDATE_STATUS: ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value); return WebGLAny(script_state, static_cast<bool>(value)); case GL_LINK_STATUS: return WebGLAny(script_state, program->LinkStatus(this)); case GL_COMPLETION_STATUS_KHR: if (!ExtensionEnabled(kKHRParallelShaderCompileName)) { SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter", "invalid parameter name"); return ScriptValue::CreateNull(script_state); } return WebGLAny(script_state, program->CompletionStatus(this)); case GL_ACTIVE_UNIFORM_BLOCKS: case GL_TRANSFORM_FEEDBACK_VARYINGS: if (!IsWebGL2OrHigher()) { SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter", "invalid parameter name"); return ScriptValue::CreateNull(script_state); } FALLTHROUGH; case GL_ATTACHED_SHADERS: case GL_ACTIVE_ATTRIBUTES: case GL_ACTIVE_UNIFORMS: ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value); return WebGLAny(script_state, value); case GL_TRANSFORM_FEEDBACK_BUFFER_MODE: if (!IsWebGL2OrHigher()) { SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter", "invalid parameter name"); return ScriptValue::CreateNull(script_state); } ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value); return WebGLAny(script_state, static_cast<unsigned>(value)); case GL_ACTIVE_ATOMIC_COUNTER_BUFFERS: if (context_type_ == Platform::kWebGL2ComputeContextType) { ContextGL()->GetProgramiv(ObjectOrZero(program), pname, &value); return WebGLAny(script_state, static_cast<unsigned>(value)); } FALLTHROUGH; default: SynthesizeGLError(GL_INVALID_ENUM, "getProgramParameter", "invalid parameter name"); return ScriptValue::CreateNull(script_state); } } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf) { int ret; /* MBIM backwards compatible function? */ if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM) return -ENODEV; /* The NCM data altsetting is fixed, so we hard-coded it. * Additionally, generic NCM devices are assumed to accept arbitrarily * placed NDP. */ ret = cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0); /* * We should get an event when network connection is "connected" or * "disconnected". Set network connection in "disconnected" state * (carrier is OFF) during attach, so the IP network stack does not * start IPv6 negotiation and more. */ usbnet_link_change(dev, 0, 0); return ret; } CWE ID: Target: 1 Example 2: Code: unsigned venc_dev::venc_resume(void) { pthread_mutex_lock(&pause_resume_mlock); paused = false; pthread_mutex_unlock(&pause_resume_mlock); return pthread_cond_signal(&pause_resume_cond); } 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 rdp_send_pdu(rdpRdp* rdp, STREAM* s, UINT16 type, UINT16 channel_id) { UINT16 length; UINT32 sec_bytes; BYTE* sec_hold; length = stream_get_length(s); stream_set_pos(s, 0); rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID); sec_bytes = rdp_get_sec_bytes(rdp); sec_hold = s->p; stream_seek(s, sec_bytes); rdp_write_share_control_header(s, length - sec_bytes, type, channel_id); s->p = sec_hold; length += rdp_security_stream_out(rdp, s, length); stream_set_pos(s, length); if (transport_write(rdp->transport, s) < 0) return FALSE; return TRUE; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_METHOD(Phar, addFile) { char *fname, *localname = NULL; size_t fname_len, localname_len = 0; php_stream *resource; zval zresource; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) { return; } #if PHP_API_VERSION < 20100412 if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, safe_mode restrictions prevent this", fname); return; } #endif if (!strstr(fname, "://") && php_check_open_basedir(fname)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname); return; } if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname); return; } if (localname) { fname = localname; fname_len = localname_len; } php_stream_to_zval(resource, &zresource); phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource); zval_ptr_dtor(&zresource); } CWE ID: CWE-20 Target: 1 Example 2: Code: GfxColorSpace *GfxDeviceNColorSpace::copy() { GfxDeviceNColorSpace *cs; int i; cs = new GfxDeviceNColorSpace(nComps, alt->copy(), func->copy()); for (i = 0; i < nComps; ++i) { cs->names[i] = names[i]->copy(); } cs->nonMarking = nonMarking; return cs; } 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 AppResult::Open(int event_flags) { RecordHistogram(APP_SEARCH_RESULT); const extensions::Extension* extension = extensions::ExtensionSystem::Get(profile_)->extension_service() ->GetInstalledExtension(app_id_); if (!extension) return; if (!extensions::util::IsAppLaunchable(app_id_, profile_)) return; if (RunExtensionEnableFlow()) return; if (display_type() != DISPLAY_RECOMMENDATION) { extensions::RecordAppListSearchLaunch(extension); content::RecordAction( base::UserMetricsAction("AppList_ClickOnAppFromSearch")); } controller_->ActivateApp( profile_, extension, AppListControllerDelegate::LAUNCH_FROM_APP_LIST_SEARCH, event_flags); } 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: exsltStrAlignFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *str, *padding, *alignment, *ret; int str_l, padding_l; if ((nargs < 2) || (nargs > 3)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 3) alignment = xmlXPathPopString(ctxt); else alignment = NULL; padding = xmlXPathPopString(ctxt); str = xmlXPathPopString(ctxt); str_l = xmlUTF8Strlen (str); padding_l = xmlUTF8Strlen (padding); if (str_l == padding_l) { xmlXPathReturnString (ctxt, str); xmlFree(padding); xmlFree(alignment); return; } if (str_l > padding_l) { ret = xmlUTF8Strndup (str, padding_l); } else { if (xmlStrEqual(alignment, (const xmlChar *) "right")) { ret = xmlUTF8Strndup (padding, padding_l - str_l); ret = xmlStrcat (ret, str); } else if (xmlStrEqual(alignment, (const xmlChar *) "center")) { int left = (padding_l - str_l) / 2; int right_start; ret = xmlUTF8Strndup (padding, left); ret = xmlStrcat (ret, str); right_start = xmlUTF8Strsize (padding, left + str_l); ret = xmlStrcat (ret, padding + right_start); } else { int str_s; str_s = xmlStrlen (str); ret = xmlStrdup (str); ret = xmlStrcat (ret, padding + str_s); } } xmlXPathReturnString (ctxt, ret); xmlFree(str); xmlFree(padding); xmlFree(alignment); } CWE ID: CWE-119 Target: 1 Example 2: Code: int CMS_RecipientInfo_encrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { switch (ri->type) { case CMS_RECIPINFO_TRANS: return cms_RecipientInfo_ktri_encrypt(cms, ri); case CMS_RECIPINFO_AGREE: return cms_RecipientInfo_kari_encrypt(cms, ri); case CMS_RECIPINFO_KEK: return cms_RecipientInfo_kekri_encrypt(cms, ri); case CMS_RECIPINFO_PASS: return cms_RecipientInfo_pwri_crypt(cms, ri, 1); default: CMSerr(CMS_F_CMS_RECIPIENTINFO_ENCRYPT, CMS_R_UNSUPPORTED_RECIPIENT_TYPE); return 0; } } CWE ID: CWE-311 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 FinalCleanupCallback(disk_cache::BackendImpl* backend) { backend->CleanupCache(); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 4, &tmp)) return -1; *val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) & 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp); return 0; } CWE ID: CWE-190 Target: 1 Example 2: Code: ForceTermination(struct upnphttp * h, const char * action, const char * ns) { UNUSED(action); UNUSED(ns); SoapError(h, 606, "Action not authorized"); } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Init(const IPC::ChannelHandle& channel_handle, PP_Module pp_module, PP_GetInterface_Func local_get_interface, const ppapi::Preferences& preferences, SyncMessageStatusReceiver* status_receiver) { dispatcher_delegate_.reset(new ProxyChannelDelegate); dispatcher_.reset(new ppapi::proxy::HostDispatcher( pp_module, local_get_interface, status_receiver)); if (!dispatcher_->InitHostWithChannel(dispatcher_delegate_.get(), channel_handle, true, // Client. preferences)) { dispatcher_.reset(); dispatcher_delegate_.reset(); return false; } return true; } 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 su3000_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[3] = { 0xe, 0x80, 0 }; u8 ibuf[] = { 0 }; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x02; obuf[2] = 1; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 0; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 1; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0x51; if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); d->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, d->fe_adap[0].fe, &dw2104_ts2020_config, &d->dev->i2c_adap)) { info("Attached DS3000/TS2020!"); return 0; } info("Failed to attach DS3000/TS2020!"); return -EIO; } CWE ID: CWE-119 Target: 1 Example 2: Code: LayoutUnit RenderBlock::pageRemainingLogicalHeightForOffset(LayoutUnit offset, PageBoundaryRule pageBoundaryRule) const { RenderView* renderView = view(); offset += offsetFromLogicalTopOfFirstPage(); RenderFlowThread* flowThread = flowThreadContainingBlock(); if (!flowThread) { LayoutUnit pageLogicalHeight = renderView->layoutState()->pageLogicalHeight(); LayoutUnit remainingHeight = pageLogicalHeight - intMod(offset, pageLogicalHeight); if (pageBoundaryRule == IncludePageBoundary) { remainingHeight = intMod(remainingHeight, pageLogicalHeight); } return remainingHeight; } return flowThread->pageRemainingLogicalHeightForOffset(offset, pageBoundaryRule); } 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: SchemaRegistryNativeHandler(V8SchemaRegistry* registry, std::unique_ptr<ScriptContext> context) : ObjectBackedNativeHandler(context.get()), context_(std::move(context)), registry_(registry) { RouteFunction("GetSchema", base::Bind(&SchemaRegistryNativeHandler::GetSchema, base::Unretained(this))); } 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: zsetstrokecolorspace(i_ctx_t * i_ctx_p) { int code; zsetstrokecolorspace(i_ctx_t * i_ctx_p) { int code; code = zswapcolors(i_ctx_p); if (code < 0) /* Now, the actual continuation routine */ push_op_estack(setstrokecolorspace_cont); code = zsetcolorspace(i_ctx_p); if (code >= 0) return o_push_estack; return code; } if (code >= 0) return o_push_estack; return code; } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst) { return assign_eip_far(ctxt, dst, ctxt->mode == X86EMUL_MODE_PROT64); } 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 uint8_t excluded_channels(bitfile *ld, drc_info *drc) { uint8_t i, n = 0; uint8_t num_excl_chan = 7; for (i = 0; i < 7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,103,"excluded_channels(): exclude_mask")); } n++; while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1) { for (i = num_excl_chan; i < num_excl_chan+7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,105,"excluded_channels(): exclude_mask")); } n++; num_excl_chan += 7; } return n; } 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: PHP_FUNCTION(locale_get_all_variants) { const char* loc_name = NULL; int loc_name_len = 0; int result = 0; char* token = NULL; char* variant = NULL; char* saved_ptr = NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_parse: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } array_init( return_value ); /* If the locale is grandfathered, stop, no variants */ if( findOffset( LOC_GRANDFATHERED , loc_name ) >= 0 ){ /* ("Grandfathered Tag. No variants."); */ } else { /* Call ICU variant */ variant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0); if( result > 0 && variant){ /* Tokenize on the "_" or "-" */ token = php_strtok_r( variant , DELIMITER , &saved_ptr); add_next_index_stringl( return_value, token , strlen(token) ,TRUE ); /* tokenize on the "_" or "-" and stop at singleton if any */ while( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){ add_next_index_stringl( return_value, token , strlen(token) ,TRUE ); } } if( variant ){ efree( variant ); } } } CWE ID: CWE-125 Target: 1 Example 2: Code: PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& es) { if (!isValidName(localName)) { es.throwUninformativeAndGenericDOMException(InvalidCharacterError); return 0; } RefPtr<Element> element; if (RuntimeEnabledFeatures::customElementsEnabled() && CustomElement::isValidName(localName) && registrationContext()) element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI)); else element = createElement(localName, es); if (RuntimeEnabledFeatures::customElementsEnabled() && !typeExtension.isNull() && !typeExtension.isEmpty()) CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension); return element; } 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: WORD32 ih264d_init(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { ih264d_init_ip_t *ps_init_ip; ih264d_init_op_t *ps_init_op; WORD32 init_status = IV_SUCCESS; ps_init_ip = (ih264d_init_ip_t *)pv_api_ip; ps_init_op = (ih264d_init_op_t *)pv_api_op; init_status = ih264d_init_video_decoder(dec_hdl, ps_init_ip, ps_init_op); if(IV_SUCCESS != init_status) { return init_status; } return init_status; } 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: GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns) { int r; static const char resp[] = "<u:%sResponse " "xmlns:u=\"%s\">" "<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>" "</u:%sResponse>"; char body[512]; int bodylen; struct NameValueParserData data; char * int_ip, * int_port, * rem_host, * rem_port, * protocol; int opt=0; /*int proto=0;*/ unsigned short iport, rport; if (GETFLAG(IPV6FCFWDISABLEDMASK)) { SoapError(h, 702, "FirewallDisabled"); return; } ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data); int_ip = GetValueFromNameValueList(&data, "InternalClient"); int_port = GetValueFromNameValueList(&data, "InternalPort"); rem_host = GetValueFromNameValueList(&data, "RemoteHost"); rem_port = GetValueFromNameValueList(&data, "RemotePort"); protocol = GetValueFromNameValueList(&data, "Protocol"); rport = (unsigned short)atoi(rem_port); iport = (unsigned short)atoi(int_port); /*proto = atoi(protocol);*/ syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol); /* TODO */ r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/ switch(r) { case 1: /* success */ bodylen = snprintf(body, sizeof(body), resp, action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/, opt, action); BuildSendAndCloseSoapResp(h, body, bodylen); break; case -5: /* Protocol not supported */ SoapError(h, 705, "ProtocolNotSupported"); break; default: SoapError(h, 501, "ActionFailed"); } ClearNameValueList(&data); } CWE ID: CWE-476 Target: 1 Example 2: Code: static void php_zip_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { ze_zip_object * intern = (ze_zip_object *) object; int i; if (!intern) { return; } if (intern->za) { if (zip_close(intern->za) != 0) { _zip_free(intern->za); } intern->za = NULL; } if (intern->buffers_cnt>0) { for (i=0; i<intern->buffers_cnt; i++) { efree(intern->buffers[i]); } efree(intern->buffers); } intern->za = NULL; #if (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION == 1 && PHP_RELEASE_VERSION > 2) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION > 1) || (PHP_MAJOR_VERSION > 5) zend_object_std_dtor(&intern->zo TSRMLS_CC); #else if (intern->zo.guards) { zend_hash_destroy(intern->zo.guards); FREE_HASHTABLE(intern->zo.guards); } if (intern->zo.properties) { zend_hash_destroy(intern->zo.properties); FREE_HASHTABLE(intern->zo.properties); } #endif if (intern->filename) { efree(intern->filename); } efree(intern); } /* }}} */ CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void cachedDirtyableAttributeRaisesAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::String> propertyName = v8AtomicString(info.GetIsolate(), "cachedDirtyableAttributeRaises"); TestObject* imp = V8TestObject::toNative(info.Holder()); if (!imp->isValueDirty()) { v8::Handle<v8::Value> jsValue = V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Holder(), propertyName); if (!jsValue.IsEmpty()) { v8SetReturnValue(info, jsValue); return; } } ExceptionState exceptionState(ExceptionState::GetterContext, "cachedDirtyableAttributeRaises", "TestObject", info.Holder(), info.GetIsolate()); ScriptValue jsValue = imp->cachedDirtyableAttributeRaises(exceptionState); if (UNLIKELY(exceptionState.throwIfNeeded())) return; V8HiddenValue::setHiddenValue(info.GetIsolate(), info.Holder(), propertyName, jsValue.v8Value()); v8SetReturnValue(info, jsValue.v8Value()); } 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 intel_pmu_handle_irq(struct pt_regs *regs) { struct perf_sample_data data; struct cpu_hw_events *cpuc; int bit, loops; u64 status; int handled; perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); /* * Some chipsets need to unmask the LVTPC in a particular spot * inside the nmi handler. As a result, the unmasking was pushed * into all the nmi handlers. * * This handler doesn't seem to have any issues with the unmasking * so it was left at the top. */ apic_write(APIC_LVTPC, APIC_DM_NMI); intel_pmu_disable_all(); handled = intel_pmu_drain_bts_buffer(); status = intel_pmu_get_status(); if (!status) { intel_pmu_enable_all(0); return handled; } loops = 0; again: intel_pmu_ack_status(status); if (++loops > 100) { WARN_ONCE(1, "perfevents: irq loop stuck!\n"); perf_event_print_debug(); intel_pmu_reset(); goto done; } inc_irq_stat(apic_perf_irqs); intel_pmu_lbr_read(); /* * PEBS overflow sets bit 62 in the global status register */ if (__test_and_clear_bit(62, (unsigned long *)&status)) { handled++; x86_pmu.drain_pebs(regs); } for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) { struct perf_event *event = cpuc->events[bit]; handled++; if (!test_bit(bit, cpuc->active_mask)) continue; if (!intel_pmu_save_and_restart(event)) continue; data.period = event->hw.last_period; if (perf_event_overflow(event, 1, &data, regs)) x86_pmu_stop(event, 0); } /* * Repeat if there is more work to be done: */ status = intel_pmu_get_status(); if (status) goto again; done: intel_pmu_enable_all(0); return handled; } CWE ID: CWE-399 Target: 1 Example 2: Code: void CoordinatorImpl::FinalizeGlobalMemoryDumpIfAllManagersReplied() { TRACE_EVENT0(base::trace_event::MemoryDumpManager::kTraceCategory, "GlobalMemoryDump.Computation"); DCHECK(!queued_memory_dump_requests_.empty()); QueuedRequest* request = &queued_memory_dump_requests_.front(); if (!request->dump_in_progress || request->pending_responses.size() > 0) return; QueuedRequestDispatcher::Finalize(request, tracing_observer_.get()); queued_memory_dump_requests_.pop_front(); request = nullptr; if (!queued_memory_dump_requests_.empty()) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&CoordinatorImpl::PerformNextQueuedGlobalMemoryDump, base::Unretained(this))); } } 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: bool AutofillManager::GetDeletionConfirmationText(const base::string16& value, int identifier, base::string16* title, base::string16* body) { if (identifier == POPUP_ITEM_ID_AUTOCOMPLETE_ENTRY) { if (title) title->assign(value); if (body) { body->assign(l10n_util::GetStringUTF16( IDS_AUTOFILL_DELETE_AUTOCOMPLETE_SUGGESTION_CONFIRMATION_BODY)); } return true; } if (identifier < 0) return false; const CreditCard* credit_card = nullptr; const AutofillProfile* profile = nullptr; if (GetCreditCard(identifier, &credit_card)) { if (credit_card->record_type() != CreditCard::LOCAL_CARD) return false; if (title) title->assign(credit_card->NetworkOrBankNameAndLastFourDigits()); if (body) { body->assign(l10n_util::GetStringUTF16( IDS_AUTOFILL_DELETE_CREDIT_CARD_SUGGESTION_CONFIRMATION_BODY)); } return true; } if (GetProfile(identifier, &profile)) { if (profile->record_type() != AutofillProfile::LOCAL_PROFILE) return false; if (title) { base::string16 street_address = profile->GetRawInfo(ADDRESS_HOME_CITY); if (!street_address.empty()) title->swap(street_address); else title->assign(value); } if (body) { body->assign(l10n_util::GetStringUTF16( IDS_AUTOFILL_DELETE_PROFILE_SUGGESTION_CONFIRMATION_BODY)); } return true; } NOTREACHED(); return false; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { #if WRITE_COMPRESSED_STREAM ++out_frames_; if (pkt->data.frame.pts == 0) write_ivf_file_header(&cfg_, 0, outfile_); write_ivf_frame_header(pkt, outfile_); (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_); #endif } CWE ID: CWE-119 Target: 1 Example 2: Code: PHP_FUNCTION(openssl_csr_get_public_key) { zval ** zcsr; zend_bool use_shortnames = 1; long csr_resource; X509_REQ * csr; EVP_PKEY *tpubkey; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &zcsr, &use_shortnames) == FAILURE) { return; } csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource TSRMLS_CC); if (csr == NULL) { RETURN_FALSE; } tpubkey=X509_REQ_get_pubkey(csr); RETVAL_RESOURCE(zend_list_insert(tpubkey, le_key TSRMLS_CC)); return; } CWE ID: CWE-754 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ScriptedAnimationController& VRDisplay::EnsureScriptedAnimationController( Document* doc) { if (!scripted_animation_controller_) scripted_animation_controller_ = ScriptedAnimationController::Create(doc); return *scripted_animation_controller_; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void lo_release(struct gendisk *disk, fmode_t mode) { struct loop_device *lo = disk->private_data; int err; if (atomic_dec_return(&lo->lo_refcnt)) return; mutex_lock(&lo->lo_ctl_mutex); if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) { /* * In autoclear mode, stop the loop thread * and remove configuration after last close. */ err = loop_clr_fd(lo); if (!err) return; } else if (lo->lo_state == Lo_bound) { /* * Otherwise keep thread (if running) and config, * but flush possible ongoing bios in thread. */ blk_mq_freeze_queue(lo->lo_queue); blk_mq_unfreeze_queue(lo->lo_queue); } mutex_unlock(&lo->lo_ctl_mutex); } CWE ID: CWE-416 Target: 1 Example 2: Code: static void pg_init_done(void *data, int errors) { struct pgpath *pgpath = data; struct priority_group *pg = pgpath->pg; struct multipath *m = pg->m; unsigned long flags; unsigned delay_retry = 0; /* device or driver problems */ switch (errors) { case SCSI_DH_OK: break; case SCSI_DH_NOSYS: if (!m->hw_handler_name) { errors = 0; break; } DMERR("Could not failover the device: Handler scsi_dh_%s " "Error %d.", m->hw_handler_name, errors); /* * Fail path for now, so we do not ping pong */ fail_path(pgpath); break; case SCSI_DH_DEV_TEMP_BUSY: /* * Probably doing something like FW upgrade on the * controller so try the other pg. */ bypass_pg(m, pg, 1); break; case SCSI_DH_RETRY: /* Wait before retrying. */ delay_retry = 1; case SCSI_DH_IMM_RETRY: case SCSI_DH_RES_TEMP_UNAVAIL: if (pg_init_limit_reached(m, pgpath)) fail_path(pgpath); errors = 0; break; default: /* * We probably do not want to fail the path for a device * error, but this is what the old dm did. In future * patches we can do more advanced handling. */ fail_path(pgpath); } spin_lock_irqsave(&m->lock, flags); if (errors) { if (pgpath == m->current_pgpath) { DMERR("Could not failover device. Error %d.", errors); m->current_pgpath = NULL; m->current_pg = NULL; } } else if (!m->pg_init_required) pg->bypassed = 0; if (--m->pg_init_in_progress) /* Activations of other paths are still on going */ goto out; if (!m->pg_init_required) m->queue_io = 0; m->pg_init_delay_retry = delay_retry; queue_work(kmultipathd, &m->process_queued_ios); /* * Wake up any thread waiting to suspend. */ wake_up(&m->pg_init_wait); out: spin_unlock_irqrestore(&m->lock, flags); } 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 do_proc_dointvec_conv(bool *negp, unsigned long *lvalp, int *valp, int write, void *data) { if (write) { *valp = *negp ? -*lvalp : *lvalp; } else { int val = *valp; if (val < 0) { *negp = true; *lvalp = (unsigned long)-val; } else { *negp = false; *lvalp = (unsigned long)val; } } 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: int vrend_create_vertex_elements_state(struct vrend_context *ctx, uint32_t handle, unsigned num_elements, const struct pipe_vertex_element *elements) { struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array); const struct util_format_description *desc; GLenum type; int i; uint32_t ret_handle; if (!v) return ENOMEM; v->count = num_elements; for (i = 0; i < num_elements; i++) { memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element)); FREE(v); return EINVAL; } type = GL_FALSE; if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) { if (desc->channel[0].size == 32) type = GL_FLOAT; else if (desc->channel[0].size == 64) type = GL_DOUBLE; else if (desc->channel[0].size == 16) type = GL_HALF_FLOAT; } else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 8) type = GL_UNSIGNED_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 8) type = GL_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 16) type = GL_UNSIGNED_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 16) type = GL_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 32) type = GL_UNSIGNED_INT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 32) type = GL_INT; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM) type = GL_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM) type = GL_UNSIGNED_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) type = GL_UNSIGNED_INT_10F_11F_11F_REV; if (type == GL_FALSE) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format); FREE(v); return EINVAL; } v->elements[i].type = type; if (desc->channel[0].normalized) v->elements[i].norm = GL_TRUE; if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z) v->elements[i].nr_chan = GL_BGRA; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) v->elements[i].nr_chan = 3; else v->elements[i].nr_chan = desc->nr_channels; } CWE ID: CWE-119 Target: 1 Example 2: Code: void ExtractFileFeatures(const base::FilePath& file_path) { base::TimeTicks start_time = base::TimeTicks::Now(); binary_feature_extractor_->CheckSignature(file_path, &signature_info_); bool is_signed = (signature_info_.certificate_chain_size() > 0); if (is_signed) { DVLOG(2) << "Downloaded a signed binary: " << file_path.value(); } else { DVLOG(2) << "Downloaded an unsigned binary: " << file_path.value(); } UMA_HISTOGRAM_BOOLEAN("SBClientDownload.SignedBinaryDownload", is_signed); UMA_HISTOGRAM_TIMES("SBClientDownload.ExtractSignatureFeaturesTime", base::TimeTicks::Now() - start_time); start_time = base::TimeTicks::Now(); image_headers_.reset(new ClientDownloadRequest_ImageHeaders()); if (!binary_feature_extractor_->ExtractImageFeatures( file_path, BinaryFeatureExtractor::kDefaultOptions, image_headers_.get(), nullptr /* signed_data */)) { image_headers_.reset(); } UMA_HISTOGRAM_TIMES("SBClientDownload.ExtractImageHeadersTime", base::TimeTicks::Now() - start_time); OnFileFeatureExtractionDone(); } 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: ExtensionsUpdatedObserver::ExtensionsUpdatedObserver( ExtensionProcessManager* manager, AutomationProvider* automation, IPC::Message* reply_message) : manager_(manager), automation_(automation->AsWeakPtr()), reply_message_(reply_message), updater_finished_(false) { registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALL_NOT_ALLOWED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UPDATE_FOUND, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UPDATING_FINISHED, content::NotificationService::AllSources()); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool TracingControllerImpl::StartTracing( const base::trace_event::TraceConfig& trace_config, StartTracingDoneCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (IsTracing()) { if (trace_config.process_filter_config().empty() || trace_config_->process_filter_config().empty()) { return false; } base::trace_event::TraceConfig old_config_copy(*trace_config_); base::trace_event::TraceConfig new_config_copy(trace_config); old_config_copy.SetProcessFilterConfig( base::trace_event::TraceConfig::ProcessFilterConfig()); new_config_copy.SetProcessFilterConfig( base::trace_event::TraceConfig::ProcessFilterConfig()); if (old_config_copy.ToString() != new_config_copy.ToString()) return false; } trace_config_ = std::make_unique<base::trace_event::TraceConfig>(trace_config); start_tracing_done_ = std::move(callback); ConnectToServiceIfNeeded(); coordinator_->StartTracing(trace_config.ToString()); if (start_tracing_done_ && (base::trace_event::TraceLog::GetInstance()->IsEnabled() || !trace_config.process_filter_config().IsEnabled( base::Process::Current().Pid()))) { std::move(start_tracing_done_).Run(); } return true; } CWE ID: CWE-19 Target: 1 Example 2: Code: ModuleExport size_t RegisterIPLImage(void) { MagickInfo *entry; entry=SetMagickInfo("IPL"); entry->decoder=(DecodeImageHandler *) ReadIPLImage; entry->encoder=(EncodeImageHandler *) WriteIPLImage; entry->magick=(IsImageFormatHandler *) IsIPL; entry->adjoin=MagickTrue; entry->description=ConstantString("IPL Image Sequence"); entry->module=ConstantString("IPL"); entry->endian_support=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } 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 struct rtable *rt_dst_alloc(struct net_device *dev, bool nopolicy, bool noxfrm) { return dst_alloc(&ipv4_dst_ops, dev, 1, -1, DST_HOST | (nopolicy ? DST_NOPOLICY : 0) | (noxfrm ? DST_NOXFRM : 0)); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void arch_pick_mmap_layout(struct mm_struct *mm) { unsigned long random_factor = 0UL; if (current->flags & PF_RANDOMIZE) random_factor = arch_mmap_rnd(); mm->mmap_legacy_base = mmap_legacy_base(random_factor); if (mmap_is_legacy()) { mm->mmap_base = mm->mmap_legacy_base; mm->get_unmapped_area = arch_get_unmapped_area; } else { mm->mmap_base = mmap_base(random_factor); mm->get_unmapped_area = arch_get_unmapped_area_topdown; } } CWE ID: CWE-254 Target: 1 Example 2: Code: Response InspectorPageAgent::enable() { enabled_ = true; state_->setBoolean(PageAgentState::kPageAgentEnabled, true); instrumenting_agents_->addInspectorPageAgent(this); return Response::OK(); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) { if (ComputeVisibleSelectionInDOMTree().IsNone()) return; SetSelection( SelectionInDOMTree::Builder( GetGranularityStrategy()->UpdateExtent(contents_point, frame_)) .SetIsHandleVisible(true) .Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetDoNotClearStrategy(true) .SetSetSelectionBy(SetSelectionBy::kUser) .Build()); } 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 struct inode *ext4_alloc_inode(struct super_block *sb) { struct ext4_inode_info *ei; ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS); if (!ei) return NULL; ei->vfs_inode.i_version = 1; ei->vfs_inode.i_data.writeback_index = 0; memset(&ei->i_cached_extent, 0, sizeof(struct ext4_ext_cache)); INIT_LIST_HEAD(&ei->i_prealloc_list); spin_lock_init(&ei->i_prealloc_lock); /* * Note: We can be called before EXT4_SB(sb)->s_journal is set, * therefore it can be null here. Don't check it, just initialize * jinode. */ jbd2_journal_init_jbd_inode(&ei->jinode, &ei->vfs_inode); ei->i_reserved_data_blocks = 0; ei->i_reserved_meta_blocks = 0; ei->i_allocated_meta_blocks = 0; ei->i_da_metadata_calc_len = 0; ei->i_delalloc_reserved_flag = 0; spin_lock_init(&(ei->i_block_reservation_lock)); #ifdef CONFIG_QUOTA ei->i_reserved_quota = 0; #endif INIT_LIST_HEAD(&ei->i_completed_io_list); ei->cur_aio_dio = NULL; ei->i_sync_tid = 0; ei->i_datasync_tid = 0; return &ei->vfs_inode; } CWE ID: Target: 1 Example 2: Code: static bool access_pmceid(struct kvm_vcpu *vcpu, struct sys_reg_params *p, const struct sys_reg_desc *r) { u64 pmceid; if (!kvm_arm_pmu_v3_ready(vcpu)) return trap_raz_wi(vcpu, p, r); BUG_ON(p->is_write); if (pmu_access_el0_disabled(vcpu)) return false; if (!(p->Op2 & 1)) pmceid = read_sysreg(pmceid0_el0); else pmceid = read_sysreg(pmceid1_el0); p->regval = pmceid; return true; } 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 get_counters(const struct ebt_counter *oldcounters, struct ebt_counter *counters, unsigned int nentries) { int i, cpu; struct ebt_counter *counter_base; /* counters of cpu 0 */ memcpy(counters, oldcounters, sizeof(struct ebt_counter) * nentries); /* add other counters to those of cpu 0 */ for_each_possible_cpu(cpu) { if (cpu == 0) continue; counter_base = COUNTER_BASE(oldcounters, nentries, cpu); for (i = 0; i < nentries; i++) { counters[i].pcnt += counter_base[i].pcnt; counters[i].bcnt += counter_base[i].bcnt; } } } 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 ion_free(struct ion_client *client, struct ion_handle *handle) { bool valid_handle; BUG_ON(client != handle->client); mutex_lock(&client->lock); valid_handle = ion_handle_validate(client, handle); if (!valid_handle) { WARN(1, "%s: invalid handle passed to free.\n", __func__); mutex_unlock(&client->lock); return; } mutex_unlock(&client->lock); ion_handle_put(handle); } CWE ID: CWE-416 Target: 1 Example 2: Code: static int cma_get_id_stats(struct sk_buff *skb, struct netlink_callback *cb) { struct nlmsghdr *nlh; struct rdma_cm_id_stats *id_stats; struct rdma_id_private *id_priv; struct rdma_cm_id *id = NULL; struct cma_device *cma_dev; int i_dev = 0, i_id = 0; /* * We export all of the IDs as a sequence of messages. Each * ID gets its own netlink message. */ mutex_lock(&lock); list_for_each_entry(cma_dev, &dev_list, list) { if (i_dev < cb->args[0]) { i_dev++; continue; } i_id = 0; list_for_each_entry(id_priv, &cma_dev->id_list, list) { if (i_id < cb->args[1]) { i_id++; continue; } id_stats = ibnl_put_msg(skb, &nlh, cb->nlh->nlmsg_seq, sizeof *id_stats, RDMA_NL_RDMA_CM, RDMA_NL_RDMA_CM_ID_STATS); if (!id_stats) goto out; memset(id_stats, 0, sizeof *id_stats); id = &id_priv->id; id_stats->node_type = id->route.addr.dev_addr.dev_type; id_stats->port_num = id->port_num; id_stats->bound_dev_if = id->route.addr.dev_addr.bound_dev_if; if (ibnl_put_attr(skb, nlh, rdma_addr_size(cma_src_addr(id_priv)), cma_src_addr(id_priv), RDMA_NL_RDMA_CM_ATTR_SRC_ADDR)) goto out; if (ibnl_put_attr(skb, nlh, rdma_addr_size(cma_src_addr(id_priv)), cma_dst_addr(id_priv), RDMA_NL_RDMA_CM_ATTR_DST_ADDR)) goto out; id_stats->pid = id_priv->owner; id_stats->port_space = id->ps; id_stats->cm_state = id_priv->state; id_stats->qp_num = id_priv->qp_num; id_stats->qp_type = id->qp_type; i_id++; } cb->args[1] = 0; i_dev++; } out: mutex_unlock(&lock); cb->args[0] = i_dev; cb->args[1] = i_id; return skb->len; } 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: ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } 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 PaymentRequest::Abort() { bool accepting_abort = !state_->IsPaymentAppInvoked(); if (accepting_abort) RecordFirstAbortReason(JourneyLogger::ABORT_REASON_ABORTED_BY_MERCHANT); if (client_.is_bound()) client_->OnAbort(accepting_abort); if (observer_for_testing_) observer_for_testing_->OnAbortCalled(); } CWE ID: CWE-189 Target: 1 Example 2: Code: get_entries(struct net *net, struct ipt_get_entries __user *uptr, const int *len) { int ret; struct ipt_get_entries get; struct xt_table *t; if (*len < sizeof(get)) return -EINVAL; if (copy_from_user(&get, uptr, sizeof(get)) != 0) return -EFAULT; if (*len != sizeof(struct ipt_get_entries) + get.size) return -EINVAL; get.name[sizeof(get.name) - 1] = '\0'; t = xt_find_table_lock(net, AF_INET, get.name); if (!IS_ERR(t)) { const struct xt_table_info *private = t->private; if (get.size == private->size) ret = copy_entries_to_user(private->size, t, uptr->entrytable); else ret = -EAGAIN; module_put(t->me); xt_table_unlock(t); } else ret = PTR_ERR(t); return ret; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BaseArena::~BaseArena() { ASSERT(!m_firstPage); ASSERT(!m_firstUnsweptPage); } 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: uint8_t smb2cli_session_security_mode(struct smbXcli_session *session) { struct smbXcli_conn *conn = session->conn; uint8_t security_mode = 0; if (conn == NULL) { return security_mode; } security_mode = SMB2_NEGOTIATE_SIGNING_ENABLED; if (conn->mandatory_signing) { security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; } return security_mode; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int ext3_statfs (struct dentry * dentry, struct kstatfs * buf) { struct super_block *sb = dentry->d_sb; struct ext3_sb_info *sbi = EXT3_SB(sb); struct ext3_super_block *es = sbi->s_es; u64 fsid; if (test_opt(sb, MINIX_DF)) { sbi->s_overhead_last = 0; } else if (sbi->s_blocks_last != le32_to_cpu(es->s_blocks_count)) { unsigned long ngroups = sbi->s_groups_count, i; ext3_fsblk_t overhead = 0; smp_rmb(); /* * Compute the overhead (FS structures). This is constant * for a given filesystem unless the number of block groups * changes so we cache the previous value until it does. */ /* * All of the blocks before first_data_block are * overhead */ overhead = le32_to_cpu(es->s_first_data_block); /* * Add the overhead attributed to the superblock and * block group descriptors. If the sparse superblocks * feature is turned on, then not all groups have this. */ for (i = 0; i < ngroups; i++) { overhead += ext3_bg_has_super(sb, i) + ext3_bg_num_gdb(sb, i); cond_resched(); } /* * Every block group has an inode bitmap, a block * bitmap, and an inode table. */ overhead += ngroups * (2 + sbi->s_itb_per_group); sbi->s_overhead_last = overhead; smp_wmb(); sbi->s_blocks_last = le32_to_cpu(es->s_blocks_count); } buf->f_type = EXT3_SUPER_MAGIC; buf->f_bsize = sb->s_blocksize; buf->f_blocks = le32_to_cpu(es->s_blocks_count) - sbi->s_overhead_last; buf->f_bfree = percpu_counter_sum_positive(&sbi->s_freeblocks_counter); buf->f_bavail = buf->f_bfree - le32_to_cpu(es->s_r_blocks_count); if (buf->f_bfree < le32_to_cpu(es->s_r_blocks_count)) buf->f_bavail = 0; buf->f_files = le32_to_cpu(es->s_inodes_count); buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter); buf->f_namelen = EXT3_NAME_LEN; fsid = le64_to_cpup((void *)es->s_uuid) ^ le64_to_cpup((void *)es->s_uuid + sizeof(u64)); buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL; buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL; return 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool NaClProcessHost::SendStart() { if (!enable_ipc_proxy_) { if (!ReplyToRenderer(IPC::ChannelHandle())) return false; } return StartNaClExecution(); } 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 WallpaperManager::StartLoadAndSetDefaultWallpaper( const base::FilePath& path, const wallpaper::WallpaperLayout layout, MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage>* result_out) { user_image_loader::StartWithFilePath( task_runner_, path, ImageDecoder::ROBUST_JPEG_CODEC, 0, // Do not crop. base::Bind(&WallpaperManager::OnDefaultWallpaperDecoded, weak_factory_.GetWeakPtr(), path, layout, base::Unretained(result_out), base::Passed(std::move(on_finish)))); } CWE ID: CWE-200 Target: 1 Example 2: Code: SyncBackendHost::Core::Core(const std::string& name, const FilePath& sync_data_folder_path, const base::WeakPtr<SyncBackendHost>& backend) : name_(name), sync_data_folder_path_(sync_data_folder_path), host_(backend), sync_loop_(NULL), registrar_(NULL) { DCHECK(backend.get()); } 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 bool ParsedIsEqual(const Parsed& a, const Parsed& b) { return a.scheme.begin == b.scheme.begin && a.scheme.len == b.scheme.len && a.username.begin == b.username.begin && a.username.len == b.username.len && a.password.begin == b.password.begin && a.password.len == b.password.len && a.host.begin == b.host.begin && a.host.len == b.host.len && a.port.begin == b.port.begin && a.port.len == b.port.len && a.path.begin == b.path.begin && a.path.len == b.path.len && a.query.begin == b.query.begin && a.query.len == b.query.len && a.ref.begin == b.ref.begin && a.ref.len == b.ref.len; } CWE ID: CWE-79 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 GestureSequence::PinchUpdate(const TouchEvent& event, const GesturePoint& point, Gestures* gestures) { DCHECK(state_ == GS_PINCH); float distance = points_[0].Distance(points_[1]); if (abs(distance - pinch_distance_current_) < kMinimumPinchUpdateDistance) { if (!points_[0].DidScroll(event, kMinimumDistanceForPinchScroll) || !points_[1].DidScroll(event, kMinimumDistanceForPinchScroll)) return false; gfx::Point center = points_[0].last_touch_position().Middle( points_[1].last_touch_position()); AppendScrollGestureUpdate(point, center, gestures); } else { AppendPinchGestureUpdate(points_[0], points_[1], distance / pinch_distance_current_, gestures); pinch_distance_current_ = distance; } return true; } CWE ID: CWE-20 Target: 1 Example 2: Code: void V8TestObject::ReflectReflectedNameAttributeTestAttributeAttributeSetterCallback( const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_reflectReflectedNameAttributeTestAttribute_Setter"); v8::Local<v8::Value> v8_value = info[0]; test_object_v8_internal::ReflectReflectedNameAttributeTestAttributeAttributeSetter(v8_value, info); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GURL DecorateFrontendURL(const GURL& base_url) { std::string frontend_url = base_url.spec(); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&") + "dockSide=undocked"); // TODO(dgozman): remove this support in M38. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableDevToolsExperiments)) url_string += "&experiments=true"; if (command_line->HasSwitch(switches::kDevToolsFlags)) { std::string flags = command_line->GetSwitchValueASCII( switches::kDevToolsFlags); flags = net::EscapeQueryParamValue(flags, false); url_string += "&flags=" + flags; } #if defined(DEBUG_DEVTOOLS) url_string += "&debugFrontend=true"; #endif // defined(DEBUG_DEVTOOLS) return GURL(url_string); } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg, bool_t *no_dispatch) { enum auth_stat retstat; XDR xdrs; SVCAUTH *auth; struct svc_rpc_gss_data *gd; struct rpc_gss_cred *gc; struct rpc_gss_init_res gr; int call_stat, offset; OM_uint32 min_stat; log_debug("in svcauth_gss()"); /* Initialize reply. */ rqst->rq_xprt->xp_verf = gssrpc__null_auth; /* Allocate and set up server auth handle. */ if (rqst->rq_xprt->xp_auth == NULL || rqst->rq_xprt->xp_auth == &svc_auth_none) { if ((auth = calloc(sizeof(*auth), 1)) == NULL) { fprintf(stderr, "svcauth_gss: out_of_memory\n"); return (AUTH_FAILED); } if ((gd = calloc(sizeof(*gd), 1)) == NULL) { fprintf(stderr, "svcauth_gss: out_of_memory\n"); return (AUTH_FAILED); } auth->svc_ah_ops = &svc_auth_gss_ops; SVCAUTH_PRIVATE(auth) = gd; rqst->rq_xprt->xp_auth = auth; } else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth); log_debug("xp_auth=%p, gd=%p", rqst->rq_xprt->xp_auth, gd); /* Deserialize client credentials. */ if (rqst->rq_cred.oa_length <= 0) return (AUTH_BADCRED); gc = (struct rpc_gss_cred *)rqst->rq_clntcred; memset(gc, 0, sizeof(*gc)); log_debug("calling xdrmem_create()"); log_debug("oa_base=%p, oa_length=%u", rqst->rq_cred.oa_base, rqst->rq_cred.oa_length); xdrmem_create(&xdrs, rqst->rq_cred.oa_base, rqst->rq_cred.oa_length, XDR_DECODE); log_debug("xdrmem_create() returned"); if (!xdr_rpc_gss_cred(&xdrs, gc)) { log_debug("xdr_rpc_gss_cred() failed"); XDR_DESTROY(&xdrs); return (AUTH_BADCRED); } XDR_DESTROY(&xdrs); retstat = AUTH_FAILED; #define ret_freegc(code) do { retstat = code; goto freegc; } while (0) /* Check version. */ if (gc->gc_v != RPCSEC_GSS_VERSION) ret_freegc (AUTH_BADCRED); /* Check RPCSEC_GSS service. */ if (gc->gc_svc != RPCSEC_GSS_SVC_NONE && gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY && gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY) ret_freegc (AUTH_BADCRED); /* Check sequence number. */ if (gd->established) { if (gc->gc_seq > MAXSEQ) ret_freegc (RPCSEC_GSS_CTXPROBLEM); if ((offset = gd->seqlast - gc->gc_seq) < 0) { gd->seqlast = gc->gc_seq; offset = 0 - offset; gd->seqmask <<= offset; offset = 0; } else if ((u_int)offset >= gd->win || (gd->seqmask & (1 << offset))) { *no_dispatch = 1; ret_freegc (RPCSEC_GSS_CTXPROBLEM); } gd->seq = gc->gc_seq; gd->seqmask |= (1 << offset); } if (gd->established) { rqst->rq_clntname = (char *)gd->client_name; rqst->rq_svccred = (char *)gd->ctx; } /* Handle RPCSEC_GSS control procedure. */ switch (gc->gc_proc) { case RPCSEC_GSS_INIT: case RPCSEC_GSS_CONTINUE_INIT: if (rqst->rq_proc != NULLPROC) ret_freegc (AUTH_FAILED); /* XXX ? */ if (!svcauth_gss_acquire_cred()) ret_freegc (AUTH_FAILED); if (!svcauth_gss_accept_sec_context(rqst, &gr)) ret_freegc (AUTH_REJECTEDCRED); if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) { gss_release_buffer(&min_stat, &gr.gr_token); mem_free(gr.gr_ctx.value, sizeof(gss_union_ctx_id_desc)); ret_freegc (AUTH_FAILED); } *no_dispatch = TRUE; call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res, (caddr_t)&gr); gss_release_buffer(&min_stat, &gr.gr_token); gss_release_buffer(&min_stat, &gd->checksum); mem_free(gr.gr_ctx.value, sizeof(gss_union_ctx_id_desc)); if (!call_stat) ret_freegc (AUTH_FAILED); if (gr.gr_major == GSS_S_COMPLETE) gd->established = TRUE; break; case RPCSEC_GSS_DATA: if (!svcauth_gss_validate(rqst, gd, msg)) ret_freegc (RPCSEC_GSS_CREDPROBLEM); if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq))) ret_freegc (AUTH_FAILED); break; case RPCSEC_GSS_DESTROY: if (rqst->rq_proc != NULLPROC) ret_freegc (AUTH_FAILED); /* XXX ? */ if (!svcauth_gss_validate(rqst, gd, msg)) ret_freegc (RPCSEC_GSS_CREDPROBLEM); if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq))) ret_freegc (AUTH_FAILED); *no_dispatch = TRUE; call_stat = svc_sendreply(rqst->rq_xprt, xdr_void, (caddr_t)NULL); log_debug("sendreply in destroy: %d", call_stat); if (!svcauth_gss_release_cred()) ret_freegc (AUTH_FAILED); SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth); rqst->rq_xprt->xp_auth = &svc_auth_none; break; default: ret_freegc (AUTH_REJECTEDCRED); break; } retstat = AUTH_OK; freegc: xdr_free(xdr_rpc_gss_cred, gc); log_debug("returning %d from svcauth_gss()", retstat); return (retstat); } CWE ID: CWE-200 Target: 1 Example 2: Code: void RenderBlock::adjustForColumns(LayoutSize& offset, const LayoutPoint& point) const { if (!hasColumns()) return; ColumnInfo* colInfo = columnInfo(); LayoutUnit logicalLeft = logicalLeftOffsetForContent(); unsigned colCount = columnCount(colInfo); LayoutUnit colLogicalWidth = colInfo->desiredColumnWidth(); LayoutUnit colLogicalHeight = colInfo->columnHeight(); for (unsigned i = 0; i < colCount; ++i) { LayoutRect sliceRect = LayoutRect(logicalLeft, borderBefore() + paddingBefore() + i * colLogicalHeight, colLogicalWidth, colLogicalHeight); if (!isHorizontalWritingMode()) sliceRect = sliceRect.transposedRect(); LayoutUnit logicalOffset = i * colLogicalHeight; if (isHorizontalWritingMode()) { if (point.y() >= sliceRect.y() && point.y() < sliceRect.maxY()) { if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) offset.expand(columnRectAt(colInfo, i).x() - logicalLeft, -logicalOffset); else offset.expand(0, columnRectAt(colInfo, i).y() - logicalOffset - borderBefore() - paddingBefore()); return; } } else { if (point.x() >= sliceRect.x() && point.x() < sliceRect.maxX()) { if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) offset.expand(-logicalOffset, columnRectAt(colInfo, i).y() - logicalLeft); else offset.expand(columnRectAt(colInfo, i).x() - logicalOffset - borderBefore() - paddingBefore(), 0); return; } } } } 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: nm_ip4_config_commit (const NMIP4Config *config, int ifindex, guint32 default_route_metric) { NMIP4ConfigPrivate *priv = NM_IP4_CONFIG_GET_PRIVATE (config); guint32 mtu = nm_ip4_config_get_mtu (config); int i; g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (ifindex > 0, FALSE); g_return_val_if_fail (config != NULL, FALSE); /* Addresses */ nm_platform_ip4_address_sync (ifindex, priv->addresses, default_route_metric); /* Routes */ { int count = nm_ip4_config_get_num_routes (config); GArray *routes = g_array_sized_new (FALSE, FALSE, sizeof (NMPlatformIP4Route), count); const NMPlatformIP4Route *route; gboolean success; for (i = 0; i < count; i++) { route = nm_ip4_config_get_route (config, i); /* Don't add the route if it's more specific than one of the subnets * the device already has an IP address on. */ if ( route->gateway == 0 && nm_ip4_config_destination_is_direct (config, route->network, route->plen)) continue; g_array_append_vals (routes, route, 1); } success = nm_route_manager_ip4_route_sync (nm_route_manager_get (), ifindex, routes); g_array_unref (routes); return FALSE; } /* MTU */ if (mtu && mtu != nm_platform_link_get_mtu (ifindex)) nm_platform_link_set_mtu (ifindex, mtu); 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: void SocketStream::set_context(URLRequestContext* context) { const URLRequestContext* prev_context = context_.get(); if (context) { context_ = context->AsWeakPtr(); } else { context_.reset(); } if (prev_context != context) { if (prev_context && pac_request_) { prev_context->proxy_service()->CancelPacRequest(pac_request_); pac_request_ = NULL; } net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE); net_log_ = BoundNetLog(); if (context) { net_log_ = BoundNetLog::Make( context->net_log(), NetLog::SOURCE_SOCKET_STREAM); net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE); } } } CWE ID: CWE-399 Target: 1 Example 2: Code: bool ContainerNode::isChildTypeAllowed(const Node& child) const { if (!child.isDocumentFragment()) return childTypeAllowed(child.nodeType()); for (Node* node = toDocumentFragment(child).firstChild(); node; node = node->nextSibling()) { if (!childTypeAllowed(node->nodeType())) return false; } return true; } 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 HTMLFrameOwnerElement::Trace(blink::Visitor* visitor) { visitor->Trace(content_frame_); visitor->Trace(embedded_content_view_); HTMLElement::Trace(visitor); FrameOwner::Trace(visitor); } CWE ID: CWE-601 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: RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const { if (interstitial_page_) return interstitial_page_->GetView(); if (render_frame_host_) return render_frame_host_->GetView(); return nullptr; } CWE ID: CWE-20 Target: 1 Example 2: Code: struct pt_regs *save_v86_state(struct kernel_vm86_regs *regs) { struct tss_struct *tss; struct pt_regs *ret; unsigned long tmp; /* * This gets called from entry.S with interrupts disabled, but * from process context. Enable interrupts here, before trying * to access user space. */ local_irq_enable(); if (!current->thread.vm86_info) { printk("no vm86_info: BAD\n"); do_exit(SIGSEGV); } set_flags(regs->pt.flags, VEFLAGS, X86_EFLAGS_VIF | current->thread.v86mask); tmp = copy_vm86_regs_to_user(&current->thread.vm86_info->regs, regs); tmp += put_user(current->thread.screen_bitmap, &current->thread.vm86_info->screen_bitmap); if (tmp) { printk("vm86: could not access userspace vm86_info\n"); do_exit(SIGSEGV); } tss = &per_cpu(init_tss, get_cpu()); current->thread.sp0 = current->thread.saved_sp0; current->thread.sysenter_cs = __KERNEL_CS; load_sp0(tss, &current->thread); current->thread.saved_sp0 = 0; put_cpu(); ret = KVM86->regs32; ret->fs = current->thread.saved_fs; set_user_gs(ret, current->thread.saved_gs); return ret; } 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 GaiaOAuthClient::Core::OnAuthTokenFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); if (!status.is_success()) { delegate_->OnNetworkError(response_code); return; } if (response_code == net::HTTP_BAD_REQUEST) { LOG(ERROR) << "Gaia response: response code=net::HTTP_BAD_REQUEST."; delegate_->OnOAuthError(); return; } if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); response_dict->GetString(kAccessTokenValue, &access_token_); response_dict->GetInteger(kExpiresInValue, &expires_in_seconds_); } VLOG(1) << "Gaia response: acess_token='" << access_token_ << "', expires in " << expires_in_seconds_ << " second(s)"; } else { LOG(ERROR) << "Gaia response: response code=" << response_code; } if (access_token_.empty()) { delegate_->OnNetworkError(response_code); } else { FetchUserInfoAndInvokeCallback(); } } 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: ui::ModalType ExtensionInstallDialogView::GetModalType() const { return ui::MODAL_TYPE_WINDOW; } CWE ID: CWE-17 Target: 1 Example 2: Code: std::string GetNewTabBackgroundTilingCSS( const ui::ThemeProvider* theme_provider) { int repeat_mode = theme_provider->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_TILING); return ThemeProperties::TilingToString(repeat_mode); } 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: scoped_refptr<PermissionSet> UnpackPermissionSet( const Permissions& permissions, std::string* error) { APIPermissionSet apis; std::vector<std::string>* permissions_list = permissions.permissions.get(); if (permissions_list) { PermissionsInfo* info = PermissionsInfo::GetInstance(); for (std::vector<std::string>::iterator it = permissions_list->begin(); it != permissions_list->end(); ++it) { if (it->find(kDelimiter) != std::string::npos) { size_t delimiter = it->find(kDelimiter); std::string permission_name = it->substr(0, delimiter); std::string permission_arg = it->substr(delimiter + 1); scoped_ptr<base::Value> permission_json( base::JSONReader::Read(permission_arg)); if (!permission_json.get()) { *error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it); return NULL; } APIPermission* permission = NULL; const APIPermissionInfo* bluetooth_device_permission_info = info->GetByID(APIPermission::kBluetoothDevice); const APIPermissionInfo* usb_device_permission_info = info->GetByID(APIPermission::kUsbDevice); if (permission_name == bluetooth_device_permission_info->name()) { permission = new BluetoothDevicePermission( bluetooth_device_permission_info); } else if (permission_name == usb_device_permission_info->name()) { permission = new UsbDevicePermission(usb_device_permission_info); } else { *error = kUnsupportedPermissionId; return NULL; } CHECK(permission); if (!permission->FromValue(permission_json.get())) { *error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it); return NULL; } apis.insert(permission); } else { const APIPermissionInfo* permission_info = info->GetByName(*it); if (!permission_info) { *error = ErrorUtils::FormatErrorMessage( kUnknownPermissionError, *it); return NULL; } apis.insert(permission_info->id()); } } } URLPatternSet origins; if (permissions.origins.get()) { for (std::vector<std::string>::iterator it = permissions.origins->begin(); it != permissions.origins->end(); ++it) { URLPattern origin(Extension::kValidHostPermissionSchemes); URLPattern::ParseResult parse_result = origin.Parse(*it); if (URLPattern::PARSE_SUCCESS != parse_result) { *error = ErrorUtils::FormatErrorMessage( kInvalidOrigin, *it, URLPattern::GetParseResultString(parse_result)); return NULL; } origins.AddPattern(origin); } } return scoped_refptr<PermissionSet>( new PermissionSet(apis, origins, URLPatternSet())); } 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 ExtensionTtsController::FinishCurrentUtterance() { if (current_utterance_) { current_utterance_->FinishAndDestroy(); current_utterance_ = NULL; } } CWE ID: CWE-20 Target: 1 Example 2: Code: static int xfrm6_tunnel_input(struct xfrm_state *x, struct sk_buff *skb) { return 0; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: megasas_setup_irqs_msix(struct megasas_instance *instance, u8 is_probe) { int i, j; struct pci_dev *pdev; pdev = instance->pdev; /* Try MSI-x */ for (i = 0; i < instance->msix_vectors; i++) { instance->irq_context[i].instance = instance; instance->irq_context[i].MSIxIndex = i; if (request_irq(pci_irq_vector(pdev, i), instance->instancet->service_isr, 0, "megasas", &instance->irq_context[i])) { dev_err(&instance->pdev->dev, "Failed to register IRQ for vector %d.\n", i); for (j = 0; j < i; j++) free_irq(pci_irq_vector(pdev, j), &instance->irq_context[j]); /* Retry irq register for IO_APIC*/ instance->msix_vectors = 0; if (is_probe) { pci_free_irq_vectors(instance->pdev); return megasas_setup_irqs_ioapic(instance); } else { return -1; } } } return 0; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ext2_xattr_delete_inode(struct inode *inode) { struct buffer_head *bh = NULL; struct mb_cache_entry *ce; down_write(&EXT2_I(inode)->xattr_sem); if (!EXT2_I(inode)->i_file_acl) goto cleanup; bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl); if (!bh) { ext2_error(inode->i_sb, "ext2_xattr_delete_inode", "inode %ld: block %d read error", inode->i_ino, EXT2_I(inode)->i_file_acl); goto cleanup; } ea_bdebug(bh, "b_count=%d", atomic_read(&(bh->b_count))); if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) || HDR(bh)->h_blocks != cpu_to_le32(1)) { ext2_error(inode->i_sb, "ext2_xattr_delete_inode", "inode %ld: bad block %d", inode->i_ino, EXT2_I(inode)->i_file_acl); goto cleanup; } ce = mb_cache_entry_get(ext2_xattr_cache, bh->b_bdev, bh->b_blocknr); lock_buffer(bh); if (HDR(bh)->h_refcount == cpu_to_le32(1)) { if (ce) mb_cache_entry_free(ce); ext2_free_blocks(inode, EXT2_I(inode)->i_file_acl, 1); get_bh(bh); bforget(bh); unlock_buffer(bh); } else { le32_add_cpu(&HDR(bh)->h_refcount, -1); if (ce) mb_cache_entry_release(ce); ea_bdebug(bh, "refcount now=%d", le32_to_cpu(HDR(bh)->h_refcount)); unlock_buffer(bh); mark_buffer_dirty(bh); if (IS_SYNC(inode)) sync_dirty_buffer(bh); dquot_free_block_nodirty(inode, 1); } EXT2_I(inode)->i_file_acl = 0; cleanup: brelse(bh); up_write(&EXT2_I(inode)->xattr_sem); } CWE ID: CWE-19 Target: 1 Example 2: Code: SYSCALL_DEFINE3(timer_create, const clockid_t, which_clock, struct sigevent __user *, timer_event_spec, timer_t __user *, created_timer_id) { if (timer_event_spec) { sigevent_t event; if (copy_from_user(&event, timer_event_spec, sizeof (event))) return -EFAULT; return do_timer_create(which_clock, &event, created_timer_id); } return do_timer_create(which_clock, NULL, created_timer_id); } 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: OMX_ERRORTYPE SoftVPXEncoder::setConfig( OMX_INDEXTYPE index, const OMX_PTR _params) { switch (index) { case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE *params = (OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } mKeyFrameRequested = params->IntraRefreshVOP; return OMX_ErrorNone; } case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE *params = (OMX_VIDEO_CONFIG_BITRATETYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } if (mBitrate != params->nEncodeBitrate) { mBitrate = params->nEncodeBitrate; mBitrateUpdated = true; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::setConfig(index, _params); } } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FrameLoader::StopAllLoaders() { if (frame_->GetDocument()->PageDismissalEventBeingDispatched() != Document::kNoDismissal) return; if (in_stop_all_loaders_) return; in_stop_all_loaders_ = true; for (Frame* child = frame_->Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) ToLocalFrame(child)->Loader().StopAllLoaders(); } frame_->GetDocument()->CancelParsing(); if (document_loader_) document_loader_->Fetcher()->StopFetching(); if (!protect_provisional_loader_) DetachDocumentLoader(provisional_document_loader_); frame_->GetNavigationScheduler().Cancel(); if (document_loader_ && !document_loader_->SentDidFinishLoad()) { document_loader_->LoadFailed( ResourceError::CancelledError(document_loader_->Url())); } in_stop_all_loaders_ = false; TakeObjectSnapshot(); } CWE ID: CWE-362 Target: 1 Example 2: Code: activation_parameters_free (ActivateParameters *parameters) { if (parameters->timed_wait_active) { eel_timed_wait_stop (cancel_activate_callback, parameters); } if (parameters->slot) { g_object_remove_weak_pointer (G_OBJECT (parameters->slot), (gpointer *) &parameters->slot); } if (parameters->parent_window) { g_object_remove_weak_pointer (G_OBJECT (parameters->parent_window), (gpointer *) &parameters->parent_window); } g_object_unref (parameters->cancellable); launch_location_list_free (parameters->locations); nautilus_file_list_free (parameters->mountables); nautilus_file_list_free (parameters->start_mountables); nautilus_file_list_free (parameters->not_mounted); g_free (parameters->activation_directory); g_free (parameters->timed_wait_prompt); g_assert (parameters->files_handle == NULL); g_free (parameters); } 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: status_t SoftHEVC::resetDecoder() { ivd_ctl_reset_ip_t s_ctl_ip; ivd_ctl_reset_op_t s_ctl_op; IV_API_CALL_STATUS_T status; s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL; s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_RESET; s_ctl_ip.u4_size = sizeof(ivd_ctl_reset_ip_t); s_ctl_op.u4_size = sizeof(ivd_ctl_reset_op_t); status = ivdec_api_function(mCodecCtx, (void *)&s_ctl_ip, (void *)&s_ctl_op); if (IV_SUCCESS != status) { ALOGE("Error in reset: 0x%x", s_ctl_op.u4_error_code); return UNKNOWN_ERROR; } mSignalledError = false; /* Set number of cores/threads to be used by the codec */ setNumCores(); mStride = 0; return OK; } CWE ID: CWE-172 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: check_user_token (const char *authfile, const char *username, const char *otp_id, int verbose, FILE *debug_file) { char buf[1024]; char *s_user, *s_token; int retval = AUTH_ERROR; int fd; struct stat st; FILE *opwfile; fd = open(authfile, O_RDONLY, 0); if (fd < 0) { if(verbose) D (debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno)); return retval; } if (fstat(fd, &st) < 0) { if(verbose) D (debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno)); close(fd); return retval; } if (!S_ISREG(st.st_mode)) { if(verbose) D (debug_file, "%s is not a regular file", authfile); close(fd); return retval; } opwfile = fdopen(fd, "r"); if (opwfile == NULL) { if(verbose) D (debug_file, "fdopen: %s", strerror(errno)); close(fd); return retval; } retval = AUTH_NO_TOKENS; while (fgets (buf, 1024, opwfile)) { char *saveptr = NULL; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (buf[0] == '#') { /* This is a comment and we may skip it. */ if(verbose) D (debug_file, "Skipping comment line: %s", buf); continue; } if(verbose) D (debug_file, "Authorization line: %s", buf); s_user = strtok_r (buf, ":", &saveptr); if (s_user && strcmp (username, s_user) == 0) { if(verbose) D (debug_file, "Matched user: %s", s_user); retval = AUTH_NOT_FOUND; /* We found at least one line for the user */ do { s_token = strtok_r (NULL, ":", &saveptr); if(verbose) D (debug_file, "Authorization token: %s", s_token); if (s_token && otp_id && strcmp (otp_id, s_token) == 0) { if(verbose) D (debug_file, "Match user/token as %s/%s", username, otp_id); return AUTH_FOUND; } } while (s_token != NULL); } } fclose (opwfile); return retval; } CWE ID: CWE-200 Target: 1 Example 2: Code: zend_string *phar_find_in_include_path(char *filename, int filename_len, phar_archive_data **pphar) /* {{{ */ { zend_string *ret; char *path, *fname, *arch, *entry, *test; int arch_len, entry_len, fname_len; phar_archive_data *phar; if (pphar) { *pphar = NULL; } else { pphar = &phar; } if (!zend_is_executing() || !PHAR_G(cwd)) { return phar_save_resolve_path(filename, filename_len); } fname = (char*)zend_get_executed_filename(); fname_len = strlen(fname); if (PHAR_G(last_phar) && !memcmp(fname, "phar://", 7) && fname_len - 7 >= PHAR_G(last_phar_name_len) && !memcmp(fname + 7, PHAR_G(last_phar_name), PHAR_G(last_phar_name_len))) { arch = estrndup(PHAR_G(last_phar_name), PHAR_G(last_phar_name_len)); arch_len = PHAR_G(last_phar_name_len); phar = PHAR_G(last_phar); goto splitted; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || SUCCESS != phar_split_fname(fname, strlen(fname), &arch, &arch_len, &entry, &entry_len, 1, 0)) { return phar_save_resolve_path(filename, filename_len); } efree(entry); if (*filename == '.') { int try_len; if (FAILURE == phar_get_archive(&phar, arch, arch_len, NULL, 0, NULL)) { efree(arch); return phar_save_resolve_path(filename, filename_len); } splitted: if (pphar) { *pphar = phar; } try_len = filename_len; test = phar_fix_filepath(estrndup(filename, filename_len), &try_len, 1); if (*test == '/') { if (zend_hash_str_exists(&(phar->manifest), test + 1, try_len - 1)) { ret = strpprintf(0, "phar://%s%s", arch, test); efree(arch); efree(test); return ret; } } else { if (zend_hash_str_exists(&(phar->manifest), test, try_len)) { ret = strpprintf(0, "phar://%s/%s", arch, test); efree(arch); efree(test); return ret; } } efree(test); } spprintf(&path, MAXPATHLEN, "phar://%s/%s%c%s", arch, PHAR_G(cwd), DEFAULT_DIR_SEPARATOR, PG(include_path)); efree(arch); ret = php_resolve_path(filename, filename_len, path); efree(path); if (ret && ZSTR_LEN(ret) > 8 && !strncmp(ZSTR_VAL(ret), "phar://", 7)) { /* found phar:// */ if (SUCCESS != phar_split_fname(ZSTR_VAL(ret), ZSTR_LEN(ret), &arch, &arch_len, &entry, &entry_len, 1, 0)) { return ret; } *pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len); if (!*pphar && PHAR_G(manifest_cached)) { *pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len); } efree(arch); efree(entry); } return ret; } /* }}} */ 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: status_t MPEG4Extractor::parseSegmentIndex(off64_t offset, size_t size) { ALOGV("MPEG4Extractor::parseSegmentIndex"); if (size < 12) { return -EINVAL; } uint32_t flags; if (!mDataSource->getUInt32(offset, &flags)) { return ERROR_MALFORMED; } uint32_t version = flags >> 24; flags &= 0xffffff; ALOGV("sidx version %d", version); uint32_t referenceId; if (!mDataSource->getUInt32(offset + 4, &referenceId)) { return ERROR_MALFORMED; } uint32_t timeScale; if (!mDataSource->getUInt32(offset + 8, &timeScale)) { return ERROR_MALFORMED; } ALOGV("sidx refid/timescale: %d/%d", referenceId, timeScale); uint64_t earliestPresentationTime; uint64_t firstOffset; offset += 12; size -= 12; if (version == 0) { if (size < 8) { return -EINVAL; } uint32_t tmp; if (!mDataSource->getUInt32(offset, &tmp)) { return ERROR_MALFORMED; } earliestPresentationTime = tmp; if (!mDataSource->getUInt32(offset + 4, &tmp)) { return ERROR_MALFORMED; } firstOffset = tmp; offset += 8; size -= 8; } else { if (size < 16) { return -EINVAL; } if (!mDataSource->getUInt64(offset, &earliestPresentationTime)) { return ERROR_MALFORMED; } if (!mDataSource->getUInt64(offset + 8, &firstOffset)) { return ERROR_MALFORMED; } offset += 16; size -= 16; } ALOGV("sidx pres/off: %" PRIu64 "/%" PRIu64, earliestPresentationTime, firstOffset); if (size < 4) { return -EINVAL; } uint16_t referenceCount; if (!mDataSource->getUInt16(offset + 2, &referenceCount)) { return ERROR_MALFORMED; } offset += 4; size -= 4; ALOGV("refcount: %d", referenceCount); if (size < referenceCount * 12) { return -EINVAL; } uint64_t total_duration = 0; for (unsigned int i = 0; i < referenceCount; i++) { uint32_t d1, d2, d3; if (!mDataSource->getUInt32(offset, &d1) || // size !mDataSource->getUInt32(offset + 4, &d2) || // duration !mDataSource->getUInt32(offset + 8, &d3)) { // flags return ERROR_MALFORMED; } if (d1 & 0x80000000) { ALOGW("sub-sidx boxes not supported yet"); } bool sap = d3 & 0x80000000; uint32_t saptype = (d3 >> 28) & 7; if (!sap || (saptype != 1 && saptype != 2)) { ALOGW("not a stream access point, or unsupported type: %08x", d3); } total_duration += d2; offset += 12; ALOGV(" item %d, %08x %08x %08x", i, d1, d2, d3); SidxEntry se; se.mSize = d1 & 0x7fffffff; se.mDurationUs = 1000000LL * d2 / timeScale; mSidxEntries.add(se); } uint64_t sidxDuration = total_duration * 1000000 / timeScale; int64_t metaDuration; if (!mLastTrack->meta->findInt64(kKeyDuration, &metaDuration) || metaDuration == 0) { mLastTrack->meta->setInt64(kKeyDuration, sidxDuration); } return OK; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void die(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); if(fmt[strlen(fmt)-1] != '\n') printf("\n"); exit(EXIT_FAILURE); } CWE ID: CWE-119 Target: 1 Example 2: Code: void FreeMenu(const PP_Flash_Menu* menu) { if (menu->items) { for (uint32_t i = 0; i < menu->count; ++i) FreeMenuItem(menu->items + i); delete [] menu->items; } delete menu; } 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 DownloadItemImpl::TogglePause() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(IsInProgress()); if (is_paused_) request_handle_->ResumeRequest(); else request_handle_->PauseRequest(); is_paused_ = !is_paused_; UpdateObservers(); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SVGStyleElement::DidNotifySubtreeInsertionsToDocument() { if (StyleElement::ProcessStyleSheet(GetDocument(), *this) == StyleElement::kProcessingFatalError) NotifyLoadedSheetAndAllCriticalSubresources( kErrorOccurredLoadingSubresource); } CWE ID: CWE-416 Target: 1 Example 2: Code: void Browser::NotifyTabOfFullscreenExitIfNecessary() { if (fullscreened_tab_) fullscreened_tab_->ExitFullscreenMode(); fullscreened_tab_ = NULL; tab_caused_fullscreen_ = false; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool CheckClientDownloadRequest::ShouldUploadForDlpScan() { if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads)) return false; int check_content_compliance = g_browser_process->local_state()->GetInteger( prefs::kCheckContentCompliance); if (check_content_compliance != CheckContentComplianceValues::CHECK_DOWNLOADS && check_content_compliance != CheckContentComplianceValues::CHECK_UPLOADS_AND_DOWNLOADS) return false; if (policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().empty()) return false; const base::ListValue* domains = g_browser_process->local_state()->GetList( prefs::kURLsToCheckComplianceOfDownloadedContent); url_matcher::URLMatcher matcher; policy::url_util::AddAllowFilters(&matcher, domains); return !matcher.MatchURL(item_->GetURL()).empty(); } 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 ppp_register_net_channel(struct net *net, struct ppp_channel *chan) { struct channel *pch; struct ppp_net *pn; pch = kzalloc(sizeof(struct channel), GFP_KERNEL); if (!pch) return -ENOMEM; pn = ppp_pernet(net); pch->ppp = NULL; pch->chan = chan; pch->chan_net = net; chan->ppp = pch; init_ppp_file(&pch->file, CHANNEL); pch->file.hdrlen = chan->hdrlen; #ifdef CONFIG_PPP_MULTILINK pch->lastseq = -1; #endif /* CONFIG_PPP_MULTILINK */ init_rwsem(&pch->chan_sem); spin_lock_init(&pch->downl); rwlock_init(&pch->upl); spin_lock_bh(&pn->all_channels_lock); pch->file.index = ++pn->last_channel_index; list_add(&pch->list, &pn->new_channels); atomic_inc(&channel_count); spin_unlock_bh(&pn->all_channels_lock); return 0; } CWE ID: CWE-416 Target: 1 Example 2: Code: static int proxy_ioc_getversion(FsContext *fs_ctx, V9fsPath *path, mode_t st_mode, uint64_t *st_gen) { int err; /* Do not try to open special files like device nodes, fifos etc * we can get fd for regular files and directories only */ if (!S_ISREG(st_mode) && !S_ISDIR(st_mode)) { errno = ENOTTY; return -1; } err = v9fs_request(fs_ctx->private, T_GETVERSION, st_gen, path); if (err < 0) { errno = -err; err = -1; } return err; } 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: setup_efi_state(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz, unsigned int efi_setup_data_offset) { struct efi_info *current_ei = &boot_params.efi_info; struct efi_info *ei = &params->efi_info; if (!current_ei->efi_memmap_size) return 0; /* * If 1:1 mapping is not enabled, second kernel can not setup EFI * and use EFI run time services. User space will have to pass * acpi_rsdp=<addr> on kernel command line to make second kernel boot * without efi. */ if (efi_enabled(EFI_OLD_MEMMAP)) return 0; ei->efi_loader_signature = current_ei->efi_loader_signature; ei->efi_systab = current_ei->efi_systab; ei->efi_systab_hi = current_ei->efi_systab_hi; ei->efi_memdesc_version = current_ei->efi_memdesc_version; ei->efi_memdesc_size = efi_get_runtime_map_desc_size(); setup_efi_info_memmap(params, params_load_addr, efi_map_offset, efi_map_sz); prepare_add_efi_setup_data(params, params_load_addr, efi_setup_data_offset); return 0; } 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: COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { long err = 0; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { err = compat_get_bitmap(bm, nmask, nr_bits); nm = compat_alloc_user_space(alloc_size); err |= copy_to_user(nm, bm, alloc_size); } if (err) return -EFAULT; return sys_set_mempolicy(mode, nm, nr_bits+1); } CWE ID: CWE-388 Target: 1 Example 2: Code: static inline void set_cmdline(int idx, const char *cmdline) { memcpy(get_saved_cmdlines(idx), cmdline, TASK_COMM_LEN); } 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: GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs) { GF_OperatingPointsInformation* ptr = (GF_OperatingPointsInformation *)entry; u32 i, j, count; if (!ptr) return GF_BAD_PARAM; ptr->scalability_mask = gf_bs_read_u16(bs); gf_bs_read_int(bs, 2);//reserved count = gf_bs_read_int(bs, 6); for (i = 0; i < count; i++) { LHEVC_ProfileTierLevel *ptl; GF_SAFEALLOC(ptl, LHEVC_ProfileTierLevel); if (!ptl) return GF_OUT_OF_MEM; ptl->general_profile_space = gf_bs_read_int(bs, 2); ptl->general_tier_flag= gf_bs_read_int(bs, 1); ptl->general_profile_idc = gf_bs_read_int(bs, 5); ptl->general_profile_compatibility_flags = gf_bs_read_u32(bs); ptl->general_constraint_indicator_flags = gf_bs_read_long_int(bs, 48); ptl->general_level_idc = gf_bs_read_u8(bs); gf_list_add(ptr->profile_tier_levels, ptl); } count = gf_bs_read_u16(bs); for (i = 0; i < count; i++) { LHEVC_OperatingPoint *op; GF_SAFEALLOC(op, LHEVC_OperatingPoint); if (!op) return GF_OUT_OF_MEM; op->output_layer_set_idx = gf_bs_read_u16(bs); op->max_temporal_id = gf_bs_read_u8(bs); op->layer_count = gf_bs_read_u8(bs); for (j = 0; j < op->layer_count; j++) { op->layers_info[j].ptl_idx = gf_bs_read_u8(bs); op->layers_info[j].layer_id = gf_bs_read_int(bs, 6); op->layers_info[j].is_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; op->layers_info[j].is_alternate_outputlayer = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; } op->minPicWidth = gf_bs_read_u16(bs); op->minPicHeight = gf_bs_read_u16(bs); op->maxPicWidth = gf_bs_read_u16(bs); op->maxPicHeight = gf_bs_read_u16(bs); op->maxChromaFormat = gf_bs_read_int(bs, 2); op->maxBitDepth = gf_bs_read_int(bs, 3) + 8; gf_bs_read_int(bs, 1);//reserved op->frame_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; op->bit_rate_info_flag = gf_bs_read_int(bs, 1) ? GF_TRUE : GF_FALSE; if (op->frame_rate_info_flag) { op->avgFrameRate = gf_bs_read_u16(bs); gf_bs_read_int(bs, 6); //reserved op->constantFrameRate = gf_bs_read_int(bs, 2); } if (op->bit_rate_info_flag) { op->maxBitRate = gf_bs_read_u32(bs); op->avgBitRate = gf_bs_read_u32(bs); } gf_list_add(ptr->operating_points, op); } count = gf_bs_read_u8(bs); for (i = 0; i < count; i++) { LHEVC_DependentLayer *dep; GF_SAFEALLOC(dep, LHEVC_DependentLayer); if (!dep) return GF_OUT_OF_MEM; dep->dependent_layerID = gf_bs_read_u8(bs); dep->num_layers_dependent_on = gf_bs_read_u8(bs); for (j = 0; j < dep->num_layers_dependent_on; j++) dep->dependent_on_layerID[j] = gf_bs_read_u8(bs); for (j = 0; j < 16; j++) { if (ptr->scalability_mask & (1 << j)) dep->dimension_identifier[j] = gf_bs_read_u8(bs); } gf_list_add(ptr->dependency_layers, dep); } return GF_OK; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xfs_attr3_leaf_add_work( struct xfs_buf *bp, struct xfs_attr3_icleaf_hdr *ichdr, struct xfs_da_args *args, int mapindex) { struct xfs_attr_leafblock *leaf; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_mount *mp; int tmp; int i; trace_xfs_attr_leaf_add_work(args); leaf = bp->b_addr; ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE); ASSERT(args->index >= 0 && args->index <= ichdr->count); /* * Force open some space in the entry array and fill it in. */ entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (args->index < ichdr->count) { tmp = ichdr->count - args->index; tmp *= sizeof(xfs_attr_leaf_entry_t); memmove(entry + 1, entry, tmp); xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry))); } ichdr->count++; /* * Allocate space for the new string (at the end of the run). */ mp = args->trans->t_mountp; ASSERT(ichdr->freemap[mapindex].base < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0); ASSERT(ichdr->freemap[mapindex].size >= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, NULL)); ASSERT(ichdr->freemap[mapindex].size < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0); ichdr->freemap[mapindex].size -= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, &tmp); entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base + ichdr->freemap[mapindex].size); entry->hashval = cpu_to_be32(args->hashval); entry->flags = tmp ? XFS_ATTR_LOCAL : 0; entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags); if (args->op_flags & XFS_DA_OP_RENAME) { entry->flags |= XFS_ATTR_INCOMPLETE; if ((args->blkno2 == args->blkno) && (args->index2 <= args->index)) { args->index2++; } } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry))); ASSERT((args->index == 0) || (be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval))); ASSERT((args->index == ichdr->count - 1) || (be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval))); /* * For "remote" attribute values, simply note that we need to * allocate space for the "remote" value. We can't actually * allocate the extents in this transaction, and we can't decide * which blocks they should be as we might allocate more blocks * as part of this transaction (a split operation for example). */ if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); name_loc->namelen = args->namelen; name_loc->valuelen = cpu_to_be16(args->valuelen); memcpy((char *)name_loc->nameval, args->name, args->namelen); memcpy((char *)&name_loc->nameval[args->namelen], args->value, be16_to_cpu(name_loc->valuelen)); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); name_rmt->namelen = args->namelen; memcpy((char *)name_rmt->name, args->name, args->namelen); entry->flags |= XFS_ATTR_INCOMPLETE; /* just in case */ name_rmt->valuelen = 0; name_rmt->valueblk = 0; args->rmtblkno = 1; args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen); } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index), xfs_attr_leaf_entsize(leaf, args->index))); /* * Update the control info for this leaf node */ if (be16_to_cpu(entry->nameidx) < ichdr->firstused) ichdr->firstused = be16_to_cpu(entry->nameidx); ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf)); tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf); for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { if (ichdr->freemap[i].base == tmp) { ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t); ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t); } } ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index); return 0; } CWE ID: CWE-19 Target: 1 Example 2: Code: void js_replace(js_State* J, int idx) { idx = idx < 0 ? TOP + idx : BOT + idx; if (idx < BOT || idx >= TOP) js_error(J, "stack error!"); STACK[idx] = STACK[--TOP]; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool CSSPaintValue::KnownToBeOpaque(const Document&, const ComputedStyle&) const { return generator_ && !generator_->HasAlpha(); } 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: linkaddr_string(netdissect_options *ndo, const u_char *ep, const unsigned int type, const unsigned int len) { register u_int i; register char *cp; register struct enamemem *tp; if (len == 0) return ("<empty>"); if (type == LINKADDR_ETHER && len == ETHER_ADDR_LEN) return (etheraddr_string(ndo, ep)); if (type == LINKADDR_FRELAY) return (q922_string(ndo, ep, len)); tp = lookup_bytestring(ndo, ep, len); if (tp->e_name) return (tp->e_name); tp->e_name = cp = (char *)malloc(len*3); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "linkaddr_string: malloc"); *cp++ = hex[*ep >> 4]; *cp++ = hex[*ep++ & 0xf]; for (i = len-1; i > 0 ; --i) { *cp++ = ':'; *cp++ = hex[*ep >> 4]; *cp++ = hex[*ep++ & 0xf]; } *cp = '\0'; return (tp->e_name); } CWE ID: CWE-125 Target: 1 Example 2: Code: static int ac3_sync(uint64_t state, AACAC3ParseContext *hdr_info, int *need_next_header, int *new_frame_start) { int err; union { uint64_t u64; uint8_t u8[8 + AV_INPUT_BUFFER_PADDING_SIZE]; } tmp = { av_be2ne64(state) }; AC3HeaderInfo hdr; GetBitContext gbc; init_get_bits(&gbc, tmp.u8+8-AC3_HEADER_SIZE, 54); err = ff_ac3_parse_header(&gbc, &hdr); if(err < 0) return 0; hdr_info->sample_rate = hdr.sample_rate; hdr_info->bit_rate = hdr.bit_rate; hdr_info->channels = hdr.channels; hdr_info->channel_layout = hdr.channel_layout; hdr_info->samples = hdr.num_blocks * 256; hdr_info->service_type = hdr.bitstream_mode; if (hdr.bitstream_mode == 0x7 && hdr.channels > 1) hdr_info->service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE; if(hdr.bitstream_id>10) hdr_info->codec_id = AV_CODEC_ID_EAC3; else if (hdr_info->codec_id == AV_CODEC_ID_NONE) hdr_info->codec_id = AV_CODEC_ID_AC3; *new_frame_start = (hdr.frame_type != EAC3_FRAME_TYPE_DEPENDENT); *need_next_header = *new_frame_start || (hdr.frame_type != EAC3_FRAME_TYPE_AC3_CONVERT); return hdr.frame_size; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: usbtest_ioctl(struct usb_interface *intf, unsigned int code, void *buf) { struct usbtest_dev *dev = usb_get_intfdata(intf); struct usbtest_param_64 *param_64 = buf; struct usbtest_param_32 temp; struct usbtest_param_32 *param_32 = buf; struct timespec64 start; struct timespec64 end; struct timespec64 duration; int retval = -EOPNOTSUPP; /* FIXME USBDEVFS_CONNECTINFO doesn't say how fast the device is. */ pattern = mod_pattern; if (mutex_lock_interruptible(&dev->lock)) return -ERESTARTSYS; /* FIXME: What if a system sleep starts while a test is running? */ /* some devices, like ez-usb default devices, need a non-default * altsetting to have any active endpoints. some tests change * altsettings; force a default so most tests don't need to check. */ if (dev->info->alt >= 0) { if (intf->altsetting->desc.bInterfaceNumber) { retval = -ENODEV; goto free_mutex; } retval = set_altsetting(dev, dev->info->alt); if (retval) { dev_err(&intf->dev, "set altsetting to %d failed, %d\n", dev->info->alt, retval); goto free_mutex; } } switch (code) { case USBTEST_REQUEST_64: temp.test_num = param_64->test_num; temp.iterations = param_64->iterations; temp.length = param_64->length; temp.sglen = param_64->sglen; temp.vary = param_64->vary; param_32 = &temp; break; case USBTEST_REQUEST_32: break; default: retval = -EOPNOTSUPP; goto free_mutex; } ktime_get_ts64(&start); retval = usbtest_do_ioctl(intf, param_32); if (retval < 0) goto free_mutex; ktime_get_ts64(&end); duration = timespec64_sub(end, start); temp.duration_sec = duration.tv_sec; temp.duration_usec = duration.tv_nsec/NSEC_PER_USEC; switch (code) { case USBTEST_REQUEST_32: param_32->duration_sec = temp.duration_sec; param_32->duration_usec = temp.duration_usec; break; case USBTEST_REQUEST_64: param_64->duration_sec = temp.duration_sec; param_64->duration_usec = temp.duration_usec; break; } free_mutex: mutex_unlock(&dev->lock); return retval; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { int v, i; if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if (length > 256 || !(s->state & PNG_PLTE)) return AVERROR_INVALIDDATA; for (i = 0; i < length; i++) { v = bytestream2_get_byte(&s->gb); s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24); } } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) { if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) || (s->color_type == PNG_COLOR_TYPE_RGB && length != 6)) return AVERROR_INVALIDDATA; for (i = 0; i < length / 2; i++) { /* only use the least significant bits */ v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth); if (s->bit_depth > 8) AV_WB16(&s->transparent_color_be[2 * i], v); else s->transparent_color_be[i] = v; } } else { return AVERROR_INVALIDDATA; } bytestream2_skip(&s->gb, 4); /* crc */ s->has_trns = 1; return 0; } CWE ID: CWE-787 Target: 1 Example 2: Code: RenderProcessHostImpl::~RenderProcessHostImpl() { DCHECK(!run_renderer_in_process()); ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID()); channel_.reset(); while (!queued_messages_.empty()) { delete queued_messages_.front(); queued_messages_.pop(); } ClearTransportDIBCache(); UnregisterHost(GetID()); } 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 perf_pmu_nop_int(struct pmu *pmu) { return 0; } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DefragRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("DefragInOrderSimpleTest", DefragInOrderSimpleTest); UtRegisterTest("DefragReverseSimpleTest", DefragReverseSimpleTest); UtRegisterTest("DefragSturgesNovakBsdTest", DefragSturgesNovakBsdTest); UtRegisterTest("DefragSturgesNovakLinuxTest", DefragSturgesNovakLinuxTest); UtRegisterTest("DefragSturgesNovakWindowsTest", DefragSturgesNovakWindowsTest); UtRegisterTest("DefragSturgesNovakSolarisTest", DefragSturgesNovakSolarisTest); UtRegisterTest("DefragSturgesNovakFirstTest", DefragSturgesNovakFirstTest); UtRegisterTest("DefragSturgesNovakLastTest", DefragSturgesNovakLastTest); UtRegisterTest("DefragIPv4NoDataTest", DefragIPv4NoDataTest); UtRegisterTest("DefragIPv4TooLargeTest", DefragIPv4TooLargeTest); UtRegisterTest("IPV6DefragInOrderSimpleTest", IPV6DefragInOrderSimpleTest); UtRegisterTest("IPV6DefragReverseSimpleTest", IPV6DefragReverseSimpleTest); UtRegisterTest("IPV6DefragSturgesNovakBsdTest", IPV6DefragSturgesNovakBsdTest); UtRegisterTest("IPV6DefragSturgesNovakLinuxTest", IPV6DefragSturgesNovakLinuxTest); UtRegisterTest("IPV6DefragSturgesNovakWindowsTest", IPV6DefragSturgesNovakWindowsTest); UtRegisterTest("IPV6DefragSturgesNovakSolarisTest", IPV6DefragSturgesNovakSolarisTest); UtRegisterTest("IPV6DefragSturgesNovakFirstTest", IPV6DefragSturgesNovakFirstTest); UtRegisterTest("IPV6DefragSturgesNovakLastTest", IPV6DefragSturgesNovakLastTest); UtRegisterTest("DefragVlanTest", DefragVlanTest); UtRegisterTest("DefragVlanQinQTest", DefragVlanQinQTest); UtRegisterTest("DefragTrackerReuseTest", DefragTrackerReuseTest); UtRegisterTest("DefragTimeoutTest", DefragTimeoutTest); UtRegisterTest("DefragMfIpv4Test", DefragMfIpv4Test); UtRegisterTest("DefragMfIpv6Test", DefragMfIpv6Test); #endif /* UNITTESTS */ } CWE ID: CWE-358 Target: 1 Example 2: Code: void WebGL2RenderingContextBase::texSubImage3D( ExecutionContext* execution_context, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, HTMLCanvasElement* canvas, ExceptionState& exception_state) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage3D", "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } TexImageHelperHTMLCanvasElement(execution_context->GetSecurityOrigin(), kTexSubImage3D, target, level, 0, format, type, xoffset, yoffset, zoffset, canvas, GetTextureSourceSubRectangle(width, height), depth, unpack_image_height_, exception_state); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static uint16_t vring_used_idx(VirtQueue *vq) { hwaddr pa; pa = vq->vring.used + offsetof(VRingUsed, idx); return lduw_phys(&address_space_memory, pa); } 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: build_config(char *prefix, struct server *server) { char *path = NULL; int path_size = strlen(prefix) + strlen(server->port) + 20; path = ss_malloc(path_size); snprintf(path, path_size, "%s/.shadowsocks_%s.conf", prefix, server->port); FILE *f = fopen(path, "w+"); if (f == NULL) { if (verbose) { LOGE("unable to open config file"); } ss_free(path); return; } fprintf(f, "{\n"); fprintf(f, "\"server_port\":%d,\n", atoi(server->port)); fprintf(f, "\"password\":\"%s\"", server->password); if (server->fast_open[0]) fprintf(f, ",\n\"fast_open\": %s", server->fast_open); if (server->mode) fprintf(f, ",\n\"mode\":\"%s\"", server->mode); if (server->method) fprintf(f, ",\n\"method\":\"%s\"", server->method); if (server->plugin) fprintf(f, ",\n\"plugin\":\"%s\"", server->plugin); if (server->plugin_opts) fprintf(f, ",\n\"plugin_opts\":\"%s\"", server->plugin_opts); fprintf(f, "\n}\n"); fclose(f); ss_free(path); } CWE ID: CWE-78 Target: 1 Example 2: Code: static void ieee80211_iface_work(struct work_struct *work) { struct ieee80211_sub_if_data *sdata = container_of(work, struct ieee80211_sub_if_data, work); struct ieee80211_local *local = sdata->local; struct sk_buff *skb; struct sta_info *sta; struct ieee80211_ra_tid *ra_tid; if (!ieee80211_sdata_running(sdata)) return; if (local->scanning) return; /* * ieee80211_queue_work() should have picked up most cases, * here we'll pick the rest. */ if (WARN(local->suspended, "interface work scheduled while going to suspend\n")) return; /* first process frames */ while ((skb = skb_dequeue(&sdata->skb_queue))) { struct ieee80211_mgmt *mgmt = (void *)skb->data; if (skb->pkt_type == IEEE80211_SDATA_QUEUE_AGG_START) { ra_tid = (void *)&skb->cb; ieee80211_start_tx_ba_cb(&sdata->vif, ra_tid->ra, ra_tid->tid); } else if (skb->pkt_type == IEEE80211_SDATA_QUEUE_AGG_STOP) { ra_tid = (void *)&skb->cb; ieee80211_stop_tx_ba_cb(&sdata->vif, ra_tid->ra, ra_tid->tid); } else if (ieee80211_is_action(mgmt->frame_control) && mgmt->u.action.category == WLAN_CATEGORY_BACK) { int len = skb->len; mutex_lock(&local->sta_mtx); sta = sta_info_get_bss(sdata, mgmt->sa); if (sta) { switch (mgmt->u.action.u.addba_req.action_code) { case WLAN_ACTION_ADDBA_REQ: ieee80211_process_addba_request( local, sta, mgmt, len); break; case WLAN_ACTION_ADDBA_RESP: ieee80211_process_addba_resp(local, sta, mgmt, len); break; case WLAN_ACTION_DELBA: ieee80211_process_delba(sdata, sta, mgmt, len); break; default: WARN_ON(1); break; } } mutex_unlock(&local->sta_mtx); } else if (ieee80211_is_data_qos(mgmt->frame_control)) { struct ieee80211_hdr *hdr = (void *)mgmt; /* * So the frame isn't mgmt, but frame_control * is at the right place anyway, of course, so * the if statement is correct. * * Warn if we have other data frame types here, * they must not get here. */ WARN_ON(hdr->frame_control & cpu_to_le16(IEEE80211_STYPE_NULLFUNC)); WARN_ON(!(hdr->seq_ctrl & cpu_to_le16(IEEE80211_SCTL_FRAG))); /* * This was a fragment of a frame, received while * a block-ack session was active. That cannot be * right, so terminate the session. */ mutex_lock(&local->sta_mtx); sta = sta_info_get_bss(sdata, mgmt->sa); if (sta) { u16 tid = *ieee80211_get_qos_ctl(hdr) & IEEE80211_QOS_CTL_TID_MASK; __ieee80211_stop_rx_ba_session( sta, tid, WLAN_BACK_RECIPIENT, WLAN_REASON_QSTA_REQUIRE_SETUP, true); } mutex_unlock(&local->sta_mtx); } else switch (sdata->vif.type) { case NL80211_IFTYPE_STATION: ieee80211_sta_rx_queued_mgmt(sdata, skb); break; case NL80211_IFTYPE_ADHOC: ieee80211_ibss_rx_queued_mgmt(sdata, skb); break; case NL80211_IFTYPE_MESH_POINT: if (!ieee80211_vif_is_mesh(&sdata->vif)) break; ieee80211_mesh_rx_queued_mgmt(sdata, skb); break; default: WARN(1, "frame for unexpected interface type"); break; } kfree_skb(skb); } /* then other type-dependent work */ switch (sdata->vif.type) { case NL80211_IFTYPE_STATION: ieee80211_sta_work(sdata); break; case NL80211_IFTYPE_ADHOC: ieee80211_ibss_work(sdata); break; case NL80211_IFTYPE_MESH_POINT: if (!ieee80211_vif_is_mesh(&sdata->vif)) break; ieee80211_mesh_work(sdata); break; default: break; } } 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 ec_mul_consttime(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, const EC_POINT *point, BN_CTX *ctx) { int i, cardinality_bits, group_top, kbit, pbit, Z_is_one; EC_POINT *s = NULL; BIGNUM *k = NULL; BIGNUM *lambda = NULL; BIGNUM *cardinality = NULL; BN_CTX *new_ctx = NULL; int ret = 0; if (ctx == NULL && (ctx = new_ctx = BN_CTX_secure_new()) == NULL) return 0; BN_CTX_start(ctx); s = EC_POINT_new(group); if (s == NULL) goto err; if (point == NULL) { if (!EC_POINT_copy(s, group->generator)) goto err; } else { if (!EC_POINT_copy(s, point)) goto err; } EC_POINT_BN_set_flags(s, BN_FLG_CONSTTIME); cardinality = BN_CTX_get(ctx); lambda = BN_CTX_get(ctx); k = BN_CTX_get(ctx); if (k == NULL || !BN_mul(cardinality, group->order, group->cofactor, ctx)) goto err; /* * Group cardinalities are often on a word boundary. * So when we pad the scalar, some timing diff might * pop if it needs to be expanded due to carries. * So expand ahead of time. */ cardinality_bits = BN_num_bits(cardinality); group_top = bn_get_top(cardinality); if ((bn_wexpand(k, group_top + 1) == NULL) || (bn_wexpand(lambda, group_top + 1) == NULL)) goto err; if (!BN_copy(k, scalar)) goto err; BN_set_flags(k, BN_FLG_CONSTTIME); if ((BN_num_bits(k) > cardinality_bits) || (BN_is_negative(k))) { /*- * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(k, k, cardinality, ctx)) goto err; } if (!BN_add(lambda, k, cardinality)) goto err; BN_set_flags(lambda, BN_FLG_CONSTTIME); if (!BN_add(k, lambda, cardinality)) goto err; /* * lambda := scalar + cardinality * k := scalar + 2*cardinality */ kbit = BN_is_bit_set(lambda, cardinality_bits); BN_consttime_swap(kbit, k, lambda, group_top + 1); group_top = bn_get_top(group->field); if ((bn_wexpand(s->X, group_top) == NULL) || (bn_wexpand(s->Y, group_top) == NULL) || (bn_wexpand(s->Z, group_top) == NULL) || (bn_wexpand(r->X, group_top) == NULL) || (bn_wexpand(r->Y, group_top) == NULL) || (bn_wexpand(r->Z, group_top) == NULL)) goto err; /*- * Apply coordinate blinding for EC_POINT. * * The underlying EC_METHOD can optionally implement this function: * ec_point_blind_coordinates() returns 0 in case of errors or 1 on * success or if coordinate blinding is not implemented for this * group. */ if (!ec_point_blind_coordinates(group, s, ctx)) goto err; /* top bit is a 1, in a fixed pos */ if (!EC_POINT_copy(r, s)) goto err; EC_POINT_BN_set_flags(r, BN_FLG_CONSTTIME); if (!EC_POINT_dbl(group, s, s, ctx)) goto err; pbit = 0; #define EC_POINT_CSWAP(c, a, b, w, t) do { \ BN_consttime_swap(c, (a)->X, (b)->X, w); \ BN_consttime_swap(c, (a)->Y, (b)->Y, w); \ BN_consttime_swap(c, (a)->Z, (b)->Z, w); \ t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \ (a)->Z_is_one ^= (t); \ (b)->Z_is_one ^= (t); \ } while(0) /*- * The ladder step, with branches, is * * k[i] == 0: S = add(R, S), R = dbl(R) * k[i] == 1: R = add(S, R), S = dbl(S) * * Swapping R, S conditionally on k[i] leaves you with state * * k[i] == 0: T, U = R, S * k[i] == 1: T, U = S, R * * Then perform the ECC ops. * * U = add(T, U) * T = dbl(T) * * Which leaves you with state * * k[i] == 0: U = add(R, S), T = dbl(R) * k[i] == 1: U = add(S, R), T = dbl(S) * * Swapping T, U conditionally on k[i] leaves you with state * * k[i] == 0: R, S = T, U * k[i] == 1: R, S = U, T * * Which leaves you with state * * k[i] == 0: S = add(R, S), R = dbl(R) * k[i] == 1: R = add(S, R), S = dbl(S) * * So we get the same logic, but instead of a branch it's a * conditional swap, followed by ECC ops, then another conditional swap. * * Optimization: The end of iteration i and start of i-1 looks like * * ... * CSWAP(k[i], R, S) * ECC * CSWAP(k[i], R, S) * (next iteration) * CSWAP(k[i-1], R, S) * ECC * CSWAP(k[i-1], R, S) * ... * * So instead of two contiguous swaps, you can merge the condition * bits and do a single swap. * * k[i] k[i-1] Outcome * 0 0 No Swap * 0 1 Swap * 1 0 Swap * 1 1 No Swap * * This is XOR. pbit tracks the previous bit of k. */ for (i = cardinality_bits - 1; i >= 0; i--) { kbit = BN_is_bit_set(k, i) ^ pbit; EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one); if (!EC_POINT_add(group, s, r, s, ctx)) goto err; if (!EC_POINT_dbl(group, r, r, ctx)) goto err; /* * pbit logic merges this cswap with that of the * next iteration */ pbit ^= kbit; } /* one final cswap to move the right value into r */ EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one); #undef EC_POINT_CSWAP ret = 1; err: EC_POINT_free(s); BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } 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: void StorageHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; } CWE ID: CWE-20 Target: 1 Example 2: Code: ia64_patch_imm64 (u64 insn_addr, u64 val) { /* The assembler may generate offset pointing to either slot 1 or slot 2 for a long (2-slot) instruction, occupying slots 1 and 2. */ insn_addr &= -16UL; ia64_patch(insn_addr + 2, 0x01fffefe000UL, ( ((val & 0x8000000000000000UL) >> 27) /* bit 63 -> 36 */ | ((val & 0x0000000000200000UL) << 0) /* bit 21 -> 21 */ | ((val & 0x00000000001f0000UL) << 6) /* bit 16 -> 22 */ | ((val & 0x000000000000ff80UL) << 20) /* bit 7 -> 27 */ | ((val & 0x000000000000007fUL) << 13) /* bit 0 -> 13 */)); ia64_patch(insn_addr + 1, 0x1ffffffffffUL, val >> 22); } 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: YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static long snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu; void __user *argp = (void __user *)arg; int __user *p = argp; tu = file->private_data; switch (cmd) { case SNDRV_TIMER_IOCTL_PVERSION: return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0; case SNDRV_TIMER_IOCTL_NEXT_DEVICE: return snd_timer_user_next_device(argp); case SNDRV_TIMER_IOCTL_TREAD: { int xarg; mutex_lock(&tu->tread_sem); if (tu->timeri) { /* too late */ mutex_unlock(&tu->tread_sem); return -EBUSY; } if (get_user(xarg, p)) { mutex_unlock(&tu->tread_sem); return -EFAULT; } tu->tread = xarg ? 1 : 0; mutex_unlock(&tu->tread_sem); return 0; } case SNDRV_TIMER_IOCTL_GINFO: return snd_timer_user_ginfo(file, argp); case SNDRV_TIMER_IOCTL_GPARAMS: return snd_timer_user_gparams(file, argp); case SNDRV_TIMER_IOCTL_GSTATUS: return snd_timer_user_gstatus(file, argp); case SNDRV_TIMER_IOCTL_SELECT: return snd_timer_user_tselect(file, argp); case SNDRV_TIMER_IOCTL_INFO: return snd_timer_user_info(file, argp); case SNDRV_TIMER_IOCTL_PARAMS: return snd_timer_user_params(file, argp); case SNDRV_TIMER_IOCTL_STATUS: return snd_timer_user_status(file, argp); case SNDRV_TIMER_IOCTL_START: case SNDRV_TIMER_IOCTL_START_OLD: return snd_timer_user_start(file); case SNDRV_TIMER_IOCTL_STOP: case SNDRV_TIMER_IOCTL_STOP_OLD: return snd_timer_user_stop(file); case SNDRV_TIMER_IOCTL_CONTINUE: case SNDRV_TIMER_IOCTL_CONTINUE_OLD: return snd_timer_user_continue(file); case SNDRV_TIMER_IOCTL_PAUSE: case SNDRV_TIMER_IOCTL_PAUSE_OLD: return snd_timer_user_pause(file); } return -ENOTTY; } CWE ID: CWE-362 Target: 1 Example 2: Code: GF_Err trpy_dump(GF_Box *a, FILE * trace) { GF_TRPYBox *p = (GF_TRPYBox *)a; gf_isom_box_dump_start(a, "LargeTotalRTPBytesBox", trace); fprintf(trace, "RTPBytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes); gf_isom_box_dump_done("LargeTotalRTPBytesBox", a, trace); return GF_OK; } 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: PasswordAutofillAgent::PasswordValueGatekeeper::PasswordValueGatekeeper() : was_user_gesture_seen_(false) { } 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: FT_Bitmap_Embolden( FT_Library library, FT_Bitmap* bitmap, FT_Pos xStrength, FT_Pos yStrength ) { FT_Error error; unsigned char* p; FT_Int i, x, y, pitch; FT_Int xstr, ystr; return FT_THROW( Invalid_Library_Handle ); if ( !bitmap || !bitmap->buffer ) return FT_THROW( Invalid_Argument ); if ( ( ( FT_PIX_ROUND( xStrength ) >> 6 ) > FT_INT_MAX ) || ( ( FT_PIX_ROUND( yStrength ) >> 6 ) > FT_INT_MAX ) ) return FT_THROW( Invalid_Argument ); xstr = (FT_Int)FT_PIX_ROUND( xStrength ) >> 6; ystr = (FT_Int)FT_PIX_ROUND( yStrength ) >> 6; if ( xstr == 0 && ystr == 0 ) return FT_Err_Ok; else if ( xstr < 0 || ystr < 0 ) return FT_THROW( Invalid_Argument ); switch ( bitmap->pixel_mode ) { case FT_PIXEL_MODE_GRAY2: case FT_PIXEL_MODE_GRAY4: { FT_Bitmap tmp; /* convert to 8bpp */ FT_Bitmap_New( &tmp ); error = FT_Bitmap_Convert( library, bitmap, &tmp, 1 ); if ( error ) return error; FT_Bitmap_Done( library, bitmap ); *bitmap = tmp; } break; case FT_PIXEL_MODE_MONO: if ( xstr > 8 ) xstr = 8; break; case FT_PIXEL_MODE_LCD: xstr *= 3; break; case FT_PIXEL_MODE_LCD_V: ystr *= 3; break; case FT_PIXEL_MODE_BGRA: /* We don't embolden color glyphs. */ return FT_Err_Ok; } error = ft_bitmap_assure_buffer( library->memory, bitmap, xstr, ystr ); if ( error ) return error; /* take care of bitmap flow */ pitch = bitmap->pitch; if ( pitch > 0 ) p = bitmap->buffer + pitch * ystr; else { pitch = -pitch; p = bitmap->buffer + pitch * ( bitmap->rows - 1 ); } /* for each row */ for ( y = 0; y < bitmap->rows ; y++ ) { /* * Horizontally: * * From the last pixel on, make each pixel or'ed with the * `xstr' pixels before it. */ for ( x = pitch - 1; x >= 0; x-- ) { unsigned char tmp; tmp = p[x]; for ( i = 1; i <= xstr; i++ ) { if ( bitmap->pixel_mode == FT_PIXEL_MODE_MONO ) { p[x] |= tmp >> i; /* the maximum value of 8 for `xstr' comes from here */ if ( x > 0 ) p[x] |= p[x - 1] << ( 8 - i ); #if 0 if ( p[x] == 0xff ) break; #endif } else { if ( x - i >= 0 ) { if ( p[x] + p[x - i] > bitmap->num_grays - 1 ) { p[x] = (unsigned char)( bitmap->num_grays - 1 ); break; } else { p[x] = (unsigned char)( p[x] + p[x - i] ); if ( p[x] == bitmap->num_grays - 1 ) break; } } else break; } } } /* * Vertically: * * Make the above `ystr' rows or'ed with it. */ for ( x = 1; x <= ystr; x++ ) { unsigned char* q; q = p - bitmap->pitch * x; for ( i = 0; i < pitch; i++ ) q[i] |= p[i]; } p += bitmap->pitch; } bitmap->width += xstr; bitmap->rows += ystr; return FT_Err_Ok; } CWE ID: CWE-119 Target: 1 Example 2: Code: ProcAllocNamedColor(ClientPtr client) { ColormapPtr pcmp; int rc; REQUEST(xAllocNamedColorReq); REQUEST_FIXED_SIZE(xAllocNamedColorReq, stuff->nbytes); rc = dixLookupResourceByType((void **) &pcmp, stuff->cmap, RT_COLORMAP, client, DixAddAccess); if (rc == Success) { xAllocNamedColorReply ancr = { .type = X_Reply, .sequenceNumber = client->sequence, .length = 0 }; if (OsLookupColor (pcmp->pScreen->myNum, (char *) &stuff[1], stuff->nbytes, &ancr.exactRed, &ancr.exactGreen, &ancr.exactBlue)) { ancr.screenRed = ancr.exactRed; ancr.screenGreen = ancr.exactGreen; ancr.screenBlue = ancr.exactBlue; ancr.pixel = 0; if ((rc = AllocColor(pcmp, &ancr.screenRed, &ancr.screenGreen, &ancr.screenBlue, &ancr.pixel, client->index))) return rc; #ifdef PANORAMIX if (noPanoramiXExtension || !pcmp->pScreen->myNum) #endif WriteReplyToClient(client, sizeof(xAllocNamedColorReply), &ancr); return Success; } else return BadName; } else { client->errorValue = stuff->cmap; return rc; } } 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: JavaScriptCallFrames V8Debugger::currentCallFrames(int limit) { if (!m_isolate->InContext()) return JavaScriptCallFrames(); v8::Local<v8::Value> currentCallFramesV8; if (m_executionState.IsEmpty()) { v8::Local<v8::Function> currentCallFramesFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.Get(m_isolate)->Get(toV8StringInternalized(m_isolate, "currentCallFrames"))); currentCallFramesV8 = v8::Debug::Call(debuggerContext(), currentCallFramesFunction, v8::Integer::New(m_isolate, limit)).ToLocalChecked(); } else { v8::Local<v8::Value> argv[] = { m_executionState, v8::Integer::New(m_isolate, limit) }; currentCallFramesV8 = callDebuggerMethod("currentCallFrames", PROTOCOL_ARRAY_LENGTH(argv), argv).ToLocalChecked(); } DCHECK(!currentCallFramesV8.IsEmpty()); if (!currentCallFramesV8->IsArray()) return JavaScriptCallFrames(); v8::Local<v8::Array> callFramesArray = currentCallFramesV8.As<v8::Array>(); JavaScriptCallFrames callFrames; for (size_t i = 0; i < callFramesArray->Length(); ++i) { v8::Local<v8::Value> callFrameValue; if (!callFramesArray->Get(debuggerContext(), i).ToLocal(&callFrameValue)) return JavaScriptCallFrames(); if (!callFrameValue->IsObject()) return JavaScriptCallFrames(); v8::Local<v8::Object> callFrameObject = callFrameValue.As<v8::Object>(); callFrames.push_back(JavaScriptCallFrame::create(debuggerContext(), v8::Local<v8::Object>::Cast(callFrameObject))); } return callFrames; } CWE ID: CWE-79 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 host_start(struct ci13xxx *ci) { struct usb_hcd *hcd; struct ehci_hcd *ehci; int ret; if (usb_disabled()) return -ENODEV; hcd = usb_create_hcd(&ci_ehci_hc_driver, ci->dev, dev_name(ci->dev)); if (!hcd) return -ENOMEM; dev_set_drvdata(ci->dev, ci); hcd->rsrc_start = ci->hw_bank.phys; hcd->rsrc_len = ci->hw_bank.size; hcd->regs = ci->hw_bank.abs; hcd->has_tt = 1; hcd->power_budget = ci->platdata->power_budget; hcd->phy = ci->transceiver; ehci = hcd_to_ehci(hcd); ehci->caps = ci->hw_bank.cap; ehci->has_hostpc = ci->hw_bank.lpm; ret = usb_add_hcd(hcd, 0, 0); if (ret) usb_put_hcd(hcd); else ci->hcd = hcd; return ret; } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline u8 *ablkcipher_get_spot(u8 *start, unsigned int len) { u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK); return max(start, end_page); } 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: static int iwgif_read_image(struct iwgifrcontext *rctx) { int retval=0; struct lzwdeccontext d; size_t subblocksize; int has_local_ct; int local_ct_size; unsigned int root_codesize; if(!iwgif_read(rctx,rctx->rbuf,9)) goto done; rctx->image_left = (int)iw_get_ui16le(&rctx->rbuf[0]); rctx->image_top = (int)iw_get_ui16le(&rctx->rbuf[2]); rctx->image_width = (int)iw_get_ui16le(&rctx->rbuf[4]); rctx->image_height = (int)iw_get_ui16le(&rctx->rbuf[6]); rctx->interlaced = (int)((rctx->rbuf[8]>>6)&0x01); has_local_ct = (int)((rctx->rbuf[8]>>7)&0x01); if(has_local_ct) { local_ct_size = (int)(rctx->rbuf[8]&0x07); rctx->colortable.num_entries = 1<<(1+local_ct_size); } if(has_local_ct) { if(!iwgif_read_color_table(rctx,&rctx->colortable)) goto done; } if(rctx->has_transparency) { rctx->colortable.entry[rctx->trans_color_index].a = 0; } if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; root_codesize = (unsigned int)rctx->rbuf[0]; if(root_codesize<2 || root_codesize>11) { iw_set_error(rctx->ctx,"Invalid LZW minimum code size"); goto done; } if(!iwgif_init_screen(rctx)) goto done; rctx->total_npixels = (size_t)rctx->image_width * (size_t)rctx->image_height; if(!iwgif_make_row_pointers(rctx)) goto done; lzw_init(&d,root_codesize); lzw_clear(&d); while(1) { if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; subblocksize = (size_t)rctx->rbuf[0]; if(subblocksize==0) break; if(!iwgif_read(rctx,rctx->rbuf,subblocksize)) goto done; if(!lzw_process_bytes(rctx,&d,rctx->rbuf,subblocksize)) goto done; if(d.eoi_flag) break; if(rctx->pixels_set >= rctx->total_npixels) break; } retval=1; done: return retval; } CWE ID: CWE-369 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: SegmentInfo::SegmentInfo( Segment* pSegment, long long start, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_pMuxingAppAsUTF8(NULL), m_pWritingAppAsUTF8(NULL), m_pTitleAsUTF8(NULL) { } CWE ID: CWE-119 Target: 1 Example 2: Code: void __init sched_init(void) { int i, j; unsigned long alloc_size = 0, ptr; #ifdef CONFIG_FAIR_GROUP_SCHED alloc_size += 2 * nr_cpu_ids * sizeof(void **); #endif #ifdef CONFIG_RT_GROUP_SCHED alloc_size += 2 * nr_cpu_ids * sizeof(void **); #endif #ifdef CONFIG_CPUMASK_OFFSTACK alloc_size += num_possible_cpus() * cpumask_size(); #endif if (alloc_size) { ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT); #ifdef CONFIG_FAIR_GROUP_SCHED root_task_group.se = (struct sched_entity **)ptr; ptr += nr_cpu_ids * sizeof(void **); root_task_group.cfs_rq = (struct cfs_rq **)ptr; ptr += nr_cpu_ids * sizeof(void **); #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED root_task_group.rt_se = (struct sched_rt_entity **)ptr; ptr += nr_cpu_ids * sizeof(void **); root_task_group.rt_rq = (struct rt_rq **)ptr; ptr += nr_cpu_ids * sizeof(void **); #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_CPUMASK_OFFSTACK for_each_possible_cpu(i) { per_cpu(load_balance_tmpmask, i) = (void *)ptr; ptr += cpumask_size(); } #endif /* CONFIG_CPUMASK_OFFSTACK */ } #ifdef CONFIG_SMP init_defrootdomain(); #endif init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime()); #ifdef CONFIG_RT_GROUP_SCHED init_rt_bandwidth(&root_task_group.rt_bandwidth, global_rt_period(), global_rt_runtime()); #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_CGROUP_SCHED list_add(&root_task_group.list, &task_groups); INIT_LIST_HEAD(&root_task_group.children); autogroup_init(&init_task); #endif /* CONFIG_CGROUP_SCHED */ for_each_possible_cpu(i) { struct rq *rq; rq = cpu_rq(i); raw_spin_lock_init(&rq->lock); rq->nr_running = 0; rq->calc_load_active = 0; rq->calc_load_update = jiffies + LOAD_FREQ; init_cfs_rq(&rq->cfs, rq); init_rt_rq(&rq->rt, rq); #ifdef CONFIG_FAIR_GROUP_SCHED root_task_group.shares = root_task_group_load; INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); /* * How much cpu bandwidth does root_task_group get? * * In case of task-groups formed thr' the cgroup filesystem, it * gets 100% of the cpu resources in the system. This overall * system cpu resource is divided among the tasks of * root_task_group and its child task-groups in a fair manner, * based on each entity's (task or task-group's) weight * (se->load.weight). * * In other words, if root_task_group has 10 tasks of weight * 1024) and two child groups A0 and A1 (of weight 1024 each), * then A0's share of the cpu resource is: * * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% * * We achieve this by letting root_task_group's tasks sit * directly in rq->cfs (i.e root_task_group->se[] = NULL). */ init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL); #endif /* CONFIG_FAIR_GROUP_SCHED */ rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime; #ifdef CONFIG_RT_GROUP_SCHED INIT_LIST_HEAD(&rq->leaf_rt_rq_list); init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL); #endif for (j = 0; j < CPU_LOAD_IDX_MAX; j++) rq->cpu_load[j] = 0; rq->last_load_update_tick = jiffies; #ifdef CONFIG_SMP rq->sd = NULL; rq->rd = NULL; rq->cpu_power = SCHED_POWER_SCALE; rq->post_schedule = 0; rq->active_balance = 0; rq->next_balance = jiffies; rq->push_cpu = 0; rq->cpu = i; rq->online = 0; rq->idle_stamp = 0; rq->avg_idle = 2*sysctl_sched_migration_cost; rq_attach_root(rq, &def_root_domain); #ifdef CONFIG_NO_HZ rq->nohz_balance_kick = 0; init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i)); #endif #endif init_rq_hrtick(rq); atomic_set(&rq->nr_iowait, 0); } set_load_weight(&init_task); #ifdef CONFIG_PREEMPT_NOTIFIERS INIT_HLIST_HEAD(&init_task.preempt_notifiers); #endif #ifdef CONFIG_SMP open_softirq(SCHED_SOFTIRQ, run_rebalance_domains); #endif #ifdef CONFIG_RT_MUTEXES plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock); #endif /* * The boot idle thread does lazy MMU switching as well: */ atomic_inc(&init_mm.mm_count); enter_lazy_tlb(&init_mm, current); /* * Make us the idle thread. Technically, schedule() should not be * called from this thread, however somewhere below it might be, * but because we are the idle thread, we just pick up running again * when this runqueue becomes "idle". */ init_idle(current, smp_processor_id()); calc_load_update = jiffies + LOAD_FREQ; /* * During early bootup we pretend to be a normal task: */ current->sched_class = &fair_sched_class; /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */ zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT); #ifdef CONFIG_SMP zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT); #ifdef CONFIG_NO_HZ zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT); atomic_set(&nohz.load_balancer, nr_cpu_ids); atomic_set(&nohz.first_pick_cpu, nr_cpu_ids); atomic_set(&nohz.second_pick_cpu, nr_cpu_ids); #endif /* May be allocated at isolcpus cmdline parse time */ if (cpu_isolated_map == NULL) zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT); #endif /* SMP */ scheduler_running = 1; } 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: krb5_ldap_get_password_policy_from_dn(krb5_context context, char *pol_name, char *pol_dn, osa_policy_ent_t *policy) { krb5_error_code st=0, tempst=0; LDAP *ld=NULL; LDAPMessage *result=NULL,*ent=NULL; kdb5_dal_handle *dal_handle=NULL; krb5_ldap_context *ldap_context=NULL; krb5_ldap_server_handle *ldap_server_handle=NULL; /* Clear the global error string */ krb5_clear_error_message(context); /* validate the input parameters */ if (pol_dn == NULL) return EINVAL; *policy = NULL; SETUP_CONTEXT(); GET_HANDLE(); *(policy) = (osa_policy_ent_t) malloc(sizeof(osa_policy_ent_rec)); if (*policy == NULL) { st = ENOMEM; goto cleanup; } memset(*policy, 0, sizeof(osa_policy_ent_rec)); LDAP_SEARCH(pol_dn, LDAP_SCOPE_BASE, "(objectclass=krbPwdPolicy)", password_policy_attributes); ent=ldap_first_entry(ld, result); if (ent != NULL) { if ((st = populate_policy(context, ld, ent, pol_name, *policy)) != 0) goto cleanup; } cleanup: ldap_msgfree(result); if (st != 0) { if (*policy != NULL) { krb5_ldap_free_password_policy(context, *policy); *policy = NULL; } } krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle); return st; } 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: juniper_atm2_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM2; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */ (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) { ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */ return l2info.header_len; if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; } CWE ID: CWE-125 Target: 1 Example 2: Code: static int tcm_loop_alloc_core_bus(void) { int ret; tcm_loop_primary = root_device_register("tcm_loop_0"); if (IS_ERR(tcm_loop_primary)) { printk(KERN_ERR "Unable to allocate tcm_loop_primary\n"); return PTR_ERR(tcm_loop_primary); } ret = bus_register(&tcm_loop_lld_bus); if (ret) { printk(KERN_ERR "bus_register() failed for tcm_loop_lld_bus\n"); goto dev_unreg; } ret = driver_register(&tcm_loop_driverfs); if (ret) { printk(KERN_ERR "driver_register() failed for" "tcm_loop_driverfs\n"); goto bus_unreg; } printk(KERN_INFO "Initialized TCM Loop Core Bus\n"); return ret; bus_unreg: bus_unregister(&tcm_loop_lld_bus); dev_unreg: root_device_unregister(tcm_loop_primary); return ret; } 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: ContentEncoding::~ContentEncoding() { ContentCompression** comp_i = compression_entries_; ContentCompression** const comp_j = compression_entries_end_; while (comp_i != comp_j) { ContentCompression* const comp = *comp_i++; delete comp; } delete [] compression_entries_; ContentEncryption** enc_i = encryption_entries_; ContentEncryption** const enc_j = encryption_entries_end_; while (enc_i != enc_j) { ContentEncryption* const enc = *enc_i++; delete enc; } delete [] encryption_entries_; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void sas_deform_port(struct asd_sas_phy *phy, int gone) { struct sas_ha_struct *sas_ha = phy->ha; struct asd_sas_port *port = phy->port; struct sas_internal *si = to_sas_internal(sas_ha->core.shost->transportt); struct domain_device *dev; unsigned long flags; if (!port) return; /* done by a phy event */ dev = port->port_dev; if (dev) dev->pathways--; if (port->num_phys == 1) { sas_unregister_domain_devices(port, gone); sas_port_delete(port->port); port->port = NULL; } else { sas_port_delete_phy(port->port, phy->phy); sas_device_set_phy(dev, port->port); } if (si->dft->lldd_port_deformed) si->dft->lldd_port_deformed(phy); spin_lock_irqsave(&sas_ha->phy_port_lock, flags); spin_lock(&port->phy_list_lock); list_del_init(&phy->port_phy_el); sas_phy_set_target(phy, NULL); phy->port = NULL; port->num_phys--; port->phy_mask &= ~(1U << phy->id); if (port->num_phys == 0) { INIT_LIST_HEAD(&port->phy_list); memset(port->sas_addr, 0, SAS_ADDR_SIZE); memset(port->attached_sas_addr, 0, SAS_ADDR_SIZE); port->class = 0; port->iproto = 0; port->tproto = 0; port->oob_mode = 0; port->phy_mask = 0; } spin_unlock(&port->phy_list_lock); spin_unlock_irqrestore(&sas_ha->phy_port_lock, flags); return; } CWE ID: Target: 1 Example 2: Code: static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk) { const uint8_t *start, *next, *end = pkt->data + pkt->size; int seq = 0, entry = 0; int key = pkt->flags & AV_PKT_FLAG_KEY; start = find_next_marker(pkt->data, end); for (next = start; next < end; start = next) { next = find_next_marker(start + 4, end); switch (AV_RB32(start)) { case VC1_CODE_SEQHDR: seq = 1; break; case VC1_CODE_ENTRYPOINT: entry = 1; break; case VC1_CODE_SLICE: trk->vc1_info.slices = 1; break; } } if (!trk->entry && trk->vc1_info.first_packet_seen) trk->vc1_info.first_frag_written = 1; if (!trk->entry && !trk->vc1_info.first_frag_written) { /* First packet in first fragment */ trk->vc1_info.first_packet_seq = seq; trk->vc1_info.first_packet_entry = entry; trk->vc1_info.first_packet_seen = 1; } else if ((seq && !trk->vc1_info.packet_seq) || (entry && !trk->vc1_info.packet_entry)) { int i; for (i = 0; i < trk->entry; i++) trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE; trk->has_keyframes = 0; if (seq) trk->vc1_info.packet_seq = 1; if (entry) trk->vc1_info.packet_entry = 1; if (!trk->vc1_info.first_frag_written) { /* First fragment */ if ((!seq || trk->vc1_info.first_packet_seq) && (!entry || trk->vc1_info.first_packet_entry)) { /* First packet had the same headers as this one, readd the * sync sample flag. */ trk->cluster[0].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes = 1; } } } if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry) key = seq && entry; else if (trk->vc1_info.packet_seq) key = seq; else if (trk->vc1_info.packet_entry) key = entry; if (key) { trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes++; } } 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: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), nullptr, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string) && combining_diacritics_exceptions_.containsNone(label_string)) { return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string) && !lgc_letters_n_ascii_.containsAll(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u30ce\u30f3\u30bd\u30be])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)" R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)" R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)" R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)" R"([a-z]\u30fb|\u30fb[a-z]|)" R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)" R"(\u0131[\u0300-\u0339]|)" R"([ijl]\u0307)", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int atalk_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sockaddr_at *sat = (struct sockaddr_at *)msg->msg_name; struct ddpehdr *ddp; int copied = 0; int offset = 0; int err = 0; struct sk_buff *skb; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); lock_sock(sk); if (!skb) goto out; /* FIXME: use skb->cb to be able to use shared skbs */ ddp = ddp_hdr(skb); copied = ntohs(ddp->deh_len_hops) & 1023; if (sk->sk_type != SOCK_RAW) { offset = sizeof(*ddp); copied -= offset; } if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } err = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, copied); if (!err) { if (sat) { sat->sat_family = AF_APPLETALK; sat->sat_port = ddp->deh_sport; sat->sat_addr.s_node = ddp->deh_snode; sat->sat_addr.s_net = ddp->deh_snet; } msg->msg_namelen = sizeof(*sat); } skb_free_datagram(sk, skb); /* Free the datagram. */ out: release_sock(sk); return err ? : copied; } CWE ID: CWE-20 Target: 1 Example 2: Code: parse_dst_operand( struct translate_ctx *ctx, struct tgsi_full_dst_register *dst ) { uint file; uint writemask; const char *cur; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (!parse_register_dst( ctx, &file, &bracket[0] )) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); if (!parse_opt_writemask( ctx, &writemask )) return FALSE; dst->Register.File = file; if (parsed_opt_brackets) { dst->Register.Dimension = 1; dst->Dimension.Indirect = 0; dst->Dimension.Dimension = 0; dst->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Dimension.Indirect = 1; dst->DimIndirect.File = bracket[0].ind_file; dst->DimIndirect.Index = bracket[0].ind_index; dst->DimIndirect.Swizzle = bracket[0].ind_comp; dst->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } dst->Register.Index = bracket[0].index; dst->Register.WriteMask = writemask; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Register.Indirect = 1; dst->Indirect.File = bracket[0].ind_file; dst->Indirect.Index = bracket[0].ind_index; dst->Indirect.Swizzle = bracket[0].ind_comp; dst->Indirect.ArrayID = bracket[0].ind_array; } return TRUE; } 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 ChromeContentRendererClient::RenderViewCreated(RenderView* render_view) { ContentSettingsObserver* content_settings = new ContentSettingsObserver(render_view); new DevToolsAgent(render_view); new ExtensionHelper(render_view, extension_dispatcher_.get()); new PageLoadHistograms(render_view, histogram_snapshots_.get()); new PrintWebViewHelper(render_view); new SearchBox(render_view); new SpellCheckProvider(render_view, spellcheck_.get()); #if defined(ENABLE_SAFE_BROWSING) safe_browsing::MalwareDOMDetails::Create(render_view); #endif #if defined(OS_MACOSX) new TextInputClientObserver(render_view); #endif // defined(OS_MACOSX) PasswordAutofillManager* password_autofill_manager = new PasswordAutofillManager(render_view); AutofillAgent* autofill_agent = new AutofillAgent(render_view, password_autofill_manager); PageClickTracker* page_click_tracker = new PageClickTracker(render_view); page_click_tracker->AddListener(password_autofill_manager); page_click_tracker->AddListener(autofill_agent); TranslateHelper* translate = new TranslateHelper(render_view, autofill_agent); new ChromeRenderViewObserver( render_view, content_settings, extension_dispatcher_.get(), translate); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { new AutomationRendererHelper(render_view); } } 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 inline int handle_dots(struct nameidata *nd, int type) { if (type == LAST_DOTDOT) { if (nd->flags & LOOKUP_RCU) { return follow_dotdot_rcu(nd); } else follow_dotdot(nd); } return 0; } CWE ID: CWE-254 Target: 1 Example 2: Code: static int bgp_attr_aggregator(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; int wantedlen = 6; /* peer with AS4 will send 4 Byte AS, peer without will send 2 Byte */ if (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) wantedlen = 8; if (length != wantedlen) { flog_err(EC_BGP_ATTR_LEN, "AGGREGATOR attribute length isn't %u [%u]", wantedlen, length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } if (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) attr->aggregator_as = stream_getl(peer->curr); else attr->aggregator_as = stream_getw(peer->curr); attr->aggregator_addr.s_addr = stream_get_ipv4(peer->curr); /* Set atomic aggregate flag. */ attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR); return BGP_ATTR_PARSE_PROCEED; } 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 parsePCPPEER_version2(const uint8_t *buf, pcp_info_t *pcp_msg_info) { pcp_msg_info->is_peer_op = 1; memcpy(pcp_msg_info->nonce, buf, 12); pcp_msg_info->protocol = buf[12]; pcp_msg_info->int_port = READNU16(buf + 16); pcp_msg_info->ext_port = READNU16(buf + 18); pcp_msg_info->peer_port = READNU16(buf + 36); pcp_msg_info->ext_ip = (struct in6_addr *)(buf + 20); pcp_msg_info->peer_ip = (struct in6_addr *)(buf + 40); } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void destroy_server_connect(SERVER_CONNECT_REC *conn) { IRC_SERVER_CONNECT_REC *ircconn; ircconn = IRC_SERVER_CONNECT(conn); if (ircconn == NULL) return; g_free_not_null(ircconn->usermode); g_free_not_null(ircconn->alternate_nick); } CWE ID: CWE-416 Target: 1 Example 2: Code: static int btpan_get_local_role() { BTIF_TRACE_DEBUG("btpan_dev_local_role:%d", btpan_dev_local_role); return btpan_dev_local_role; } 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 enum hrtimer_restart posix_timer_fn(struct hrtimer *timer) { struct k_itimer *timr; unsigned long flags; int si_private = 0; enum hrtimer_restart ret = HRTIMER_NORESTART; timr = container_of(timer, struct k_itimer, it.real.timer); spin_lock_irqsave(&timr->it_lock, flags); timr->it_active = 0; if (timr->it_interval != 0) si_private = ++timr->it_requeue_pending; if (posix_timer_event(timr, si_private)) { /* * signal was not sent because of sig_ignor * we will not get a call back to restart it AND * it should be restarted. */ if (timr->it_interval != 0) { ktime_t now = hrtimer_cb_get_time(timer); /* * FIXME: What we really want, is to stop this * timer completely and restart it in case the * SIG_IGN is removed. This is a non trivial * change which involves sighand locking * (sigh !), which we don't want to do late in * the release cycle. * * For now we just let timers with an interval * less than a jiffie expire every jiffie to * avoid softirq starvation in case of SIG_IGN * and a very small interval, which would put * the timer right back on the softirq pending * list. By moving now ahead of time we trick * hrtimer_forward() to expire the timer * later, while we still maintain the overrun * accuracy, but have some inconsistency in * the timer_gettime() case. This is at least * better than a starved softirq. A more * complex fix which solves also another related * inconsistency is already in the pipeline. */ #ifdef CONFIG_HIGH_RES_TIMERS { ktime_t kj = NSEC_PER_SEC / HZ; if (timr->it_interval < kj) now = ktime_add(now, kj); } #endif timr->it_overrun += (unsigned int) hrtimer_forward(timer, now, timr->it_interval); ret = HRTIMER_RESTART; ++timr->it_requeue_pending; timr->it_active = 1; } } unlock_timer(timr, flags); return ret; } 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: xsltAddTemplate(xsltStylesheetPtr style, xsltTemplatePtr cur, const xmlChar *mode, const xmlChar *modeURI) { xsltCompMatchPtr pat, list, next; /* * 'top' will point to style->xxxMatch ptr - declaring as 'void' * avoids gcc 'type-punned pointer' warning. */ void **top = NULL; const xmlChar *name = NULL; float priority; /* the priority */ if ((style == NULL) || (cur == NULL) || (cur->match == NULL)) return(-1); priority = cur->priority; pat = xsltCompilePatternInternal(cur->match, style->doc, cur->elem, style, NULL, 1); if (pat == NULL) return(-1); while (pat) { next = pat->next; pat->next = NULL; name = NULL; pat->template = cur; if (mode != NULL) pat->mode = xmlDictLookup(style->dict, mode, -1); if (modeURI != NULL) pat->modeURI = xmlDictLookup(style->dict, modeURI, -1); if (priority != XSLT_PAT_NO_PRIORITY) pat->priority = priority; /* * insert it in the hash table list corresponding to its lookup name */ switch (pat->steps[0].op) { case XSLT_OP_ATTR: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->attrMatch); break; case XSLT_OP_PARENT: case XSLT_OP_ANCESTOR: top = &(style->elemMatch); break; case XSLT_OP_ROOT: top = &(style->rootMatch); break; case XSLT_OP_KEY: top = &(style->keyMatch); break; case XSLT_OP_ID: /* TODO optimize ID !!! */ case XSLT_OP_NS: case XSLT_OP_ALL: top = &(style->elemMatch); break; case XSLT_OP_END: case XSLT_OP_PREDICATE: xsltTransformError(NULL, style, NULL, "xsltAddTemplate: invalid compiled pattern\n"); xsltFreeCompMatch(pat); return(-1); /* * TODO: some flags at the top level about type based patterns * would be faster than inclusion in the hash table. */ case XSLT_OP_PI: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->piMatch); break; case XSLT_OP_COMMENT: top = &(style->commentMatch); break; case XSLT_OP_TEXT: top = &(style->textMatch); break; case XSLT_OP_ELEM: case XSLT_OP_NODE: if (pat->steps[0].value != NULL) name = pat->steps[0].value; else top = &(style->elemMatch); break; } if (name != NULL) { if (style->templatesHash == NULL) { style->templatesHash = xmlHashCreate(1024); if (style->templatesHash == NULL) { xsltFreeCompMatch(pat); return(-1); } xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat); } else { list = (xsltCompMatchPtr) xmlHashLookup3(style->templatesHash, name, mode, modeURI); if (list == NULL) { xmlHashAddEntry3(style->templatesHash, name, mode, modeURI, pat); } else { /* * Note '<=' since one must choose among the matching * template rules that are left, the one that occurs * last in the stylesheet */ if (list->priority <= pat->priority) { pat->next = list; xmlHashUpdateEntry3(style->templatesHash, name, mode, modeURI, pat, NULL); } else { while (list->next != NULL) { if (list->next->priority <= pat->priority) break; list = list->next; } pat->next = list->next; list->next = pat; } } } } else if (top != NULL) { list = *top; if (list == NULL) { *top = pat; pat->next = NULL; } else if (list->priority <= pat->priority) { pat->next = list; *top = pat; } else { while (list->next != NULL) { if (list->next->priority <= pat->priority) break; list = list->next; } pat->next = list->next; list->next = pat; } } else { xsltTransformError(NULL, style, NULL, "xsltAddTemplate: invalid compiled pattern\n"); xsltFreeCompMatch(pat); return(-1); } #ifdef WITH_XSLT_DEBUG_PATTERN if (mode) xsltGenericDebug(xsltGenericDebugContext, "added pattern : '%s' mode '%s' priority %f\n", pat->pattern, pat->mode, pat->priority); else xsltGenericDebug(xsltGenericDebugContext, "added pattern : '%s' priority %f\n", pat->pattern, pat->priority); #endif pat = next; } return(0); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int handle_invept(struct kvm_vcpu *vcpu) { u32 vmx_instruction_info, types; unsigned long type; gva_t gva; struct x86_exception e; struct { u64 eptp, gpa; } operand; if (!(nested_vmx_secondary_ctls_high & SECONDARY_EXEC_ENABLE_EPT) || !(nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } if (!nested_vmx_check_permission(vcpu)) return 1; if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf); types = (nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6; if (!(types & (1UL << type))) { nested_vmx_failValid(vcpu, VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); return 1; } /* According to the Intel VMX instruction reference, the memory * operand is read even if it isn't needed (e.g., for type==global) */ if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION), vmx_instruction_info, &gva)) return 1; if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand, sizeof(operand), &e)) { kvm_inject_page_fault(vcpu, &e); return 1; } switch (type) { case VMX_EPT_EXTENT_GLOBAL: kvm_mmu_sync_roots(vcpu); kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu); nested_vmx_succeed(vcpu); break; default: /* Trap single context invalidation invept calls */ BUG_ON(1); break; } skip_emulated_instruction(vcpu); return 1; } 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 cJSON *cJSON_New_Item( void ) { cJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) ); if ( node ) memset( node, 0, sizeof(cJSON) ); return node; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } } } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); GetContentSecurityPolicy()->BindToExecutionContext(this); } CWE ID: CWE-732 Target: 1 Example 2: Code: CSSStyleSheet* CSSStyleSheet::CreateInline(StyleSheetContents* sheet, Node& owner_node, const TextPosition& start_position) { DCHECK(sheet); return new CSSStyleSheet(sheet, owner_node, true, start_position); } 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 int hwsim_fops_group_read(void *dat, u64 *val) { struct mac80211_hwsim_data *data = dat; *val = data->group; return 0; } 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: MagickExport int LocaleLowercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); } CWE ID: CWE-125 Target: 1 Example 2: Code: ScreenSaverExtensionInit(void) { ExtensionEntry *extEntry; int i; ScreenPtr pScreen; if (!dixRegisterPrivateKey(&ScreenPrivateKeyRec, PRIVATE_SCREEN, 0)) return; AttrType = CreateNewResourceType(ScreenSaverFreeAttr, "SaverAttr"); SaverEventType = CreateNewResourceType(ScreenSaverFreeEvents, "SaverEvent"); SuspendType = CreateNewResourceType(ScreenSaverFreeSuspend, "SaverSuspend"); for (i = 0; i < screenInfo.numScreens; i++) { pScreen = screenInfo.screens[i]; SetScreenPrivate(pScreen, NULL); } if (AttrType && SaverEventType && SuspendType && (extEntry = AddExtension(ScreenSaverName, ScreenSaverNumberEvents, 0, ProcScreenSaverDispatch, SProcScreenSaverDispatch, NULL, StandardMinorOpcode))) { ScreenSaverEventBase = extEntry->eventBase; EventSwapVector[ScreenSaverEventBase] = (EventSwapPtr) SScreenSaverNotifyEvent; } } 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: char *curl_easy_unescape(CURL *handle, const char *string, int length, int *olen) { int alloc = (length?length:(int)strlen(string))+1; char *ns = malloc(alloc); unsigned char in; int strindex=0; unsigned long hex; CURLcode res; if(!ns) return NULL; while(--alloc > 0) { in = *string; if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(handle, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return NULL; } string+=2; alloc-=2; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; return ns; } CWE ID: CWE-89 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 mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct arpt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->arp)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } CWE ID: CWE-119 Target: 1 Example 2: Code: void WebBluetoothServiceImpl::RemoteServiceGetCharacteristics( const std::string& service_instance_id, blink::mojom::WebBluetoothGATTQueryQuantity quantity, const base::Optional<BluetoothUUID>& characteristics_uuid, RemoteServiceGetCharacteristicsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RecordGetCharacteristicsCharacteristic(quantity, characteristics_uuid); if (characteristics_uuid && BluetoothBlocklist::Get().IsExcluded(characteristics_uuid.value())) { RecordGetCharacteristicsOutcome(quantity, UMAGetCharacteristicOutcome::BLOCKLISTED); std::move(callback).Run( blink::mojom::WebBluetoothResult::BLOCKLISTED_CHARACTERISTIC_UUID, base::nullopt /* characteristics */); return; } const CacheQueryResult query_result = QueryCacheForService(service_instance_id); if (query_result.outcome == CacheQueryOutcome::BAD_RENDERER) { return; } if (query_result.outcome != CacheQueryOutcome::SUCCESS) { RecordGetCharacteristicsOutcome(quantity, query_result.outcome); std::move(callback).Run(query_result.GetWebResult(), base::nullopt /* characteristics */); return; } std::vector<device::BluetoothRemoteGattCharacteristic*> characteristics = characteristics_uuid ? query_result.service->GetCharacteristicsByUUID( characteristics_uuid.value()) : query_result.service->GetCharacteristics(); std::vector<blink::mojom::WebBluetoothRemoteGATTCharacteristicPtr> response_characteristics; for (device::BluetoothRemoteGattCharacteristic* characteristic : characteristics) { if (BluetoothBlocklist::Get().IsExcluded(characteristic->GetUUID())) { continue; } std::string characteristic_instance_id = characteristic->GetIdentifier(); auto insert_result = characteristic_id_to_service_id_.insert( std::make_pair(characteristic_instance_id, service_instance_id)); if (!insert_result.second) DCHECK(insert_result.first->second == service_instance_id); blink::mojom::WebBluetoothRemoteGATTCharacteristicPtr characteristic_ptr = blink::mojom::WebBluetoothRemoteGATTCharacteristic::New(); characteristic_ptr->instance_id = characteristic_instance_id; characteristic_ptr->uuid = characteristic->GetUUID(); characteristic_ptr->properties = static_cast<uint32_t>(characteristic->GetProperties()); response_characteristics.push_back(std::move(characteristic_ptr)); if (quantity == blink::mojom::WebBluetoothGATTQueryQuantity::SINGLE) { break; } } if (!response_characteristics.empty()) { RecordGetCharacteristicsOutcome(quantity, UMAGetCharacteristicOutcome::SUCCESS); std::move(callback).Run(blink::mojom::WebBluetoothResult::SUCCESS, std::move(response_characteristics)); return; } RecordGetCharacteristicsOutcome( quantity, characteristics_uuid ? UMAGetCharacteristicOutcome::NOT_FOUND : UMAGetCharacteristicOutcome::NO_CHARACTERISTICS); std::move(callback).Run( characteristics_uuid ? blink::mojom::WebBluetoothResult::CHARACTERISTIC_NOT_FOUND : blink::mojom::WebBluetoothResult::NO_CHARACTERISTICS_FOUND, base::nullopt /* characteristics */); } 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 AutofillDialogViews::ShowDialogInMode(DialogMode dialog_mode) { loading_shield_->SetVisible(dialog_mode == LOADING); sign_in_web_view_->SetVisible(dialog_mode == SIGN_IN); notification_area_->SetVisible(dialog_mode == DETAIL_INPUT); scrollable_area_->SetVisible(dialog_mode == DETAIL_INPUT); FocusInitialView(); } 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: hstore_recv(PG_FUNCTION_ARGS) { int32 buflen; HStore *out; Pairs *pairs; int32 i; int32 pcount; StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); pcount = pq_getmsgint(buf, 4); if (pcount == 0) { out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); } pairs = palloc(pcount * sizeof(Pairs)); for (i = 0; i < pcount; ++i) { int rawlen = pq_getmsgint(buf, 4); int len; if (rawlen < 0) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("null value not allowed for hstore key"))); pairs[i].key = pq_getmsgtext(buf, rawlen, &len); pairs[i].keylen = hstoreCheckKeyLen(len); pairs[i].needfree = true; rawlen = pq_getmsgint(buf, 4); if (rawlen < 0) { pairs[i].val = NULL; pairs[i].vallen = 0; pairs[i].isnull = true; } else { pairs[i].val = pq_getmsgtext(buf, rawlen, &len); pairs[i].vallen = hstoreCheckValLen(len); pairs[i].isnull = false; } } pcount = hstoreUniquePairs(pairs, pcount, &buflen); out = hstorePairs(pairs, pcount, buflen); PG_RETURN_POINTER(out); } CWE ID: CWE-189 Target: 1 Example 2: Code: int dtls1_dispatch_alert(SSL *s) { int i,j; void (*cb)(const SSL *ssl,int type,int val)=NULL; unsigned char buf[DTLS1_AL_HEADER_LENGTH]; unsigned char *ptr = &buf[0]; s->s3->alert_dispatch=0; memset(buf, 0x00, sizeof(buf)); *ptr++ = s->s3->send_alert[0]; *ptr++ = s->s3->send_alert[1]; #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { s2n(s->d1->handshake_read_seq, ptr); #if 0 if ( s->d1->r_msg_hdr.frag_off == 0) /* waiting for a new msg */ else s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */ #endif #if 0 fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq); #endif l2n3(s->d1->r_msg_hdr.frag_off, ptr); } #endif i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0); if (i <= 0) { s->s3->alert_dispatch=1; /* fprintf( stderr, "not done with alert\n" ); */ } else { if (s->s3->send_alert[0] == SSL3_AL_FATAL #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE #endif ) (void)BIO_flush(s->wbio); if (s->msg_callback) s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; if (cb != NULL) { j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1]; cb(s,SSL_CB_WRITE_ALERT,j); } } return(i); } 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: checkcondition_bit(void *checkval, ITEM *item) { return GETBIT(checkval, HASHVAL(item->val)); } 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: FileEntrySync* DirectoryEntrySync::getFile(const String& path, const Dictionary& options, ExceptionState& exceptionState) { FileSystemFlags flags(options); RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create(); m_fileSystem->getFile(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return static_cast<FileEntrySync*>(helper->getResult(exceptionState)); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool SelectionEditor::ShouldAlwaysUseDirectionalSelection() const { return GetFrame() ->GetEditor() .Behavior() .ShouldConsiderSelectionAsDirectional(); } 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: initpyfribidi (void) { PyObject *module; /* XXX What should be done if we fail here? */ module = Py_InitModule3 ("pyfribidi", PyfribidiMethods, _pyfribidi__doc__); PyModule_AddIntConstant (module, "RTL", (long) FRIBIDI_TYPE_RTL); PyModule_AddIntConstant (module, "LTR", (long) FRIBIDI_TYPE_LTR); PyModule_AddIntConstant (module, "ON", (long) FRIBIDI_TYPE_ON); PyModule_AddStringConstant (module, "__author__", "Yaacov Zamir and Nir Soffer"); } 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: spnego_gss_complete_auth_token( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer) { OM_uint32 ret; ret = gss_complete_auth_token(minor_status, context_handle, input_message_buffer); return (ret); } CWE ID: CWE-18 Target: 1 Example 2: Code: bool Document::cssRegionsEnabled() const { return RuntimeEnabledFeatures::cssRegionsEnabled(); } 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: SchedulerObject::release(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Release: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!releaseJob(id.cluster, id.proc, reason.c_str(), true, // Always perform this action within a transaction false, // Do not email the user about this action false // Do not email admin about this action )) { text = "Failed to release job"; return false; } 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 __net_init int setup_net(struct net *net, struct user_namespace *user_ns) { /* Must be called with pernet_ops_rwsem held */ const struct pernet_operations *ops, *saved_ops; int error = 0; LIST_HEAD(net_exit_list); refcount_set(&net->count, 1); refcount_set(&net->passive, 1); net->dev_base_seq = 1; net->user_ns = user_ns; idr_init(&net->netns_ids); spin_lock_init(&net->nsid_lock); mutex_init(&net->ipv4.ra_mutex); list_for_each_entry(ops, &pernet_list, list) { error = ops_init(ops, net); if (error < 0) goto out_undo; } down_write(&net_rwsem); list_add_tail_rcu(&net->list, &net_namespace_list); up_write(&net_rwsem); out: return error; out_undo: /* Walk through the list backwards calling the exit functions * for the pernet modules whose init functions did not fail. */ list_add(&net->exit_list, &net_exit_list); saved_ops = ops; list_for_each_entry_continue_reverse(ops, &pernet_list, list) ops_exit_list(ops, &net_exit_list); ops = saved_ops; list_for_each_entry_continue_reverse(ops, &pernet_list, list) ops_free_list(ops, &net_exit_list); rcu_barrier(); goto out; } CWE ID: CWE-200 Target: 1 Example 2: Code: int main(int argc, char *argv[]) { FILE *fp_rd = stdin; FILE *fp_al = NULL; FILE *fp_wr = stdout; BOOL interlace = FALSE; BOOL alpha = FALSE; int argi; for (argi = 1; argi < argc; argi++) { if (argv[argi][0] == '-') { switch (argv[argi][1]) { case 'i': interlace = TRUE; break; case 'a': alpha = TRUE; argi++; if ((fp_al = fopen (argv[argi], "rb")) == NULL) { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: alpha-channel file %s does not exist\n", argv[argi]); exit (1); } break; case 'h': case '?': usage(); exit(0); break; default: fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: unknown option %s\n", argv[argi]); usage(); exit(1); break; } /* end switch */ } else if (fp_rd == stdin) { if ((fp_rd = fopen (argv[argi], "rb")) == NULL) { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: file %s does not exist\n", argv[argi]); exit (1); } } else if (fp_wr == stdout) { if ((fp_wr = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: can not create PNG-file %s\n", argv[argi]); exit (1); } } else { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: too many parameters\n"); usage(); exit (1); } } /* end for */ #ifdef __TURBOC__ /* set stdin/stdout to binary, we're reading the PNM always! in binary format */ if (fp_rd == stdin) { setmode (STDIN, O_BINARY); } if (fp_wr == stdout) { setmode (STDOUT, O_BINARY); } #endif /* call the conversion program itself */ if (pnm2png (fp_rd, fp_wr, fp_al, interlace, alpha) == FALSE) { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: unsuccessful converting to PNG-image\n"); exit (1); } /* close input file */ fclose (fp_rd); /* close output file */ fclose (fp_wr); /* close alpha file */ if (alpha) fclose (fp_al); 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: bool ContentSecurityPolicy::AllowPluginTypeForDocument( const Document& document, const String& type, const String& type_attribute, const KURL& url, SecurityViolationReportingPolicy reporting_policy) const { if (document.GetContentSecurityPolicy() && !document.GetContentSecurityPolicy()->AllowPluginType( type, type_attribute, url, reporting_policy)) return false; LocalFrame* frame = document.GetFrame(); if (frame && frame->Tree().Parent() && document.IsPluginDocument()) { ContentSecurityPolicy* parent_csp = frame->Tree() .Parent() ->GetSecurityContext() ->GetContentSecurityPolicy(); if (parent_csp && !parent_csp->AllowPluginType(type, type_attribute, url, reporting_policy)) return false; } 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: void FragmentPaintPropertyTreeBuilder::UpdateOverflowControlsClip() { DCHECK(properties_); if (!NeedsPaintPropertyUpdate()) return; if (NeedsOverflowControlsClip()) { properties_->UpdateOverflowControlsClip( context_.current.clip, ClipPaintPropertyNode::State{ context_.current.transform, ToClipRect(LayoutRect(context_.current.paint_offset, ToLayoutBox(object_).Size()))}); } else { properties_->ClearOverflowControlsClip(); } } CWE ID: Target: 1 Example 2: Code: void TestPin( const std::string& resource_id, const std::string& md5, base::PlatformFileError expected_error, int expected_cache_state, GDataRootDirectory::CacheSubDirectoryType expected_sub_dir_type) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; expected_sub_dir_type_ = expected_sub_dir_type; file_system_->Pin(resource_id, md5, base::Bind(&GDataFileSystemTest::VerifyCacheFileState, base::Unretained(this))); RunAllPendingForIO(); } 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: FileTransfer::Init( ClassAd *Ad, bool want_check_perms, priv_state priv, bool use_file_catalog) { char buf[ATTRLIST_MAX_EXPRESSION]; char *dynamic_buf = NULL; ASSERT( daemonCore ); // full Init require DaemonCore methods if( did_init ) { return 1; } dprintf(D_FULLDEBUG,"entering FileTransfer::Init\n"); m_use_file_catalog = use_file_catalog; simple_init = false; if (!TranskeyTable) { if (!(TranskeyTable = new TranskeyHashTable(7, compute_transkey_hash))) { return 0; } } if (ActiveTransferTid >= 0) { EXCEPT("FileTransfer::Init called during active transfer!"); } if (!TransThreadTable) { if (!(TransThreadTable = new TransThreadHashTable(7, compute_transthread_hash))) { return 0; } } if ( !CommandsRegistered ) { CommandsRegistered = TRUE; daemonCore->Register_Command(FILETRANS_UPLOAD,"FILETRANS_UPLOAD", (CommandHandler)&FileTransfer::HandleCommands, "FileTransfer::HandleCommands()",NULL,WRITE); daemonCore->Register_Command(FILETRANS_DOWNLOAD,"FILETRANS_DOWNLOAD", (CommandHandler)&FileTransfer::HandleCommands, "FileTransfer::HandleCommands()",NULL,WRITE); ReaperId = daemonCore->Register_Reaper("FileTransfer::Reaper", (ReaperHandler)&FileTransfer::Reaper, "FileTransfer::Reaper()",NULL); if (ReaperId == 1) { EXCEPT("FileTransfer::Reaper() can not be the default reaper!\n"); } set_seed( time(NULL) + (unsigned long)this + (unsigned long)Ad ); } if (Ad->LookupString(ATTR_TRANSFER_KEY, buf) != 1) { char tempbuf[80]; sprintf(tempbuf,"%x#%x%x%x",++SequenceNum,(unsigned)time(NULL), get_random_int(),get_random_int()); TransKey = strdup(tempbuf); user_supplied_key = FALSE; sprintf(tempbuf,"%s=\"%s\"",ATTR_TRANSFER_KEY,TransKey); Ad->InsertOrUpdate(tempbuf); char const *mysocket = global_dc_sinful(); ASSERT(mysocket); Ad->Assign(ATTR_TRANSFER_SOCKET,mysocket); } else { TransKey = strdup(buf); user_supplied_key = TRUE; } if ( !SimpleInit(Ad, want_check_perms, IsServer(), NULL, priv, m_use_file_catalog ) ) { return 0; } if (Ad->LookupString(ATTR_TRANSFER_SOCKET, buf) != 1) { return 0; } TransSock = strdup(buf); buf[0] = '\0'; if ( IsServer() && upload_changed_files ) { CommitFiles(); MyString filelist; const char* current_file = NULL; bool print_comma = false; Directory spool_space( SpoolSpace, desired_priv_state ); while ( (current_file=spool_space.Next()) ) { if ( UserLogFile && !file_strcmp(UserLogFile,current_file) ) { continue; } time_t mod_time; filesize_t filesize; if ( LookupInFileCatalog(current_file, &mod_time, &filesize) ) { if((filesize==-1)) { if(spool_space.GetModifyTime() <= mod_time) { dprintf( D_FULLDEBUG, "Not including file %s, t: %ld<=%ld, s: N/A\n", current_file, spool_space.GetModifyTime(), mod_time); continue; } } else if((spool_space.GetModifyTime()==mod_time) && (spool_space.GetFileSize()==filesize) ) { dprintf( D_FULLDEBUG, "Not including file %s, t: %ld, " "s: " FILESIZE_T_FORMAT "\n", current_file, spool_space.GetModifyTime(), spool_space.GetFileSize()); continue; } dprintf( D_FULLDEBUG, "Including changed file %s, t: %ld, %ld, " "s: " FILESIZE_T_FORMAT ", " FILESIZE_T_FORMAT "\n", current_file, spool_space.GetModifyTime(), mod_time, spool_space.GetFileSize(), filesize ); } if ( print_comma ) { filelist += ","; } else { print_comma = true; } filelist += current_file; } if ( print_comma ) { MyString intermediateFilesBuf; intermediateFilesBuf.sprintf( "%s=\"%s\"", ATTR_TRANSFER_INTERMEDIATE_FILES,filelist.Value()); Ad->InsertOrUpdate(intermediateFilesBuf.Value()); dprintf(D_FULLDEBUG,"%s\n",buf); } } if ( IsClient() && upload_changed_files ) { dynamic_buf = NULL; Ad->LookupString(ATTR_TRANSFER_INTERMEDIATE_FILES,&dynamic_buf); dprintf(D_FULLDEBUG,"%s=\"%s\"\n", ATTR_TRANSFER_INTERMEDIATE_FILES, dynamic_buf ? dynamic_buf : "(none)"); if ( dynamic_buf ) { SpooledIntermediateFiles = strnewp(dynamic_buf); free(dynamic_buf); dynamic_buf = NULL; } } if ( IsServer() ) { MyString key(TransKey); FileTransfer *transobject; if ( TranskeyTable->lookup(key,transobject) < 0 ) { if ( TranskeyTable->insert(key,this) < 0 ) { dprintf(D_ALWAYS, "FileTransfer::Init failed to insert key in our table\n"); return 0; } } else { EXCEPT("FileTransfer: Duplicate TransferKeys!"); } } did_init = true; return 1; } CWE ID: CWE-134 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: VP9PictureToVaapiDecodeSurface(const scoped_refptr<VP9Picture>& pic) { VaapiVP9Picture* vaapi_pic = pic->AsVaapiVP9Picture(); CHECK(vaapi_pic); return vaapi_pic->dec_surface(); } CWE ID: CWE-362 Target: 1 Example 2: Code: void ChromeContentRendererClient::PrefetchHostName(const char* hostname, size_t length) { net_predictor_->Resolve(hostname, length); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void activityLoggingAccessPerWorldBindingsLongAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); V8PerContextData* contextData = V8PerContextData::from(info.GetIsolate()->GetCurrentContext()); if (contextData && contextData->activityLogger()) contextData->activityLogger()->log("TestObjectPython.activityLoggingAccessPerWorldBindingsLongAttribute", 0, 0, "Getter"); TestObjectPythonV8Internal::activityLoggingAccessPerWorldBindingsLongAttributeAttributeGetter(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: tt_cmap4_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p; FT_UInt length; FT_Byte *ends, *starts, *offsets, *deltas, *glyph_ids; FT_UInt num_segs; FT_Error error = FT_Err_Ok; if ( table + 2 + 2 > valid->limit ) FT_INVALID_TOO_SHORT; p = table + 2; /* skip format */ length = TT_NEXT_USHORT( p ); if ( length < 16 ) FT_INVALID_TOO_SHORT; /* in certain fonts, the `length' field is invalid and goes */ /* out of bound. We try to correct this here... */ if ( table + length > valid->limit ) /* in certain fonts, the `length' field is invalid and goes */ /* out of bound. We try to correct this here... */ if ( table + length > valid->limit ) { length = (FT_UInt)( valid->limit - table ); } p = table + 6; num_segs = TT_NEXT_USHORT( p ); /* read segCountX2 */ if ( valid->level >= FT_VALIDATE_PARANOID ) { /* check that we have an even value here */ if ( num_segs & 1 ) FT_INVALID_DATA; } num_segs /= 2; if ( length < 16 + num_segs * 2 * 4 ) FT_INVALID_TOO_SHORT; /* check the search parameters - even though we never use them */ /* */ if ( valid->level >= FT_VALIDATE_PARANOID ) { /* check the values of `searchRange', `entrySelector', `rangeShift' */ FT_UInt search_range = TT_NEXT_USHORT( p ); FT_UInt entry_selector = TT_NEXT_USHORT( p ); FT_UInt range_shift = TT_NEXT_USHORT( p ); if ( ( search_range | range_shift ) & 1 ) /* must be even values */ FT_INVALID_DATA; search_range /= 2; range_shift /= 2; /* `search range' is the greatest power of 2 that is <= num_segs */ if ( search_range > num_segs || search_range * 2 < num_segs || search_range + range_shift != num_segs || search_range != ( 1U << entry_selector ) ) FT_INVALID_DATA; } ends = table + 14; starts = table + 16 + num_segs * 2; deltas = starts + num_segs * 2; offsets = deltas + num_segs * 2; glyph_ids = offsets + num_segs * 2; /* check last segment; its end count value must be 0xFFFF */ if ( valid->level >= FT_VALIDATE_PARANOID ) { p = ends + ( num_segs - 1 ) * 2; if ( TT_PEEK_USHORT( p ) != 0xFFFFU ) FT_INVALID_DATA; } { FT_UInt start, end, offset, n; FT_UInt last_start = 0, last_end = 0; FT_Int delta; FT_Byte* p_start = starts; FT_Byte* p_end = ends; FT_Byte* p_delta = deltas; FT_Byte* p_offset = offsets; for ( n = 0; n < num_segs; n++ ) { p = p_offset; start = TT_NEXT_USHORT( p_start ); end = TT_NEXT_USHORT( p_end ); delta = TT_NEXT_SHORT( p_delta ); offset = TT_NEXT_USHORT( p_offset ); if ( start > end ) FT_INVALID_DATA; /* this test should be performed at default validation level; */ /* unfortunately, some popular Asian fonts have overlapping */ /* ranges in their charmaps */ /* */ if ( start <= last_end && n > 0 ) { if ( valid->level >= FT_VALIDATE_TIGHT ) FT_INVALID_DATA; else { /* allow overlapping segments, provided their start points */ /* and end points, respectively, are in ascending order */ /* */ if ( last_start > start || last_end > end ) error |= TT_CMAP_FLAG_UNSORTED; else error |= TT_CMAP_FLAG_OVERLAPPING; } } if ( offset && offset != 0xFFFFU ) { p += offset; /* start of glyph ID array */ /* check that we point within the glyph IDs table only */ if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( p < glyph_ids || p + ( end - start + 1 ) * 2 > table + length ) FT_INVALID_DATA; } /* Some fonts handle the last segment incorrectly. In */ /* theory, 0xFFFF might point to an ordinary glyph -- */ /* a cmap 4 is versatile and could be used for any */ /* encoding, not only Unicode. However, reality shows */ /* that far too many fonts are sloppy and incorrectly */ /* set all fields but `start' and `end' for the last */ /* segment if it contains only a single character. */ /* */ /* We thus omit the test here, delaying it to the */ /* routines which actually access the cmap. */ else if ( n != num_segs - 1 || !( start == 0xFFFFU && end == 0xFFFFU ) ) { if ( p < glyph_ids || p + ( end - start + 1 ) * 2 > valid->limit ) FT_INVALID_DATA; } /* check glyph indices within the segment range */ if ( valid->level >= FT_VALIDATE_TIGHT ) { FT_UInt i, idx; for ( i = start; i < end; i++ ) { idx = FT_NEXT_USHORT( p ); if ( idx != 0 ) { idx = (FT_UInt)( idx + delta ) & 0xFFFFU; if ( idx >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; } } } } else if ( offset == 0xFFFFU ) { /* some fonts (erroneously?) use a range offset of 0xFFFF */ /* to mean missing glyph in cmap table */ /* */ if ( valid->level >= FT_VALIDATE_PARANOID || n != num_segs - 1 || !( start == 0xFFFFU && end == 0xFFFFU ) ) FT_INVALID_DATA; } last_start = start; last_end = end; } } return error; } CWE ID: CWE-119 Target: 1 Example 2: Code: void LayerTreeCoordinator::scrollNonCompositedContents(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset) { setNonCompositedContentsNeedDisplay(scrollRect); } 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: XvQueryAdaptors( Display *dpy, Window window, unsigned int *p_nAdaptors, XvAdaptorInfo **p_pAdaptors) { XExtDisplayInfo *info = xv_find_display(dpy); xvQueryAdaptorsReq *req; xvQueryAdaptorsReply rep; size_t size; unsigned int ii, jj; char *name; XvAdaptorInfo *pas = NULL, *pa; XvFormat *pfs, *pf; char *buffer = NULL; char *buffer; char *string; xvAdaptorInfo *pa; xvFormat *pf; } u; 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 HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(obj TSRMLS_CC); HashTable *rv; zval *tmp, zrv; char *pnstr, *path; int pnlen, path_len; char stmp[2]; *is_temp = 1; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } ALLOC_HASHTABLE(rv); ZEND_INIT_SYMTABLE_EX(rv, zend_hash_num_elements(intern->std.properties) + 3, 0); INIT_PZVAL(&zrv); Z_ARRVAL(zrv) = rv; zend_hash_copy(rv, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "pathName", sizeof("pathName")-1, &pnlen TSRMLS_CC); path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, path, path_len, 1); efree(pnstr); if (intern->file_name) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "fileName", sizeof("fileName")-1, &pnlen TSRMLS_CC); spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name, intern->file_name_len, 1); } efree(pnstr); } if (intern->type == SPL_FS_DIR) { #ifdef HAVE_GLOB pnstr = spl_gen_private_prop_name(spl_ce_DirectoryIterator, "glob", sizeof("glob")-1, &pnlen TSRMLS_CC); if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->_path, intern->_path_len, 1); } else { add_assoc_bool_ex(&zrv, pnstr, pnlen+1, 0); } efree(pnstr); #endif pnstr = spl_gen_private_prop_name(spl_ce_RecursiveDirectoryIterator, "subPathName", sizeof("subPathName")-1, &pnlen TSRMLS_CC); if (intern->u.dir.sub_path) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, "", 0, 1); } efree(pnstr); } if (intern->type == SPL_FS_FILE) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "openMode", sizeof("openMode")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.file.open_mode, intern->u.file.open_mode_len, 1); efree(pnstr); stmp[1] = '\0'; stmp[0] = intern->u.file.delimiter; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "delimiter", sizeof("delimiter")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); stmp[0] = intern->u.file.enclosure; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "enclosure", sizeof("enclosure")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); } return rv; } /* }}} */ CWE ID: CWE-190 Target: 1 Example 2: Code: bool SharedWorkerDevToolsAgentHost::Matches(SharedWorkerHost* worker_host) { return instance_->Matches(*worker_host->instance()); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct kioctx *lookup_ioctx(unsigned long ctx_id) { struct mm_struct *mm = current->mm; struct kioctx *ctx, *ret = NULL; struct hlist_node *n; rcu_read_lock(); hlist_for_each_entry_rcu(ctx, n, &mm->ioctx_list, list) { /* * RCU protects us against accessing freed memory but * we have to be careful not to get a reference when the * reference count already dropped to 0 (ctx->dead test * is unreliable because of races). */ if (ctx->user_id == ctx_id && !ctx->dead && try_get_ioctx(ctx)){ ret = ctx; break; } } rcu_read_unlock(); return ret; } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Response ServiceWorkerHandler::DispatchSyncEvent( const std::string& origin, const std::string& registration_id, const std::string& tag, bool last_chance) { if (!enabled_) return CreateDomainNotEnabledErrorResponse(); if (!process_) return CreateContextErrorResponse(); int64_t id = 0; if (!base::StringToInt64(registration_id, &id)) return CreateInvalidVersionIdErrorResponse(); StoragePartitionImpl* partition = static_cast<StoragePartitionImpl*>(process_->GetStoragePartition()); BackgroundSyncContext* sync_context = partition->GetBackgroundSyncContext(); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&DispatchSyncEventOnIO, context_, base::WrapRefCounted(sync_context), GURL(origin), id, tag, last_chance)); return Response::OK(); } CWE ID: CWE-20 Target: 1 Example 2: Code: void AppListSyncableService::ProcessNewSyncItem(SyncItem* sync_item) { VLOG(2) << "ProcessNewSyncItem: " << sync_item->ToString(); switch (sync_item->item_type) { case sync_pb::AppListSpecifics::TYPE_APP: { return; } case sync_pb::AppListSpecifics::TYPE_REMOVE_DEFAULT_APP: { VLOG(1) << this << ": Uninstall: " << sync_item->ToString(); if (IsDriveAppSyncId(sync_item->item_id)) { if (drive_app_provider_) { drive_app_provider_->AddUninstalledDriveAppFromSync( GetDriveAppIdFromSyncId(sync_item->item_id)); } } else { UninstallExtension(extension_system_->extension_service(), sync_item->item_id); } return; } case sync_pb::AppListSpecifics::TYPE_FOLDER: { AppListItem* app_item = model_->FindItem(sync_item->item_id); if (!app_item) return; // Don't create new folders here, the model will do that. UpdateAppItemFromSyncItem(sync_item, app_item); return; } case sync_pb::AppListSpecifics::TYPE_URL: { LOG(WARNING) << "TYPE_URL not supported"; return; } } NOTREACHED() << "Unrecognized sync item type: " << sync_item->ToString(); } 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 ResourceDispatcherHostImpl::IsTransferredNavigation( const GlobalRequestID& transferred_request_id) const { return transferred_navigations_.find(transferred_request_id) != transferred_navigations_.end(); } 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 jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; cmpt = 0; if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { goto error; } if (!jas_safe_intfast32_add(tlx, width, 0) || !jas_safe_intfast32_add(tly, height, 0)) { goto error; } if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) || !jas_safe_size_mul(size, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (size > 0) { if (size - 1 > LONG_MAX) { goto error; } if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; } CWE ID: CWE-190 Target: 1 Example 2: Code: MagickExport const ModuleInfo **GetModuleInfoList(const char *pattern, size_t *number_modules,ExceptionInfo *exception) { const ModuleInfo **modules; register const ModuleInfo *p; register ssize_t i; /* Allocate module list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_modules != (size_t *) NULL); *number_modules=0; p=GetModuleInfo("*",exception); if (p == (const ModuleInfo *) NULL) return((const ModuleInfo **) NULL); modules=(const ModuleInfo **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(module_list)+1UL,sizeof(*modules)); if (modules == (const ModuleInfo **) NULL) return((const ModuleInfo **) NULL); /* Generate module list. */ LockSemaphoreInfo(module_semaphore); ResetSplayTreeIterator(module_list); p=(const ModuleInfo *) GetNextValueInSplayTree(module_list); for (i=0; p != (const ModuleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickFalse) != MagickFalse)) modules[i++]=p; p=(const ModuleInfo *) GetNextValueInSplayTree(module_list); } UnlockSemaphoreInfo(module_semaphore); qsort((void *) modules,(size_t) i,sizeof(*modules),ModuleInfoCompare); modules[i]=(ModuleInfo *) NULL; *number_modules=(size_t) i; return(modules); } CWE ID: CWE-22 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void UrlFetcher::Core::Detach() { DCHECK(delegate_message_loop_->BelongsToCurrentThread()); network_task_runner_->PostTask( FROM_HERE, base::Bind(&UrlFetcher::Core::CancelRequest, this)); done_callback_.Reset(); } 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 pptp_bind(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len) { struct sock *sk = sock->sk; struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr; struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; int error = 0; lock_sock(sk); opt->src_addr = sp->sa_addr.pptp; if (add_chan(po)) error = -EBUSY; release_sock(sk); return error; } CWE ID: CWE-200 Target: 1 Example 2: Code: static int local_closedir(FsContext *ctx, V9fsFidOpenState *fs) { return closedir(fs->dir.stream); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TestLoadTimingReusedWithPac(const net::LoadTimingInfo& load_timing_info) { EXPECT_TRUE(load_timing_info.socket_reused); EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id); net::ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing); EXPECT_FALSE(load_timing_info.proxy_resolve_start.is_null()); EXPECT_LE(load_timing_info.proxy_resolve_start, load_timing_info.proxy_resolve_end); EXPECT_LE(load_timing_info.proxy_resolve_end, load_timing_info.send_start); EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end); EXPECT_TRUE(load_timing_info.request_start_time.is_null()); EXPECT_TRUE(load_timing_info.request_start.is_null()); EXPECT_TRUE(load_timing_info.receive_headers_end.is_null()); } CWE ID: CWE-19 Output:
0