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 ServiceWorkerPaymentInstrument::OnPaymentAppInvoked( mojom::PaymentHandlerResponsePtr response) { DCHECK(delegate_); if (delegate_ != nullptr) { delegate_->OnInstrumentDetailsReady(response->method_name, response->stringified_details); delegate_ = nullptr; } } CWE ID: CWE-416 Target: 1 Example 2: Code: static inline int imgCoordMungeLowerC(SplashCoord x, GBool glyphMode) { return glyphMode ? (splashCeil(x + 0.5) - 1) : splashFloor(x); } 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 OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID, cmsUInt32Number n, cmsUInt32Number ColorantCount, const char* Prefix, const char* Suffix) { cmsNAMEDCOLORLIST* v = (cmsNAMEDCOLORLIST*) _cmsMallocZero(ContextID, sizeof(cmsNAMEDCOLORLIST)); if (v == NULL) return NULL; v ->List = NULL; v ->nColors = 0; v ->ContextID = ContextID; while (v -> Allocated < n) GrowNamedColorList(v); strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix)); strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix)); v->Prefix[32] = v->Suffix[32] = 0; v -> ColorantCount = ColorantCount; return v; } CWE ID: Target: 1 Example 2: Code: SWFInput_readBits(SWFInput input, int number) { int ret = input->buffer; if ( number == input->bufbits ) { input->bufbits = 0; input->buffer = 0; return ret; } if ( number > input->bufbits ) { number -= input->bufbits; while( number > 8 ) { ret <<= 8; ret += SWFInput_getChar(input); number -= 8; } input->buffer = SWFInput_getChar(input); if ( number > 0 ) { ret <<= number; input->bufbits = 8-number; ret += input->buffer >> (8-number); input->buffer &= (1<<input->bufbits)-1; } return ret; } ret = input->buffer >> (input->bufbits-number); input->bufbits -= number; input->buffer &= (1<<input->bufbits)-1; return ret; } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int dns_resolver_match_preparse(struct key_match_data *match_data) { match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE; match_data->cmp = dns_resolver_cmp; return 0; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *error; zend_string *stub; size_t index_len = 0, webindex_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); return; } RETURN_NEW_STR(stub); } CWE ID: CWE-20 Target: 1 Example 2: Code: BrowserFrameGtk::~BrowserFrameGtk() { } 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: long long Cluster::GetLastTime() const { const BlockEntry* pEntry; const long status = GetLast(pEntry); if (status < 0) //error return status; if (pEntry == NULL) //empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int handle(int s, unsigned char* data, int len, struct sockaddr_in *s_in) { char buf[2048]; unsigned short *cmd = (unsigned short *)buf; int plen; struct in_addr *addr = &s_in->sin_addr; unsigned short *pid = (unsigned short*) data; /* inet check */ if (len == S_HELLO_LEN && memcmp(data, "sorbo", 5) == 0) { unsigned short *id = (unsigned short*) (data+5); int x = 2+4+2; *cmd = htons(S_CMD_INET_CHECK); memcpy(cmd+1, addr, 4); memcpy(cmd+1+2, id, 2); printf("Inet check by %s %d\n", inet_ntoa(*addr), ntohs(*id)); if (send(s, buf, x, 0) != x) return 1; return 0; } *cmd++ = htons(S_CMD_PACKET); *cmd++ = *pid; plen = len - 2; last_id = ntohs(*pid); if (last_id > 20000) wrap = 1; if (wrap && last_id < 100) { wrap = 0; memset(ids, 0, sizeof(ids)); } printf("Got packet %d %d", last_id, plen); if (is_dup(last_id)) { printf(" (DUP)\n"); return 0; } printf("\n"); *cmd++ = htons(plen); memcpy(cmd, data+2, plen); plen += 2 + 2 + 2; assert(plen <= (int) sizeof(buf)); if (send(s, buf, plen, 0) != plen) return 1; return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: InitializeSprite(DeviceIntPtr pDev, WindowPtr pWin) { SpritePtr pSprite; ScreenPtr pScreen; CursorPtr pCursor; if (!pDev->spriteInfo->sprite) { DeviceIntPtr it; pDev->spriteInfo->sprite = (SpritePtr) calloc(1, sizeof(SpriteRec)); if (!pDev->spriteInfo->sprite) FatalError("InitializeSprite: failed to allocate sprite struct"); /* We may have paired another device with this device before our * device had a actual sprite. We need to check for this and reset the * sprite field for all paired devices. * * The VCK is always paired with the VCP before the VCP has a sprite. */ for (it = inputInfo.devices; it; it = it->next) { if (it->spriteInfo->paired == pDev) it->spriteInfo->sprite = pDev->spriteInfo->sprite; } if (inputInfo.keyboard->spriteInfo->paired == pDev) inputInfo.keyboard->spriteInfo->sprite = pDev->spriteInfo->sprite; } pSprite = pDev->spriteInfo->sprite; pDev->spriteInfo->spriteOwner = TRUE; pScreen = (pWin) ? pWin->drawable.pScreen : (ScreenPtr) NULL; pSprite->hot.pScreen = pScreen; pSprite->hotPhys.pScreen = pScreen; if (pScreen) { pSprite->hotPhys.x = pScreen->width / 2; pSprite->hotPhys.y = pScreen->height / 2; pSprite->hotLimits.x2 = pScreen->width; pSprite->hotLimits.y2 = pScreen->height; } pSprite->hot = pSprite->hotPhys; pSprite->win = pWin; if (pWin) { pCursor = wCursor(pWin); pSprite->spriteTrace = (WindowPtr *) calloc(1, 32 * sizeof(WindowPtr)); if (!pSprite->spriteTrace) FatalError("Failed to allocate spriteTrace"); pSprite->spriteTraceSize = 32; RootWindow(pDev->spriteInfo->sprite) = pWin; pSprite->spriteTraceGood = 1; pSprite->pEnqueueScreen = pScreen; pSprite->pDequeueScreen = pSprite->pEnqueueScreen; } else { pCursor = NullCursor; pSprite->spriteTrace = NULL; pSprite->spriteTraceSize = 0; pSprite->spriteTraceGood = 0; pSprite->pEnqueueScreen = screenInfo.screens[0]; pSprite->pDequeueScreen = pSprite->pEnqueueScreen; } pCursor = RefCursor(pCursor); if (pSprite->current) FreeCursor(pSprite->current, None); pSprite->current = pCursor; if (pScreen) { (*pScreen->RealizeCursor) (pDev, pScreen, pSprite->current); (*pScreen->CursorLimits) (pDev, pScreen, pSprite->current, &pSprite->hotLimits, &pSprite->physLimits); pSprite->confined = FALSE; (*pScreen->ConstrainCursor) (pDev, pScreen, &pSprite->physLimits); (*pScreen->SetCursorPosition) (pDev, pScreen, pSprite->hot.x, pSprite->hot.y, FALSE); (*pScreen->DisplayCursor) (pDev, pScreen, pSprite->current); } #ifdef PANORAMIX if (!noPanoramiXExtension) { pSprite->hotLimits.x1 = -screenInfo.screens[0]->x; pSprite->hotLimits.y1 = -screenInfo.screens[0]->y; pSprite->hotLimits.x2 = PanoramiXPixWidth - screenInfo.screens[0]->x; pSprite->hotLimits.y2 = PanoramiXPixHeight - screenInfo.screens[0]->y; pSprite->physLimits = pSprite->hotLimits; pSprite->confineWin = NullWindow; pSprite->hotShape = NullRegion; pSprite->screen = pScreen; /* gotta UNINIT these someplace */ RegionNull(&pSprite->Reg1); RegionNull(&pSprite->Reg2); } #endif } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int NsSetParameter (preproc_effect_t *effect, void *pParam, void *pValue) { int status = 0; return status; } 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 InspectorPageAgent::setDeviceOrientationOverride(ErrorString* error, double alpha, double beta, double gamma) { DeviceOrientationController* controller = DeviceOrientationController::from(mainFrame()->document()); if (!controller) { *error = "Internal error: unable to override device orientation"; return; } controller->didChangeDeviceOrientation(DeviceOrientationData::create(true, alpha, true, beta, true, gamma).get()); } CWE ID: Target: 1 Example 2: Code: static void __d_instantiate(struct dentry *dentry, struct inode *inode) { unsigned add_flags = d_flags_for_inode(inode); WARN_ON(d_in_lookup(dentry)); spin_lock(&dentry->d_lock); hlist_add_head(&dentry->d_u.d_alias, &inode->i_dentry); raw_write_seqcount_begin(&dentry->d_seq); __d_set_inode_and_type(dentry, inode, add_flags); raw_write_seqcount_end(&dentry->d_seq); fsnotify_update_flags(dentry); spin_unlock(&dentry->d_lock); } 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 CorePageLoadMetricsObserver::OnCommit( content::NavigationHandle* navigation_handle) { transition_ = navigation_handle->GetPageTransition(); initiated_by_user_gesture_ = navigation_handle->HasUserGesture(); } 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: valid_host(cupsd_client_t *con) /* I - Client connection */ { cupsd_alias_t *a; /* Current alias */ cupsd_netif_t *netif; /* Current network interface */ const char *end; /* End character */ char *ptr; /* Pointer into host value */ /* * Copy the Host: header for later use... */ strlcpy(con->clientname, httpGetField(con->http, HTTP_FIELD_HOST), sizeof(con->clientname)); if ((ptr = strrchr(con->clientname, ':')) != NULL && !strchr(ptr, ']')) { *ptr++ = '\0'; con->clientport = atoi(ptr); } else con->clientport = con->serverport; /* * Then validate... */ if (httpAddrLocalhost(httpGetAddress(con->http))) { /* * Only allow "localhost" or the equivalent IPv4 or IPv6 numerical * addresses when accessing CUPS via the loopback interface... */ return (!_cups_strcasecmp(con->clientname, "localhost") || !_cups_strcasecmp(con->clientname, "localhost.") || #ifdef __linux !_cups_strcasecmp(con->clientname, "localhost.localdomain") || #endif /* __linux */ !strcmp(con->clientname, "127.0.0.1") || !strcmp(con->clientname, "[::1]")); } #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI) /* * Check if the hostname is something.local (Bonjour); if so, allow it. */ if ((end = strrchr(con->clientname, '.')) != NULL && end > con->clientname && !end[1]) { /* * "." on end, work back to second-to-last "."... */ for (end --; end > con->clientname && *end != '.'; end --); } if (end && (!_cups_strcasecmp(end, ".local") || !_cups_strcasecmp(end, ".local."))) return (1); #endif /* HAVE_DNSSD || HAVE_AVAHI */ /* * Check if the hostname is an IP address... */ if (isdigit(con->clientname[0] & 255) || con->clientname[0] == '[') { /* * Possible IPv4/IPv6 address... */ http_addrlist_t *addrlist; /* List of addresses */ if ((addrlist = httpAddrGetList(con->clientname, AF_UNSPEC, NULL)) != NULL) { /* * Good IPv4/IPv6 address... */ httpAddrFreeList(addrlist); return (1); } } /* * Check for (alias) name matches... */ for (a = (cupsd_alias_t *)cupsArrayFirst(ServerAlias); a; a = (cupsd_alias_t *)cupsArrayNext(ServerAlias)) { /* * "ServerAlias *" allows all host values through... */ if (!strcmp(a->name, "*")) return (1); if (!_cups_strncasecmp(con->clientname, a->name, a->namelen)) { /* * Prefix matches; check the character at the end - it must be "." or nul. */ end = con->clientname + a->namelen; if (!*end || (*end == '.' && !end[1])) return (1); } } #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI) for (a = (cupsd_alias_t *)cupsArrayFirst(DNSSDAlias); a; a = (cupsd_alias_t *)cupsArrayNext(DNSSDAlias)) { /* * "ServerAlias *" allows all host values through... */ if (!strcmp(a->name, "*")) return (1); if (!_cups_strncasecmp(con->clientname, a->name, a->namelen)) { /* * Prefix matches; check the character at the end - it must be "." or nul. */ end = con->clientname + a->namelen; if (!*end || (*end == '.' && !end[1])) return (1); } } #endif /* HAVE_DNSSD || HAVE_AVAHI */ /* * Check for interface hostname matches... */ for (netif = (cupsd_netif_t *)cupsArrayFirst(NetIFList); netif; netif = (cupsd_netif_t *)cupsArrayNext(NetIFList)) { if (!_cups_strncasecmp(con->clientname, netif->hostname, netif->hostlen)) { /* * Prefix matches; check the character at the end - it must be "." or nul. */ end = con->clientname + netif->hostlen; if (!*end || (*end == '.' && !end[1])) return (1); } } return (0); } CWE ID: CWE-290 Target: 1 Example 2: Code: GF_Err moov_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e; e = gf_isom_box_array_read(s, bs, moov_AddBox); if (e) { return e; } else { if (!((GF_MovieBox *)s)->mvhd) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MovieHeaderBox\n")); return GF_ISOM_INVALID_FILE; } } return e; } 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: SYSCALL_DEFINE3(shmctl, int, shmid, int, cmd, struct shmid_ds __user *, buf) { struct shmid_kernel *shp; int err, version; struct ipc_namespace *ns; if (cmd < 0 || shmid < 0) return -EINVAL; version = ipc_parse_version(&cmd); ns = current->nsproxy->ipc_ns; switch (cmd) { case IPC_INFO: case SHM_INFO: case SHM_STAT: case IPC_STAT: return shmctl_nolock(ns, shmid, cmd, version, buf); case IPC_RMID: case IPC_SET: return shmctl_down(ns, shmid, cmd, buf, version); case SHM_LOCK: case SHM_UNLOCK: { struct file *shm_file; rcu_read_lock(); shp = shm_obtain_object_check(ns, shmid); if (IS_ERR(shp)) { err = PTR_ERR(shp); goto out_unlock1; } audit_ipc_obj(&(shp->shm_perm)); err = security_shm_shmctl(shp, cmd); if (err) goto out_unlock1; ipc_lock_object(&shp->shm_perm); if (!ns_capable(ns->user_ns, CAP_IPC_LOCK)) { kuid_t euid = current_euid(); err = -EPERM; if (!uid_eq(euid, shp->shm_perm.uid) && !uid_eq(euid, shp->shm_perm.cuid)) goto out_unlock0; if (cmd == SHM_LOCK && !rlimit(RLIMIT_MEMLOCK)) goto out_unlock0; } shm_file = shp->shm_file; if (is_file_hugepages(shm_file)) goto out_unlock0; if (cmd == SHM_LOCK) { struct user_struct *user = current_user(); err = shmem_lock(shm_file, 1, user); if (!err && !(shp->shm_perm.mode & SHM_LOCKED)) { shp->shm_perm.mode |= SHM_LOCKED; shp->mlock_user = user; } goto out_unlock0; } /* SHM_UNLOCK */ if (!(shp->shm_perm.mode & SHM_LOCKED)) goto out_unlock0; shmem_lock(shm_file, 0, shp->mlock_user); shp->shm_perm.mode &= ~SHM_LOCKED; shp->mlock_user = NULL; get_file(shm_file); ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); shmem_unlock_mapping(shm_file->f_mapping); fput(shm_file); return err; } default: return -EINVAL; } out_unlock0: ipc_unlock_object(&shp->shm_perm); out_unlock1: rcu_read_unlock(); return err; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BluetoothDeviceChooserController::PostErrorCallback( blink::mojom::WebBluetoothResult error) { if (!base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(error_callback_, error))) { LOG(WARNING) << "No TaskRunner."; } } CWE ID: CWE-119 Target: 1 Example 2: Code: void vhost_dev_init(struct vhost_dev *dev, struct vhost_virtqueue **vqs, int nvqs) { struct vhost_virtqueue *vq; int i; dev->vqs = vqs; dev->nvqs = nvqs; mutex_init(&dev->mutex); dev->log_ctx = NULL; dev->log_file = NULL; dev->memory = NULL; dev->mm = NULL; spin_lock_init(&dev->work_lock); INIT_LIST_HEAD(&dev->work_list); dev->worker = NULL; for (i = 0; i < dev->nvqs; ++i) { vq = dev->vqs[i]; vq->log = NULL; vq->indirect = NULL; vq->heads = NULL; vq->dev = dev; mutex_init(&vq->mutex); vhost_vq_reset(dev, vq); if (vq->handle_kick) vhost_poll_init(&vq->poll, vq->handle_kick, POLLIN, dev); } } 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: set_default_smtp_connection_timeout(data_t * data) { data->smtp_connection_to = DEFAULT_SMTP_CONNECTION_TIMEOUT; } 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 CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const { ParaNdis_CheckSumVerifyFlat(IpHeader, EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum, __FUNCTION__); } CWE ID: CWE-20 Target: 1 Example 2: Code: static jint android_net_wifi_doIntCommand(JNIEnv* env, jobject, jstring javaCommand) { return doIntCommand(env, javaCommand); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb1; u32 seq, end_seq; tcp_ecn_check_ce(tp, skb); if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFODROP); tcp_drop(sk, skb); return; } /* Disable header prediction. */ tp->pred_flags = 0; inet_csk_schedule_ack(sk); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOQUEUE); SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); skb1 = skb_peek_tail(&tp->out_of_order_queue); if (!skb1) { /* Initial out of order segment, build 1 SACK. */ if (tcp_is_sack(tp)) { tp->rx_opt.num_sacks = 1; tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq; tp->selective_acks[0].end_seq = TCP_SKB_CB(skb)->end_seq; } __skb_queue_head(&tp->out_of_order_queue, skb); goto end; } seq = TCP_SKB_CB(skb)->seq; end_seq = TCP_SKB_CB(skb)->end_seq; if (seq == TCP_SKB_CB(skb1)->end_seq) { bool fragstolen; if (!tcp_try_coalesce(sk, skb1, skb, &fragstolen)) { __skb_queue_after(&tp->out_of_order_queue, skb1, skb); } else { tcp_grow_window(sk, skb); kfree_skb_partial(skb, fragstolen); skb = NULL; } if (!tp->rx_opt.num_sacks || tp->selective_acks[0].end_seq != seq) goto add_sack; /* Common case: data arrive in order after hole. */ tp->selective_acks[0].end_seq = end_seq; goto end; } /* Find place to insert this segment. */ while (1) { if (!after(TCP_SKB_CB(skb1)->seq, seq)) break; if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) { skb1 = NULL; break; } skb1 = skb_queue_prev(&tp->out_of_order_queue, skb1); } /* Do skb overlap to previous one? */ if (skb1 && before(seq, TCP_SKB_CB(skb1)->end_seq)) { if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) { /* All the bits are present. Drop. */ NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE); tcp_drop(sk, skb); skb = NULL; tcp_dsack_set(sk, seq, end_seq); goto add_sack; } if (after(seq, TCP_SKB_CB(skb1)->seq)) { /* Partial overlap. */ tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq); } else { if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) skb1 = NULL; else skb1 = skb_queue_prev( &tp->out_of_order_queue, skb1); } } if (!skb1) __skb_queue_head(&tp->out_of_order_queue, skb); else __skb_queue_after(&tp->out_of_order_queue, skb1, skb); /* And clean segments covered by new one as whole. */ while (!skb_queue_is_last(&tp->out_of_order_queue, skb)) { skb1 = skb_queue_next(&tp->out_of_order_queue, skb); if (!after(end_seq, TCP_SKB_CB(skb1)->seq)) break; if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) { tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq, end_seq); break; } __skb_unlink(skb1, &tp->out_of_order_queue); tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq, TCP_SKB_CB(skb1)->end_seq); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE); tcp_drop(sk, skb1); } add_sack: if (tcp_is_sack(tp)) tcp_sack_new_ofo_skb(sk, seq, end_seq); end: if (skb) { tcp_grow_window(sk, skb); skb_set_owner_r(skb, sk); } } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AppControllerImpl::LaunchApp(const std::string& app_id) { app_service_proxy_->Launch(app_id, ui::EventFlags::EF_NONE, apps::mojom::LaunchSource::kFromAppListGrid, display::kDefaultDisplayId); } CWE ID: CWE-416 Target: 1 Example 2: Code: bitsubstr_no_len(PG_FUNCTION_ARGS) { PG_RETURN_VARBIT_P(bitsubstring(PG_GETARG_VARBIT_P(0), PG_GETARG_INT32(1), -1, true)); } 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 BluetoothDeviceChromeOS::OnUnregisterAgentError( const std::string& error_name, const std::string& error_message) { LOG(WARNING) << object_path_.value() << ": Failed to unregister agent: " << error_name << ": " << error_message; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void __munlock_pagevec(struct pagevec *pvec, struct zone *zone) { int i; int nr = pagevec_count(pvec); int delta_munlocked; struct pagevec pvec_putback; int pgrescued = 0; pagevec_init(&pvec_putback, 0); /* Phase 1: page isolation */ spin_lock_irq(zone_lru_lock(zone)); for (i = 0; i < nr; i++) { struct page *page = pvec->pages[i]; if (TestClearPageMlocked(page)) { /* * We already have pin from follow_page_mask() * so we can spare the get_page() here. */ if (__munlock_isolate_lru_page(page, false)) continue; else __munlock_isolation_failed(page); } /* * We won't be munlocking this page in the next phase * but we still need to release the follow_page_mask() * pin. We cannot do it under lru_lock however. If it's * the last pin, __page_cache_release() would deadlock. */ pagevec_add(&pvec_putback, pvec->pages[i]); pvec->pages[i] = NULL; } delta_munlocked = -nr + pagevec_count(&pvec_putback); __mod_zone_page_state(zone, NR_MLOCK, delta_munlocked); spin_unlock_irq(zone_lru_lock(zone)); /* Now we can release pins of pages that we are not munlocking */ pagevec_release(&pvec_putback); /* Phase 2: page munlock */ for (i = 0; i < nr; i++) { struct page *page = pvec->pages[i]; if (page) { lock_page(page); if (!__putback_lru_fast_prepare(page, &pvec_putback, &pgrescued)) { /* * Slow path. We don't want to lose the last * pin before unlock_page() */ get_page(page); /* for putback_lru_page() */ __munlock_isolated_page(page); unlock_page(page); put_page(page); /* from follow_page_mask() */ } } } /* * Phase 3: page putback for pages that qualified for the fast path * This will also call put_page() to return pin from follow_page_mask() */ if (pagevec_count(&pvec_putback)) __putback_lru_fast(&pvec_putback, pgrescued); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void rfc4106_exit(struct crypto_tfm *tfm) { struct aesni_rfc4106_gcm_ctx *ctx = (struct aesni_rfc4106_gcm_ctx *) PTR_ALIGN((u8 *)crypto_tfm_ctx(tfm), AESNI_ALIGN); if (!IS_ERR(ctx->cryptd_tfm)) cryptd_free_aead(ctx->cryptd_tfm); 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: static int movw_pcdisp_reg(RAnal* anal, RAnalOp* op, ut16 code){ op->type = R_ANAL_OP_TYPE_LOAD; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); op->src[0] = anal_pcrel_disp_mov (anal, op, code&0xFF, WORD_SIZE); return op->size; } 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: PHP_FUNCTION( msgfmt_format_message ) { zval *args; UChar *spattern = NULL; int spattern_len = 0; char *pattern = NULL; int pattern_len = 0; const char *slocale = NULL; int slocale_len = 0; MessageFormatter_object mf = {0}; MessageFormatter_object *mfo = &mf; /* Parse parameters. */ if( zend_parse_method_parameters( ZEND_NUM_ARGS() TSRMLS_CC, getThis(), "ssa", &slocale, &slocale_len, &pattern, &pattern_len, &args ) == FAILURE ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "msgfmt_format_message: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } msgformat_data_init(&mfo->mf_data TSRMLS_CC); if(pattern && pattern_len) { intl_convert_utf8_to_utf16(&spattern, &spattern_len, pattern, pattern_len, &INTL_DATA_ERROR_CODE(mfo)); if( U_FAILURE(INTL_DATA_ERROR_CODE((mfo))) ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "msgfmt_format_message: error converting pattern to UTF-16", 0 TSRMLS_CC ); RETURN_FALSE; } } else { spattern_len = 0; spattern = NULL; } if(slocale_len == 0) { slocale = intl_locale_get_default(TSRMLS_C); } #ifdef MSG_FORMAT_QUOTE_APOS if(msgformat_fix_quotes(&spattern, &spattern_len, &INTL_DATA_ERROR_CODE(mfo)) != SUCCESS) { intl_error_set( NULL, U_INVALID_FORMAT_ERROR, "msgfmt_format_message: error converting pattern to quote-friendly format", 0 TSRMLS_CC ); RETURN_FALSE; } #endif /* Create an ICU message formatter. */ MSG_FORMAT_OBJECT(mfo) = umsg_open(spattern, spattern_len, slocale, NULL, &INTL_DATA_ERROR_CODE(mfo)); if(spattern && spattern_len) { efree(spattern); } INTL_METHOD_CHECK_STATUS(mfo, "Creating message formatter failed"); msgfmt_do_format(mfo, args, return_value TSRMLS_CC); /* drop the temporary formatter */ msgformat_data_free(&mfo->mf_data TSRMLS_CC); } CWE ID: CWE-119 Target: 1 Example 2: Code: void LockContentsView::CreateLowDensityLayout( const std::vector<mojom::LoginUserInfoPtr>& users) { DCHECK_EQ(users.size(), 2u); main_view_->AddChildView(MakeOrientationViewWithWidths( kLowDensityDistanceBetweenUsersInLandscapeDp, kLowDensityDistanceBetweenUsersInPortraitDp)); opt_secondary_big_view_ = AllocateLoginBigUserView(users[1], false /*is_primary*/); main_view_->AddChildView(opt_secondary_big_view_); } 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 MediaControlsProgressView::HandleSeeking( const gfx::Point& location_in_bar) { double seek_to_progress = static_cast<double>(location_in_bar.x()) / progress_bar_->width(); seek_callback_.Run(seek_to_progress); } 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: mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir, const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt) { /* * Note: FILE_SEARCH and FILE_REGEX do not actually copy * anything, but setup pointers into the source */ if (indir == 0) { switch (type) { case FILE_SEARCH: ms->search.s = RCAST(const char *, s) + offset; ms->search.s_len = nbytes - offset; ms->search.offset = offset; return 0; case FILE_REGEX: { const char *b; const char *c; const char *last; /* end of search region */ const char *buf; /* start of search region */ const char *end; size_t lines; if (s == NULL) { ms->search.s_len = 0; ms->search.s = NULL; return 0; } buf = RCAST(const char *, s) + offset; end = last = RCAST(const char *, s) + nbytes; /* mget() guarantees buf <= last */ for (lines = linecnt, b = buf; lines && b < end && ((b = CAST(const char *, memchr(c = b, '\n', CAST(size_t, (end - b))))) || (b = CAST(const char *, memchr(c, '\r', CAST(size_t, (end - c)))))); lines--, b++) { last = b; if (b[0] == '\r' && b[1] == '\n') b++; } if (lines) last = RCAST(const char *, s) + nbytes; ms->search.s = buf; ms->search.s_len = last - buf; ms->search.offset = offset; ms->search.rm_len = 0; return 0; } case FILE_BESTRING16: case FILE_LESTRING16: { const unsigned char *src = s + offset; const unsigned char *esrc = s + nbytes; char *dst = p->s; char *edst = &p->s[sizeof(p->s) - 1]; if (type == FILE_BESTRING16) src++; /* check that offset is within range */ if (offset >= nbytes) break; for (/*EMPTY*/; src < esrc; src += 2, dst++) { if (dst < edst) *dst = *src; else break; if (*dst == '\0') { if (type == FILE_BESTRING16 ? *(src - 1) != '\0' : *(src + 1) != '\0') *dst = ' '; } } *edst = '\0'; return 0; } case FILE_STRING: /* XXX - these two should not need */ case FILE_PSTRING: /* to copy anything, but do anyway. */ default: break; } } if (offset >= nbytes) { (void)memset(p, '\0', sizeof(*p)); return 0; } if (nbytes - offset < sizeof(*p)) nbytes = nbytes - offset; else nbytes = sizeof(*p); (void)memcpy(p, s + offset, nbytes); /* * the usefulness of padding with zeroes eludes me, it * might even cause problems */ if (nbytes < sizeof(*p)) (void)memset(((char *)(void *)p) + nbytes, '\0', sizeof(*p) - nbytes); return 0; } CWE ID: CWE-399 Target: 1 Example 2: Code: float RenderViewImpl::GetDeviceScaleFactor() const { return device_scale_factor_; } 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: ImportArrayTIFF_Rational ( const TIFF_Manager::TagInfo & tagInfo, const bool nativeEndian, SXMPMeta * xmp, const char * xmpNS, const char * xmpProp ) { try { // Don't let errors with one stop the others. XMP_Uns32 * binPtr = (XMP_Uns32*)tagInfo.dataPtr; xmp->DeleteProperty ( xmpNS, xmpProp ); // ! Don't keep appending, create a new array. for ( size_t i = 0; i < tagInfo.count; ++i, binPtr += 2 ) { XMP_Uns32 binNum = GetUns32AsIs ( &binPtr[0] ); XMP_Uns32 binDenom = GetUns32AsIs ( &binPtr[1] ); if ( ! nativeEndian ) { binNum = Flip4 ( binNum ); binDenom = Flip4 ( binDenom ); } char strValue[40]; snprintf ( strValue, sizeof(strValue), "%lu/%lu", (unsigned long)binNum, (unsigned long)binDenom ); // AUDIT: Using sizeof(strValue) is safe. xmp->AppendArrayItem ( xmpNS, xmpProp, kXMP_PropArrayIsOrdered, strValue ); } } catch ( ... ) { } } // ImportArrayTIFF_Rational 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 HTMLInputElement::HandleFocusEvent(Element* old_focused_element, WebFocusType type) { input_type_->EnableSecureTextInput(); } CWE ID: Target: 1 Example 2: Code: frobnicate_signal_handler (DBusGProxy *proxy, int val, void *user_data) { n_times_frobnicate_received += 1; g_assert (val == 42); g_print ("Got Frobnicate signal\n"); g_main_loop_quit (loop); g_source_remove (exit_timeout); } 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 ResetPaddingKeyForTesting() { *GetPaddingKey() = SymmetricKey::GenerateRandomKey(kPaddingKeyAlgorithm, 128); } 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: void BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl() { element()->setFocus(true); } CWE ID: CWE-399 Target: 1 Example 2: Code: void Document::ProcessBaseElement() { UseCounter::Count(*this, WebFeature::kBaseElement); const AtomicString* href = nullptr; const AtomicString* target = nullptr; for (HTMLBaseElement* base = Traversal<HTMLBaseElement>::FirstWithin(*this); base && (!href || !target); base = Traversal<HTMLBaseElement>::Next(*base)) { if (!href) { const AtomicString& value = base->FastGetAttribute(kHrefAttr); if (!value.IsNull()) href = &value; } if (!target) { const AtomicString& value = base->FastGetAttribute(kTargetAttr); if (!value.IsNull()) target = &value; } if (GetContentSecurityPolicy()->IsActive()) { UseCounter::Count(*this, WebFeature::kContentSecurityPolicyWithBaseElement); } } KURL base_element_url; if (href) { String stripped_href = StripLeadingAndTrailingHTMLSpaces(*href); if (!stripped_href.IsEmpty()) base_element_url = KURL(FallbackBaseURL(), stripped_href); } if (!base_element_url.IsEmpty()) { if (base_element_url.ProtocolIsData() || base_element_url.ProtocolIsJavaScript()) { UseCounter::Count(*this, WebFeature::kBaseWithDataHref); AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "'" + base_element_url.Protocol() + "' URLs may not be used as base URLs for a document.")); } if (!GetSecurityOrigin()->CanRequest(base_element_url)) UseCounter::Count(*this, WebFeature::kBaseWithCrossOriginHref); } if (base_element_url != base_element_url_ && !base_element_url.ProtocolIsData() && !base_element_url.ProtocolIsJavaScript() && GetContentSecurityPolicy()->AllowBaseURI(base_element_url)) { base_element_url_ = base_element_url; UpdateBaseURL(); } if (target) { if (target->Contains('\n') || target->Contains('\r')) UseCounter::Count(*this, WebFeature::kBaseWithNewlinesInTarget); if (target->Contains('<')) UseCounter::Count(*this, WebFeature::kBaseWithOpenBracketInTarget); base_target_ = *target; } else { base_target_ = g_null_atom; } } 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 MultibufferDataSource::HasSingleOrigin() { DCHECK(render_task_runner_->BelongsToCurrentThread()); return single_origin_; } 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: const ClipPaintPropertyNode* c0() { return ClipPaintPropertyNode::Root(); } CWE ID: Target: 1 Example 2: Code: ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix) { struct pci_dev *pdev = vdev->pdev; unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; int ret; if (!is_irq_none(vdev)) return -EINVAL; vdev->ctx = kzalloc(nvec * sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; /* return the number of supported vectors if we can't get all: */ ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag); if (ret < nvec) { if (ret > 0) pci_free_irq_vectors(pdev); kfree(vdev->ctx); return ret; } vdev->num_ctx = nvec; vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; if (!msix) { /* * Compute the virtual hardware field for max msi vectors - * it is the log base 2 of the number of vectors. */ vdev->msi_qmax = fls(nvec * 2 - 1) - 1; } return 0; } 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: mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m); size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) len = sizeof(p->s) - 1; while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } } CWE ID: CWE-119 Target: 1 Example 2: Code: StatNodeRef stat_add_node(StatNodeRef parent, const char *name, int visible) { StatNodeRef ref; SpiceStatNode *node; spice_assert(name && strlen(name) > 0); if (strlen(name) >= sizeof(node->name)) { return INVALID_STAT_REF; } pthread_mutex_lock(&reds->stat_lock); ref = (parent == INVALID_STAT_REF ? reds->stat->root_index : reds->stat->nodes[parent].first_child_index); while (ref != INVALID_STAT_REF) { node = &reds->stat->nodes[ref]; if (strcmp(name, node->name)) { ref = node->next_sibling_index; } else { pthread_mutex_unlock(&reds->stat_lock); return ref; } } if (reds->stat->num_of_nodes >= REDS_MAX_STAT_NODES || reds->stat == NULL) { pthread_mutex_unlock(&reds->stat_lock); return INVALID_STAT_REF; } reds->stat->generation++; reds->stat->num_of_nodes++; for (ref = 0; ref <= REDS_MAX_STAT_NODES; ref++) { node = &reds->stat->nodes[ref]; if (!(node->flags & SPICE_STAT_NODE_FLAG_ENABLED)) { break; } } spice_assert(!(node->flags & SPICE_STAT_NODE_FLAG_ENABLED)); node->value = 0; node->flags = SPICE_STAT_NODE_FLAG_ENABLED | (visible ? SPICE_STAT_NODE_FLAG_VISIBLE : 0); g_strlcpy(node->name, name, sizeof(node->name)); insert_stat_node(parent, ref); pthread_mutex_unlock(&reds->stat_lock); return ref; } 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: GfxImageColorMap::GfxImageColorMap(int bitsA, Object *decode, GfxColorSpace *colorSpaceA) { GfxIndexedColorSpace *indexedCS; GfxSeparationColorSpace *sepCS; int maxPixel, indexHigh; Guchar *lookup2; Function *sepFunc; Object obj; double x[gfxColorMaxComps]; double y[gfxColorMaxComps]; int i, j, k, byte; double mapped; ok = gTrue; bits = bitsA; maxPixel = (1 << bits) - 1; colorSpace = colorSpaceA; if (maxPixel > 255) maxPixel = 255; for (k = 0; k < gfxColorMaxComps; ++k) { lookup[k] = NULL; } if (decode->isNull()) { nComps = colorSpace->getNComps(); colorSpace->getDefaultRanges(decodeLow, decodeRange, maxPixel); } else if (decode->isArray()) { nComps = decode->arrayGetLength() / 2; if (nComps != colorSpace->getNComps()) { goto err1; } for (i = 0; i < nComps; ++i) { decode->arrayGet(2*i, &obj); if (!obj.isNum()) { goto err2; } decodeLow[i] = obj.getNum(); obj.free(); decode->arrayGet(2*i+1, &obj); if (!obj.isNum()) { goto err2; } decodeRange[i] = obj.getNum() - decodeLow[i]; obj.free(); } } else { goto err1; } colorSpace2 = NULL; nComps2 = 0; if (colorSpace->getMode() == csIndexed) { indexedCS = (GfxIndexedColorSpace *)colorSpace; colorSpace2 = indexedCS->getBase(); indexHigh = indexedCS->getIndexHigh(); nComps2 = colorSpace2->getNComps(); lookup2 = indexedCS->getLookup(); colorSpace2->getDefaultRanges(x, y, indexHigh); byte_lookup = (Guchar *)gmalloc ((maxPixel + 1) * nComps2); for (k = 0; k < nComps2; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { j = (int)(decodeLow[0] + (i * decodeRange[0]) / maxPixel + 0.5); if (j < 0) { j = 0; } else if (j > indexHigh) { j = indexHigh; } mapped = x[k] + (lookup2[j*nComps2 + k] / 255.0) * y[k]; lookup[k][i] = dblToCol(mapped); byte_lookup[i * nComps2 + k] = (Guchar) (mapped * 255); } } } else if (colorSpace->getMode() == csSeparation) { sepCS = (GfxSeparationColorSpace *)colorSpace; colorSpace2 = sepCS->getAlt(); nComps2 = colorSpace2->getNComps(); sepFunc = sepCS->getFunc(); byte_lookup = (Guchar *)gmallocn ((maxPixel + 1), nComps2); for (k = 0; k < nComps2; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { x[0] = decodeLow[0] + (i * decodeRange[0]) / maxPixel; sepFunc->transform(x, y); lookup[k][i] = dblToCol(y[k]); byte_lookup[i*nComps2 + k] = (Guchar) (y[k] * 255); } } } else { byte_lookup = (Guchar *)gmallocn ((maxPixel + 1), nComps); for (k = 0; k < nComps; ++k) { lookup[k] = (GfxColorComp *)gmallocn(maxPixel + 1, sizeof(GfxColorComp)); for (i = 0; i <= maxPixel; ++i) { mapped = decodeLow[k] + (i * decodeRange[k]) / maxPixel; lookup[k][i] = dblToCol(mapped); byte = (int) (mapped * 255.0 + 0.5); if (byte < 0) byte = 0; else if (byte > 255) byte = 255; byte_lookup[i * nComps + k] = byte; } } } return; err2: obj.free(); err1: ok = gFalse; byte_lookup = NULL; } 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: image_transform_png_set_rgb_to_gray_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { PNG_CONST int error_action = 1; /* no error, no defines in png.h */ # ifdef PNG_FLOATING_POINT_SUPPORTED png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set); # else png_set_rgb_to_gray_fixed(pp, error_action, data.red_to_set, data.green_to_set); # endif # ifdef PNG_READ_cHRM_SUPPORTED if (that->pm->current_encoding != 0) { /* We have an encoding so a cHRM chunk may have been set; if so then * check that the libpng APIs give the correct (X,Y,Z) values within * some margin of error for the round trip through the chromaticity * form. */ # ifdef PNG_FLOATING_POINT_SUPPORTED # define API_function png_get_cHRM_XYZ # define API_form "FP" # define API_type double # define API_cvt(x) (x) # else # define API_function png_get_cHRM_XYZ_fixed # define API_form "fixed" # define API_type png_fixed_point # define API_cvt(x) ((double)(x)/PNG_FP_1) # endif API_type rX, gX, bX; API_type rY, gY, bY; API_type rZ, gZ, bZ; if ((API_function(pp, pi, &rX, &rY, &rZ, &gX, &gY, &gZ, &bX, &bY, &bZ) & PNG_INFO_cHRM) != 0) { double maxe; PNG_CONST char *el; color_encoding e, o; /* Expect libpng to return a normalized result, but the original * color space encoding may not be normalized. */ modifier_current_encoding(that->pm, &o); normalize_color_encoding(&o); /* Sanity check the pngvalid code - the coefficients should match * the normalized Y values of the encoding unless they were * overridden. */ if (data.red_to_set == -1 && data.green_to_set == -1 && (fabs(o.red.Y - data.red_coefficient) > DBL_EPSILON || fabs(o.green.Y - data.green_coefficient) > DBL_EPSILON || fabs(o.blue.Y - data.blue_coefficient) > DBL_EPSILON)) png_error(pp, "internal pngvalid cHRM coefficient error"); /* Generate a colour space encoding. */ e.gamma = o.gamma; /* not used */ e.red.X = API_cvt(rX); e.red.Y = API_cvt(rY); e.red.Z = API_cvt(rZ); e.green.X = API_cvt(gX); e.green.Y = API_cvt(gY); e.green.Z = API_cvt(gZ); e.blue.X = API_cvt(bX); e.blue.Y = API_cvt(bY); e.blue.Z = API_cvt(bZ); /* This should match the original one from the png_modifier, within * the range permitted by the libpng fixed point representation. */ maxe = 0; el = "-"; /* Set to element name with error */ # define CHECK(col,x)\ {\ double err = fabs(o.col.x - e.col.x);\ if (err > maxe)\ {\ maxe = err;\ el = #col "(" #x ")";\ }\ } CHECK(red,X) CHECK(red,Y) CHECK(red,Z) CHECK(green,X) CHECK(green,Y) CHECK(green,Z) CHECK(blue,X) CHECK(blue,Y) CHECK(blue,Z) /* Here in both fixed and floating cases to check the values read * from the cHRm chunk. PNG uses fixed point in the cHRM chunk, so * we can't expect better than +/-.5E-5 on the result, allow 1E-5. */ if (maxe >= 1E-5) { size_t pos = 0; char buffer[256]; pos = safecat(buffer, sizeof buffer, pos, API_form); pos = safecat(buffer, sizeof buffer, pos, " cHRM "); pos = safecat(buffer, sizeof buffer, pos, el); pos = safecat(buffer, sizeof buffer, pos, " error: "); pos = safecatd(buffer, sizeof buffer, pos, maxe, 7); pos = safecat(buffer, sizeof buffer, pos, " "); /* Print the color space without the gamma value: */ pos = safecat_color_encoding(buffer, sizeof buffer, pos, &o, 0); pos = safecat(buffer, sizeof buffer, pos, " -> "); pos = safecat_color_encoding(buffer, sizeof buffer, pos, &e, 0); png_error(pp, buffer); } } } # endif /* READ_cHRM */ this->next->set(this->next, that, pp, pi); } CWE ID: Target: 1 Example 2: Code: u32 a_copy_from_user(void *to, const void *from, u32 n) { return(copy_from_user(to, from, n)); } 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: PHP_FUNCTION(mcrypt_module_open) { char *cipher, *cipher_dir; char *mode, *mode_dir; int cipher_len, cipher_dir_len; int mode_len, mode_dir_len; MCRYPT td; php_mcrypt *pm; if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &cipher, &cipher_len, &cipher_dir, &cipher_dir_len, &mode, &mode_len, &mode_dir, &mode_dir_len)) { return; } td = mcrypt_module_open ( cipher, cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir), mode, mode_dir_len > 0 ? mode_dir : MCG(modes_dir) ); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module"); RETURN_FALSE; } else { pm = emalloc(sizeof(php_mcrypt)); pm->td = td; pm->init = 0; ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt); } } 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: Utterance::~Utterance() { DCHECK_EQ(completion_task_, static_cast<Task *>(NULL)); } CWE ID: CWE-20 Target: 1 Example 2: Code: int __glXDisp_RenderLarge(__GLXclientState *cl, GLbyte *pc) { xGLXRenderLargeReq *req; ClientPtr client= cl->client; size_t dataBytes; __GLXrenderLargeHeader *hdr; __GLXcontext *glxc; int error; CARD16 opcode; __GLX_DECLARE_SWAP_VARIABLES; req = (xGLXRenderLargeReq *) pc; if (client->swapped) { __GLX_SWAP_SHORT(&req->length); __GLX_SWAP_INT(&req->contextTag); __GLX_SWAP_INT(&req->dataBytes); __GLX_SWAP_SHORT(&req->requestNumber); __GLX_SWAP_SHORT(&req->requestTotal); } glxc = __glXForceCurrent(cl, req->contextTag, &error); if (!glxc) { /* Reset in case this isn't 1st request. */ __glXResetLargeCommandStatus(cl); return error; } dataBytes = req->dataBytes; /* ** Check the request length. */ if ((req->length << 2) != __GLX_PAD(dataBytes) + sz_xGLXRenderLargeReq) { client->errorValue = req->length; /* Reset in case this isn't 1st request. */ __glXResetLargeCommandStatus(cl); return BadLength; } pc += sz_xGLXRenderLargeReq; if (cl->largeCmdRequestsSoFar == 0) { __GLXrenderSizeData entry; int extra; size_t cmdlen; int err; /* ** This is the first request of a multi request command. ** Make enough space in the buffer, then copy the entire request. */ if (req->requestNumber != 1) { client->errorValue = req->requestNumber; return __glXError(GLXBadLargeRequest); } hdr = (__GLXrenderLargeHeader *) pc; if (client->swapped) { __GLX_SWAP_INT(&hdr->length); __GLX_SWAP_INT(&hdr->opcode); } cmdlen = hdr->length; opcode = hdr->opcode; /* ** Check for core opcodes and grab entry data. */ err = __glXGetProtocolSizeData(& Render_dispatch_info, opcode, & entry); if (err < 0) { client->errorValue = opcode; return __glXError(GLXBadLargeRequest); } if (entry.varsize) { /* ** If it's a variable-size command (a command whose length must ** be computed from its parameters), all the parameters needed ** will be in the 1st request, so it's okay to do this. */ extra = (*entry.varsize)(pc + __GLX_RENDER_LARGE_HDR_SIZE, client->swapped); if (extra < 0) { extra = 0; } /* large command's header is 4 bytes longer, so add 4 */ if (cmdlen != __GLX_PAD(entry.bytes + 4 + extra)) { return BadLength; } } else { /* constant size command */ if (cmdlen != __GLX_PAD(entry.bytes + 4)) { return BadLength; } } /* ** Make enough space in the buffer, then copy the entire request. */ if (cl->largeCmdBufSize < cmdlen) { if (!cl->largeCmdBuf) { cl->largeCmdBuf = (GLbyte *) malloc(cmdlen); } else { cl->largeCmdBuf = (GLbyte *) realloc(cl->largeCmdBuf, cmdlen); } if (!cl->largeCmdBuf) { return BadAlloc; } cl->largeCmdBufSize = cmdlen; } memcpy(cl->largeCmdBuf, pc, dataBytes); cl->largeCmdBytesSoFar = dataBytes; cl->largeCmdBytesTotal = cmdlen; cl->largeCmdRequestsSoFar = 1; cl->largeCmdRequestsTotal = req->requestTotal; return Success; } else { /* ** We are receiving subsequent (i.e. not the first) requests of a ** multi request command. */ /* ** Check the request number and the total request count. */ if (req->requestNumber != cl->largeCmdRequestsSoFar + 1) { client->errorValue = req->requestNumber; __glXResetLargeCommandStatus(cl); return __glXError(GLXBadLargeRequest); } if (req->requestTotal != cl->largeCmdRequestsTotal) { client->errorValue = req->requestTotal; __glXResetLargeCommandStatus(cl); return __glXError(GLXBadLargeRequest); } /* ** Check that we didn't get too much data. */ if ((cl->largeCmdBytesSoFar + dataBytes) > cl->largeCmdBytesTotal) { client->errorValue = dataBytes; __glXResetLargeCommandStatus(cl); return __glXError(GLXBadLargeRequest); } memcpy(cl->largeCmdBuf + cl->largeCmdBytesSoFar, pc, dataBytes); cl->largeCmdBytesSoFar += dataBytes; cl->largeCmdRequestsSoFar++; if (req->requestNumber == cl->largeCmdRequestsTotal) { __GLXdispatchRenderProcPtr proc; /* ** This is the last request; it must have enough bytes to complete ** the command. */ /* NOTE: the two pad macros have been added below; they are needed ** because the client library pads the total byte count, but not ** the per-request byte counts. The Protocol Encoding says the ** total byte count should not be padded, so a proposal will be ** made to the ARB to relax the padding constraint on the total ** byte count, thus preserving backward compatibility. Meanwhile, ** the padding done below fixes a bug that did not allow ** large commands of odd sizes to be accepted by the server. */ if (__GLX_PAD(cl->largeCmdBytesSoFar) != __GLX_PAD(cl->largeCmdBytesTotal)) { client->errorValue = dataBytes; __glXResetLargeCommandStatus(cl); return __glXError(GLXBadLargeRequest); } hdr = (__GLXrenderLargeHeader *) cl->largeCmdBuf; /* ** The opcode and length field in the header had already been ** swapped when the first request was received. ** ** Use the opcode to index into the procedure table. */ opcode = hdr->opcode; proc = (__GLXdispatchRenderProcPtr) __glXGetProtocolDecodeFunction(& Render_dispatch_info, opcode, client->swapped); if (proc == NULL) { client->errorValue = opcode; return __glXError(GLXBadLargeRequest); } /* ** Skip over the header and execute the command. */ (*proc)(cl->largeCmdBuf + __GLX_RENDER_LARGE_HDR_SIZE); __GLX_NOTE_UNFLUSHED_CMDS(glxc); /* ** Reset for the next RenderLarge series. */ __glXResetLargeCommandStatus(cl); } else { /* ** This is neither the first nor the last request. */ } return Success; } } 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 LauncherView::IsShowingMenu() const { #if !defined(OS_MACOSX) return (overflow_menu_runner_.get() && overflow_menu_runner_->IsRunning()) || (launcher_menu_runner_.get() && launcher_menu_runner_->IsRunning()); #endif return false; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool btsock_thread_remove_fd_and_close(int thread_handle, int fd) { if (thread_handle < 0 || thread_handle >= MAX_THREAD) { APPL_TRACE_ERROR("%s invalid thread handle: %d", __func__, thread_handle); return false; } if (fd == -1) { APPL_TRACE_ERROR("%s invalid file descriptor.", __func__); return false; } sock_cmd_t cmd = {CMD_REMOVE_FD, fd, 0, 0, 0}; return send(ts[thread_handle].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd); } CWE ID: CWE-284 Target: 1 Example 2: Code: static int set_qf_name(struct super_block *sb, int qtype, substring_t *args) { struct ext4_sb_info *sbi = EXT4_SB(sb); char *qname; int ret = -1; if (sb_any_quota_loaded(sb) && !sbi->s_qf_names[qtype]) { ext4_msg(sb, KERN_ERR, "Cannot change journaled " "quota options when quota turned on"); return -1; } if (ext4_has_feature_quota(sb)) { ext4_msg(sb, KERN_INFO, "Journaled quota options " "ignored when QUOTA feature is enabled"); return 1; } qname = match_strdup(args); if (!qname) { ext4_msg(sb, KERN_ERR, "Not enough memory for storing quotafile name"); return -1; } if (sbi->s_qf_names[qtype]) { if (strcmp(sbi->s_qf_names[qtype], qname) == 0) ret = 1; else ext4_msg(sb, KERN_ERR, "%s quota file already specified", QTYPE2NAME(qtype)); goto errout; } if (strchr(qname, '/')) { ext4_msg(sb, KERN_ERR, "quotafile must be on filesystem root"); goto errout; } sbi->s_qf_names[qtype] = qname; set_opt(sb, QUOTA); return 1; errout: kfree(qname); return ret; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset, int nb_clusters) { BDRVQcowState *s = bs->opaque; uint64_t cluster_index; uint64_t i; int refcount, ret; assert(nb_clusters >= 0); if (nb_clusters == 0) { return 0; } do { /* Check how many clusters there are free */ cluster_index = offset >> s->cluster_bits; for(i = 0; i < nb_clusters; i++) { refcount = get_refcount(bs, cluster_index++); if (refcount < 0) { return refcount; } else if (refcount != 0) { break; } } /* And then allocate them */ ret = update_refcount(bs, offset, i << s->cluster_bits, 1, QCOW2_DISCARD_NEVER); } while (ret == -EAGAIN); if (ret < 0) { return ret; } return i; } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(locale_get_primary_language ) { get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } CWE ID: CWE-125 Target: 1 Example 2: Code: int _ilog(unsigned int v){ int ret=0; while(v){ ret++; v>>=1; } return(ret); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void detect_allow_debuggers(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--allow-debuggers") == 0) { arg_allow_debuggers = 1; break; } if (strcmp(argv[i], "--") == 0) break; if (strncmp(argv[i], "--", 2) != 0) break; } } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int em_sysenter(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; ops->get_msr(ctxt, MSR_EFER, &efer); /* inject #GP if in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL) return emulate_gp(ctxt, 0); /* * Not recognized on AMD in compat mode (but is recognized in legacy * mode). */ if ((ctxt->mode == X86EMUL_MODE_PROT32) && (efer & EFER_LMA) && !vendor_intel(ctxt)) return emulate_ud(ctxt); /* sysenter/sysexit have not been tested in 64bit mode. */ if (ctxt->mode == X86EMUL_MODE_PROT64) return X86EMUL_UNHANDLEABLE; setup_syscalls_segments(ctxt, &cs, &ss); ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (ctxt->mode) { case X86EMUL_MODE_PROT32: if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); break; case X86EMUL_MODE_PROT64: if (msr_data == 0x0) return emulate_gp(ctxt, 0); break; default: break; } ctxt->eflags &= ~(EFLG_VM | EFLG_IF); cs_sel = (u16)msr_data; cs_sel &= ~SELECTOR_RPL_MASK; ss_sel = cs_sel + 8; ss_sel &= ~SELECTOR_RPL_MASK; if (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data); *reg_write(ctxt, VCPU_REGS_RSP) = msr_data; return X86EMUL_CONTINUE; } CWE ID: CWE-362 Target: 1 Example 2: Code: xsltGetSAS(xsltStylesheetPtr style, const xmlChar *name, const xmlChar *ns) { xsltAttrElemPtr values; while (style != NULL) { values = xmlHashLookup2(style->attributeSets, name, ns); if (values != NULL) return(values); style = xsltNextImport(style); } return(NULL); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int my_csr_reader( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, REALTYPE** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return -1; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return -1; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (REALTYPE*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return -1; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return -1; } /* now we read the actual content */ } else { unsigned int l_row, l_column; REALTYPE l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return -1; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return -1; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } return 0; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: double AudioTrack::GetSamplingRate() const { return m_rate; } CWE ID: CWE-119 Target: 1 Example 2: Code: AutofillManager::AutofillManager( AutofillDriver* driver, AutofillClient* client, const std::string& app_locale, AutofillDownloadManagerState enable_download_manager) : AutofillManager(driver, client, client->GetPersonalDataManager(), app_locale, enable_download_manager) {} 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 BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[]) { tBTM_SEC_DEV_REC *p_dev_rec; BTM_TRACE_API ("BTM_PINCodeReply(): PairState: %s PairFlags: 0x%02x PinLen:%d Result:%d", btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, pin_len, res); /* If timeout already expired or has been canceled, ignore the reply */ if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) { BTM_TRACE_WARNING ("BTM_PINCodeReply() - Wrong State: %d", btm_cb.pairing_state); return; } if (memcmp (bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) { BTM_TRACE_ERROR ("BTM_PINCodeReply() - Wrong BD Addr"); return; } if ((p_dev_rec = btm_find_dev (bd_addr)) == NULL) { BTM_TRACE_ERROR ("BTM_PINCodeReply() - no dev CB"); return; } if ( (pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL) ) res = BTM_ILLEGAL_VALUE; if (res != BTM_SUCCESS) { /* if peer started dd OR we started dd and pre-fetch pin was not used send negative reply */ if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) || ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) ) { /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed event */ btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; btsnd_hcic_pin_code_neg_reply (bd_addr); } else { p_dev_rec->security_required = BTM_SEC_NONE; btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); } return; } if (trusted_mask) BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask); p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED; if ( (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) && (btm_cb.security_mode_changed == FALSE) ) { /* This is start of the dedicated bonding if local device is 2.0 */ btm_cb.pin_code_len = pin_len; memcpy (btm_cb.pin_code, p_pin, pin_len); btm_cb.security_mode_changed = TRUE; #ifdef APPL_AUTH_WRITE_EXCEPTION if(!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr)) #endif btsnd_hcic_write_auth_enable (TRUE); btm_cb.acl_disc_reason = 0xff ; /* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */ /* before originating */ if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) { BTM_TRACE_WARNING ("BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected incoming connection"); /* we change state little bit early so btm_sec_connected() will originate connection */ /* when existing ACL link is down completely */ btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ); } /* if we already accepted incoming connection from pairing device */ else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) { BTM_TRACE_WARNING ("BTM_PINCodeReply(): link is connecting so wait pin code request from peer"); btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ); } else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) { btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED; if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_AUTH_FAILURE); } return; } btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btm_cb.acl_disc_reason = HCI_SUCCESS; #ifdef PORCHE_PAIRING_CONFLICT BTM_TRACE_EVENT("BTM_PINCodeReply(): Saving pin_len: %d btm_cb.pin_code_len: %d", pin_len, btm_cb.pin_code_len); /* if this was not pre-fetched, save the PIN */ if (btm_cb.pin_code_len == 0) memcpy (btm_cb.pin_code, p_pin, pin_len); btm_cb.pin_code_len_saved = pin_len; #endif btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin); } 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* sspi_SecureHandleGetLowerPointer(SecHandle* handle) { void* pointer; if (!handle) return NULL; pointer = (void*) ~((size_t) handle->dwLower); return pointer; } CWE ID: CWE-476 Target: 1 Example 2: Code: static struct macvtap_queue *macvtap_get_queue(struct net_device *dev, struct sk_buff *skb) { struct macvlan_dev *vlan = netdev_priv(dev); struct macvtap_queue *tap = NULL; int numvtaps = vlan->numvtaps; __u32 rxq; if (!numvtaps) goto out; /* Check if we can use flow to select a queue */ rxq = skb_get_rxhash(skb); if (rxq) { tap = rcu_dereference(vlan->taps[rxq % numvtaps]); if (tap) goto out; } if (likely(skb_rx_queue_recorded(skb))) { rxq = skb_get_rx_queue(skb); while (unlikely(rxq >= numvtaps)) rxq -= numvtaps; tap = rcu_dereference(vlan->taps[rxq]); if (tap) goto out; } /* Everything failed - find first available queue */ for (rxq = 0; rxq < MAX_MACVTAP_QUEUES; rxq++) { tap = rcu_dereference(vlan->taps[rxq]); if (tap) break; } out: return tap; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); } 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: static int unix_dgram_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock_iocb *siocb = kiocb_to_siocb(iocb); struct scm_cookie tmp_scm; struct sock *sk = sock->sk; struct unix_sock *u = unix_sk(sk); int noblock = flags & MSG_DONTWAIT; struct sk_buff *skb; int err; int peeked, skip; err = -EOPNOTSUPP; if (flags&MSG_OOB) goto out; msg->msg_namelen = 0; err = mutex_lock_interruptible(&u->readlock); if (err) { err = sock_intr_errno(sock_rcvtimeo(sk, noblock)); goto out; } skip = sk_peek_offset(sk, flags); skb = __skb_recv_datagram(sk, flags, &peeked, &skip, &err); if (!skb) { unix_state_lock(sk); /* Signal EOF on disconnected non-blocking SEQPACKET socket. */ if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN && (sk->sk_shutdown & RCV_SHUTDOWN)) err = 0; unix_state_unlock(sk); goto out_unlock; } wake_up_interruptible_sync_poll(&u->peer_wait, POLLOUT | POLLWRNORM | POLLWRBAND); if (msg->msg_name) unix_copy_addr(msg, skb->sk); if (size > skb->len - skip) size = skb->len - skip; else if (size < skb->len - skip) msg->msg_flags |= MSG_TRUNC; err = skb_copy_datagram_iovec(skb, skip, msg->msg_iov, size); if (err) goto out_free; if (sock_flag(sk, SOCK_RCVTSTAMP)) __sock_recv_timestamp(msg, sk, skb); if (!siocb->scm) { siocb->scm = &tmp_scm; memset(&tmp_scm, 0, sizeof(tmp_scm)); } scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid); unix_set_secdata(siocb->scm, skb); if (!(flags & MSG_PEEK)) { if (UNIXCB(skb).fp) unix_detach_fds(siocb->scm, skb); sk_peek_offset_bwd(sk, skb->len); } else { /* It is questionable: on PEEK we could: - do not return fds - good, but too simple 8) - return fds, and do not return them on read (old strategy, apparently wrong) - clone fds (I chose it for now, it is the most universal solution) POSIX 1003.1g does not actually define this clearly at all. POSIX 1003.1g doesn't define a lot of things clearly however! */ sk_peek_offset_fwd(sk, size); if (UNIXCB(skb).fp) siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp); } err = (flags & MSG_TRUNC) ? skb->len - skip : size; scm_recv(sock, msg, siocb->scm, flags); out_free: skb_free_datagram(sk, skb); out_unlock: mutex_unlock(&u->readlock); out: return err; } CWE ID: CWE-20 Target: 1 Example 2: Code: static TriState StateOrderedList(LocalFrame& frame, Event*) { return SelectionListState(frame.Selection(), olTag); } 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 BIGNUM *srp_Calc_k(BIGNUM *N, BIGNUM *g) { /* k = SHA1(N | PAD(g)) -- tls-srp draft 8 */ unsigned char digest[SHA_DIGEST_LENGTH]; unsigned char *tmp; EVP_MD_CTX ctxt; int longg ; int longN = BN_num_bytes(N); if ((tmp = OPENSSL_malloc(longN)) == NULL) return NULL; BN_bn2bin(N,tmp) ; EVP_DigestUpdate(&ctxt, tmp, longN); memset(tmp, 0, longN); longg = BN_bn2bin(g,tmp) ; /* use the zeros behind to pad on left */ EVP_DigestUpdate(&ctxt, tmp + longg, longN-longg); EVP_DigestUpdate(&ctxt, tmp, longg); OPENSSL_free(tmp); EVP_DigestFinal_ex(&ctxt, digest, NULL); EVP_MD_CTX_cleanup(&ctxt); return BN_bin2bn(digest, sizeof(digest), NULL); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WebString WebPageSerializer::generateMarkOfTheWebDeclaration(const WebURL& url) { return String::format("\n<!-- saved from url=(%04d)%s -->\n", static_cast<int>(url.spec().length()), url.spec().data()); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void reflectReflectedNameAttributeTestAttributeAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); V8TRYCATCH_VOID(TestInterface*, cppValue, V8TestInterface::toNativeWithTypeCheck(info.GetIsolate(), jsValue)); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; imp->setAttribute(HTMLNames::reflectedNameAttributeAttr, WTF::getPtr(cppValue)); } 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: uint32_t CommandBufferProxyImpl::CreateStreamTexture(uint32_t texture_id) { CheckLock(); base::AutoLock lock(last_state_lock_); if (last_state_.error != gpu::error::kNoError) return 0; int32_t stream_id = channel_->GenerateRouteID(); bool succeeded = false; Send(new GpuCommandBufferMsg_CreateStreamTexture(route_id_, texture_id, stream_id, &succeeded)); if (!succeeded) { DLOG(ERROR) << "GpuCommandBufferMsg_CreateStreamTexture returned failure"; return 0; } return stream_id; } 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: void ChromeContentBrowserClient::OpenURL( content::BrowserContext* browser_context, const content::OpenURLParams& params, const base::Callback<void(content::WebContents*)>& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); #if defined(OS_ANDROID) ServiceTabLauncher::GetInstance()->LaunchTab(browser_context, params, callback); #else NavigateParams nav_params(Profile::FromBrowserContext(browser_context), params.url, params.transition); nav_params.FillNavigateParamsFromOpenURLParams(params); nav_params.user_gesture = params.user_gesture; Navigate(&nav_params); callback.Run(nav_params.navigated_or_inserted_contents); #endif } CWE ID: CWE-264 Target: 1 Example 2: Code: status_t OMX::createInputSurface( node_id node, OMX_U32 port_index, sp<IGraphicBufferProducer> *bufferProducer, MetadataBufferType *type) { return findInstance(node)->createInputSurface( port_index, bufferProducer, type); } 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 powermate_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev (intf); struct usb_host_interface *interface; struct usb_endpoint_descriptor *endpoint; struct powermate_device *pm; struct input_dev *input_dev; int pipe, maxp; int error = -ENOMEM; interface = intf->cur_altsetting; endpoint = &interface->endpoint[0].desc; if (!usb_endpoint_is_int_in(endpoint)) return -EIO; usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0a, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, interface->desc.bInterfaceNumber, NULL, 0, USB_CTRL_SET_TIMEOUT); pm = kzalloc(sizeof(struct powermate_device), GFP_KERNEL); input_dev = input_allocate_device(); if (!pm || !input_dev) goto fail1; if (powermate_alloc_buffers(udev, pm)) goto fail2; pm->irq = usb_alloc_urb(0, GFP_KERNEL); if (!pm->irq) goto fail2; pm->config = usb_alloc_urb(0, GFP_KERNEL); if (!pm->config) goto fail3; pm->udev = udev; pm->intf = intf; pm->input = input_dev; usb_make_path(udev, pm->phys, sizeof(pm->phys)); strlcat(pm->phys, "/input0", sizeof(pm->phys)); spin_lock_init(&pm->lock); switch (le16_to_cpu(udev->descriptor.idProduct)) { case POWERMATE_PRODUCT_NEW: input_dev->name = pm_name_powermate; break; case POWERMATE_PRODUCT_OLD: input_dev->name = pm_name_soundknob; break; default: input_dev->name = pm_name_soundknob; printk(KERN_WARNING "powermate: unknown product id %04x\n", le16_to_cpu(udev->descriptor.idProduct)); } input_dev->phys = pm->phys; usb_to_input_id(udev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, pm); input_dev->event = powermate_input_event; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL) | BIT_MASK(EV_MSC); input_dev->keybit[BIT_WORD(BTN_0)] = BIT_MASK(BTN_0); input_dev->relbit[BIT_WORD(REL_DIAL)] = BIT_MASK(REL_DIAL); input_dev->mscbit[BIT_WORD(MSC_PULSELED)] = BIT_MASK(MSC_PULSELED); /* get a handle to the interrupt data pipe */ pipe = usb_rcvintpipe(udev, endpoint->bEndpointAddress); maxp = usb_maxpacket(udev, pipe, usb_pipeout(pipe)); if (maxp < POWERMATE_PAYLOAD_SIZE_MIN || maxp > POWERMATE_PAYLOAD_SIZE_MAX) { printk(KERN_WARNING "powermate: Expected payload of %d--%d bytes, found %d bytes!\n", POWERMATE_PAYLOAD_SIZE_MIN, POWERMATE_PAYLOAD_SIZE_MAX, maxp); maxp = POWERMATE_PAYLOAD_SIZE_MAX; } usb_fill_int_urb(pm->irq, udev, pipe, pm->data, maxp, powermate_irq, pm, endpoint->bInterval); pm->irq->transfer_dma = pm->data_dma; pm->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* register our interrupt URB with the USB system */ if (usb_submit_urb(pm->irq, GFP_KERNEL)) { error = -EIO; goto fail4; } error = input_register_device(pm->input); if (error) goto fail5; /* force an update of everything */ pm->requires_update = UPDATE_PULSE_ASLEEP | UPDATE_PULSE_AWAKE | UPDATE_PULSE_MODE | UPDATE_STATIC_BRIGHTNESS; powermate_pulse_led(pm, 0x80, 255, 0, 1, 0); // set default pulse parameters usb_set_intfdata(intf, pm); return 0; fail5: usb_kill_urb(pm->irq); fail4: usb_free_urb(pm->config); fail3: usb_free_urb(pm->irq); fail2: powermate_free_buffers(udev, pm); fail1: input_free_device(input_dev); kfree(pm); return error; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int wait_for_fpga_config(void) { int ret = 0, done; /* approx 5 s */ u32 timeout = 500000; printf("PCIe FPGA config:"); do { done = qrio_get_gpio(GPIO_A, FPGA_DONE); if (timeout-- == 0) { printf(" FPGA_DONE timeout\n"); ret = -EFAULT; goto err_out; } udelay(10); } while (!done); printf(" done\n"); err_out: /* deactive CONF_SEL and give the CPU conf EEPROM access */ qrio_set_gpio(GPIO_A, CONF_SEL_L, 1); toggle_fpga_eeprom_bus(true); return ret; } CWE ID: CWE-787 Target: 1 Example 2: Code: static int rawv6_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { switch (level) { case SOL_RAW: break; case SOL_ICMPV6: if (inet_sk(sk)->inet_num != IPPROTO_ICMPV6) return -EOPNOTSUPP; return rawv6_seticmpfilter(sk, level, optname, optval, optlen); case SOL_IPV6: if (optname == IPV6_CHECKSUM) break; default: return ipv6_setsockopt(sk, level, optname, optval, optlen); } return do_rawv6_setsockopt(sk, level, optname, optval, optlen); } 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: processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) { const char *textStart, *textEnd; const char *next; enum XML_Error result; OPEN_INTERNAL_ENTITY *openEntity; if (parser->m_freeInternalEntities) { openEntity = parser->m_freeInternalEntities; parser->m_freeInternalEntities = openEntity->next; } else { openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY)); if (! openEntity) return XML_ERROR_NO_MEMORY; } entity->open = XML_TRUE; entity->processed = 0; openEntity->next = parser->m_openInternalEntities; parser->m_openInternalEntities = openEntity; openEntity->entity = entity; openEntity->startTagLevel = parser->m_tagLevel; openEntity->betweenDecl = betweenDecl; openEntity->internalEventPtr = NULL; openEntity->internalEventEndPtr = NULL; textStart = (char *)entity->textPtr; textEnd = (char *)(entity->textPtr + entity->textLen); /* Set a safe default value in case 'next' does not get set */ next = textStart; #ifdef XML_DTD if (entity->is_param) { int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, next, &next, XML_FALSE); } else #endif /* XML_DTD */ result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart, textEnd, &next, XML_FALSE); if (result == XML_ERROR_NONE) { if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { entity->processed = (int)(next - textStart); parser->m_processor = internalEntityProcessor; } else { entity->open = XML_FALSE; parser->m_openInternalEntities = openEntity->next; /* put openEntity back in list of free instances */ openEntity->next = parser->m_freeInternalEntities; parser->m_freeInternalEntities = openEntity; } } return result; } CWE ID: CWE-611 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: M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress_cb_t cb, M_uint32 progress_flags) { char *norm_path; char *join_path; M_fs_dir_entries_t *entries; const M_fs_dir_entry_t *entry; M_fs_info_t *info; M_fs_progress_t *progress = NULL; M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE; M_fs_type_t type; /* The result that will be returned by this function. */ M_fs_error_t res; /* The result of the delete itself. */ M_fs_error_t res2; size_t len; size_t i; M_uint64 total_size = 0; M_uint64 total_size_progress = 0; M_uint64 entry_size; /* Normalize the path we are going to delete so we have a valid path to pass around. */ res = M_fs_path_norm(&norm_path, path, M_FS_PATH_NORM_HOME, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path); return res; } /* We need the info to determine if the path is valid and because we need the type. */ res = M_fs_info(&info, norm_path, M_FS_PATH_INFO_FLAGS_BASIC); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path); return res; } /* We must know the type because there are different functions for deleting a file and deleting a directory. */ type = M_fs_info_get_type(info); if (type == M_FS_TYPE_UNKNOWN) { M_fs_info_destroy(info); M_free(norm_path); return M_FS_ERROR_GENERIC; } /* Create a list of entries to store all the places we need to delete. */ entries = M_fs_dir_entries_create(); /* Recursive directory deletion isn't intuitive. We have to generate a list of files and delete the list. * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior * is undefined in Posix and HFS is known to skip files if the directory contents is modifies as the * directory is being walked. */ if (type == M_FS_TYPE_DIR && remove_children) { /* We need to read the basic info if the we need to report the size totals to the cb. */ if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC; } M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path, NULL, filter)); } /* Add the original path to the list of entries. This may be the only entry in the list. We need to add * it after a potential walk because we can't delete a directory that isn't empty. * Note: * - The info will be owned by the entry and destroyed when it is destroyed. * - The basic info param doesn't get the info in this case. it's set so the info is stored in the entry. */ M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC)); len = M_fs_dir_entries_len(entries); if (cb) { /* Create the progress. The same progress will be used for the entire operation. It will be updated with * new info as necessary. */ progress = M_fs_progress_create(); /* Get the total size of all files to be deleted if using the progress cb and size totals is set. */ if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size += entry_size; } /* Change the progress total size to reflect all entries. */ M_fs_progress_set_size_total(progress, total_size); } /* Change the progress count to reflect the count. */ if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count_total(progress, len); } } /* Assume success. Set error if there is an error. */ res = M_FS_ERROR_SUCCESS; /* Loop though all entries and delete. */ for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); join_path = M_fs_path_join(norm_path, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); /* Call the appropriate delete function. */ if (M_fs_dir_entry_get_type(entry) == M_FS_TYPE_DIR) { res2 = M_fs_delete_dir(join_path); } else { res2 = M_fs_delete_file(join_path); } /* Set the return result to denote there was an error. The real error will be sent via the * progress callback for the entry. */ if (res2 != M_FS_ERROR_SUCCESS) { res = M_FS_ERROR_GENERIC; } /* Set the progress data for the entry. */ if (cb) { entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size_progress += entry_size; M_fs_progress_set_path(progress, join_path); M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry)); M_fs_progress_set_result(progress, res2); if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, i+1); } if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, total_size_progress); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current(progress, entry_size); M_fs_progress_set_size_current_progress(progress, entry_size); } } M_free(join_path); /* Call the callback and stop processing if requested. */ if (cb && !cb(progress)) { res = M_FS_ERROR_CANCELED; break; } } M_fs_dir_entries_destroy(entries); M_fs_progress_destroy(progress); M_free(norm_path); return res; } CWE ID: CWE-732 Target: 1 Example 2: Code: explicit SelectionAdapter(Plugin* plugin) : pp::Selection_Dev(plugin), plugin_(plugin) { BrowserPpp* proxy = plugin_->ppapi_proxy(); CHECK(proxy != NULL); ppp_selection_ = static_cast<const PPP_Selection_Dev*>( proxy->GetPluginInterface(PPP_SELECTION_DEV_INTERFACE)); } 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: ConflictResolver::ProcessSimpleConflict(WriteTransaction* trans, const Id& id, const Cryptographer* cryptographer, StatusController* status) { MutableEntry entry(trans, syncable::GET_BY_ID, id); CHECK(entry.good()); if (!entry.Get(syncable::IS_UNAPPLIED_UPDATE) || !entry.Get(syncable::IS_UNSYNCED)) { return NO_SYNC_PROGRESS; } if (entry.Get(syncable::IS_DEL) && entry.Get(syncable::SERVER_IS_DEL)) { entry.Put(syncable::IS_UNSYNCED, false); entry.Put(syncable::IS_UNAPPLIED_UPDATE, false); return NO_SYNC_PROGRESS; } if (!entry.Get(syncable::SERVER_IS_DEL)) { bool name_matches = entry.Get(syncable::NON_UNIQUE_NAME) == entry.Get(syncable::SERVER_NON_UNIQUE_NAME); bool parent_matches = entry.Get(syncable::PARENT_ID) == entry.Get(syncable::SERVER_PARENT_ID); bool entry_deleted = entry.Get(syncable::IS_DEL); syncable::Id server_prev_id = entry.ComputePrevIdFromServerPosition( entry.Get(syncable::SERVER_PARENT_ID)); bool needs_reinsertion = !parent_matches || server_prev_id != entry.Get(syncable::PREV_ID); DVLOG_IF(1, needs_reinsertion) << "Insertion needed, server prev id " << " is " << server_prev_id << ", local prev id is " << entry.Get(syncable::PREV_ID); const sync_pb::EntitySpecifics& specifics = entry.Get(syncable::SPECIFICS); const sync_pb::EntitySpecifics& server_specifics = entry.Get(syncable::SERVER_SPECIFICS); const sync_pb::EntitySpecifics& base_server_specifics = entry.Get(syncable::BASE_SERVER_SPECIFICS); std::string decrypted_specifics, decrypted_server_specifics; bool specifics_match = false; bool server_encrypted_with_default_key = false; if (specifics.has_encrypted()) { DCHECK(cryptographer->CanDecryptUsingDefaultKey(specifics.encrypted())); decrypted_specifics = cryptographer->DecryptToString( specifics.encrypted()); } else { decrypted_specifics = specifics.SerializeAsString(); } if (server_specifics.has_encrypted()) { server_encrypted_with_default_key = cryptographer->CanDecryptUsingDefaultKey( server_specifics.encrypted()); decrypted_server_specifics = cryptographer->DecryptToString( server_specifics.encrypted()); } else { decrypted_server_specifics = server_specifics.SerializeAsString(); } if (decrypted_server_specifics == decrypted_specifics && server_encrypted_with_default_key == specifics.has_encrypted()) { specifics_match = true; } bool base_server_specifics_match = false; if (server_specifics.has_encrypted() && IsRealDataType(GetModelTypeFromSpecifics(base_server_specifics))) { std::string decrypted_base_server_specifics; if (!base_server_specifics.has_encrypted()) { decrypted_base_server_specifics = base_server_specifics.SerializeAsString(); } else { decrypted_base_server_specifics = cryptographer->DecryptToString( base_server_specifics.encrypted()); } if (decrypted_server_specifics == decrypted_base_server_specifics) base_server_specifics_match = true; } if (entry.GetModelType() == syncable::NIGORI) { sync_pb::EntitySpecifics specifics = entry.Get(syncable::SERVER_SPECIFICS); sync_pb::NigoriSpecifics* server_nigori = specifics.mutable_nigori(); cryptographer->UpdateNigoriFromEncryptedTypes(server_nigori); if (cryptographer->is_ready()) { cryptographer->GetKeys(server_nigori->mutable_encrypted()); server_nigori->set_using_explicit_passphrase( entry.Get(syncable::SPECIFICS).nigori(). using_explicit_passphrase()); } if (entry.Get(syncable::SPECIFICS).nigori().sync_tabs()) { server_nigori->set_sync_tabs(true); } entry.Put(syncable::SPECIFICS, specifics); DVLOG(1) << "Resolving simple conflict, merging nigori nodes: " << entry; status->increment_num_server_overwrites(); OverwriteServerChanges(trans, &entry); UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", NIGORI_MERGE, CONFLICT_RESOLUTION_SIZE); } else if (!entry_deleted && name_matches && parent_matches && specifics_match && !needs_reinsertion) { DVLOG(1) << "Resolving simple conflict, everything matches, ignoring " << "changes for: " << entry; OverwriteServerChanges(trans, &entry); IgnoreLocalChanges(&entry); UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", CHANGES_MATCH, CONFLICT_RESOLUTION_SIZE); } else if (base_server_specifics_match) { DVLOG(1) << "Resolving simple conflict, ignoring server encryption " << " changes for: " << entry; status->increment_num_server_overwrites(); OverwriteServerChanges(trans, &entry); UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", IGNORE_ENCRYPTION, CONFLICT_RESOLUTION_SIZE); } else if (entry_deleted || !name_matches || !parent_matches) { OverwriteServerChanges(trans, &entry); status->increment_num_server_overwrites(); DVLOG(1) << "Resolving simple conflict, overwriting server changes " << "for: " << entry; UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", OVERWRITE_SERVER, CONFLICT_RESOLUTION_SIZE); } else { DVLOG(1) << "Resolving simple conflict, ignoring local changes for: " << entry; IgnoreLocalChanges(&entry); status->increment_num_local_overwrites(); UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", OVERWRITE_LOCAL, CONFLICT_RESOLUTION_SIZE); } entry.Put(syncable::BASE_SERVER_SPECIFICS, sync_pb::EntitySpecifics()); return SYNC_PROGRESS; } else { // SERVER_IS_DEL is true if (entry.Get(syncable::IS_DIR)) { Directory::ChildHandles children; trans->directory()->GetChildHandlesById(trans, entry.Get(syncable::ID), &children); if (0 != children.size()) { DVLOG(1) << "Entry is a server deleted directory with local contents, " << "should be a hierarchy conflict. (race condition)."; return NO_SYNC_PROGRESS; } } if (!entry.Get(syncable::UNIQUE_CLIENT_TAG).empty()) { DCHECK_EQ(entry.Get(syncable::SERVER_VERSION), 0) << "For the server to " "know to re-create, client-tagged items should revert to version 0 " "when server-deleted."; OverwriteServerChanges(trans, &entry); status->increment_num_server_overwrites(); DVLOG(1) << "Resolving simple conflict, undeleting server entry: " << entry; UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", OVERWRITE_SERVER, CONFLICT_RESOLUTION_SIZE); entry.Put(syncable::SERVER_VERSION, 0); entry.Put(syncable::BASE_VERSION, 0); } else { SyncerUtil::SplitServerInformationIntoNewEntry(trans, &entry); MutableEntry server_update(trans, syncable::GET_BY_ID, id); CHECK(server_update.good()); CHECK(server_update.Get(syncable::META_HANDLE) != entry.Get(syncable::META_HANDLE)) << server_update << entry; UMA_HISTOGRAM_ENUMERATION("Sync.ResolveSimpleConflict", UNDELETE, CONFLICT_RESOLUTION_SIZE); } return SYNC_PROGRESS; } } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: struct addr_t* MACH0_(get_entrypoint)(struct MACH0_(obj_t)* bin) { struct addr_t *entry; int i; if (!bin->entry && !bin->sects) { return NULL; } if (!(entry = calloc (1, sizeof (struct addr_t)))) { return NULL; } if (bin->entry) { entry->addr = entry_to_vaddr (bin); entry->offset = addr_to_offset (bin, entry->addr); entry->haddr = sdb_num_get (bin->kv, "mach0.entry.offset", 0); } if (!bin->entry || entry->offset == 0) { for (i = 0; i < bin->nsects; i++) { if (!strncmp (bin->sects[i].sectname, "__text", 6)) { entry->offset = (ut64)bin->sects[i].offset; sdb_num_set (bin->kv, "mach0.entry", entry->offset, 0); entry->addr = (ut64)bin->sects[i].addr; if (!entry->addr) { // workaround for object files entry->addr = entry->offset; } break; } } bin->entry = entry->addr; } return entry; } CWE ID: CWE-416 Target: 1 Example 2: Code: int FlateStream::getChars(int nChars, Guchar *buffer) { if (pred) { return pred->getChars(nChars, buffer); } else { for (int i = 0; i < nChars; ++i) { const int c = doGetRawChar(); if (likely(c != EOF)) buffer[i] = c; else return i; } return nChars; } } 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: SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data) { int rc; struct cifs_ses *ses = sess_data->ses; struct smb2_sess_setup_req *req; struct smb2_sess_setup_rsp *rsp = NULL; unsigned char *ntlmssp_blob = NULL; bool use_spnego = false; /* else use raw ntlmssp */ u16 blob_length = 0; rc = SMB2_sess_alloc_buffer(sess_data); if (rc) goto out; req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base; req->hdr.sync_hdr.SessionId = ses->Suid; rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length, ses, sess_data->nls_cp); if (rc) { cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc); goto out; } if (use_spnego) { /* BB eventually need to add this */ cifs_dbg(VFS, "spnego not supported for SMB2 yet\n"); rc = -EOPNOTSUPP; goto out; } sess_data->iov[1].iov_base = ntlmssp_blob; sess_data->iov[1].iov_len = blob_length; rc = SMB2_sess_sendreceive(sess_data); if (rc) goto out; rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base; ses->Suid = rsp->hdr.sync_hdr.SessionId; ses->session_flags = le16_to_cpu(rsp->SessionFlags); if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) cifs_dbg(VFS, "SMB3 encryption not supported yet\n"); rc = SMB2_sess_establish_session(sess_data); out: kfree(ntlmssp_blob); SMB2_sess_free_buffer(sess_data); kfree(ses->ntlmssp); ses->ntlmssp = NULL; sess_data->result = rc; sess_data->func = NULL; } 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: hb_buffer_create (unsigned int pre_alloc_size) { hb_buffer_t *buffer; if (!HB_OBJECT_DO_CREATE (hb_buffer_t, buffer)) return &_hb_buffer_nil; if (pre_alloc_size) hb_buffer_ensure(buffer, pre_alloc_size); buffer->unicode = &_hb_unicode_funcs_nil; return buffer; } CWE ID: Target: 1 Example 2: Code: static void megasas_xfer_complete(SCSIRequest *req, uint32_t len) { MegasasCmd *cmd = req->hba_private; uint8_t *buf; uint32_t opcode; trace_megasas_io_complete(cmd->index, len); if (cmd->frame->header.frame_cmd != MFI_CMD_DCMD) { scsi_req_continue(req); return; } buf = scsi_req_get_buf(req); opcode = le32_to_cpu(cmd->frame->dcmd.opcode); if (opcode == MFI_DCMD_PD_GET_INFO && cmd->iov_buf) { struct mfi_pd_info *info = cmd->iov_buf; if (info->inquiry_data[0] == 0x7f) { memset(info->inquiry_data, 0, sizeof(info->inquiry_data)); memcpy(info->inquiry_data, buf, len); } else if (info->vpd_page83[0] == 0x7f) { memset(info->vpd_page83, 0, sizeof(info->vpd_page83)); memcpy(info->vpd_page83, buf, len); } scsi_req_continue(req); } else if (opcode == MFI_DCMD_LD_GET_INFO) { struct mfi_ld_info *info = cmd->iov_buf; if (cmd->iov_buf) { memcpy(info->vpd_page83, buf, sizeof(info->vpd_page83)); scsi_req_continue(req); } } } 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: asmlinkage void do_ade(struct pt_regs *regs) { unsigned int __user *pc; mm_segment_t seg; perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, regs->cp0_badvaddr); /* * Did we catch a fault trying to load an instruction? * Or are we running in MIPS16 mode? */ if ((regs->cp0_badvaddr == regs->cp0_epc) || (regs->cp0_epc & 0x1)) goto sigbus; pc = (unsigned int __user *) exception_epc(regs); if (user_mode(regs) && !test_thread_flag(TIF_FIXADE)) goto sigbus; if (unaligned_action == UNALIGNED_ACTION_SIGNAL) goto sigbus; else if (unaligned_action == UNALIGNED_ACTION_SHOW) show_registers(regs); /* * Do branch emulation only if we didn't forward the exception. * This is all so but ugly ... */ seg = get_fs(); if (!user_mode(regs)) set_fs(KERNEL_DS); emulate_load_store_insn(regs, (void __user *)regs->cp0_badvaddr, pc); set_fs(seg); return; sigbus: die_if_kernel("Kernel unaligned instruction access", regs); force_sig(SIGBUS, current); /* * XXX On return from the signal handler we should advance the epc */ } 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: virtual void SetUp() { full_itxfm_ = GET_PARAM(0); partial_itxfm_ = GET_PARAM(1); tx_size_ = GET_PARAM(2); last_nonzero_ = GET_PARAM(3); } CWE ID: CWE-119 Target: 1 Example 2: Code: ExecuteCodeInTabFunction::ExecuteCodeInTabFunction() : chrome_details_(this), execute_tab_id_(-1) { } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void sctp_assoc_update(struct sctp_association *asoc, struct sctp_association *new) { struct sctp_transport *trans; struct list_head *pos, *temp; /* Copy in new parameters of peer. */ asoc->c = new->c; asoc->peer.rwnd = new->peer.rwnd; asoc->peer.sack_needed = new->peer.sack_needed; asoc->peer.i = new->peer.i; sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, asoc->peer.i.initial_tsn, GFP_ATOMIC); /* Remove any peer addresses not present in the new association. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { trans = list_entry(pos, struct sctp_transport, transports); if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) { sctp_assoc_rm_peer(asoc, trans); continue; } if (asoc->state >= SCTP_STATE_ESTABLISHED) sctp_transport_reset(trans); } /* If the case is A (association restart), use * initial_tsn as next_tsn. If the case is B, use * current next_tsn in case data sent to peer * has been discarded and needs retransmission. */ if (asoc->state >= SCTP_STATE_ESTABLISHED) { asoc->next_tsn = new->next_tsn; asoc->ctsn_ack_point = new->ctsn_ack_point; asoc->adv_peer_ack_point = new->adv_peer_ack_point; /* Reinitialize SSN for both local streams * and peer's streams. */ sctp_ssnmap_clear(asoc->ssnmap); /* Flush the ULP reassembly and ordered queue. * Any data there will now be stale and will * cause problems. */ sctp_ulpq_flush(&asoc->ulpq); /* reset the overall association error count so * that the restarted association doesn't get torn * down on the next retransmission timer. */ asoc->overall_error_count = 0; } else { /* Add any peer addresses from the new association. */ list_for_each_entry(trans, &new->peer.transport_addr_list, transports) { if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr)) sctp_assoc_add_peer(asoc, &trans->ipaddr, GFP_ATOMIC, trans->state); } asoc->ctsn_ack_point = asoc->next_tsn - 1; asoc->adv_peer_ack_point = asoc->ctsn_ack_point; if (!asoc->ssnmap) { /* Move the ssnmap. */ asoc->ssnmap = new->ssnmap; new->ssnmap = NULL; } if (!asoc->assoc_id) { /* get a new association id since we don't have one * yet. */ sctp_assoc_set_id(asoc, GFP_ATOMIC); } } /* SCTP-AUTH: Save the peer parameters from the new associations * and also move the association shared keys over */ kfree(asoc->peer.peer_random); asoc->peer.peer_random = new->peer.peer_random; new->peer.peer_random = NULL; kfree(asoc->peer.peer_chunks); asoc->peer.peer_chunks = new->peer.peer_chunks; new->peer.peer_chunks = NULL; kfree(asoc->peer.peer_hmacs); asoc->peer.peer_hmacs = new->peer.peer_hmacs; new->peer.peer_hmacs = NULL; sctp_auth_key_put(asoc->asoc_shared_key); sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC); } 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 ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior, UpdateFromElementBehavior update_behavior, const KURL& url, ReferrerPolicy referrer_policy, UpdateType update_type) { pending_task_.reset(); std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter; load_delay_counter.swap(delay_until_do_update_from_element_); Document& document = element_->GetDocument(); if (!document.IsActive()) return; AtomicString image_source_url = element_->ImageSourceURL(); ImageResourceContent* new_image_content = nullptr; if (!url.IsNull() && !url.IsEmpty()) { ResourceLoaderOptions resource_loader_options; resource_loader_options.initiator_info.name = GetElement()->localName(); ResourceRequest resource_request(url); if (update_behavior == kUpdateForcedReload) { resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache); resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform); } if (referrer_policy != kReferrerPolicyDefault) { resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_policy, url, document.OutgoingReferrer())); } if (IsHTMLPictureElement(GetElement()->parentNode()) || !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) { resource_request.SetRequestContext( WebURLRequest::kRequestContextImageSet); } else if (IsHTMLObjectElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextObject); } else if (IsHTMLEmbedElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextEmbed); } bool page_is_being_dismissed = document.PageDismissalEventBeingDispatched() != Document::kNoDismissal; if (page_is_being_dismissed) { resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); resource_request.SetKeepalive(true); resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); } FetchParameters params(resource_request, resource_loader_options); ConfigureRequest(params, bypass_behavior, *element_, document.GetClientHintsPreferences()); if (update_behavior != kUpdateForcedReload && document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params); new_image_content = ImageResourceContent::Fetch(params, document.Fetcher()); if (page_is_being_dismissed) new_image_content = nullptr; ClearFailedLoadURL(); } else { if (!image_source_url.IsNull()) { DispatchErrorEvent(); } NoImageResourceToLoad(); } ImageResourceContent* old_image_content = image_content_.Get(); if (old_image_content != new_image_content) RejectPendingDecodes(update_type); if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() && element_->GetLayoutObject()->IsImage() && new_image_content == old_image_content) { ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged(); } else { if (pending_load_event_.IsActive()) pending_load_event_.Cancel(); if (pending_error_event_.IsActive() && new_image_content) pending_error_event_.Cancel(); UpdateImageState(new_image_content); UpdateLayoutObject(); if (new_image_content) { new_image_content->AddObserver(this); } if (old_image_content) { old_image_content->RemoveObserver(this); } } if (LayoutImageResource* image_resource = GetLayoutImageResource()) image_resource->ResetAnimation(); } CWE ID: Target: 1 Example 2: Code: nfsd_create(struct svc_rqst *rqstp, struct svc_fh *fhp, char *fname, int flen, struct iattr *iap, int type, dev_t rdev, struct svc_fh *resfhp) { struct dentry *dentry, *dchild = NULL; struct inode *dirp; __be32 err; int host_err; if (isdotent(fname, flen)) return nfserr_exist; err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_NOP); if (err) return err; dentry = fhp->fh_dentry; dirp = d_inode(dentry); host_err = fh_want_write(fhp); if (host_err) return nfserrno(host_err); fh_lock_nested(fhp, I_MUTEX_PARENT); dchild = lookup_one_len(fname, dentry, flen); host_err = PTR_ERR(dchild); if (IS_ERR(dchild)) return nfserrno(host_err); err = fh_compose(resfhp, fhp->fh_export, dchild, fhp); /* * We unconditionally drop our ref to dchild as fh_compose will have * already grabbed its own ref for it. */ dput(dchild); if (err) return err; return nfsd_create_locked(rqstp, fhp, fname, flen, iap, type, rdev, resfhp); } CWE ID: CWE-404 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { struct bpf_verifier_env *env; struct bpf_verifer_log *log; int ret = -EINVAL; /* no program is valid */ if (ARRAY_SIZE(bpf_verifier_ops) == 0) return -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; log = &env->log; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; env->ops = bpf_verifier_ops[env->prog->type]; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log->level = attr->log_level; log->ubuf = (char __user *) (unsigned long) attr->log_buf; log->len_total = attr->log_size; ret = -EINVAL; /* log attributes have to be sane */ if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || !log->level || !log->ubuf) goto err_unlock; } env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) env->strict_alignment = true; if (env->prog->aux->offload) { ret = bpf_prog_offload_verifier_prep(env); if (ret) goto err_unlock; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); if (env->cur_state) { free_verifier_state(env->cur_state, true); env->cur_state = NULL; } skip_full_check: while (!pop_stack(env, NULL, NULL)); free_states(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log->level && bpf_verifier_log_full(log)) ret = -ENOSPC; if (log->level && !log->ubuf) { ret = -EFAULT; goto err_release_maps; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto err_release_maps; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } err_release_maps: if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; } 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: MediaRecorderHandler::~MediaRecorderHandler() { DCHECK(main_render_thread_checker_.CalledOnValidThread()); if (client_) client_->WriteData( nullptr, 0u, true, (TimeTicks::Now() - TimeTicks::UnixEpoch()).InMillisecondsF()); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int oz_urb_process(struct oz_hcd *ozhcd, struct urb *urb) { int rc = 0; struct oz_port *port = urb->hcpriv; u8 ep_addr; /* When we are paranoid we keep a list of urbs which we check against * before handing one back. This is just for debugging during * development and should be turned off in the released driver. */ oz_remember_urb(urb); /* Check buffer is valid. */ if (!urb->transfer_buffer && urb->transfer_buffer_length) return -EINVAL; /* Check if there is a device at the port - refuse if not. */ if ((port->flags & OZ_PORT_F_PRESENT) == 0) return -EPIPE; ep_addr = usb_pipeendpoint(urb->pipe); if (ep_addr) { /* If the request is not for EP0 then queue it. */ if (oz_enqueue_ep_urb(port, ep_addr, usb_pipein(urb->pipe), urb, 0)) rc = -EPIPE; } else { oz_process_ep0_urb(ozhcd, urb, GFP_ATOMIC); } return rc; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm, u32 kvm_nr_mmu_pages) { if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES) return -EINVAL; mutex_lock(&kvm->slots_lock); kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages); kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages; mutex_unlock(&kvm->slots_lock); return 0; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb, bool compat) { ssize_t ret; #ifdef CONFIG_COMPAT if (compat) ret = compat_rw_copy_check_uvector(type, (struct compat_iovec __user *)kiocb->ki_buf, kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec, &kiocb->ki_iovec, 1); else #endif ret = rw_copy_check_uvector(type, (struct iovec __user *)kiocb->ki_buf, kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec, &kiocb->ki_iovec, 1); if (ret < 0) goto out; kiocb->ki_nr_segs = kiocb->ki_nbytes; kiocb->ki_cur_seg = 0; /* ki_nbytes/left now reflect bytes instead of segs */ kiocb->ki_nbytes = ret; kiocb->ki_left = ret; ret = 0; out: return ret; } CWE ID: Target: 1 Example 2: Code: void V8TestObject::UseToImpl4ArgumentsCheckingIfPossibleWithOptionalArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_useToImpl4ArgumentsCheckingIfPossibleWithOptionalArg"); test_object_v8_internal::UseToImpl4ArgumentsCheckingIfPossibleWithOptionalArgMethod(info); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) + len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); } 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: bool SoftVPX::outputBuffers(bool flushDecoder, bool display, bool eos, bool *portWillReset) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); BufferInfo *outInfo = NULL; OMX_BUFFERHEADERTYPE *outHeader = NULL; vpx_codec_iter_t iter = NULL; if (flushDecoder && mFrameParallelMode) { if (vpx_codec_decode((vpx_codec_ctx_t *)mCtx, NULL, 0, NULL, 0)) { ALOGE("Failed to flush on2 decoder."); return false; } } if (!display) { if (!flushDecoder) { ALOGE("Invalid operation."); return false; } while ((mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter))) { } return true; } while (!outQueue.empty()) { if (mImg == NULL) { mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter); if (mImg == NULL) { break; } } uint32_t width = mImg->d_w; uint32_t height = mImg->d_h; outInfo = *outQueue.begin(); outHeader = outInfo->mHeader; CHECK_EQ(mImg->fmt, VPX_IMG_FMT_I420); handlePortSettingsChange(portWillReset, width, height); if (*portWillReset) { return true; } outHeader->nOffset = 0; outHeader->nFlags = 0; outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2; outHeader->nTimeStamp = *(OMX_TICKS *)mImg->user_priv; uint8_t *dst = outHeader->pBuffer; const uint8_t *srcY = (const uint8_t *)mImg->planes[VPX_PLANE_Y]; const uint8_t *srcU = (const uint8_t *)mImg->planes[VPX_PLANE_U]; const uint8_t *srcV = (const uint8_t *)mImg->planes[VPX_PLANE_V]; size_t srcYStride = mImg->stride[VPX_PLANE_Y]; size_t srcUStride = mImg->stride[VPX_PLANE_U]; size_t srcVStride = mImg->stride[VPX_PLANE_V]; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mImg = NULL; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } if (!eos) { return true; } if (!outQueue.empty()) { outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); outHeader = outInfo->mHeader; outHeader->nTimeStamp = 0; outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); mEOSStatus = OUTPUT_FRAMES_FLUSHED; } return true; } CWE ID: CWE-264 Target: 1 Example 2: Code: static int ecryptfs_init_global_auth_toks( struct ecryptfs_mount_crypt_stat *mount_crypt_stat) { struct ecryptfs_global_auth_tok *global_auth_tok; struct ecryptfs_auth_tok *auth_tok; int rc = 0; list_for_each_entry(global_auth_tok, &mount_crypt_stat->global_auth_tok_list, mount_crypt_stat_list) { rc = ecryptfs_keyring_auth_tok_for_sig( &global_auth_tok->global_auth_tok_key, &auth_tok, global_auth_tok->sig); if (rc) { printk(KERN_ERR "Could not find valid key in user " "session keyring for sig specified in mount " "option: [%s]\n", global_auth_tok->sig); global_auth_tok->flags |= ECRYPTFS_AUTH_TOK_INVALID; goto out; } else { global_auth_tok->flags &= ~ECRYPTFS_AUTH_TOK_INVALID; up_write(&(global_auth_tok->global_auth_tok_key)->sem); } } out: return rc; } 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: bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) { if (isUserInteractionEvent(event)) return true; LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject)); if (!slider.isNull() && !slider.inDragMode()) return false; const AtomicString& type = event->type(); return type == EventTypeNames::mouseover || type == EventTypeNames::mouseout || type == EventTypeNames::mousemove; } 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 bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } fclose(fp); return true; } CWE ID: CWE-59 Target: 1 Example 2: Code: explicit DummyCryptoServerStreamHelper(quic::QuicRandom* random) : random_(random) {} CWE ID: CWE-284 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int hash_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_toiovec(msg->msg_iov, ctx->result, len); unlock: release_sock(sk); return err ?: len; } 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: xmlParseEntityRef(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr ent = NULL; GROW; if (RAW != '&') return(NULL); NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseEntityRef: no name\n"); return(NULL); } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return(NULL); } NEXT; /* * Predefined entites override any extra definition */ if ((ctxt->options & XML_PARSE_OLDSAX) == 0) { ent = xmlGetPredefinedEntity(name); if (ent != NULL) return(ent); } /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Ask first SAX for entity resolution, otherwise try the * entities which may have stored in the parser context. */ if (ctxt->sax != NULL) { if (ctxt->sax->getEntity != NULL) ent = ctxt->sax->getEntity(ctxt->userData, name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX)) ent = xmlGetPredefinedEntity(name); if ((ctxt->wellFormed == 1 ) && (ent == NULL) && (ctxt->userData==ctxt)) { ent = xmlSAX2GetEntity(ctxt, name); } } /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", the * Name given in the entity reference must match that in an * entity declaration, except that well-formed documents * need not declare any of the following entities: amp, lt, * gt, apos, quot. * The declaration of a parameter entity must precede any * reference to it. * Similarly, the declaration of a general entity must * precede any reference to it which appears in a default * value in an attribute-list declaration. Note that if * entities are declared in the external subset or in * external parameter entities, a non-validating processor * is not obligated to read and process their declarations; * for such documents, the rule that an entity must be * declared is a well-formedness constraint only if * standalone='yes'. */ if (ent == NULL) { if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } else { xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); if ((ctxt->inSubset == 0) && (ctxt->sax != NULL) && (ctxt->sax->reference != NULL)) { ctxt->sax->reference(ctxt->userData, name); } } ctxt->valid = 0; } /* * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an * unparsed entity */ else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY, "Entity reference to unparsed entity %s\n", name); } /* * [ WFC: No External Entity References ] * Attribute values cannot contain direct or indirect * entity references to external entities. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL, "Attribute references external entity '%s'\n", name); } /* * [ WFC: No < in Attribute Values ] * The replacement text of any entity referred to directly or * indirectly in an attribute value (other than "&lt;") must * not contain a <. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent != NULL) && (ent->content != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (xmlStrchr(ent->content, '<'))) { xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, "'<' in entity '%s' is not allowed in attributes values\n", name); } /* * Internal check, no parameter entities here ... */ else { switch (ent->etype) { case XML_INTERNAL_PARAMETER_ENTITY: case XML_EXTERNAL_PARAMETER_ENTITY: xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "Attempt to reference the parameter entity '%s'\n", name); break; default: break; } } /* * [ WFC: No Recursion ] * A parsed entity must not contain a recursive reference * to itself, either directly or indirectly. * Done somewhere else */ return(ent); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int csnmp_config_add_data_blacklist(data_definition_t *dd, oconfig_item_t *ci) { if (ci->values_num < 1) return (0); for (int i = 0; i < ci->values_num; i++) { if (ci->values[i].type != OCONFIG_TYPE_STRING) { WARNING("snmp plugin: `Ignore' needs only string argument."); return (-1); } } dd->ignores_len = 0; dd->ignores = NULL; for (int i = 0; i < ci->values_num; ++i) { if (strarray_add(&(dd->ignores), &(dd->ignores_len), ci->values[i].value.string) != 0) { ERROR("snmp plugin: Can't allocate memory"); strarray_free(dd->ignores, dd->ignores_len); return (ENOMEM); } } return 0; } /* int csnmp_config_add_data_blacklist */ CWE ID: CWE-415 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 countFinalize(sqlite3_context *context){ CountCtx *p; p = sqlite3_aggregate_context(context, 0); sqlite3_result_int64(context, p ? p->n : 0); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _gcry_ecc_eddsa_sign (gcry_mpi_t input, ECC_secret_key *skey, gcry_mpi_t r_r, gcry_mpi_t s, int hashalgo, gcry_mpi_t pk) { int rc; mpi_ec_t ctx = NULL; int b; unsigned int tmp; unsigned char *digest = NULL; gcry_buffer_t hvec[3]; const void *mbuf; size_t mlen; unsigned char *rawmpi = NULL; unsigned int rawmpilen; unsigned char *encpk = NULL; /* Encoded public key. */ unsigned int encpklen; mpi_point_struct I; /* Intermediate value. */ mpi_point_struct Q; /* Public key. */ gcry_mpi_t a, x, y, r; memset (hvec, 0, sizeof hvec); if (!mpi_is_opaque (input)) return GPG_ERR_INV_DATA; /* Initialize some helpers. */ point_init (&I); point_init (&Q); a = mpi_snew (0); x = mpi_new (0); y = mpi_new (0); r = mpi_new (0); ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0, skey->E.p, skey->E.a, skey->E.b); b = (ctx->nbits+7)/8; if (b != 256/8) { rc = GPG_ERR_INTERNAL; /* We only support 256 bit. */ goto leave; } rc = _gcry_ecc_eddsa_compute_h_d (&digest, skey->d, ctx); if (rc) goto leave; _gcry_mpi_set_buffer (a, digest, 32, 0); /* Compute the public key if it has not been supplied as optional parameter. */ if (pk) { rc = _gcry_ecc_eddsa_decodepoint (pk, ctx, &Q, &encpk, &encpklen); if (rc) goto leave; if (DBG_CIPHER) log_printhex ("* e_pk", encpk, encpklen); if (!_gcry_mpi_ec_curve_point (&Q, ctx)) { rc = GPG_ERR_BROKEN_PUBKEY; goto leave; } } else { _gcry_mpi_ec_mul_point (&Q, a, &skey->E.G, ctx); rc = _gcry_ecc_eddsa_encodepoint (&Q, ctx, x, y, 0, &encpk, &encpklen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_pk", encpk, encpklen); } /* Compute R. */ mbuf = mpi_get_opaque (input, &tmp); mlen = (tmp +7)/8; if (DBG_CIPHER) log_printhex (" m", mbuf, mlen); hvec[0].data = digest; hvec[0].off = 32; hvec[0].len = 32; hvec[1].data = (char*)mbuf; hvec[1].len = mlen; rc = _gcry_md_hash_buffers (hashalgo, 0, digest, hvec, 2); if (rc) goto leave; reverse_buffer (digest, 64); if (DBG_CIPHER) log_printhex (" r", digest, 64); _gcry_mpi_set_buffer (r, digest, 64, 0); _gcry_mpi_ec_mul_point (&I, r, &skey->E.G, ctx); if (DBG_CIPHER) log_printpnt (" r", &I, ctx); /* Convert R into affine coordinates and apply encoding. */ rc = _gcry_ecc_eddsa_encodepoint (&I, ctx, x, y, 0, &rawmpi, &rawmpilen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_r", rawmpi, rawmpilen); /* S = r + a * H(encodepoint(R) + encodepoint(pk) + m) mod n */ hvec[0].data = rawmpi; /* (this is R) */ hvec[0].off = 0; hvec[0].len = rawmpilen; hvec[1].data = encpk; hvec[1].off = 0; hvec[1].len = encpklen; hvec[2].data = (char*)mbuf; hvec[2].off = 0; hvec[2].len = mlen; rc = _gcry_md_hash_buffers (hashalgo, 0, digest, hvec, 3); if (rc) goto leave; /* No more need for RAWMPI thus we now transfer it to R_R. */ mpi_set_opaque (r_r, rawmpi, rawmpilen*8); rawmpi = NULL; reverse_buffer (digest, 64); if (DBG_CIPHER) log_printhex (" H(R+)", digest, 64); _gcry_mpi_set_buffer (s, digest, 64, 0); mpi_mulm (s, s, a, skey->E.n); mpi_addm (s, s, r, skey->E.n); rc = eddsa_encodempi (s, b, &rawmpi, &rawmpilen); if (rc) goto leave; if (DBG_CIPHER) log_printhex (" e_s", rawmpi, rawmpilen); mpi_set_opaque (s, rawmpi, rawmpilen*8); rawmpi = NULL; rc = 0; leave: _gcry_mpi_release (a); _gcry_mpi_release (x); _gcry_mpi_release (y); _gcry_mpi_release (r); xfree (digest); _gcry_mpi_ec_free (ctx); point_free (&I); point_free (&Q); xfree (encpk); xfree (rawmpi); return rc; } CWE ID: CWE-200 Target: 1 Example 2: Code: void CheckAuthenticatedState(TabContents* tab, bool displayed_insecure_content) { NavigationEntry* entry = tab->controller().GetActiveEntry(); ASSERT_TRUE(entry); EXPECT_EQ(NORMAL_PAGE, entry->page_type()); EXPECT_EQ(SECURITY_STYLE_AUTHENTICATED, entry->ssl().security_style()); EXPECT_EQ(0, entry->ssl().cert_status() & net::CERT_STATUS_ALL_ERRORS); EXPECT_EQ(displayed_insecure_content, entry->ssl().displayed_insecure_content()); EXPECT_FALSE(entry->ssl().ran_insecure_content()); } 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: adisplay_change_gamma( ADisplay display, double delta ) { display->gamma += delta; if ( display->gamma > 3.0 ) display->gamma = 3.0; else if ( display->gamma < 0.0 ) display->gamma = 0.0; grSetGlyphGamma( display->gamma ); } 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 *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs) { pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel); void *memory; if (dma_alloc_from_coherent(dev, size, handle, &memory)) return memory; return __dma_alloc(dev, size, handle, gfp, prot, false, __builtin_return_address(0)); } CWE ID: CWE-264 Target: 1 Example 2: Code: bool BaseRenderingContext2D::ComputeDirtyRect( const FloatRect& local_rect, const SkIRect& transformed_clip_bounds, SkIRect* dirty_rect) { FloatRect canvas_rect = GetState().Transform().MapRect(local_rect); if (AlphaChannel(GetState().ShadowColor())) { FloatRect shadow_rect(canvas_rect); shadow_rect.Move(GetState().ShadowOffset()); shadow_rect.Inflate(GetState().ShadowBlur()); canvas_rect.Unite(shadow_rect); } SkIRect canvas_i_rect; static_cast<SkRect>(canvas_rect).roundOut(&canvas_i_rect); if (!canvas_i_rect.intersect(transformed_clip_bounds)) return false; if (dirty_rect) *dirty_rect = canvas_i_rect; return true; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos, double *pv) { unsigned int field_type; unsigned int value_count; unsigned int value_pos; unsigned int numer, denom; field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian); value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian); if(value_count!=1) return 0; if(field_type!=5) return 0; // 5=Rational (two uint32's) value_pos = iw_get_ui32_e(&e->d[tag_pos+8],e->endian); if(value_pos > e->d_len-8) return 0; numer = iw_get_ui32_e(&e->d[value_pos ],e->endian); denom = iw_get_ui32_e(&e->d[value_pos+4],e->endian); if(denom==0) return 0; *pv = ((double)numer)/denom; return 1; } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int scsi_disk_emulate_command(SCSIDiskReq *r, uint8_t *outbuf) { SCSIRequest *req = &r->req; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev); uint64_t nb_sectors; int buflen = 0; switch (req->cmd.buf[0]) { case TEST_UNIT_READY: if (s->tray_open || !bdrv_is_inserted(s->bs)) goto not_ready; break; case INQUIRY: buflen = scsi_disk_emulate_inquiry(req, outbuf); if (buflen < 0) goto illegal_request; break; case MODE_SENSE: case MODE_SENSE_10: buflen = scsi_disk_emulate_mode_sense(r, outbuf); if (buflen < 0) goto illegal_request; break; case READ_TOC: buflen = scsi_disk_emulate_read_toc(req, outbuf); if (buflen < 0) goto illegal_request; break; case RESERVE: if (req->cmd.buf[1] & 1) goto illegal_request; break; case RESERVE_10: if (req->cmd.buf[1] & 3) goto illegal_request; break; case RELEASE: if (req->cmd.buf[1] & 1) goto illegal_request; break; case RELEASE_10: if (req->cmd.buf[1] & 3) goto illegal_request; break; case START_STOP: if (scsi_disk_emulate_start_stop(r) < 0) { return -1; } break; case ALLOW_MEDIUM_REMOVAL: s->tray_locked = req->cmd.buf[4] & 1; bdrv_lock_medium(s->bs, req->cmd.buf[4] & 1); break; case READ_CAPACITY_10: /* The normal LEN field for this command is zero. */ memset(outbuf, 0, 8); bdrv_get_geometry(s->bs, &nb_sectors); if (!nb_sectors) goto not_ready; nb_sectors /= s->cluster_size; /* Returned value is the address of the last sector. */ nb_sectors--; /* Remember the new size for read/write sanity checking. */ s->max_lba = nb_sectors; /* Clip to 2TB, instead of returning capacity modulo 2TB. */ if (nb_sectors > UINT32_MAX) nb_sectors = UINT32_MAX; outbuf[0] = (nb_sectors >> 24) & 0xff; outbuf[1] = (nb_sectors >> 16) & 0xff; outbuf[2] = (nb_sectors >> 8) & 0xff; outbuf[3] = nb_sectors & 0xff; outbuf[4] = 0; outbuf[5] = 0; outbuf[6] = s->cluster_size * 2; outbuf[7] = 0; buflen = 8; break; case GET_CONFIGURATION: memset(outbuf, 0, 8); /* ??? This should probably return much more information. For now just return the basic header indicating the CD-ROM profile. */ outbuf[7] = 8; // CD-ROM buflen = 8; break; case SERVICE_ACTION_IN_16: /* Service Action In subcommands. */ if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) { DPRINTF("SAI READ CAPACITY(16)\n"); memset(outbuf, 0, req->cmd.xfer); bdrv_get_geometry(s->bs, &nb_sectors); if (!nb_sectors) goto not_ready; nb_sectors /= s->cluster_size; /* Returned value is the address of the last sector. */ nb_sectors--; /* Remember the new size for read/write sanity checking. */ s->max_lba = nb_sectors; outbuf[0] = (nb_sectors >> 56) & 0xff; outbuf[1] = (nb_sectors >> 48) & 0xff; outbuf[2] = (nb_sectors >> 40) & 0xff; outbuf[3] = (nb_sectors >> 32) & 0xff; outbuf[4] = (nb_sectors >> 24) & 0xff; outbuf[5] = (nb_sectors >> 16) & 0xff; outbuf[6] = (nb_sectors >> 8) & 0xff; outbuf[7] = nb_sectors & 0xff; outbuf[8] = 0; outbuf[9] = 0; outbuf[10] = s->cluster_size * 2; outbuf[11] = 0; outbuf[12] = 0; outbuf[13] = get_physical_block_exp(&s->qdev.conf); /* set TPE bit if the format supports discard */ if (s->qdev.conf.discard_granularity) { outbuf[14] = 0x80; } /* Protection, exponent and lowest lba field left blank. */ buflen = req->cmd.xfer; break; } DPRINTF("Unsupported Service Action In\n"); goto illegal_request; case VERIFY_10: break; default: scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE)); return -1; } return buflen; not_ready: if (s->tray_open || !bdrv_is_inserted(s->bs)) { scsi_check_condition(r, SENSE_CODE(NO_MEDIUM)); } else { scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY)); } return -1; illegal_request: if (r->req.status == -1) { scsi_check_condition(r, SENSE_CODE(INVALID_FIELD)); } return -1; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void mtrr_lookup_fixed_next(struct mtrr_iter *iter) { /* terminate the lookup. */ if (fixed_mtrr_range_end_addr(iter->seg, iter->index) >= iter->end) { iter->fixed = false; iter->range = NULL; return; } iter->index++; /* have looked up for all fixed MTRRs. */ if (iter->index >= ARRAY_SIZE(iter->mtrr_state->fixed_ranges)) return mtrr_lookup_var_start(iter); /* switch to next segment. */ if (iter->index > fixed_mtrr_seg_end_range_index(iter->seg)) iter->seg++; } CWE ID: CWE-284 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Textfield::OnBoundsChanged(const gfx::Rect& previous_bounds) { gfx::Rect bounds = GetLocalBounds(); const gfx::Insets insets = GetInsets(); bounds.Inset(insets.left(), 0, insets.right(), 0); GetRenderText()->SetDisplayRect(bounds); OnCaretBoundsChanged(); UpdateCursorViewPosition(); UpdateCursorVisibility(); } 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: perform_formatting_test(png_store *volatile ps) { #ifdef PNG_TIME_RFC1123_SUPPORTED /* The handle into the formatting code is the RFC1123 support; this test does * nothing if that is compiled out. */ context(ps, fault); Try { png_const_charp correct = "29 Aug 2079 13:53:60 +0000"; png_const_charp result; # if PNG_LIBPNG_VER >= 10600 char timestring[29]; # endif png_structp pp; png_time pt; pp = set_store_for_write(ps, NULL, "libpng formatting test"); if (pp == NULL) Throw ps; /* Arbitrary settings: */ pt.year = 2079; pt.month = 8; pt.day = 29; pt.hour = 13; pt.minute = 53; pt.second = 60; /* a leap second */ # if PNG_LIBPNG_VER < 10600 result = png_convert_to_rfc1123(pp, &pt); # else if (png_convert_to_rfc1123_buffer(timestring, &pt)) result = timestring; else result = NULL; # endif if (result == NULL) png_error(pp, "png_convert_to_rfc1123 failed"); if (strcmp(result, correct) != 0) { size_t pos = 0; char msg[128]; pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123("); pos = safecat(msg, sizeof msg, pos, correct); pos = safecat(msg, sizeof msg, pos, ") returned: '"); pos = safecat(msg, sizeof msg, pos, result); pos = safecat(msg, sizeof msg, pos, "'"); png_error(pp, msg); } store_write_reset(ps); } Catch(fault) { store_write_reset(fault); } #else UNUSED(ps) #endif } CWE ID: Target: 1 Example 2: Code: RenderViewHostImpl* RenderFrameHostManager::pending_render_view_host() const { if (!pending_render_frame_host_) return nullptr; return pending_render_frame_host_->render_view_host(); } 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 get_int32_le(QEMUFile *f, void *pv, size_t size) { int32_t loaded; int32_t loaded; qemu_get_sbe32s(f, &loaded); if (loaded <= *cur) { *cur = loaded; return 0; } } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char * Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) // should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = new (std::nothrow) char[len + 1]; if (dst == NULL) return -1; strcpy(dst, src); return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: void ewk_frame_response_received(Evas_Object* ewkFrame, Ewk_Frame_Resource_Response* response) { evas_object_smart_callback_call(ewkFrame, "resource,response,received", response); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AccessibilityUIElement::isVisible() const { return checkElementState(m_element, ATK_STATE_VISIBLE); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool Block::IsInvisible() const { return bool(int(m_flags & 0x08) != 0); } CWE ID: CWE-119 Target: 1 Example 2: Code: testThread(void) { unsigned int i, repeat; unsigned int num_threads = sizeof(testfiles) / sizeof(testfiles[0]); void *results[MAX_ARGC]; int ret; int res = 0; xmlInitParser(); for (repeat = 0; repeat < 500; repeat++) { xmlLoadCatalog(catalog); nb_tests++; for (i = 0; i < num_threads; i++) { results[i] = NULL; tid[i] = (pthread_t) - 1; } for (i = 0; i < num_threads; i++) { ret = pthread_create(&tid[i], 0, thread_specific_data, (void *) testfiles[i]); if (ret != 0) { fprintf(stderr, "pthread_create failed\n"); return (1); } } for (i = 0; i < num_threads; i++) { ret = pthread_join(tid[i], &results[i]); if (ret != 0) { fprintf(stderr, "pthread_join failed\n"); return (1); } } xmlCatalogCleanup(); for (i = 0; i < num_threads; i++) if (results[i] != (void *) Okay) { fprintf(stderr, "Thread %d handling %s failed\n", i, testfiles[i]); res = 1; } } return (res); } 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 bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) { int i; ut8 *directory_base; struct minidump_directory *entry; directory_base = obj->b->buf + obj->hdr->stream_directory_rva; sdb_num_set (obj->kv, "mdmp_directory.offset", obj->hdr->stream_directory_rva, 0); sdb_set (obj->kv, "mdmp_directory.format", "[4]E? " "(mdmp_stream_type)StreamType " "(mdmp_location_descriptor)Location", 0); /* Parse each entry in the directory */ for (i = 0; i < (int)obj->hdr->number_of_streams; i++) { entry = (struct minidump_directory *)(directory_base + (i * sizeof (struct minidump_directory))); r_bin_mdmp_init_directory_entry (obj, entry); } return true; } 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 AutofillDialogViews::SectionContainer::SetActive(bool active) { bool is_active = active && proxy_button_->visible(); if (is_active == !!background()) return; set_background(is_active ? views::Background::CreateSolidBackground(kShadingColor) : NULL); SchedulePaint(); } CWE ID: CWE-20 Target: 1 Example 2: Code: int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len) { gfn_t gfn = gpa >> PAGE_SHIFT; int seg; int offset = offset_in_page(gpa); int ret; while ((seg = next_segment(len, offset)) != 0) { ret = kvm_clear_guest_page(kvm, gfn, offset, seg); if (ret < 0) return ret; offset = 0; len -= seg; ++gfn; } return 0; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) { FILE *f = NULL; int w, h, prec; int i, numcomps, max; OPJ_COLOR_SPACE color_space; opj_image_cmptparm_t cmptparm; /* maximum of 1 component */ opj_image_t * image = NULL; int adjustS, ushift, dshift, force8; char endian1, endian2, sign; char signtmp[32]; char temp[32]; int bigendian; opj_image_comp_t *comp = NULL; numcomps = 1; color_space = OPJ_CLRSPC_GRAY; memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t)); max = 0; f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Failed to open %s for reading !\n", filename); return NULL; } fseek(f, 0, SEEK_SET); if (fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d", temp, &endian1, &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) { fclose(f); fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n"); return NULL; } i = 0; sign = '+'; while (signtmp[i] != '\0') { if (signtmp[i] == '-') { sign = '-'; } i++; } fgetc(f); if (endian1 == 'M' && endian2 == 'L') { bigendian = 1; } else if (endian2 == 'M' && endian1 == 'L') { bigendian = 0; } else { fclose(f); fprintf(stderr, "Bad pgx header, please check input file\n"); return NULL; } /* initialize image component */ cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0; cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0; cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1; cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1; if (sign == '-') { cmptparm.sgnd = 1; } else { cmptparm.sgnd = 0; } if (prec < 8) { force8 = 1; ushift = 8 - prec; dshift = prec - ushift; if (cmptparm.sgnd) { adjustS = (1 << (prec - 1)); } else { adjustS = 0; } cmptparm.sgnd = 0; prec = 8; } else { ushift = dshift = force8 = adjustS = 0; } cmptparm.prec = (OPJ_UINT32)prec; cmptparm.bpp = (OPJ_UINT32)prec; cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy; /* create the image */ image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space); if (!image) { fclose(f); return NULL; } /* set image offset and reference grid */ image->x0 = cmptparm.x0; image->y0 = cmptparm.x0; image->x1 = cmptparm.w; image->y1 = cmptparm.h; /* set image data */ comp = &image->comps[0]; for (i = 0; i < w * h; i++) { int v; if (force8) { v = readuchar(f) + adjustS; v = (v << ushift) + (v >> dshift); comp->data[i] = (unsigned char)v; if (v > max) { max = v; } continue; } if (comp->prec == 8) { if (!comp->sgnd) { v = readuchar(f); } else { v = (char) readuchar(f); } } else if (comp->prec <= 16) { if (!comp->sgnd) { v = readushort(f, bigendian); } else { v = (short) readushort(f, bigendian); } } else { if (!comp->sgnd) { v = (int)readuint(f, bigendian); } else { v = (int) readuint(f, bigendian); } } if (v > max) { max = v; } comp->data[i] = v; } fclose(f); comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1; return image; } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SendTabToSelfInfoBarDelegate::SendTabToSelfInfoBarDelegate( const SendTabToSelfEntry* entry) { entry_ = entry; } CWE ID: CWE-190 Target: 1 Example 2: Code: TestPaintArtifact& TestPaintArtifact::Chunk(DisplayItemClient& client, const PropertyTreeState& state) { auto& chunks = paint_chunks_data_.chunks; if (!chunks.IsEmpty()) chunks.back().end_index = display_item_list_.size(); chunks.push_back( PaintChunk(display_item_list_.size(), 0, PaintChunk::Id(client, DisplayItem::kDrawingFirst), state)); chunks.back().client_is_just_created = false; return *this; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gss_pseudo_random (OM_uint32 *minor_status, gss_ctx_id_t context_handle, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (context_handle == GSS_C_NO_CONTEXT) return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT; if (prf_in == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT; if (prf_out == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_WRITE | GSS_S_NO_CONTEXT; prf_out->length = 0; prf_out->value = NULL; /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech != NULL) { if (mech->gss_pseudo_random != NULL) { status = mech->gss_pseudo_random(minor_status, ctx->internal_ctx_id, prf_key, prf_in, desired_output_len, prf_out); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return status; } return GSS_S_BAD_MECH; } CWE ID: CWE-415 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int get_gate_page(struct mm_struct *mm, unsigned long address, unsigned int gup_flags, struct vm_area_struct **vma, struct page **page) { pgd_t *pgd; p4d_t *p4d; pud_t *pud; pmd_t *pmd; pte_t *pte; int ret = -EFAULT; /* user gate pages are read-only */ if (gup_flags & FOLL_WRITE) return -EFAULT; if (address > TASK_SIZE) pgd = pgd_offset_k(address); else pgd = pgd_offset_gate(mm, address); BUG_ON(pgd_none(*pgd)); p4d = p4d_offset(pgd, address); BUG_ON(p4d_none(*p4d)); pud = pud_offset(p4d, address); BUG_ON(pud_none(*pud)); pmd = pmd_offset(pud, address); if (!pmd_present(*pmd)) return -EFAULT; VM_BUG_ON(pmd_trans_huge(*pmd)); pte = pte_offset_map(pmd, address); if (pte_none(*pte)) goto unmap; *vma = get_gate_vma(mm); if (!page) goto out; *page = vm_normal_page(*vma, address, *pte); if (!*page) { if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte))) goto unmap; *page = pte_page(*pte); /* * This should never happen (a device public page in the gate * area). */ if (is_device_public_page(*page)) goto unmap; } get_page(*page); out: ret = 0; unmap: pte_unmap(pte); return ret; } CWE ID: CWE-416 Target: 1 Example 2: Code: static unsigned char mem_inq(const struct si_sm_io *io, unsigned int offset) { return (readq((io->addr)+(offset * io->regspacing)) >> io->regshift) & 0xff; } 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 __exit ip6_tables_fini(void) { nf_unregister_sockopt(&ip6t_sockopts); xt_unregister_matches(ip6t_builtin_mt, ARRAY_SIZE(ip6t_builtin_mt)); xt_unregister_targets(ip6t_builtin_tg, ARRAY_SIZE(ip6t_builtin_tg)); unregister_pernet_subsys(&ip6_tables_net_ops); } 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 PrintWebViewHelper::OnPrintForSystemDialog() { blink::WebLocalFrame* frame = print_preview_context_.source_frame(); if (!frame) { NOTREACHED(); return; } Print(frame, print_preview_context_.source_node(), false); } CWE ID: Target: 1 Example 2: Code: static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu) { struct hrtimer *hr = &cpuctx->hrtimer; struct pmu *pmu = cpuctx->ctx.pmu; int timer; /* no multiplexing needed for SW PMU */ if (pmu->task_ctx_nr == perf_sw_context) return; /* * check default is sane, if not set then force to * default interval (1/tick) */ timer = pmu->hrtimer_interval_ms; if (timer < 1) timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER; cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED); hr->function = perf_cpu_hrtimer_handler; } 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: KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() { return keyboard_lib_.GetDefaultImpl(use_stub_impl_); } 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 int userns_install(struct nsproxy *nsproxy, void *ns) { struct user_namespace *user_ns = ns; struct cred *cred; /* Don't allow gaining capabilities by reentering * the same user namespace. */ if (user_ns == current_user_ns()) return -EINVAL; /* Threaded processes may not enter a different user namespace */ if (atomic_read(&current->mm->mm_users) > 1) return -EINVAL; if (!ns_capable(user_ns, CAP_SYS_ADMIN)) return -EPERM; cred = prepare_creds(); if (!cred) return -ENOMEM; put_user_ns(cred->user_ns); set_cred_user_ns(cred, get_user_ns(user_ns)); return commit_creds(cred); } CWE ID: CWE-264 Target: 1 Example 2: Code: device_generate_kernel_change_event (Device *device) { FILE *f; char *filename; filename = g_build_filename (device->priv->native_path, "uevent", NULL); f = fopen (filename, "w"); if (f == NULL) { g_warning ("error opening %s for writing: %m", filename); } else { if (fputs ("change", f) == EOF) { g_warning ("error writing 'change' to %s: %m", filename); } fclose (f); } g_free (filename); } 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 rds_ib_laddr_check(__be32 addr) { int ret; struct rdma_cm_id *cm_id; struct sockaddr_in sin; /* Create a CMA ID and try to bind it. This catches both * IB and iWARP capable NICs. */ cm_id = rdma_create_id(NULL, NULL, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(cm_id)) return PTR_ERR(cm_id); memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = addr; /* rdma_bind_addr will only succeed for IB & iWARP devices */ ret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin); /* due to this, we will claim to support iWARP devices unless we check node_type. */ if (ret || cm_id->device->node_type != RDMA_NODE_IB_CA) ret = -EADDRNOTAVAIL; rdsdebug("addr %pI4 ret %d node type %d\n", &addr, ret, cm_id->device ? cm_id->device->node_type : -1); rdma_destroy_id(cm_id); return ret; } 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: int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { size_t cn_len; int ret; int pathlen = 0, selfsigned = 0; mbedtls_x509_crt *parent; mbedtls_x509_name *name; mbedtls_x509_sequence *cur = NULL; mbedtls_pk_type_t pk_type; *flags = 0; if( profile == NULL ) { ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA; goto exit; } if( cn != NULL ) { name = &crt->subject; cn_len = strlen( cn ); if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) { cur = &crt->subject_alt_names; while( cur != NULL ) { if( cur->buf.len == cn_len && x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 ) break; if( cur->buf.len > 2 && memcmp( cur->buf.p, "*.", 2 ) == 0 && x509_check_wildcard( cn, &cur->buf ) == 0 ) { break; } cur = cur->next; } if( cur == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } else { while( name != NULL ) { if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 ) { if( name->val.len == cn_len && x509_memcasecmp( name->val.p, cn, cn_len ) == 0 ) break; if( name->val.len > 2 && memcmp( name->val.p, "*.", 2 ) == 0 && x509_check_wildcard( cn, &name->val ) == 0 ) break; } name = name->next; } if( name == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } } /* Check the type and size of the key */ pk_type = mbedtls_pk_get_type( &crt->pk ); if( x509_profile_check_pk_alg( profile, pk_type ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; /* Look for a parent in trusted CAs */ for( parent = trust_ca; parent != NULL; parent = parent->next ) { if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 ) break; } if( parent != NULL ) { ret = x509_crt_verify_top( crt, parent, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) goto exit; } else { /* Look for a parent upwards the chain */ for( parent = crt->next; parent != NULL; parent = parent->next ) if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 ) break; /* Are we part of the chain or at the top? */ if( parent != NULL ) { ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) goto exit; } else { ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) goto exit; } } exit: if( ret != 0 ) { *flags = (uint32_t) -1; return( ret ); } if( *flags != 0 ) return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); return( 0 ); } CWE ID: CWE-287 Target: 1 Example 2: Code: cf2_doFlex( CF2_Stack opStack, CF2_Fixed* curX, CF2_Fixed* curY, CF2_GlyphPath glyphPath, const FT_Bool* readFromStack, FT_Bool doConditionalLastRead ) { CF2_Fixed vals[14]; CF2_UInt index; FT_Bool isHFlex; CF2_Int top, i, j; vals[0] = *curX; vals[1] = *curY; index = 0; isHFlex = readFromStack[9] == FALSE; top = isHFlex ? 9 : 10; for ( i = 0; i < top; i++ ) { vals[i + 2] = vals[i]; if ( readFromStack[i] ) vals[i + 2] += cf2_stack_getReal( opStack, index++ ); } if ( isHFlex ) vals[9 + 2] = *curY; if ( doConditionalLastRead ) { FT_Bool lastIsX = (FT_Bool)( cf2_fixedAbs( vals[10] - *curX ) > cf2_fixedAbs( vals[11] - *curY ) ); CF2_Fixed lastVal = cf2_stack_getReal( opStack, index ); if ( lastIsX ) { vals[12] = vals[10] + lastVal; vals[13] = *curY; } else { vals[12] = *curX; vals[13] = vals[11] + lastVal; } } else { if ( readFromStack[10] ) vals[12] = vals[10] + cf2_stack_getReal( opStack, index++ ); else vals[12] = *curX; if ( readFromStack[11] ) vals[13] = vals[11] + cf2_stack_getReal( opStack, index ); else vals[13] = *curY; } for ( j = 0; j < 2; j++ ) cf2_glyphpath_curveTo( glyphPath, vals[j * 6 + 2], vals[j * 6 + 3], vals[j * 6 + 4], vals[j * 6 + 5], vals[j * 6 + 6], vals[j * 6 + 7] ); cf2_stack_clear( opStack ); *curX = vals[12]; *curY = vals[13]; } 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: do_async_increment (IncrementData *data) { gint32 newx = data->x + 1; dbus_g_method_return (data->context, newx); g_free (data); return FALSE; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int treeRead(struct READER *reader, struct DATAOBJECT *data) { int i, j, err, olen, elements, size, x, y, z, b, e, dy, dz, sx, sy, sz, dzy, szy; char *input, *output; uint8_t node_type, node_level; uint16_t entries_used; uint32_t size_of_chunk; uint32_t filter_mask; uint64_t address_of_left_sibling, address_of_right_sibling, start[4], child_pointer, key, store; char buf[4]; UNUSED(node_level); UNUSED(address_of_right_sibling); UNUSED(address_of_left_sibling); UNUSED(key); if (data->ds.dimensionality > 3) { log("TREE dimensions > 3"); return MYSOFA_INVALID_FORMAT; } /* read signature */ if (fread(buf, 1, 4, reader->fhd) != 4 || strncmp(buf, "TREE", 4)) { log("cannot read signature of TREE\n"); return MYSOFA_INVALID_FORMAT; } log("%08lX %.4s\n", (uint64_t )ftell(reader->fhd) - 4, buf); node_type = (uint8_t)fgetc(reader->fhd); node_level = (uint8_t)fgetc(reader->fhd); entries_used = (uint16_t)readValue(reader, 2); if(entries_used>0x1000) return MYSOFA_UNSUPPORTED_FORMAT; address_of_left_sibling = readValue(reader, reader->superblock.size_of_offsets); address_of_right_sibling = readValue(reader, reader->superblock.size_of_offsets); elements = 1; for (j = 0; j < data->ds.dimensionality; j++) elements *= data->datalayout_chunk[j]; dy = data->datalayout_chunk[1]; dz = data->datalayout_chunk[2]; sx = data->ds.dimension_size[0]; sy = data->ds.dimension_size[1]; sz = data->ds.dimension_size[2]; dzy = dz * dy; szy = sz * sy; size = data->datalayout_chunk[data->ds.dimensionality]; log("elements %d size %d\n",elements,size); if (!(output = malloc(elements * size))) { return MYSOFA_NO_MEMORY; } for (e = 0; e < entries_used * 2; e++) { if (node_type == 0) { key = readValue(reader, reader->superblock.size_of_lengths); } else { size_of_chunk = (uint32_t)readValue(reader, 4); filter_mask = (uint32_t)readValue(reader, 4); if (filter_mask) { log("TREE all filters must be enabled\n"); free(output); return MYSOFA_INVALID_FORMAT; } for (j = 0; j < data->ds.dimensionality; j++) { start[j] = readValue(reader, 8); log("start %d %lu\n",j,start[j]); } if (readValue(reader, 8)) { break; } child_pointer = readValue(reader, reader->superblock.size_of_offsets); log(" data at %lX len %u\n", child_pointer, size_of_chunk); /* read data */ store = ftell(reader->fhd); if (fseek(reader->fhd, child_pointer, SEEK_SET)<0) { free(output); return errno; } if (!(input = malloc(size_of_chunk))) { free(output); return MYSOFA_NO_MEMORY; } if (fread(input, 1, size_of_chunk, reader->fhd) != size_of_chunk) { free(output); free(input); return MYSOFA_INVALID_FORMAT; } olen = elements * size; err = gunzip(size_of_chunk, input, &olen, output); free(input); log(" gunzip %d %d %d\n",err, olen, elements*size); if (err || olen != elements * size) { free(output); return MYSOFA_INVALID_FORMAT; } switch (data->ds.dimensionality) { case 1: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements + start[0]; if (x < sx) { j = x * size + b; ((char*)data->data)[j] = output[i]; } } break; case 2: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements; y = x % dy + start[1]; x = x / dy + start[0]; if (y < sy && x < sx) { j = ((x * sy + y) * size) + b; ((char*)data->data)[j] = output[i]; } } break; case 3: for (i = 0; i < olen; i++) { b = i / elements; x = i % elements; z = x % dz + start[2]; y = (x / dz) % dy + start[1]; x = (x / dzy) + start[0]; if (z < sz && y < sy && x < sx) { j = (x * szy + y * sz + z) * size + b; ((char*)data->data)[j] = output[i]; } } break; default: log("invalid dim\n"); return MYSOFA_INTERNAL_ERROR; } if(fseek(reader->fhd, store, SEEK_SET)<0) { free(output); return errno; } } } free(output); if(fseek(reader->fhd, 4, SEEK_CUR)<0) /* skip checksum */ return errno; return MYSOFA_OK; } CWE ID: CWE-20 Target: 1 Example 2: Code: static TEE_Result user_ta_enter_open_session(struct tee_ta_session *s, struct tee_ta_param *param, TEE_ErrorOrigin *eo) { return user_ta_enter(eo, s, UTEE_ENTRY_FUNC_OPEN_SESSION, 0, param); } 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 CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); } 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 run_post_create(const char *dirname) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dirname)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location); return 400; /* Bad Request */ } if (!dump_dir_accessible_by_uid(dirname, client_uid)) { if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dirname); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid); return 403; /* Forbidden */ } int child_stdout_fd; int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd); char *dup_of_dir = NULL; struct strbuf *cmd_output = strbuf_new(); bool child_is_post_create = 1; /* else it is a notify child */ read_child_output: /* Read streamed data and split lines */ for (;;) { char buf[250]; /* usually we get one line, no need to have big buf */ errno = 0; int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1); if (r <= 0) break; buf[r] = '\0'; /* split lines in the current buffer */ char *raw = buf; char *newline; while ((newline = strchr(raw, '\n')) != NULL) { *newline = '\0'; strbuf_append_str(cmd_output, raw); char *msg = cmd_output->buf; /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */ log("%s", msg); if (child_is_post_create && prefixcmp(msg, "DUP_OF_DIR: ") == 0 ) { free(dup_of_dir); dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: ")); } strbuf_clear(cmd_output); /* jump to next line */ raw = newline + 1; } /* beginning of next line. the line continues by next read */ strbuf_append_str(cmd_output, raw); } /* EOF/error */ /* Wait for child to actually exit, collect status */ int status = 0; if (safe_waitpid(child_pid, &status, 0) <= 0) /* should not happen */ perror_msg("waitpid(%d)", child_pid); /* If it was a "notify[-dup]" event, then we're done */ if (!child_is_post_create) goto ret; /* exit 0 means "this is a good, non-dup dir" */ /* exit with 1 + "DUP_OF_DIR: dir" string => dup */ if (status != 0) { if (WIFSIGNALED(status)) { log("'post-create' on '%s' killed by signal %d", dirname, WTERMSIG(status)); goto delete_bad_dir; } /* else: it is WIFEXITED(status) */ if (!dup_of_dir) { log("'post-create' on '%s' exited with %d", dirname, WEXITSTATUS(status)); goto delete_bad_dir; } } const char *work_dir = (dup_of_dir ? dup_of_dir : dirname); /* Load problem_data (from the *first dir* if this one is a dup) */ struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0); if (!dd) /* dd_opendir already emitted error msg */ goto delete_bad_dir; /* Update count */ char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT); unsigned long count = strtoul(count_str, NULL, 10); /* Don't increase crash count if we are working with newly uploaded * directory (remote crash) which already has its crash count set. */ if ((status != 0 && dup_of_dir) || count == 0) { count++; char new_count_str[sizeof(long)*3 + 2]; sprintf(new_count_str, "%lu", count); dd_save_text(dd, FILENAME_COUNT, new_count_str); /* This condition can be simplified to either * (status * != 0 && * dup_of_dir) or (count == 1). But the * chosen form is much more reliable and safe. We must not call * dd_opendir() to locked dd otherwise we go into a deadlock. */ if (strcmp(dd->dd_dirname, dirname) != 0) { /* Update the last occurrence file by the time file of the new problem */ struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY); char *last_ocr = NULL; if (new_dd) { /* TIME must exists in a valid dump directory but we don't want to die * due to broken duplicated dump directory */ last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT); dd_close(new_dd); } else { /* dd_opendir() already produced a message with good information about failure */ error_msg("Can't read the last occurrence file from the new dump directory."); } if (!last_ocr) { /* the new dump directory may lie in the dump location for some time */ log("Using current time for the last occurrence file which may be incorrect."); time_t t = time(NULL); last_ocr = xasprintf("%lu", (long)t); } dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr); free(last_ocr); } } /* Reset mode/uig/gid to correct values for all files created by event run */ dd_sanitize_mode_and_owner(dd); dd_close(dd); if (!dup_of_dir) log_notice("New problem directory %s, processing", work_dir); else { log_warning("Deleting problem directory %s (dup of %s)", strrchr(dirname, '/') + 1, strrchr(dup_of_dir, '/') + 1); delete_dump_dir(dirname); } /* Run "notify[-dup]" event */ int fd; child_pid = spawn_event_handler_child( work_dir, (dup_of_dir ? "notify-dup" : "notify"), &fd ); xmove_fd(fd, child_stdout_fd); child_is_post_create = 0; strbuf_clear(cmd_output); free(dup_of_dir); dup_of_dir = NULL; goto read_child_output; delete_bad_dir: log_warning("Deleting problem directory '%s'", dirname); delete_dump_dir(dirname); ret: strbuf_free(cmd_output); free(dup_of_dir); close(child_stdout_fd); return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: void ATSParser::Program::signalEOS(status_t finalResult) { for (size_t i = 0; i < mStreams.size(); ++i) { mStreams.editValueAt(i)->signalEOS(finalResult); } } 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: unsigned DOMWindow::length() const { return GetFrame() ? GetFrame()->Tree().ScopedChildCount() : 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: static struct o2nm_cluster *to_o2nm_cluster_from_node(struct o2nm_node *node) { /* through the first node_set .parent * mycluster/nodes/mynode == o2nm_cluster->o2nm_node_group->o2nm_node */ return to_o2nm_cluster(node->nd_item.ci_parent->ci_parent); } CWE ID: CWE-476 Target: 1 Example 2: Code: static inline void nohz_newidle_balance(struct rq *this_rq) { } CWE ID: CWE-400 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static apr_size_t config_getstr(ap_configfile_t *cfg, char *buf, size_t bufsiz) { apr_size_t i = 0; if (cfg->getstr) { apr_status_t rc = (cfg->getstr) (buf, bufsiz, cfg->param); if (rc == APR_SUCCESS) { i = strlen(buf); if (i && buf[i - 1] == '\n') ++cfg->line_number; } else { buf[0] = '\0'; i = 0; } } else { while (i < bufsiz) { char ch; apr_status_t rc = (cfg->getch) (&ch, cfg->param); if (rc != APR_SUCCESS) break; buf[i++] = ch; if (ch == '\n') { ++cfg->line_number; break; } } } return i; } 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: ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length) { register const struct rip6 *rp = (const struct rip6 *)dat; register const struct netinfo6 *ni; register u_int amt; register u_int i; int j; int trunc; if (ndo->ndo_snapend < dat) return; amt = ndo->ndo_snapend - dat; i = min(length, amt); if (i < (sizeof(struct rip6) - sizeof(struct netinfo6))) return; i -= (sizeof(struct rip6) - sizeof(struct netinfo6)); switch (rp->rip6_cmd) { case RIP6_REQUEST: j = length / sizeof(*ni); if (j == 1 && rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6 && IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) { ND_PRINT((ndo, " ripng-req dump")); break; } if (j * sizeof(*ni) != length - 4) ND_PRINT((ndo, " ripng-req %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-req %d:", j)); trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i); for (ni = rp->rip6_nets; i >= sizeof(*ni); i -= sizeof(*ni), ++ni) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, 0); } break; case RIP6_RESPONSE: j = length / sizeof(*ni); if (j * sizeof(*ni) != length - 4) ND_PRINT((ndo, " ripng-resp %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-resp %d:", j)); trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i); for (ni = rp->rip6_nets; i >= sizeof(*ni); i -= sizeof(*ni), ++ni) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, ni->rip6_metric); } if (trunc) ND_PRINT((ndo, "[|ripng]")); break; default: ND_PRINT((ndo, " ripng-%d ?? %u", rp->rip6_cmd, length)); break; } if (rp->rip6_vers != RIP6_VERSION) ND_PRINT((ndo, " [vers %d]", rp->rip6_vers)); } CWE ID: CWE-125 Target: 1 Example 2: Code: AXObject* AXObjectCacheImpl::focusedObject() { if (!accessibilityEnabled()) return nullptr; Node* focusedNode = m_document->focusedElement(); if (!focusedNode) focusedNode = m_document; if (isHTMLAreaElement(focusedNode)) return focusedImageMapUIElement(toHTMLAreaElement(focusedNode)); Element* adjustedFocusedElement = m_document->adjustedFocusedElement(); if (isHTMLInputElement(adjustedFocusedElement)) { if (AXObject* axPopup = toHTMLInputElement(adjustedFocusedElement)->popupRootAXObject()) { if (Element* focusedElementInPopup = axPopup->getDocument()->focusedElement()) focusedNode = focusedElementInPopup; } } AXObject* obj = getOrCreate(focusedNode); if (!obj) return nullptr; if (obj->accessibilityIsIgnored()) obj = obj->parentObjectUnignored(); return obj; } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewImpl::SetEditCommandForNextKeyEvent(const std::string& name, const std::string& value) { EditCommands edit_commands; edit_commands.push_back(EditCommand(name, value)); OnSetEditCommandsForNextKeyEvent(edit_commands); } 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: const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const { if (idx < 0) return 0; if (idx >= m_void_element_count) return 0; return m_void_elements + idx; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void qeth_start_kernel_thread(struct work_struct *work) { struct task_struct *ts; struct qeth_card *card = container_of(work, struct qeth_card, kernel_thread_starter); QETH_CARD_TEXT(card , 2, "strthrd"); if (card->read.state != CH_STATE_UP && card->write.state != CH_STATE_UP) return; if (qeth_do_start_thread(card, QETH_RECOVER_THREAD)) { ts = kthread_run(card->discipline->recover, (void *)card, "qeth_recover"); if (IS_ERR(ts)) { qeth_clear_thread_start_bit(card, QETH_RECOVER_THREAD); qeth_clear_thread_running_bit(card, QETH_RECOVER_THREAD); } } } 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 catc_stats_timer(unsigned long data) { struct catc *catc = (void *) data; int i; for (i = 0; i < 8; i++) catc_get_reg_async(catc, EthStats + 7 - i, catc_stats_done); mod_timer(&catc->timer, jiffies + STATS_UPDATE); } 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 ImageBitmapFactories::ImageBitmapLoader::LoadBlobAsync( Blob* blob) { loader_->Start(blob->GetBlobDataHandle()); } CWE ID: CWE-416 Target: 1 Example 2: Code: static int md5_sparc64_init(struct shash_desc *desc) { struct md5_state *mctx = shash_desc_ctx(desc); mctx->hash[0] = cpu_to_le32(0x67452301); mctx->hash[1] = cpu_to_le32(0xefcdab89); mctx->hash[2] = cpu_to_le32(0x98badcfe); mctx->hash[3] = cpu_to_le32(0x10325476); mctx->byte_count = 0; return 0; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int cJSON_strcasecmp( const char *s1, const char *s2 ) { if ( ! s1 ) return ( s1 == s2 ) ? 0 : 1; if ( ! s2 ) return 1; for ( ; tolower(*s1) == tolower(*s2); ++s1, ++s2) if( *s1 == 0 ) return 0; return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); } 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 RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() { if (render_frame_host_->GetView() && render_frame_host_->render_view_host()->GetWidget()->is_hidden() != delegate_->IsHidden()) { if (delegate_->IsHidden()) { render_frame_host_->GetView()->Hide(); } else { render_frame_host_->GetView()->Show(); } } } CWE ID: CWE-20 Target: 1 Example 2: Code: void TabLifecycleUnitSource::TabLifecycleUnit::SetFocused(bool focused) { const bool was_focused = last_focused_time_ == base::TimeTicks::Max(); if (focused == was_focused) return; last_focused_time_ = focused ? base::TimeTicks::Max() : NowTicks(); if (!focused) return; switch (GetState()) { case LifecycleUnitState::DISCARDED: { SetState(LifecycleUnitState::ACTIVE, StateChangeReason::BROWSER_INITIATED); bool loaded = Load(); DCHECK(loaded); break; } case LifecycleUnitState::PENDING_DISCARD: { freeze_timeout_timer_->Stop(); SetState(LifecycleUnitState::PENDING_FREEZE, StateChangeReason::BROWSER_INITIATED); break; } default: break; } } 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 willRemoveChildren(ContainerNode* container) { NodeVector children; getChildNodes(container, children); container->document().nodeChildrenWillBeRemoved(container); ChildListMutationScope mutation(container); for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) { Node* child = it->get(); mutation.willRemoveChild(child); child->notifyMutationObserversNodeWillDetach(); dispatchChildRemovalEvents(child); } ChildFrameDisconnector(container).disconnect(ChildFrameDisconnector::DescendantsOnly); } 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: cJSON *cJSON_GetArrayItem( cJSON *array, int item ) { cJSON *c = array->child; while ( c && item > 0 ) { --item; c = c->next; } return c; } CWE ID: CWE-119 Target: 1 Example 2: Code: WorkerFetchContext::WorkerFetchContext( WorkerOrWorkletGlobalScope& global_scope, std::unique_ptr<WebWorkerFetchContext> web_context) : global_scope_(global_scope), web_context_(std::move(web_context)), loading_task_runner_( TaskRunnerHelper::Get(TaskType::kUnspecedLoading, global_scope_)) { web_context_->InitializeOnWorkerThread( loading_task_runner_->ToSingleThreadTaskRunner()); std::unique_ptr<blink::WebDocumentSubresourceFilter> web_filter = web_context_->TakeSubresourceFilter(); if (web_filter) { subresource_filter_ = SubresourceFilter::Create(global_scope, std::move(web_filter)); } } 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 ssize_t qib_write(struct file *fp, const char __user *data, size_t count, loff_t *off) { const struct qib_cmd __user *ucmd; struct qib_ctxtdata *rcd; const void __user *src; size_t consumed, copy = 0; struct qib_cmd cmd; ssize_t ret = 0; void *dest; if (count < sizeof(cmd.type)) { ret = -EINVAL; goto bail; } ucmd = (const struct qib_cmd __user *) data; if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) { ret = -EFAULT; goto bail; } consumed = sizeof(cmd.type); switch (cmd.type) { case QIB_CMD_ASSIGN_CTXT: case QIB_CMD_USER_INIT: copy = sizeof(cmd.cmd.user_info); dest = &cmd.cmd.user_info; src = &ucmd->cmd.user_info; break; case QIB_CMD_RECV_CTRL: copy = sizeof(cmd.cmd.recv_ctrl); dest = &cmd.cmd.recv_ctrl; src = &ucmd->cmd.recv_ctrl; break; case QIB_CMD_CTXT_INFO: copy = sizeof(cmd.cmd.ctxt_info); dest = &cmd.cmd.ctxt_info; src = &ucmd->cmd.ctxt_info; break; case QIB_CMD_TID_UPDATE: case QIB_CMD_TID_FREE: copy = sizeof(cmd.cmd.tid_info); dest = &cmd.cmd.tid_info; src = &ucmd->cmd.tid_info; break; case QIB_CMD_SET_PART_KEY: copy = sizeof(cmd.cmd.part_key); dest = &cmd.cmd.part_key; src = &ucmd->cmd.part_key; break; case QIB_CMD_DISARM_BUFS: case QIB_CMD_PIOAVAILUPD: /* force an update of PIOAvail reg */ copy = 0; src = NULL; dest = NULL; break; case QIB_CMD_POLL_TYPE: copy = sizeof(cmd.cmd.poll_type); dest = &cmd.cmd.poll_type; src = &ucmd->cmd.poll_type; break; case QIB_CMD_ARMLAUNCH_CTRL: copy = sizeof(cmd.cmd.armlaunch_ctrl); dest = &cmd.cmd.armlaunch_ctrl; src = &ucmd->cmd.armlaunch_ctrl; break; case QIB_CMD_SDMA_INFLIGHT: copy = sizeof(cmd.cmd.sdma_inflight); dest = &cmd.cmd.sdma_inflight; src = &ucmd->cmd.sdma_inflight; break; case QIB_CMD_SDMA_COMPLETE: copy = sizeof(cmd.cmd.sdma_complete); dest = &cmd.cmd.sdma_complete; src = &ucmd->cmd.sdma_complete; break; case QIB_CMD_ACK_EVENT: copy = sizeof(cmd.cmd.event_mask); dest = &cmd.cmd.event_mask; src = &ucmd->cmd.event_mask; break; default: ret = -EINVAL; goto bail; } if (copy) { if ((count - consumed) < copy) { ret = -EINVAL; goto bail; } if (copy_from_user(dest, src, copy)) { ret = -EFAULT; goto bail; } consumed += copy; } rcd = ctxt_fp(fp); if (!rcd && cmd.type != QIB_CMD_ASSIGN_CTXT) { ret = -EINVAL; goto bail; } switch (cmd.type) { case QIB_CMD_ASSIGN_CTXT: ret = qib_assign_ctxt(fp, &cmd.cmd.user_info); if (ret) goto bail; break; case QIB_CMD_USER_INIT: ret = qib_do_user_init(fp, &cmd.cmd.user_info); if (ret) goto bail; ret = qib_get_base_info(fp, (void __user *) (unsigned long) cmd.cmd.user_info.spu_base_info, cmd.cmd.user_info.spu_base_info_size); break; case QIB_CMD_RECV_CTRL: ret = qib_manage_rcvq(rcd, subctxt_fp(fp), cmd.cmd.recv_ctrl); break; case QIB_CMD_CTXT_INFO: ret = qib_ctxt_info(fp, (struct qib_ctxt_info __user *) (unsigned long) cmd.cmd.ctxt_info); break; case QIB_CMD_TID_UPDATE: ret = qib_tid_update(rcd, fp, &cmd.cmd.tid_info); break; case QIB_CMD_TID_FREE: ret = qib_tid_free(rcd, subctxt_fp(fp), &cmd.cmd.tid_info); break; case QIB_CMD_SET_PART_KEY: ret = qib_set_part_key(rcd, cmd.cmd.part_key); break; case QIB_CMD_DISARM_BUFS: (void)qib_disarm_piobufs_ifneeded(rcd); ret = disarm_req_delay(rcd); break; case QIB_CMD_PIOAVAILUPD: qib_force_pio_avail_update(rcd->dd); break; case QIB_CMD_POLL_TYPE: rcd->poll_type = cmd.cmd.poll_type; break; case QIB_CMD_ARMLAUNCH_CTRL: rcd->dd->f_set_armlaunch(rcd->dd, cmd.cmd.armlaunch_ctrl); break; case QIB_CMD_SDMA_INFLIGHT: ret = qib_sdma_get_inflight(user_sdma_queue_fp(fp), (u32 __user *) (unsigned long) cmd.cmd.sdma_inflight); break; case QIB_CMD_SDMA_COMPLETE: ret = qib_sdma_get_complete(rcd->ppd, user_sdma_queue_fp(fp), (u32 __user *) (unsigned long) cmd.cmd.sdma_complete); break; case QIB_CMD_ACK_EVENT: ret = qib_user_event_ack(rcd, subctxt_fp(fp), cmd.cmd.event_mask); break; } if (ret >= 0) ret = consumed; bail: return ret; } 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: static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is recovered."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path) { int k, l = path->p_depth; ext_debug("path:"); for (k = 0; k <= l; k++, path++) { if (path->p_idx) { ext_debug(" %d->%llu", le32_to_cpu(path->p_idx->ei_block), ext4_idx_pblock(path->p_idx)); } else if (path->p_ext) { ext_debug(" %d:[%d]%d:%llu ", le32_to_cpu(path->p_ext->ee_block), ext4_ext_is_uninitialized(path->p_ext), ext4_ext_get_actual_len(path->p_ext), ext4_ext_pblock(path->p_ext)); } else ext_debug(" []"); } ext_debug("\n"); } 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: cnid_to_array(uint32_t cnid, uint8_t array[4]) { array[3] = (cnid >> 0) & 0xff; array[2] = (cnid >> 8) & 0xff; array[1] = (cnid >> 16) & 0xff; array[0] = (cnid >> 24) & 0xff; } 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: Track::Info::~Info() { Clear(); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void acm_ctrl_irq(struct urb *urb) { struct acm *acm = urb->context; struct usb_cdc_notification *dr = urb->transfer_buffer; unsigned char *data; int newctrl; int difference; int retval; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&acm->control->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_dbg(&acm->control->dev, "%s - nonzero urb status received: %d\n", __func__, status); goto exit; } usb_mark_last_busy(acm->dev); data = (unsigned char *)(dr + 1); switch (dr->bNotificationType) { case USB_CDC_NOTIFY_NETWORK_CONNECTION: dev_dbg(&acm->control->dev, "%s - network connection: %d\n", __func__, dr->wValue); break; case USB_CDC_NOTIFY_SERIAL_STATE: newctrl = get_unaligned_le16(data); if (!acm->clocal && (acm->ctrlin & ~newctrl & ACM_CTRL_DCD)) { dev_dbg(&acm->control->dev, "%s - calling hangup\n", __func__); tty_port_tty_hangup(&acm->port, false); } difference = acm->ctrlin ^ newctrl; spin_lock(&acm->read_lock); acm->ctrlin = newctrl; acm->oldcount = acm->iocount; if (difference & ACM_CTRL_DSR) acm->iocount.dsr++; if (difference & ACM_CTRL_BRK) acm->iocount.brk++; if (difference & ACM_CTRL_RI) acm->iocount.rng++; if (difference & ACM_CTRL_DCD) acm->iocount.dcd++; if (difference & ACM_CTRL_FRAMING) acm->iocount.frame++; if (difference & ACM_CTRL_PARITY) acm->iocount.parity++; if (difference & ACM_CTRL_OVERRUN) acm->iocount.overrun++; spin_unlock(&acm->read_lock); if (difference) wake_up_all(&acm->wioctl); break; default: dev_dbg(&acm->control->dev, "%s - unknown notification %d received: index %d " "len %d data0 %d data1 %d\n", __func__, dr->bNotificationType, dr->wIndex, dr->wLength, data[0], data[1]); break; } exit: retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval && retval != -EPERM) dev_err(&acm->control->dev, "%s - usb_submit_urb failed: %d\n", __func__, retval); } 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 enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { if (settings.verbose > 0) fprintf(stderr, "Couldn't realloc input buffer\n"); c->rbytes = 0; /* ignore what we read */ out_string(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = read(c->sfd, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void server_real_connect(SERVER_REC *server, IPADDR *ip, const char *unix_socket) { GIOChannel *handle; IPADDR *own_ip = NULL; const char *errmsg; char *errmsg2; char ipaddr[MAX_IP_LEN]; int port; g_return_if_fail(ip != NULL || unix_socket != NULL); signal_emit("server connecting", 2, server, ip); if (server->connrec->no_connect) return; if (ip != NULL) { own_ip = ip == NULL ? NULL : (IPADDR_IS_V6(ip) ? server->connrec->own_ip6 : server->connrec->own_ip4); port = server->connrec->proxy != NULL ? server->connrec->proxy_port : server->connrec->port; handle = server->connrec->use_ssl ? net_connect_ip_ssl(ip, port, own_ip, server->connrec->ssl_cert, server->connrec->ssl_pkey, server->connrec->ssl_cafile, server->connrec->ssl_capath, server->connrec->ssl_verify) : net_connect_ip(ip, port, own_ip); } else { handle = net_connect_unix(unix_socket); } if (handle == NULL) { /* failed */ errmsg = g_strerror(errno); errmsg2 = NULL; if (errno == EADDRNOTAVAIL) { if (own_ip != NULL) { /* show the IP which is causing the error */ net_ip2host(own_ip, ipaddr); errmsg2 = g_strconcat(errmsg, ": ", ipaddr, NULL); } server->no_reconnect = TRUE; } if (server->connrec->use_ssl && errno == ENOSYS) server->no_reconnect = TRUE; server->connection_lost = TRUE; server_connect_failed(server, errmsg2 ? errmsg2 : errmsg); g_free(errmsg2); } else { server->handle = net_sendbuffer_create(handle, 0); #ifdef HAVE_OPENSSL if (server->connrec->use_ssl) server_connect_callback_init_ssl(server, handle); else #endif server->connect_tag = g_input_add(handle, G_INPUT_WRITE | G_INPUT_READ, (GInputFunction) server_connect_callback_init, server); } } CWE ID: CWE-20 Target: 1 Example 2: Code: void rtnl_set_sk_err(struct net *net, u32 group, int error) { struct sock *rtnl = net->rtnl; netlink_set_err(rtnl, 0, group, error); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool RenderViewImpl::ForceCompositingModeEnabled() { return webkit_preferences_.force_compositing_mode; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BluetoothDeviceChromeOS::Release() { DCHECK(agent_.get()); DCHECK(pairing_delegate_); VLOG(1) << object_path_.value() << ": Release"; pincode_callback_.Reset(); passkey_callback_.Reset(); confirmation_callback_.Reset(); UnregisterAgent(); } CWE ID: Target: 1 Example 2: Code: char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) { return FS_ListFilteredFiles( path, extension, NULL, numfiles, qfalse ); } 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: authentic_manage_sdo_encode_prvkey(struct sc_card *card, struct sc_pkcs15_prkey *prvkey, unsigned char **out, size_t *out_len) { struct sc_context *ctx = card->ctx; struct sc_pkcs15_prkey_rsa rsa; unsigned char *blob = NULL, *blob01 = NULL; size_t blob_len = 0, blob01_len = 0; int rv; if (!prvkey || !out || !out_len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments"); if (prvkey->algorithm != SC_ALGORITHM_RSA) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO operation"); rsa = prvkey->u.rsa; /* Encode private RSA key part */ rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_P, rsa.p.data, rsa.p.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA P encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_Q, rsa.q.data, rsa.q.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA Q encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_PQ, rsa.iqmp.data, rsa.iqmp.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA PQ encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_DP1, rsa.dmp1.data, rsa.dmp1.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA DP1 encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_DQ1, rsa.dmq1.data, rsa.dmq1.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA DQ1 encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE, blob, blob_len, &blob01, &blob01_len); LOG_TEST_RET(ctx, rv, "SDO RSA Private encode error"); free (blob); blob = NULL; blob_len = 0; /* Encode public RSA key part */ sc_log(ctx, "modulus.len:%"SC_FORMAT_LEN_SIZE_T"u blob_len:%"SC_FORMAT_LEN_SIZE_T"u", rsa.modulus.len, blob_len); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC_MODULUS, rsa.modulus.data, rsa.modulus.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA Modulus encode error"); sc_log(ctx, "exponent.len:%"SC_FORMAT_LEN_SIZE_T"u blob_len:%"SC_FORMAT_LEN_SIZE_T"u", rsa.exponent.len, blob_len); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC_EXPONENT, rsa.exponent.data, rsa.exponent.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA Exponent encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC, blob, blob_len, &blob01, &blob01_len); LOG_TEST_RET(ctx, rv, "SDO RSA Private encode error"); free (blob); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA, blob01, blob01_len, out, out_len); LOG_TEST_RET(ctx, rv, "SDO RSA encode error"); free(blob01); LOG_FUNC_RETURN(ctx, rv); } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void fdct8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fdct8x8_c(in, out, stride); } CWE ID: CWE-119 Target: 1 Example 2: Code: auth_update_binary(struct sc_card *card, unsigned int offset, const unsigned char *buf, size_t count, unsigned long flags) { int rv = 0; LOG_FUNC_CALLED(card->ctx); sc_log(card->ctx, "offset %i; count %"SC_FORMAT_LEN_SIZE_T"u", offset, count); sc_log(card->ctx, "last selected : magic %X; ef %X", auth_current_ef->magic, auth_current_ef->ef_structure); if (offset & ~0x7FFF) LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid file offset"); if (auth_current_ef->magic==SC_FILE_MAGIC && auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_RSA_PUBLIC) { rv = write_publickey(card, offset, buf, count); } else if (auth_current_ef->magic==SC_FILE_MAGIC && auth_current_ef->ef_structure == SC_CARDCTL_OBERTHUR_KEY_DES) { struct auth_update_component_info args; memset(&args, 0, sizeof(args)); args.type = SC_CARDCTL_OBERTHUR_KEY_DES; args.data = (unsigned char *)buf; args.len = count; rv = auth_update_component(card, &args); } else { rv = iso_ops->update_binary(card, offset, buf, count, 0); } LOG_FUNC_RETURN(card->ctx, rv); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int xts_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct twofish_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); return glue_xts_crypt_128bit(&twofish_dec_xts, desc, dst, src, nbytes, XTS_TWEAK_CAST(twofish_enc_blk), &ctx->tweak_ctx, &ctx->crypt_ctx); } 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: IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b) { return (b[0]<<8) | b[1]; } CWE ID: CWE-682 Target: 1 Example 2: Code: eXosip_set_cbsip_message (struct eXosip_t *excontext, CbSipCallback cbsipCallback) { excontext->cbsipCallback = cbsipCallback; return 0; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool MediaElementAudioSourceHandler::PassesCORSAccessCheck() { DCHECK(MediaElement()); return (MediaElement()->GetWebMediaPlayer() && MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) || passes_current_src_cors_access_check_; } 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 GDataDirectoryService::InitializeRootEntry(const std::string& root_id) { root_.reset(new GDataDirectory(NULL, this)); root_->set_title(kGDataRootDirectory); root_->SetBaseNameFromTitle(); root_->set_resource_id(root_id); AddEntryToResourceMap(root_.get()); } CWE ID: CWE-399 Target: 1 Example 2: Code: static int ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, struct fib_result *res) { struct in_device *in_dev = __in_dev_get_rcu(dev); struct ip_tunnel_info *tun_info; struct flowi4 fl4; unsigned int flags = 0; u32 itag = 0; struct rtable *rth; int err = -EINVAL; struct net *net = dev_net(dev); bool do_cache; /* IP on this device is disabled. */ if (!in_dev) goto out; /* Check for the most weird martians, which can be not detected by fib_lookup. */ tun_info = skb_tunnel_info(skb); if (tun_info && !(tun_info->mode & IP_TUNNEL_INFO_TX)) fl4.flowi4_tun_key.tun_id = tun_info->key.tun_id; else fl4.flowi4_tun_key.tun_id = 0; skb_dst_drop(skb); if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr)) goto martian_source; res->fi = NULL; res->table = NULL; if (ipv4_is_lbcast(daddr) || (saddr == 0 && daddr == 0)) goto brd_input; /* Accept zero addresses only to limited broadcast; * I even do not know to fix it or not. Waiting for complains :-) */ if (ipv4_is_zeronet(saddr)) goto martian_source; if (ipv4_is_zeronet(daddr)) goto martian_destination; /* Following code try to avoid calling IN_DEV_NET_ROUTE_LOCALNET(), * and call it once if daddr or/and saddr are loopback addresses */ if (ipv4_is_loopback(daddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_destination; } else if (ipv4_is_loopback(saddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_source; } /* * Now we are ready to route packet. */ fl4.flowi4_oif = 0; fl4.flowi4_iif = dev->ifindex; fl4.flowi4_mark = skb->mark; fl4.flowi4_tos = tos; fl4.flowi4_scope = RT_SCOPE_UNIVERSE; fl4.flowi4_flags = 0; fl4.daddr = daddr; fl4.saddr = saddr; fl4.flowi4_uid = sock_net_uid(net, NULL); err = fib_lookup(net, &fl4, res, 0); if (err != 0) { if (!IN_DEV_FORWARD(in_dev)) err = -EHOSTUNREACH; goto no_route; } if (res->type == RTN_BROADCAST) goto brd_input; if (res->type == RTN_LOCAL) { err = fib_validate_source(skb, saddr, daddr, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source; goto local_input; } if (!IN_DEV_FORWARD(in_dev)) { err = -EHOSTUNREACH; goto no_route; } if (res->type != RTN_UNICAST) goto martian_destination; err = ip_mkroute_input(skb, res, in_dev, daddr, saddr, tos); out: return err; brd_input: if (skb->protocol != htons(ETH_P_IP)) goto e_inval; if (!ipv4_is_zeronet(saddr)) { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source; } flags |= RTCF_BROADCAST; res->type = RTN_BROADCAST; RT_CACHE_STAT_INC(in_brd); local_input: do_cache = false; if (res->fi) { if (!itag) { rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); err = 0; goto out; } do_cache = true; } } rth = rt_dst_alloc(l3mdev_master_dev_rcu(dev) ? : net->loopback_dev, flags | RTCF_LOCAL, res->type, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache); if (!rth) goto e_nobufs; rth->dst.output= ip_rt_bug; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->rt_is_input = 1; if (res->table) rth->rt_table_id = res->table->tb_id; RT_CACHE_STAT_INC(in_slow_tot); if (res->type == RTN_UNREACHABLE) { rth->dst.input= ip_error; rth->dst.error= -err; rth->rt_flags &= ~RTCF_LOCAL; } if (do_cache) { struct fib_nh *nh = &FIB_RES_NH(*res); rth->dst.lwtstate = lwtstate_get(nh->nh_lwtstate); if (lwtunnel_input_redirect(rth->dst.lwtstate)) { WARN_ON(rth->dst.input == lwtunnel_input); rth->dst.lwtstate->orig_input = rth->dst.input; rth->dst.input = lwtunnel_input; } if (unlikely(!rt_cache_route(nh, rth))) rt_add_uncached_list(rth); } skb_dst_set(skb, &rth->dst); err = 0; goto out; no_route: RT_CACHE_STAT_INC(in_no_route); res->type = RTN_UNREACHABLE; res->fi = NULL; res->table = NULL; goto local_input; /* * Do not cache martian addresses: they should be logged (RFC1812) */ martian_destination: RT_CACHE_STAT_INC(in_martian_dst); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) net_warn_ratelimited("martian destination %pI4 from %pI4, dev %s\n", &daddr, &saddr, dev->name); #endif e_inval: err = -EINVAL; goto out; e_nobufs: err = -ENOBUFS; goto out; martian_source: ip_handle_martian_source(dev, in_dev, skb, daddr, saddr); goto out; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int putint(jas_stream_t *out, int sgnd, int prec, long val) { int n; int c; bool s; ulong tmp; assert((!sgnd && prec >= 1) || (sgnd && prec >= 2)); if (sgnd) { val = encode_twos_comp(val, prec); } assert(val >= 0); val &= (1 << prec) - 1; n = (prec + 7) / 8; while (--n >= 0) { c = (val >> (n * 8)) & 0xff; if (jas_stream_putc(out, c) != c) return -1; } return 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 HTMLMediaElement::MediaLoadingFailed(WebMediaPlayer::NetworkState error, const String& message) { BLINK_MEDIA_LOG << "MediaLoadingFailed(" << (void*)this << ", " << static_cast<int>(error) << ", message='" << message << "')"; StopPeriodicTimers(); if (ready_state_ < kHaveMetadata && load_state_ == kLoadingFromSourceElement) { if (current_source_node_) { current_source_node_->ScheduleErrorEvent(); } else { BLINK_MEDIA_LOG << "mediaLoadingFailed(" << (void*)this << ") - error event not sent, <source> was removed"; } ForgetResourceSpecificTracks(); if (HavePotentialSourceChild()) { BLINK_MEDIA_LOG << "mediaLoadingFailed(" << (void*)this << ") - scheduling next <source>"; ScheduleNextSourceChild(); } else { BLINK_MEDIA_LOG << "mediaLoadingFailed(" << (void*)this << ") - no more <source> elements, waiting"; WaitForSourceChange(); } return; } if (error == WebMediaPlayer::kNetworkStateNetworkError && ready_state_ >= kHaveMetadata) { MediaEngineError(MediaError::Create(MediaError::kMediaErrNetwork, message)); } else if (error == WebMediaPlayer::kNetworkStateDecodeError) { MediaEngineError(MediaError::Create(MediaError::kMediaErrDecode, message)); } else if ((error == WebMediaPlayer::kNetworkStateFormatError || error == WebMediaPlayer::kNetworkStateNetworkError) && load_state_ == kLoadingFromSrcAttr) { if (message.IsEmpty()) { NoneSupported(BuildElementErrorMessage( error == WebMediaPlayer::kNetworkStateFormatError ? "Format error" : "Network error")); } else { NoneSupported(message); } } UpdateDisplayState(); } CWE ID: CWE-200 Target: 1 Example 2: Code: void AXObjectCacheImpl::listboxOptionStateChanged(HTMLOptionElement* option) { postNotification(option, AXCheckedStateChanged); } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AXARIAGridCell::isAriaRowHeader() const { const AtomicString& role = getAttribute(HTMLNames::roleAttr); return equalIgnoringCase(role, "rowheader"); } 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: static sk_sp<SkImage> unPremulSkImageToPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kPremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(input->width()) * info.bytesPerPixel()); } CWE ID: CWE-787 Target: 1 Example 2: Code: base::FilePath GetPrefStorePath() { base::FilePath path; base::PathService::Get(base::DIR_ANDROID_APP_DATA, &path); path = path.Append(FILE_PATH_LITERAL("pref_store")); return path; } 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 SerializedFlashMenu::ReadFromMessage(const IPC::Message* m, PickleIterator* iter) { DCHECK(!pp_menu_); pp_menu_ = ReadMenu(0, m, iter); if (!pp_menu_) return false; own_menu_ = true; return true; } 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: png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { png_byte compression_type; png_bytep pC; png_charp profile; png_uint_32 skip = 0; png_uint_32 profile_size, profile_length; png_size_t slength, prefix_length, data_length; png_debug(1, "in png_handle_iCCP"); if (!(png_ptr->mode & PNG_HAVE_IHDR)) png_error(png_ptr, "Missing IHDR before iCCP"); else if (png_ptr->mode & PNG_HAVE_IDAT) { png_warning(png_ptr, "Invalid iCCP after IDAT"); png_crc_finish(png_ptr, length); return; } else if (png_ptr->mode & PNG_HAVE_PLTE) /* Should be an error, but we can cope with it */ png_warning(png_ptr, "Out of place iCCP chunk"); if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)) { png_warning(png_ptr, "Duplicate iCCP chunk"); png_crc_finish(png_ptr, length); return; } #ifdef PNG_MAX_MALLOC_64K if (length > (png_uint_32)65535L) { png_warning(png_ptr, "iCCP chunk too large to fit in memory"); skip = length - (png_uint_32)65535L; length = (png_uint_32)65535L; } #endif png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = (png_charp)png_malloc(png_ptr, length + 1); slength = (png_size_t)length; png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); if (png_crc_finish(png_ptr, skip)) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; return; } png_ptr->chunkdata[slength] = 0x00; for (profile = png_ptr->chunkdata; *profile; profile++) /* Empty loop to find end of name */ ; ++profile; /* There should be at least one zero (the compression type byte) * following the separator, and we should be on it */ if ( profile >= png_ptr->chunkdata + slength - 1) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Malformed iCCP chunk"); return; } /* Compression_type should always be zero */ compression_type = *profile++; if (compression_type) { png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk"); compression_type = 0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8 wrote nonzero) */ } prefix_length = profile - png_ptr->chunkdata; png_decompress_chunk(png_ptr, compression_type, slength, prefix_length, &data_length); profile_length = data_length - prefix_length; if ( prefix_length > data_length || profile_length < 4) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Profile size field missing from iCCP chunk"); return; } /* Check the profile_size recorded in the first 32 bits of the ICC profile */ pC = (png_bytep)(png_ptr->chunkdata + prefix_length); profile_size = ((*(pC ))<<24) | ((*(pC + 1))<<16) | ((*(pC + 2))<< 8) | ((*(pC + 3)) ); if (profile_size < profile_length) profile_length = profile_size; if (profile_size > profile_length) { png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; png_warning(png_ptr, "Ignoring truncated iCCP profile."); return; } png_set_iCCP(png_ptr, info_ptr, png_ptr->chunkdata, compression_type, png_ptr->chunkdata + prefix_length, profile_length); png_free(png_ptr, png_ptr->chunkdata); png_ptr->chunkdata = NULL; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void slab_put_obj(struct kmem_cache *cachep, struct page *page, void *objp) { unsigned int objnr = obj_to_index(cachep, page, objp); #if DEBUG unsigned int i; /* Verify double free bug */ for (i = page->active; i < cachep->num; i++) { if (get_free_obj(page, i) == objnr) { pr_err("slab: double free detected in cache '%s', objp %p\n", cachep->name, objp); BUG(); } } #endif page->active--; if (!page->freelist) page->freelist = objp + obj_offset(cachep); set_free_obj(page, page->active, objnr); } 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 __local_bh_enable(unsigned int cnt) { lockdep_assert_irqs_disabled(); if (softirq_count() == (cnt & SOFTIRQ_MASK)) trace_softirqs_on(_RET_IP_); preempt_count_sub(cnt); } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: dissect_ac_if_hdr_body(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_, proto_tree *tree, usb_conv_info_t *usb_conv_info) { gint offset_start; guint16 bcdADC; guint8 ver_major; double ver; guint8 if_in_collection, i; audio_conv_info_t *audio_conv_info; offset_start = offset; bcdADC = tvb_get_letohs(tvb, offset); ver_major = USB_AUDIO_BCD44_TO_DEC(bcdADC>>8); ver = ver_major + USB_AUDIO_BCD44_TO_DEC(bcdADC&0xFF) / 100.0; proto_tree_add_double_format_value(tree, hf_ac_if_hdr_ver, tvb, offset, 2, ver, "%2.2f", ver); audio_conv_info = (audio_conv_info_t *)usb_conv_info->class_data; if(!audio_conv_info) { audio_conv_info = wmem_new(wmem_file_scope(), audio_conv_info_t); usb_conv_info->class_data = audio_conv_info; /* XXX - set reasonable default values for all components that are not filled in by this function */ } audio_conv_info->ver_major = ver_major; offset += 2; /* version 1 refers to the Basic Audio Device specification, version 2 is the Audio Device class specification, see above */ if (ver_major==1) { proto_tree_add_item(tree, hf_ac_if_hdr_total_len, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; if_in_collection = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_ac_if_hdr_bInCollection, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; for (i=0; i<if_in_collection; i++) { proto_tree_add_item(tree, hf_ac_if_hdr_if_num, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; } } return offset-offset_start; } CWE ID: CWE-476 Target: 1 Example 2: Code: PaintPatcher::PaintPatcher() : refcount_(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: VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::VaapiVP8Accelerator( VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper) : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { DCHECK(vaapi_wrapper_); DCHECK(vaapi_dec_); } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t OMXNodeInstance::updateNativeHandleInMeta( OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { return BAD_VALUE; } BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate); sp<ABuffer> data = bufferMeta->getBuffer( header, false /* backup */, false /* limit */); bufferMeta->setNativeHandle(nativeHandle); if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource && data->capacity() >= sizeof(VideoNativeHandleMetadata)) { VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data()); metadata.eType = mMetadataType[portIndex]; metadata.pHandle = nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle()); } else { CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)", portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity()); return BAD_VALUE; } CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p", portString(portIndex), portIndex, buffer, nativeHandle == NULL ? NULL : nativeHandle->handle()); return OK; } CWE ID: CWE-200 Target: 1 Example 2: Code: static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node) { struct page *page; int searchnode = (node == -1) ? numa_node_id() : node; page = get_partial_node(get_node(s, searchnode)); if (page || (flags & __GFP_THISNODE)) return page; return get_any_partial(s, 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 AutofillManager::OnHeuristicsRequestError( const std::string& form_signature, AutofillDownloadManager::AutofillRequestType request_type, int http_error) { } 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: ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } CWE ID: CWE-125 Target: 1 Example 2: Code: void ChromeContentBrowserClient::RegisterUserPrefs( PrefRegistrySyncable* registry) { registry->RegisterBooleanPref(prefs::kDisable3DAPIs, false, PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing, true, PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref(prefs::kEnableMemoryInfo, false, PrefRegistrySyncable::UNSYNCABLE_PREF); } 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: bool ChromeClientImpl::CanTakeFocus(WebFocusType) { return !LayoutTestSupport::IsRunningLayoutTest(); } 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: search_make_new(const struct search_state *const state, int n, const char *const base_name) { const size_t base_len = strlen(base_name); const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1; struct search_domain *dom; for (dom = state->head; dom; dom = dom->next) { if (!n--) { /* this is the postfix we want */ /* the actual postfix string is kept at the end of the structure */ const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain); const int postfix_len = dom->len; char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1); if (!newname) return NULL; memcpy(newname, base_name, base_len); if (need_to_append_dot) newname[base_len] = '.'; memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len); newname[base_len + need_to_append_dot + postfix_len] = 0; return newname; } } /* we ran off the end of the list and still didn't find the requested string */ EVUTIL_ASSERT(0); return NULL; /* unreachable; stops warnings in some compilers. */ } CWE ID: CWE-125 Target: 1 Example 2: Code: xmlFatalErrMsgStr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, const xmlChar * val) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, (const char *) val, NULL, NULL, 0, 0, msg, val); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } CWE ID: CWE-611 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); } 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 mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) { assert(len <= UINT_MAX); int index = 1; lua_newtable(L); while(len--) { lua_pushnumber(L,index++); mp_decode_to_lua_type(L,c); if (c->err) return; lua_settable(L,-3); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int cxusb_mygica_d689_tuner_attach(struct dvb_usb_adapter *adap) { struct dvb_frontend *fe; fe = dvb_attach(max2165_attach, adap->fe_adap[0].fe, &adap->dev->i2c_adap, &mygica_d689_max2165_cfg); return (fe == NULL) ? -EIO : 0; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_RSHUTDOWN_FUNCTION(phar) /* {{{ */ { int i; PHAR_G(request_ends) = 1; if (PHAR_G(request_init)) { phar_release_functions(); zend_hash_destroy(&(PHAR_G(phar_alias_map))); PHAR_G(phar_alias_map.u.flags) = 0; zend_hash_destroy(&(PHAR_G(phar_fname_map))); PHAR_G(phar_fname_map.u.flags) = 0; zend_hash_destroy(&(PHAR_G(phar_persist_map))); PHAR_G(phar_persist_map.u.flags) = 0; PHAR_G(phar_SERVER_mung_list) = 0; if (PHAR_G(cached_fp)) { for (i = 0; i < zend_hash_num_elements(&cached_phars); ++i) { if (PHAR_G(cached_fp)[i].fp) { php_stream_close(PHAR_G(cached_fp)[i].fp); } if (PHAR_G(cached_fp)[i].ufp) { php_stream_close(PHAR_G(cached_fp)[i].ufp); } efree(PHAR_G(cached_fp)[i].manifest); } efree(PHAR_G(cached_fp)); PHAR_G(cached_fp) = 0; } PHAR_G(request_init) = 0; if (PHAR_G(cwd)) { efree(PHAR_G(cwd)); } PHAR_G(cwd) = NULL; PHAR_G(cwd_len) = 0; PHAR_G(cwd_init) = 0; } PHAR_G(request_done) = 1; return SUCCESS; } /* }}} */ 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: long keyctl_set_reqkey_keyring(int reqkey_defl) { struct cred *new; int ret, old_setting; old_setting = current_cred_xxx(jit_keyring); if (reqkey_defl == KEY_REQKEY_DEFL_NO_CHANGE) return old_setting; new = prepare_creds(); if (!new) return -ENOMEM; switch (reqkey_defl) { case KEY_REQKEY_DEFL_THREAD_KEYRING: ret = install_thread_keyring_to_cred(new); if (ret < 0) goto error; goto set; case KEY_REQKEY_DEFL_PROCESS_KEYRING: ret = install_process_keyring_to_cred(new); if (ret < 0) { if (ret != -EEXIST) goto error; ret = 0; } goto set; case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_SESSION_KEYRING: case KEY_REQKEY_DEFL_USER_KEYRING: case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: goto set; case KEY_REQKEY_DEFL_NO_CHANGE: case KEY_REQKEY_DEFL_GROUP_KEYRING: default: ret = -EINVAL; goto error; } set: new->jit_keyring = reqkey_defl; commit_creds(new); return old_setting; error: abort_creds(new); return ret; } CWE ID: CWE-404 Target: 1 Example 2: Code: scoped_refptr<MainThreadTaskQueue> RendererSchedulerImpl::NewTaskQueue( const MainThreadTaskQueue::QueueCreationParams& params) { helper_.CheckOnValidThread(); scoped_refptr<MainThreadTaskQueue> task_queue(helper_.NewTaskQueue(params)); std::unique_ptr<TaskQueue::QueueEnabledVoter> voter; if (params.can_be_blocked || params.can_be_paused || params.can_be_stopped) voter = task_queue->CreateQueueEnabledVoter(); auto insert_result = task_runners_.insert(std::make_pair(task_queue, std::move(voter))); auto queue_class = task_queue->queue_class(); if (queue_class == MainThreadTaskQueue::QueueClass::kTimer) { task_queue->AddTaskObserver(&main_thread_only().timer_task_cost_estimator); } else if (queue_class == MainThreadTaskQueue::QueueClass::kLoading) { task_queue->AddTaskObserver( &main_thread_only().loading_task_cost_estimator); } ApplyTaskQueuePolicy( task_queue.get(), insert_result.first->second.get(), TaskQueuePolicy(), main_thread_only().current_policy.GetQueuePolicy(queue_class)); if (task_queue->CanBeThrottled()) AddQueueToWakeUpBudgetPool(task_queue.get()); if (queue_class == MainThreadTaskQueue::QueueClass::kTimer) { if (main_thread_only().virtual_time_stopped) task_queue->InsertFence(TaskQueue::InsertFencePosition::kNow); } return task_queue; } 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: AXObjectInclusion AXLayoutObject::defaultObjectInclusion( IgnoredReasons* ignoredReasons) const { if (!m_layoutObject) { if (ignoredReasons) ignoredReasons->push_back(IgnoredReason(AXNotRendered)); return IgnoreObject; } if (m_layoutObject->style()->visibility() != EVisibility::kVisible) { if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "false")) return DefaultBehavior; if (ignoredReasons) ignoredReasons->push_back(IgnoredReason(AXNotVisible)); return IgnoreObject; } return AXObject::defaultObjectInclusion(ignoredReasons); } CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, int srcWidth, int srcHeight, SplashCoord *mat, GBool glyphMode) { SplashBitmap *scaledMask; SplashClipResult clipRes, clipRes2; SplashPipe pipe; int scaledWidth, scaledHeight, t0, t1; SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11; SplashCoord vx[4], vy[4]; int xMin, yMin, xMax, yMax; ImageSection section[3]; int nSections; int y, xa, xb, x, i, xx, yy; vx[0] = mat[4]; vy[0] = mat[5]; vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5]; vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5]; vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5]; xMin = imgCoordMungeLowerC(vx[0], glyphMode); xMax = imgCoordMungeUpperC(vx[0], glyphMode); yMin = imgCoordMungeLowerC(vy[0], glyphMode); yMax = imgCoordMungeUpperC(vy[0], glyphMode); for (i = 1; i < 4; ++i) { t0 = imgCoordMungeLowerC(vx[i], glyphMode); if (t0 < xMin) { xMin = t0; } t0 = imgCoordMungeUpperC(vx[i], glyphMode); if (t0 > xMax) { xMax = t0; } t1 = imgCoordMungeLowerC(vy[i], glyphMode); if (t1 < yMin) { yMin = t1; } t1 = imgCoordMungeUpperC(vy[i], glyphMode); if (t1 > yMax) { yMax = t1; } } clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1); opClipRes = clipRes; if (clipRes == splashClipAllOutside) { return; } if (mat[0] >= 0) { t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) - imgCoordMungeLowerC(mat[4], glyphMode); } else { t0 = imgCoordMungeUpperC(mat[4], glyphMode) - imgCoordMungeLowerC(mat[0] + mat[4], glyphMode); } if (mat[1] >= 0) { t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) - imgCoordMungeLowerC(mat[5], glyphMode); } else { t1 = imgCoordMungeUpperC(mat[5], glyphMode) - imgCoordMungeLowerC(mat[1] + mat[5], glyphMode); } scaledWidth = t0 > t1 ? t0 : t1; if (mat[2] >= 0) { t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) - imgCoordMungeLowerC(mat[4], glyphMode); } else { t0 = imgCoordMungeUpperC(mat[4], glyphMode) - imgCoordMungeLowerC(mat[2] + mat[4], glyphMode); } if (mat[3] >= 0) { t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) - imgCoordMungeLowerC(mat[5], glyphMode); } else { t1 = imgCoordMungeUpperC(mat[5], glyphMode) - imgCoordMungeLowerC(mat[3] + mat[5], glyphMode); } scaledHeight = t0 > t1 ? t0 : t1; if (scaledWidth == 0) { scaledWidth = 1; } if (scaledHeight == 0) { scaledHeight = 1; } r00 = mat[0] / scaledWidth; r01 = mat[1] / scaledWidth; r10 = mat[2] / scaledHeight; r11 = mat[3] / scaledHeight; det = r00 * r11 - r01 * r10; if (splashAbs(det) < 1e-6) { return; } ir00 = r11 / det; ir01 = -r01 / det; ir10 = -r10 / det; ir11 = r00 / det; scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, scaledWidth, scaledHeight); i = (vy[2] <= vy[3]) ? 2 : 3; } CWE ID: Target: 1 Example 2: Code: void gdImageFilledRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { _gdImageFilledVRectangle(im, x1, y1, x2, y2, color); } 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 JSTestInterfacePrototype::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { JSTestInterfacePrototype* thisObject = jsCast<JSTestInterfacePrototype*>(object); return getStaticPropertyDescriptor<JSTestInterfacePrototype, JSObject>(exec, &JSTestInterfacePrototypeTable, thisObject, propertyName, descriptor); } 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 gs_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct gs_usb *dev; int rc = -ENOMEM; unsigned int icount, i; struct gs_host_config hconf = { .byte_order = 0x0000beef, }; struct gs_device_config dconf; /* send host config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_sndctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_HOST_FORMAT, USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, &hconf, sizeof(hconf), 1000); if (rc < 0) { dev_err(&intf->dev, "Couldn't send data format (err=%d)\n", rc); return rc; } /* read device config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_rcvctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_DEVICE_CONFIG, USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, &dconf, sizeof(dconf), 1000); if (rc < 0) { dev_err(&intf->dev, "Couldn't get device config: (err=%d)\n", rc); return rc; } icount = dconf.icount + 1; dev_info(&intf->dev, "Configuring for %d interfaces\n", icount); if (icount > GS_MAX_INTF) { dev_err(&intf->dev, "Driver cannot handle more that %d CAN interfaces\n", GS_MAX_INTF); return -EINVAL; } dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; init_usb_anchor(&dev->rx_submitted); atomic_set(&dev->active_channels, 0); usb_set_intfdata(intf, dev); dev->udev = interface_to_usbdev(intf); for (i = 0; i < icount; i++) { dev->canch[i] = gs_make_candev(i, intf, &dconf); if (IS_ERR_OR_NULL(dev->canch[i])) { /* save error code to return later */ rc = PTR_ERR(dev->canch[i]); /* on failure destroy previously created candevs */ icount = i; for (i = 0; i < icount; i++) gs_destroy_candev(dev->canch[i]); usb_kill_anchored_urbs(&dev->rx_submitted); kfree(dev); return rc; } dev->canch[i]->parent = dev; } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: ImageBuffer* WebGLRenderingContextBase::LRUImageBufferCache::GetImageBuffer( const IntSize& size) { int i; for (i = 0; i < capacity_; ++i) { ImageBuffer* buf = buffers_[i].get(); if (!buf) break; if (buf->Size() != size) continue; BubbleToFront(i); return buf; } std::unique_ptr<ImageBuffer> temp(ImageBuffer::Create(size)); if (!temp) return nullptr; i = std::min(capacity_ - 1, i); buffers_[i] = std::move(temp); ImageBuffer* buf = buffers_[i].get(); BubbleToFront(i); return buf; } 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: freelist_extract(SSL_CTX *ctx, int for_read, int sz) { SSL3_BUF_FREELIST *list; SSL3_BUF_FREELIST_ENTRY *ent = NULL; void *result = NULL; CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX); list = for_read ? ctx->rbuf_freelist : ctx->wbuf_freelist; if (list != NULL && sz == (int)list->chunklen) ent = list->head; if (ent != NULL) { list->head = ent->next; result = ent; if (--list->len == 0) list->chunklen = 0; } CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX); if (!result) result = OPENSSL_malloc(sz); return result; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char **argv) { FILE *infile = NULL; vpx_codec_ctx_t codec; vpx_codec_enc_cfg_t cfg; int frame_count = 0; vpx_image_t raw; vpx_codec_err_t res; VpxVideoInfo info = {0}; VpxVideoWriter *writer = NULL; const VpxInterface *encoder = NULL; const int fps = 30; // TODO(dkovalev) add command line argument const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument int keyframe_interval = 0; const char *codec_arg = NULL; const char *width_arg = NULL; const char *height_arg = NULL; const char *infile_arg = NULL; const char *outfile_arg = NULL; const char *keyframe_interval_arg = NULL; exec_name = argv[0]; if (argc < 7) die("Invalid number of arguments"); codec_arg = argv[1]; width_arg = argv[2]; height_arg = argv[3]; infile_arg = argv[4]; outfile_arg = argv[5]; keyframe_interval_arg = argv[6]; encoder = get_vpx_encoder_by_name(codec_arg); if (!encoder) die("Unsupported codec."); info.codec_fourcc = encoder->fourcc; info.frame_width = strtol(width_arg, NULL, 0); info.frame_height = strtol(height_arg, NULL, 0); info.time_base.numerator = 1; info.time_base.denominator = fps; 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."); } keyframe_interval = strtol(keyframe_interval_arg, NULL, 0); if (keyframe_interval < 0) die("Invalid keyframe interval value."); 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; cfg.g_error_resilient = argc > 7 ? strtol(argv[7], NULL, 0) : 0; writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info); if (!writer) die("Failed to open %s for writing.", outfile_arg); 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)) { int flags = 0; if (keyframe_interval > 0 && frame_count % keyframe_interval == 0) flags |= VPX_EFLAG_FORCE_KF; encode_frame(&codec, &raw, frame_count++, flags, writer); } encode_frame(&codec, NULL, -1, 0, writer); // flush the encoder printf("\n"); fclose(infile); printf("Processed %d frames.\n", frame_count); vpx_img_free(&raw); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_writer_close(writer); return EXIT_SUCCESS; } CWE ID: CWE-119 Target: 1 Example 2: Code: SelectorQueryCache& Document::GetSelectorQueryCache() { if (!selector_query_cache_) selector_query_cache_ = std::make_unique<SelectorQueryCache>(); return *selector_query_cache_; } 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 long pipe_set_size(struct pipe_inode_info *pipe, unsigned long nr_pages) { struct pipe_buffer *bufs; /* * We can shrink the pipe, if arg >= pipe->nrbufs. Since we don't * expect a lot of shrink+grow operations, just free and allocate * again like we would do for growing. If the pipe currently * contains more buffers than arg, then return busy. */ if (nr_pages < pipe->nrbufs) return -EBUSY; bufs = kcalloc(nr_pages, sizeof(*bufs), GFP_KERNEL | __GFP_NOWARN); if (unlikely(!bufs)) return -ENOMEM; /* * The pipe array wraps around, so just start the new one at zero * and adjust the indexes. */ if (pipe->nrbufs) { unsigned int tail; unsigned int head; tail = pipe->curbuf + pipe->nrbufs; if (tail < pipe->buffers) tail = 0; else tail &= (pipe->buffers - 1); head = pipe->nrbufs - tail; if (head) memcpy(bufs, pipe->bufs + pipe->curbuf, head * sizeof(struct pipe_buffer)); if (tail) memcpy(bufs + head, pipe->bufs, tail * sizeof(struct pipe_buffer)); } pipe->curbuf = 0; kfree(pipe->bufs); pipe->bufs = bufs; pipe->buffers = nr_pages; return nr_pages * PAGE_SIZE; } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SProcXResQueryResourceBytes (ClientPtr client) { REQUEST(xXResQueryResourceBytesReq); int c; xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff)); int c; xXResResourceIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff)); swapl(&stuff->numSpecs); REQUEST_AT_LEAST_SIZE(xXResQueryResourceBytesReq); REQUEST_FIXED_SIZE(xXResQueryResourceBytesReq, stuff->numSpecs * sizeof(specs[0])); } CWE ID: CWE-20 Target: 1 Example 2: Code: void LayerTreeCoordinator::setVisibleContentsRect(const IntRect& rect, float scale, const FloatPoint& trajectoryVector) { bool contentsRectDidChange = rect != m_visibleContentsRect; bool contentsScaleDidChange = scale != m_contentsScale; toCoordinatedGraphicsLayer(m_nonCompositedContentLayer.get())->setVisibleContentRectTrajectoryVector(trajectoryVector); if (contentsRectDidChange || contentsScaleDidChange) { m_visibleContentsRect = rect; m_contentsScale = scale; HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator end = m_registeredLayers.end(); for (HashSet<WebCore::CoordinatedGraphicsLayer*>::iterator it = m_registeredLayers.begin(); it != end; ++it) { if (contentsScaleDidChange) (*it)->setContentsScale(scale); if (contentsRectDidChange) (*it)->adjustVisibleRect(); } } scheduleLayerFlush(); if (m_webPage->useFixedLayout()) m_webPage->setFixedVisibleContentRect(rect); if (contentsRectDidChange) m_shouldSendScrollPositionUpdate = 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: void GotSystemSlotOnIOThread( base::Callback<void(crypto::ScopedPK11Slot)> callback_ui_thread, crypto::ScopedPK11Slot system_slot) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::BindOnce(&GotSystemSlotOnUIThread, callback_ui_thread, std::move(system_slot))); } 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: PHPAPI PHP_FUNCTION(fread) { zval *arg1; long len; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) { RETURN_FALSE; } PHP_STREAM_TO_ZVAL(stream, &arg1); if (len <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(len + 1); Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } CWE ID: CWE-190 Target: 1 Example 2: Code: int usb_port_suspend(struct usb_device *udev, pm_message_t msg) { struct usb_hub *hub = usb_hub_to_struct_hub(udev->parent); struct usb_port *port_dev = hub->ports[udev->portnum - 1]; int port1 = udev->portnum; int status; bool really_suspend = true; usb_lock_port(port_dev); /* enable remote wakeup when appropriate; this lets the device * wake up the upstream hub (including maybe the root hub). * * NOTE: OTG devices may issue remote wakeup (or SRP) even when * we don't explicitly enable it here. */ if (udev->do_remote_wakeup) { status = usb_enable_remote_wakeup(udev); if (status) { dev_dbg(&udev->dev, "won't remote wakeup, status %d\n", status); /* bail if autosuspend is requested */ if (PMSG_IS_AUTO(msg)) goto err_wakeup; } } /* disable USB2 hardware LPM */ if (udev->usb2_hw_lpm_enabled == 1) usb_set_usb2_hardware_lpm(udev, 0); if (usb_disable_ltm(udev)) { dev_err(&udev->dev, "Failed to disable LTM before suspend\n"); status = -ENOMEM; if (PMSG_IS_AUTO(msg)) goto err_ltm; } /* see 7.1.7.6 */ if (hub_is_superspeed(hub->hdev)) status = hub_set_port_link_state(hub, port1, USB_SS_PORT_LS_U3); /* * For system suspend, we do not need to enable the suspend feature * on individual USB-2 ports. The devices will automatically go * into suspend a few ms after the root hub stops sending packets. * The USB 2.0 spec calls this "global suspend". * * However, many USB hubs have a bug: They don't relay wakeup requests * from a downstream port if the port's suspend feature isn't on. * Therefore we will turn on the suspend feature if udev or any of its * descendants is enabled for remote wakeup. */ else if (PMSG_IS_AUTO(msg) || wakeup_enabled_descendants(udev) > 0) status = set_port_feature(hub->hdev, port1, USB_PORT_FEAT_SUSPEND); else { really_suspend = false; status = 0; } if (status) { dev_dbg(&port_dev->dev, "can't suspend, status %d\n", status); /* Try to enable USB3 LTM again */ usb_enable_ltm(udev); err_ltm: /* Try to enable USB2 hardware LPM again */ if (udev->usb2_hw_lpm_capable == 1) usb_set_usb2_hardware_lpm(udev, 1); if (udev->do_remote_wakeup) (void) usb_disable_remote_wakeup(udev); err_wakeup: /* System sleep transitions should never fail */ if (!PMSG_IS_AUTO(msg)) status = 0; } else { dev_dbg(&udev->dev, "usb %ssuspend, wakeup %d\n", (PMSG_IS_AUTO(msg) ? "auto-" : ""), udev->do_remote_wakeup); if (really_suspend) { udev->port_is_suspended = 1; /* device has up to 10 msec to fully suspend */ msleep(10); } usb_set_device_state(udev, USB_STATE_SUSPENDED); } if (status == 0 && !udev->do_remote_wakeup && udev->persist_enabled && test_and_clear_bit(port1, hub->child_usage_bits)) pm_runtime_put_sync(&port_dev->dev); usb_mark_last_busy(hub->hdev); usb_unlock_port(port_dev); return status; } 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: int cg_mkdir(const char *path, mode_t mode) { struct fuse_context *fc = fuse_get_context(); char *fpath = NULL, *path1, *cgdir = NULL, *controller; const char *cgroup; int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EINVAL; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) path1 = "/"; else path1 = cgdir; if (!fc_may_access(fc, controller, path1, NULL, O_RDWR)) { ret = -EACCES; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { ret = -EACCES; goto out; } ret = cgfs_create(controller, cgroup, fc->uid, fc->gid); printf("cgfs_create returned %d for %s %s\n", ret, controller, cgroup); out: free(cgdir); return ret; } 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 VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val - 1); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void shrink_submounts(struct mount *mnt) { LIST_HEAD(graveyard); struct mount *m; /* extract submounts of 'mountpoint' from the expiration list */ while (select_submounts(mnt, &graveyard)) { while (!list_empty(&graveyard)) { m = list_first_entry(&graveyard, struct mount, mnt_expire); touch_mnt_namespace(m->mnt_ns); umount_tree(m, 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: GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes. { if (ms) { int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; if (size + 2 <= nestsize) return GPMF_OK; } return GPMF_ERROR_BAD_STRUCTURE; } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BlockGroup::BlockGroup( Cluster* pCluster, long idx, long long block_start, long long block_size, long long prev, long long next, long long duration, long long discard_padding) : BlockEntry(pCluster, idx), m_block(block_start, block_size, discard_padding), m_prev(prev), m_next(next), m_duration(duration) { } CWE ID: CWE-119 Target: 1 Example 2: Code: smb2_parse_lease_state(struct TCP_Server_Info *server, struct smb2_create_rsp *rsp, unsigned int *epoch, char *lease_key) { char *data_offset; struct create_context *cc; unsigned int next; unsigned int remaining; char *name; data_offset = (char *)rsp + le32_to_cpu(rsp->CreateContextsOffset); remaining = le32_to_cpu(rsp->CreateContextsLength); cc = (struct create_context *)data_offset; while (remaining >= sizeof(struct create_context)) { name = le16_to_cpu(cc->NameOffset) + (char *)cc; if (le16_to_cpu(cc->NameLength) == 4 && strncmp(name, "RqLs", 4) == 0) return server->ops->parse_lease_buf(cc, epoch, lease_key); next = le32_to_cpu(cc->Next); if (!next) break; remaining -= next; cc = (struct create_context *)((char *)cc + next); } return 0; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::GetFrameContext( const scoped_refptr<VP9Picture>& pic, Vp9FrameContext* frame_ctx) { NOTIMPLEMENTED() << "Frame context update not supported"; return false; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool asn1_write_LDAPString(struct asn1_data *data, const char *s) { asn1_write(data, s, strlen(s)); return !data->has_error; } CWE ID: CWE-399 Target: 1 Example 2: Code: void Document::EvaluateMediaQueryListIfNeeded() { if (!evaluate_media_queries_on_style_recalc_) return; EvaluateMediaQueryList(); evaluate_media_queries_on_style_recalc_ = false; } 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 MojoAudioInputStream::OnStreamCreated( int stream_id, const base::SharedMemory* shared_memory, std::unique_ptr<base::CancelableSyncSocket> foreign_socket, bool initially_muted) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(stream_created_callback_); DCHECK(shared_memory); DCHECK(foreign_socket); base::SharedMemoryHandle foreign_memory_handle = shared_memory->GetReadOnlyHandle(); if (!base::SharedMemory::IsHandleValid(foreign_memory_handle)) { OnStreamError(/*not used*/ 0); return; } mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle( foreign_memory_handle, shared_memory->requested_size(), /*read_only*/ true); mojo::ScopedHandle socket_handle = mojo::WrapPlatformFile(foreign_socket->Release()); DCHECK(buffer_handle.is_valid()); DCHECK(socket_handle.is_valid()); base::ResetAndReturn(&stream_created_callback_) .Run(std::move(buffer_handle), std::move(socket_handle), initially_muted); } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj) { switch (mrb_type(obj)) { case MRB_TT_CLASS: case MRB_TT_MODULE: copy_class(mrb, dest, obj); mrb_iv_copy(mrb, dest, obj); mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__")); break; case MRB_TT_OBJECT: case MRB_TT_SCLASS: case MRB_TT_HASH: case MRB_TT_DATA: case MRB_TT_EXCEPTION: mrb_iv_copy(mrb, dest, obj); break; case MRB_TT_ISTRUCT: mrb_istruct_copy(dest, obj); break; default: break; } mrb_funcall(mrb, dest, "initialize_copy", 1, obj); } CWE ID: CWE-824 Target: 1 Example 2: Code: static void tty_ldisc_put(struct tty_ldisc *ld) { if (WARN_ON_ONCE(!ld)) return; put_ldops(ld->ops); kfree(ld); } 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: stub_charset () { locale = get_locale_var ("LC_CTYPE"); locale = get_locale_var ("LC_CTYPE"); if (locale == 0 || *locale == 0) return "ASCII"; s = strrchr (locale, '.'); if (s) { t = strchr (s, '@'); if (t) *t = 0; return ++s; } else if (STREQ (locale, "UTF-8")) return "UTF-8"; else return "ASCII"; } 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 AppCache::RemoveEntry(const GURL& url) { auto found = entries_.find(url); DCHECK(found != entries_.end()); cache_size_ -= found->second.response_size(); entries_.erase(found); } CWE ID: CWE-200 Target: 1 Example 2: Code: void ImageLoader::dispose() { RESOURCE_LOADING_DVLOG(1) << "~ImageLoader " << this << "; m_hasPendingLoadEvent=" << m_hasPendingLoadEvent << ", m_hasPendingErrorEvent=" << m_hasPendingErrorEvent; if (m_image) { m_image->removeObserver(this); m_image = nullptr; } } 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 file_sb_list_add(struct file *file, struct super_block *sb) { if (likely(!(file->f_mode & FMODE_WRITE))) return; if (!S_ISREG(file_inode(file)->i_mode)) return; lg_local_lock(&files_lglock); __file_sb_list_add(file, sb); lg_local_unlock(&files_lglock); } CWE ID: CWE-17 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: __switch_to(struct task_struct *prev_p, struct task_struct *next_p) { struct thread_struct *prev = &prev_p->thread; struct thread_struct *next = &next_p->thread; int cpu = smp_processor_id(); struct tss_struct *tss = &per_cpu(init_tss, cpu); unsigned fsindex, gsindex; fpu_switch_t fpu; fpu = switch_fpu_prepare(prev_p, next_p, cpu); /* * Reload esp0, LDT and the page table pointer: */ load_sp0(tss, next); /* * Switch DS and ES. * This won't pick up thread selector changes, but I guess that is ok. */ savesegment(es, prev->es); if (unlikely(next->es | prev->es)) loadsegment(es, next->es); savesegment(ds, prev->ds); if (unlikely(next->ds | prev->ds)) loadsegment(ds, next->ds); /* We must save %fs and %gs before load_TLS() because * %fs and %gs may be cleared by load_TLS(). * * (e.g. xen_load_tls()) */ savesegment(fs, fsindex); savesegment(gs, gsindex); load_TLS(next, cpu); /* * Leave lazy mode, flushing any hypercalls made here. * This must be done before restoring TLS segments so * the GDT and LDT are properly updated, and must be * done before math_state_restore, so the TS bit is up * to date. */ arch_end_context_switch(next_p); /* * Switch FS and GS. * * Segment register != 0 always requires a reload. Also * reload when it has changed. When prev process used 64bit * base always reload to avoid an information leak. */ if (unlikely(fsindex | next->fsindex | prev->fs)) { loadsegment(fs, next->fsindex); /* * Check if the user used a selector != 0; if yes * clear 64bit base, since overloaded base is always * mapped to the Null selector */ if (fsindex) prev->fs = 0; } /* when next process has a 64bit base use it */ if (next->fs) wrmsrl(MSR_FS_BASE, next->fs); prev->fsindex = fsindex; if (unlikely(gsindex | next->gsindex | prev->gs)) { load_gs_index(next->gsindex); if (gsindex) prev->gs = 0; } if (next->gs) wrmsrl(MSR_KERNEL_GS_BASE, next->gs); prev->gsindex = gsindex; switch_fpu_finish(next_p, fpu); /* * Switch the PDA and FPU contexts. */ prev->usersp = this_cpu_read(old_rsp); this_cpu_write(old_rsp, next->usersp); this_cpu_write(current_task, next_p); /* * If it were not for PREEMPT_ACTIVE we could guarantee that the * preempt_count of all tasks was equal here and this would not be * needed. */ task_thread_info(prev_p)->saved_preempt_count = this_cpu_read(__preempt_count); this_cpu_write(__preempt_count, task_thread_info(next_p)->saved_preempt_count); this_cpu_write(kernel_stack, (unsigned long)task_stack_page(next_p) + THREAD_SIZE - KERNEL_STACK_OFFSET); /* * Now maybe reload the debug registers and handle I/O bitmaps */ if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT || task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV)) __switch_to_xtra(prev_p, next_p, tss); return prev_p; } CWE ID: CWE-200 Target: 1 Example 2: Code: GF_Err gf_isom_lhvc_config_update(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_HEVCConfig *cfg, GF_ISOMLHEVCTrackType track_type) { if (cfg) cfg->is_lhvc = GF_TRUE; switch (track_type) { case GF_ISOM_LEHVC_ONLY: return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, GF_ISOM_HVCC_SET_LHVC); case GF_ISOM_LEHVC_WITH_BASE: return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, GF_ISOM_HVCC_SET_LHVC_WITH_BASE); case GF_ISOM_LEHVC_WITH_BASE_BACKWARD: return gf_isom_hevc_config_update_ex(the_file, trackNumber, DescriptionIndex, cfg, GF_ISOM_HVCC_SET_LHVC_WITH_BASE_BACKWARD); default: return GF_BAD_PARAM; } } 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 PHP_FUNCTION(xmlwriter_write_element) { zval *pind; xmlwriter_object *intern; xmlTextWriterPtr ptr; char *name, *content = NULL; int name_len, content_len, retval; #ifdef ZEND_ENGINE_2 zval *this = getThis(); if (this) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &name, &name_len, &content, &content_len) == FAILURE) { return; } XMLWRITER_FROM_OBJECT(intern, this); } else #endif { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|s!", &pind, &name, &name_len, &content, &content_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(intern,xmlwriter_object *, &pind, -1, "XMLWriter", le_xmlwriter); } XMLW_NAME_CHK("Invalid Element Name"); ptr = intern->ptr; if (ptr) { if (!content) { retval = xmlTextWriterStartElement(ptr, (xmlChar *)name); if (retval == -1) { RETURN_FALSE; } xmlTextWriterEndElement(ptr); if (retval == -1) { RETURN_FALSE; } } else { retval = xmlTextWriterWriteElement(ptr, (xmlChar *)name, (xmlChar *)content); } if (retval != -1) { RETURN_TRUE; } } RETURN_FALSE; } CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintWebViewHelper::OnPrintPreview(const DictionaryValue& settings) { DCHECK(is_preview_); print_preview_context_.OnPrintPreview(); if (!InitPrintSettings(print_preview_context_.frame(), print_preview_context_.node(), true)) { Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings( routing_id(), print_pages_params_->params.document_cookie)); return; } if (!UpdatePrintSettings(settings, true)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PREVIEW); return; } if (!print_pages_params_->params.is_first_request && old_print_pages_params_.get() && PrintMsg_Print_Params_IsEqual(*old_print_pages_params_, *print_pages_params_)) { PrintHostMsg_DidPreviewDocument_Params preview_params; preview_params.reuse_existing_data = true; preview_params.data_size = 0; preview_params.document_cookie = print_pages_params_->params.document_cookie; preview_params.expected_pages_count = print_preview_context_.total_page_count(); preview_params.modifiable = print_preview_context_.IsModifiable(); preview_params.preview_request_id = print_pages_params_->params.preview_request_id; Send(new PrintHostMsg_MetafileReadyForPrinting(routing_id(), preview_params)); return; } old_print_pages_params_.reset(); is_print_ready_metafile_sent_ = false; print_pages_params_->params.supports_alpha_blend = true; bool generate_draft_pages = false; if (!settings.GetBoolean(printing::kSettingGenerateDraftData, &generate_draft_pages)) { NOTREACHED(); } print_preview_context_.set_generate_draft_pages(generate_draft_pages); if (CreatePreviewDocument()) { DidFinishPrinting(OK); } else { if (notify_browser_of_print_failure_) LOG(ERROR) << "CreatePreviewDocument failed"; DidFinishPrinting(FAIL_PREVIEW); } } CWE ID: CWE-399 Target: 1 Example 2: Code: static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool jsvIsInt(const JsVar *v) { return v && ((v->flags&JSV_VARTYPEMASK)==JSV_INTEGER || (v->flags&JSV_VARTYPEMASK)==JSV_PIN || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_INT || (v->flags&JSV_VARTYPEMASK)==JSV_NAME_INT_BOOL); } 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 rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; int bitsp, bitsq, ok = -1, n = 0; BN_CTX *ctx = NULL; unsigned long error = 0; /* * When generating ridiculously small keys, we can get stuck * continually regenerating the same prime values. */ if (bits < 16) { ok = 0; /* we set our own err */ RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL); goto err; } ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); r3 = BN_CTX_get(ctx); if (r3 == NULL) goto err; bitsp = (bits + 1) / 2; bitsq = bits - bitsp; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL)) goto err; if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL)) goto err; if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL)) goto err; if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL)) goto err; if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL)) goto err; if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL)) goto err; if (BN_copy(rsa->e, e_value) == NULL) goto err; BN_set_flags(r2, BN_FLG_CONSTTIME); /* generate p and q */ for (;;) { if (!BN_sub(r2, rsa->p, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 0)) goto err; for (;;) { do { if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb)) goto err; } while (BN_cmp(rsa->p, rsa->q) == 0); if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 1)) goto err; if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* calculate n */ if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* calculate d */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* p-1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* q-1 */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* (p-1)(q-1) */ { BIGNUM *pr0 = BN_new(); if (pr0 == NULL) goto err; BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) { BN_free(pr0); goto err; /* d */ } /* We MUST free pr0 before any further use of r0 */ BN_free(pr0); } { BIGNUM *d = BN_new(); if (d == NULL) goto err; BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); if ( /* calculate d mod (p-1) */ !BN_mod(rsa->dmp1, d, r1, ctx) /* calculate d mod (q-1) */ || !BN_mod(rsa->dmq1, d, r2, ctx)) { BN_free(d); goto err; } /* We MUST free d before any further use of rsa->d */ BN_free(d); } { BIGNUM *p = BN_new(); if (p == NULL) goto err; BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME); /* calculate inverse of q mod p */ if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) { BN_free(p); goto err; } /* We MUST free p before any further use of rsa->p */ BN_free(p); } ok = 1; err: if (ok == -1) { RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN); ok = 0; } if (ctx != NULL) BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; } CWE ID: CWE-327 Target: 1 Example 2: Code: is_write_comp_null (gnutls_session_t session) { record_parameters_st *record_params; _gnutls_epoch_get (session, EPOCH_WRITE_CURRENT, &record_params); if (record_params->compression_algorithm == GNUTLS_COMP_NULL) return 0; return 1; } 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: void giveup_vsx(struct task_struct *tsk) { giveup_fpu_maybe_transactional(tsk); giveup_altivec_maybe_transactional(tsk); __giveup_vsx(tsk); } 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: QString IRCView::openTags(TextHtmlData* data, int from) { QString ret, tag; int i = from; for ( ; i < data->openHtmlTags.count(); ++i) { tag = data->openHtmlTags.at(i); if (data->reverse) { ret += fontColorOpenTag(Preferences::self()->color(Preferences::TextViewBackground).name()); } else { ret += fontColorOpenTag(data->lastFgColor); } } else if (tag == QLatin1String("span")) { if (data->reverse) { ret += spanColorOpenTag(data->defaultColor); } else { ret += spanColorOpenTag(data->lastBgColor); } } else { ret += QLatin1Char('<') + tag + QLatin1Char('>'); } } CWE ID: Target: 1 Example 2: Code: void Browser::OpenCreateShortcutsDialog() { UserMetrics::RecordAction(UserMetricsAction("CreateShortcut"), profile_); #if defined(OS_WIN) || defined(OS_LINUX) TabContentsWrapper* current_tab = GetSelectedTabContentsWrapper(); DCHECK(current_tab && web_app::IsValidUrl(current_tab->tab_contents()->GetURL())) << "Menu item should be disabled."; NavigationEntry* entry = current_tab->controller().GetLastCommittedEntry(); if (!entry) return; DCHECK(pending_web_app_action_ == NONE); pending_web_app_action_ = CREATE_SHORTCUT; current_tab->render_view_host()->GetApplicationInfo(entry->page_id()); #else NOTIMPLEMENTED(); #endif } 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 _make_words(char *l,long n,ogg_uint32_t *r,long quantvals, codebook *b, oggpack_buffer *opb,int maptype){ long i,j,count=0; long top=0; ogg_uint32_t marker[MARKER_SIZE]; if (n<1) return 1; if(n<2){ r[0]=0x80000000; }else{ memset(marker,0,sizeof(marker)); for(i=0;i<n;i++){ long length=l[i]; if(length){ if (length < 0 || length >= MARKER_SIZE) { ALOGE("b/23881715"); return 1; } ogg_uint32_t entry=marker[length]; long chase=0; if(count && !entry)return -1; /* overpopulated tree! */ /* chase the tree as far as it's already populated, fill in past */ for(j=0;j<length-1;j++){ int bit=(entry>>(length-j-1))&1; if(chase>=top){ if (chase < 0 || chase >= n) return 1; top++; r[chase*2]=top; r[chase*2+1]=0; }else if (chase < 0 || chase >= n || chase*2+bit > n*2+1) return 1; if(!r[chase*2+bit]) r[chase*2+bit]=top; chase=r[chase*2+bit]; if (chase < 0 || chase >= n) return 1; } { int bit=(entry>>(length-j-1))&1; if(chase>=top){ top++; r[chase*2+1]=0; } r[chase*2+bit]= decpack(i,count++,quantvals,b,opb,maptype) | 0x80000000; } /* Look to see if the next shorter marker points to the node above. if so, update it and repeat. */ for(j=length;j>0;j--){ if(marker[j]&1){ marker[j]=marker[j-1]<<1; break; } marker[j]++; } /* prune the tree; the implicit invariant says all the longer markers were dangling from our just-taken node. Dangle them from our *new* node. */ for(j=length+1;j<MARKER_SIZE;j++) if((marker[j]>>1) == entry){ entry=marker[j]; marker[j]=marker[j-1]<<1; }else break; } } } /* sanity check the huffman tree; an underpopulated tree must be rejected. The only exception is the one-node pseudo-nil tree, which appears to be underpopulated because the tree doesn't really exist; there's only one possible 'codeword' or zero bits, but the above tree-gen code doesn't mark that. */ if(b->used_entries != 1){ for(i=1;i<MARKER_SIZE;i++) if(marker[i] & (0xffffffffUL>>(32-i))){ return 1; } } return 0; } 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: void NTPResourceCache::CreateNewTabHTML() { DictionaryValue localized_strings; localized_strings.SetString("bookmarkbarattached", profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) ? "true" : "false"); localized_strings.SetString("hasattribution", ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage( IDR_THEME_NTP_ATTRIBUTION) ? "true" : "false"); localized_strings.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); localized_strings.SetString("mostvisited", l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)); localized_strings.SetString("restoreThumbnailsShort", l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK)); localized_strings.SetString("recentlyclosed", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); localized_strings.SetString("closedwindowsingle", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); localized_strings.SetString("closedwindowmultiple", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); localized_strings.SetString("attributionintro", l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); localized_strings.SetString("thumbnailremovednotification", l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); localized_strings.SetString("undothumbnailremove", l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); localized_strings.SetString("removethumbnailtooltip", l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); localized_strings.SetString("appuninstall", l10n_util::GetStringFUTF16( IDS_EXTENSIONS_UNINSTALL, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME))); localized_strings.SetString("appoptions", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); localized_strings.SetString("appdisablenotifications", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DISABLE_NOTIFICATIONS)); localized_strings.SetString("appcreateshortcut", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); localized_strings.SetString("appDefaultPageName", l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)); localized_strings.SetString("applaunchtypepinned", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); localized_strings.SetString("applaunchtyperegular", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); localized_strings.SetString("applaunchtypewindow", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); localized_strings.SetString("applaunchtypefullscreen", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); localized_strings.SetString("syncpromotext", l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); localized_strings.SetString("syncLinkText", l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS)); #if defined(OS_CHROMEOS) localized_strings.SetString("expandMenu", l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); #endif NewTabPageHandler::GetLocalizedValues(profile_, &localized_strings); NTPLoginHandler::GetLocalizedValues(profile_, &localized_strings); if (profile_->GetProfileSyncService()) localized_strings.SetString("syncispresent", "true"); else localized_strings.SetString("syncispresent", "false"); ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings); std::string anim = ui::Animation::ShouldRenderRichAnimation() ? "true" : "false"; localized_strings.SetString("anim", anim); int alignment; ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_); tp->GetDisplayProperty(ThemeService::NTP_BACKGROUND_ALIGNMENT, &alignment); localized_strings.SetString("themegravity", (alignment & ThemeService::ALIGN_RIGHT) ? "right" : ""); if (profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoStart) && profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoEnd)) { localized_strings.SetString("customlogo", InDateRange(profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoStart), profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoEnd)) ? "true" : "false"); } else { localized_strings.SetString("customlogo", "false"); } if (PromoResourceService::CanShowNotificationPromo(profile_)) { localized_strings.SetString("serverpromo", profile_->GetPrefs()->GetString(prefs::kNTPPromoLine)); } std::string full_html; base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_NEW_TAB_4_HTML)); full_html = jstemplate_builder::GetI18nTemplateHtml(new_tab_html, &localized_strings); new_tab_html_ = base::RefCountedString::TakeString(&full_html); } CWE ID: CWE-119 Target: 1 Example 2: Code: int open_net_fd(const char *spec) { char *p; int fd, port; struct sockaddr_in sa; struct hostent *he; p = strchr(spec, ':'); if (!p) return -1; *p++ = '\0'; port = strtol(p, NULL, 10); /* printf("Host %s, port %d\n",spec,port); */ sa.sin_family = PF_INET; sa.sin_port = htons(port); he = gethostbyname(spec); if (!he) { #ifdef HAVE_HERROR herror("open_net_fd"); #endif return -1; } memcpy(&sa.sin_addr, he->h_addr, he->h_length); /* printf("using ip %s\n",inet_ntoa(sa.sin_addr)); */ fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd < 0) return fd; if (connect(fd, (struct sockaddr *) &sa, sizeof (sa)) < 0) return -1; return fd; } 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 PasswordInputType::EnableSecureTextInput() { LocalFrame* frame = GetElement().GetDocument().GetFrame(); if (!frame) return; frame->Selection().SetUseSecureKeyboardEntryWhenActive(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: bool WebMediaPlayerMS::DidPassCORSAccessCheck() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } CWE ID: CWE-732 Target: 1 Example 2: Code: void DevToolsAgent::OnFrontendLoaded() { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) web_agent->frontendLoaded(); } 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 mem_open(struct inode* inode, struct file* file) { file->private_data = (void*)((long)current->self_exec_id); /* OK to pass negative loff_t, we can catch out-of-range */ file->f_mode |= FMODE_UNSIGNED_OFFSET; return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height) { const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; int i, v, offset, count, segments; segments = bytestream2_get_le16(gb); while (segments--) { if (bytestream2_get_bytes_left(gb) < 2) return AVERROR_INVALIDDATA; if (mask == 0x10000) { bitbuf = bytestream2_get_le16u(gb); mask = 1; } if (bitbuf & mask) { v = bytestream2_get_le16(gb); offset = (v & 0x1FFF) << 2; count = ((v >> 13) + 2) << 1; if (frame - frame_start < offset || frame_end - frame < count*2 + width) return AVERROR_INVALIDDATA; for (i = 0; i < count; i++) { frame[0] = frame[1] = frame[width] = frame[width + 1] = frame[-offset]; frame += 2; } } else if (bitbuf & (mask << 1)) { v = bytestream2_get_le16(gb)*2; if (frame - frame_end < v) return AVERROR_INVALIDDATA; frame += v; } else { if (frame_end - frame < width + 3) return AVERROR_INVALIDDATA; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; } mask <<= 2; } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void webkit_web_view_drag_data_get(GtkWidget* widget, GdkDragContext* context, GtkSelectionData* selectionData, guint info, guint) { WebKitWebViewPrivate* priv = WEBKIT_WEB_VIEW(widget)->priv; if (!priv->draggingDataObjects.contains(context)) return; pasteboardHelperInstance()->fillSelectionData(selectionData, info, priv->draggingDataObjects.get(context).get()); } 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 void test_filesize() { char rule[80]; snprintf( rule, sizeof(rule), "rule test { condition: filesize == %zd }", sizeof(PE32_FILE)); assert_true_rule_blob( rule, PE32_FILE); } 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 TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session ) { TPM_RC rval; TPM2B_ENCRYPTED_SECRET key; char label[] = "ATH"; UINT16 bytes; int i; key.t.size = 0; if( session->nonceOlder.t.size == 0 ) { /* this is an internal routine to TSS and should be removed */ session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 ); for( i = 0; i < session->nonceOlder.t.size; i++ ) session->nonceOlder.t.buffer[i] = 0; } session->nonceNewer.t.size = session->nonceOlder.t.size; rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0, &( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType, &( session->symmetric ), session->authHash, &( session->sessionHandle ), &( session->nonceNewer ), 0 ); if( rval == TPM_RC_SUCCESS ) { if( session->tpmKey == TPM_RH_NULL ) session->salt.t.size = 0; if( session->bind == TPM_RH_NULL ) session->authValueBind.t.size = 0; if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL ) { session->sessionKey.b.size = 0; } else { bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } bytes = GetDigestSize( session->authHash ); if( key.t.size == 0 ) { session->sessionKey.t.size = 0; } else { rval = tpm_kdfa(sapi_context, session->authHash, &(key.b), label, &( session->nonceNewer.b ), &( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) ); } if( rval != TPM_RC_SUCCESS ) { return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED ); } } session->nonceTpmDecrypt.b.size = 0; session->nonceTpmEncrypt.b.size = 0; session->nvNameChanged = 0; } return rval; } CWE ID: CWE-522 Target: 1 Example 2: Code: void warning(char *str) { fprintf(stderr, "warning: %s\n", str); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: mobility_print(netdissect_options *ndo, const u_char *bp, const u_char *bp2 _U_) { const struct ip6_mobility *mh; const u_char *ep; unsigned mhlen, hlen; uint8_t type; mh = (const struct ip6_mobility *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; if (!ND_TTEST(mh->ip6m_len)) { /* * There's not enough captured data to include the * mobility header length. * * Our caller expects us to return the length, however, * so return a value that will run to the end of the * captured data. * * XXX - "ip6_print()" doesn't do anything with the * returned length, however, as it breaks out of the * header-processing loop. */ mhlen = ep - bp; goto trunc; } mhlen = (mh->ip6m_len + 1) << 3; /* XXX ip6m_cksum */ ND_TCHECK(mh->ip6m_type); type = mh->ip6m_type; if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) { ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type)); goto trunc; } ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type))); switch (type) { case IP6M_BINDING_REQUEST: hlen = IP6M_MINLEN; break; case IP6M_HOME_TEST_INIT: case IP6M_CAREOF_TEST_INIT: hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_HOME_TEST: case IP6M_CAREOF_TEST: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Init Cookie=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; if (ndo->ndo_vflag) { ND_TCHECK2(*mh, hlen + 8); ND_PRINT((ndo, " %s Keygen Token=%08x:%08x", type == IP6M_HOME_TEST ? "Home" : "Care-of", EXTRACT_32BITS(&bp[hlen]), EXTRACT_32BITS(&bp[hlen + 4]))); } hlen += 8; break; case IP6M_BINDING_UPDATE: ND_TCHECK(mh->ip6m_data16[0]); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0]))); hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 1); if (bp[hlen] & 0xf0) ND_PRINT((ndo, " ")); if (bp[hlen] & 0x80) ND_PRINT((ndo, "A")); if (bp[hlen] & 0x40) ND_PRINT((ndo, "H")); if (bp[hlen] & 0x20) ND_PRINT((ndo, "L")); if (bp[hlen] & 0x10) ND_PRINT((ndo, "K")); /* Reserved (4bits) */ hlen += 1; /* Reserved (8bits) */ hlen += 1; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ACK: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); if (mh->ip6m_data8[1] & 0x80) ND_PRINT((ndo, " K")); /* Reserved (7bits) */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 2); ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen]))); hlen += 2; ND_TCHECK2(*mh, hlen + 2); /* units of 4 secs */ ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2)); hlen += 2; break; case IP6M_BINDING_ERROR: ND_TCHECK(mh->ip6m_data8[0]); ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0])); /* Reserved */ hlen = IP6M_MINLEN; ND_TCHECK2(*mh, hlen + 16); ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen]))); hlen += 16; break; default: ND_PRINT((ndo, " len=%u", mh->ip6m_len)); return(mhlen); break; } if (ndo->ndo_vflag) if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen)) goto trunc; return(mhlen); trunc: ND_PRINT((ndo, "%s", tstr)); return(-1); } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void addArgumentToVtab(Parse *pParse){ if( pParse->sArg.z && pParse->pNewTable ){ const char *z = (const char*)pParse->sArg.z; int n = pParse->sArg.n; sqlite3 *db = pParse->db; addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); } } CWE ID: CWE-190 Target: 1 Example 2: Code: bool IsInPasswordFieldWithUnrevealedPassword(const Position& position) { TextControlElement* text_control = EnclosingTextControl(position); if (!isHTMLInputElement(text_control)) return false; HTMLInputElement* input = toHTMLInputElement(text_control); return (input->type() == InputTypeNames::password) && !input->ShouldRevealPassword(); } 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: Chapters::Edition::~Edition() { } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int SpdyProxyClientSocket::DoReadReplyComplete(int result) { if (result < 0) return result; if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) return ERR_TUNNEL_CONNECTION_FAILED; net_log_.AddEvent( NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS, base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers)); switch (response_.headers->response_code()) { case 200: // OK next_state_ = STATE_OPEN; return OK; case 302: // Found / Moved Temporarily if (SanitizeProxyRedirect(&response_, request_.url)) { redirect_has_load_timing_info_ = spdy_stream_->GetLoadTimingInfo(&redirect_load_timing_info_); spdy_stream_->DetachDelegate(); next_state_ = STATE_DISCONNECTED; return ERR_HTTPS_PROXY_TUNNEL_RESPONSE; } else { LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } case 407: // Proxy Authentication Required next_state_ = STATE_OPEN; return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_); default: LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } } CWE ID: CWE-19 Target: 1 Example 2: Code: NavigationType navigation_type() { return navigation_type_; } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void __user *compat_alloc_user_space(unsigned long len) { void __user *ptr; /* If len would occupy more than half of the entire compat space... */ if (unlikely(len > (((compat_uptr_t)~0) >> 1))) return NULL; ptr = arch_compat_alloc_user_space(len); if (unlikely(!access_ok(VERIFY_WRITE, ptr, len))) return NULL; return ptr; } 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 BluetoothOptionsHandler::DeviceNotification( const DictionaryValue& device) { web_ui_->CallJavascriptFunction( "options.SystemOptions.addBluetoothDevice", device); } CWE ID: CWE-119 Target: 1 Example 2: Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) { } } 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: my_object_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { MyObject *mobject; mobject = MY_OBJECT (object); switch (prop_id) { case PROP_THIS_IS_A_STRING: g_value_set_string (value, mobject->this_is_a_string); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } 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: static void record_and_restart(struct perf_event *event, unsigned long val, struct pt_regs *regs, int nmi) { u64 period = event->hw.sample_period; s64 prev, delta, left; int record = 0; if (event->hw.state & PERF_HES_STOPPED) { write_pmc(event->hw.idx, 0); return; } /* we don't have to worry about interrupts here */ prev = local64_read(&event->hw.prev_count); delta = (val - prev) & 0xfffffffful; local64_add(delta, &event->count); /* * See if the total period for this event has expired, * and update for the next period. */ val = 0; left = local64_read(&event->hw.period_left) - delta; if (period) { if (left <= 0) { left += period; if (left <= 0) left = period; record = 1; event->hw.last_period = event->hw.sample_period; } if (left < 0x80000000LL) val = 0x80000000LL - left; } write_pmc(event->hw.idx, val); local64_set(&event->hw.prev_count, val); local64_set(&event->hw.period_left, left); perf_event_update_userpage(event); /* * Finally record data if requested. */ if (record) { struct perf_sample_data data; perf_sample_data_init(&data, 0); data.period = event->hw.last_period; if (perf_event_overflow(event, nmi, &data, regs)) fsl_emb_pmu_stop(event, 0); } } CWE ID: CWE-399 Target: 1 Example 2: Code: static void put_buffer(QEMUFile *f, void *pv, size_t size) { uint8_t *v = pv; qemu_put_buffer(f, v, size); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Browser::CanReloadContents(TabContents* source) const { return type() != TYPE_DEVTOOLS; } 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: TestPaintArtifact& TestPaintArtifact::ScrollHitTest( DisplayItemClient& client, scoped_refptr<const TransformPaintPropertyNode> scroll_offset) { display_item_list_.AllocateAndConstruct<ScrollHitTestDisplayItem>( client, DisplayItem::kScrollHitTest, std::move(scroll_offset)); return *this; } CWE ID: Target: 1 Example 2: Code: int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen) { int from, to, merge, todo; struct skb_frag_struct *fragfrom, *fragto; BUG_ON(shiftlen > skb->len); if (skb_headlen(skb)) return 0; todo = shiftlen; from = 0; to = skb_shinfo(tgt)->nr_frags; fragfrom = &skb_shinfo(skb)->frags[from]; /* Actual merge is delayed until the point when we know we can * commit all, so that we don't have to undo partial changes */ if (!to || !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom), fragfrom->page_offset)) { merge = -1; } else { merge = to - 1; todo -= skb_frag_size(fragfrom); if (todo < 0) { if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt)) return 0; /* All previous frag pointers might be stale! */ fragfrom = &skb_shinfo(skb)->frags[from]; fragto = &skb_shinfo(tgt)->frags[merge]; skb_frag_size_add(fragto, shiftlen); skb_frag_size_sub(fragfrom, shiftlen); fragfrom->page_offset += shiftlen; goto onlymerged; } from++; } /* Skip full, not-fitting skb to avoid expensive operations */ if ((shiftlen == skb->len) && (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to)) return 0; if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt)) return 0; while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) { if (to == MAX_SKB_FRAGS) return 0; fragfrom = &skb_shinfo(skb)->frags[from]; fragto = &skb_shinfo(tgt)->frags[to]; if (todo >= skb_frag_size(fragfrom)) { *fragto = *fragfrom; todo -= skb_frag_size(fragfrom); from++; to++; } else { __skb_frag_ref(fragfrom); fragto->page = fragfrom->page; fragto->page_offset = fragfrom->page_offset; skb_frag_size_set(fragto, todo); fragfrom->page_offset += todo; skb_frag_size_sub(fragfrom, todo); todo = 0; to++; break; } } /* Ready to "commit" this state change to tgt */ skb_shinfo(tgt)->nr_frags = to; if (merge >= 0) { fragfrom = &skb_shinfo(skb)->frags[0]; fragto = &skb_shinfo(tgt)->frags[merge]; skb_frag_size_add(fragto, skb_frag_size(fragfrom)); __skb_frag_unref(fragfrom); } /* Reposition in the original skb */ to = 0; while (from < skb_shinfo(skb)->nr_frags) skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++]; skb_shinfo(skb)->nr_frags = to; BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags); onlymerged: /* Most likely the tgt won't ever need its checksum anymore, skb on * the other hand might need it if it needs to be resent */ tgt->ip_summed = CHECKSUM_PARTIAL; skb->ip_summed = CHECKSUM_PARTIAL; /* Yak, is it really working this way? Some helper please? */ skb->len -= shiftlen; skb->data_len -= shiftlen; skb->truesize -= shiftlen; tgt->len += shiftlen; tgt->data_len += shiftlen; tgt->truesize += shiftlen; return shiftlen; } 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: PHP_FUNCTION(openssl_seal) { zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL; HashTable *pubkeysht; EVP_PKEY **pkeys; zend_resource ** key_resources; /* so we know what to cleanup */ int i, len1, len2, *eksl, nkeys, iv_len; unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks; char * data; size_t data_len; char *method =NULL; size_t method_len = 0; const EVP_CIPHER *cipher; EVP_CIPHER_CTX *ctx; if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/a/|sz/", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) { return; } pubkeysht = Z_ARRVAL_P(pubkeys); nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0; if (!nkeys) { php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array"); RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data); if (method) { cipher = EVP_get_cipherbyname(method); if (!cipher) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm."); RETURN_FALSE; } } else { cipher = EVP_rc4(); } iv_len = EVP_CIPHER_iv_length(cipher); if (!iv && iv_len > 0) { php_error_docref(NULL, E_WARNING, "Cipher algorithm requires an IV to be supplied as a sixth parameter"); RETURN_FALSE; } pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0); eksl = safe_emalloc(nkeys, sizeof(*eksl), 0); eks = safe_emalloc(nkeys, sizeof(*eks), 0); memset(eks, 0, sizeof(*eks) * nkeys); key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0); memset(key_resources, 0, sizeof(zend_resource*) * nkeys); memset(pkeys, 0, sizeof(*pkeys) * nkeys); /* get the public keys we are using to seal this data */ i = 0; ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) { pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]); if (pkeys[i] == NULL) { php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1); RETVAL_FALSE; goto clean_exit; } eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1); i++; } ZEND_HASH_FOREACH_END(); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) { EVP_CIPHER_CTX_free(ctx); php_openssl_store_errors(); RETVAL_FALSE; goto clean_exit; } /* allocate one byte extra to make room for \0 */ buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx)); EVP_CIPHER_CTX_cleanup(ctx); if (!EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) || !EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) || !EVP_SealFinal(ctx, buf + len1, &len2)) { efree(buf); EVP_CIPHER_CTX_free(ctx); php_openssl_store_errors(); RETVAL_FALSE; goto clean_exit; } if (len1 + len2 > 0) { zval_dtor(sealdata); ZVAL_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0)); efree(buf); zval_dtor(ekeys); array_init(ekeys); for (i=0; i<nkeys; i++) { eks[i][eksl[i]] = '\0'; add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]); efree(eks[i]); eks[i] = NULL; } if (iv) { zval_dtor(iv); iv_buf[iv_len] = '\0'; ZVAL_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0)); } } else { efree(buf); } RETVAL_LONG(len1 + len2); EVP_CIPHER_CTX_free(ctx); clean_exit: for (i=0; i<nkeys; i++) { if (key_resources[i] == NULL && pkeys[i] != NULL) { EVP_PKEY_free(pkeys[i]); } if (eks[i]) { efree(eks[i]); } } efree(eks); efree(eksl); efree(pkeys); efree(key_resources); } CWE ID: CWE-754 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: const EffectPaintPropertyNode* e0() { return EffectPaintPropertyNode::Root(); } CWE ID: Target: 1 Example 2: Code: int sas_notify_lldd_dev_found(struct domain_device *dev) { int res = 0; struct sas_ha_struct *sas_ha = dev->port->ha; struct Scsi_Host *shost = sas_ha->core.shost; struct sas_internal *i = to_sas_internal(shost->transportt); if (!i->dft->lldd_dev_found) return 0; res = i->dft->lldd_dev_found(dev); if (res) { printk("sas: driver on pcidev %s cannot handle " "device %llx, error:%d\n", dev_name(sas_ha->dev), SAS_ADDR(dev->sas_addr), res); } set_bit(SAS_DEV_FOUND, &dev->state); kref_get(&dev->kref); return res; } 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: btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, u64 objectid, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; key.type = BTRFS_DIR_INDEX_KEY; key.offset = objectid; ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return ERR_PTR(-ENOENT); return btrfs_match_dir_item_name(root, path, name, name_len); } CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: icmp6_opt_print(netdissect_options *ndo, const u_char *bp, int resid) { const struct nd_opt_hdr *op; const struct nd_opt_prefix_info *opp; const struct nd_opt_mtu *opm; const struct nd_opt_rdnss *oprd; const struct nd_opt_dnssl *opds; const struct nd_opt_advinterval *opa; const struct nd_opt_homeagent_info *oph; const struct nd_opt_route_info *opri; const u_char *cp, *ep, *domp; struct in6_addr in6; const struct in6_addr *in6p; size_t l; u_int i; #define ECHECK(var) if ((const u_char *)&(var) > ep - sizeof(var)) return cp = bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; while (cp < ep) { op = (const struct nd_opt_hdr *)cp; ECHECK(op->nd_opt_len); if (resid <= 0) return; if (op->nd_opt_len == 0) goto trunc; if (cp + (op->nd_opt_len << 3) > ep) goto trunc; ND_PRINT((ndo,"\n\t %s option (%u), length %u (%u): ", tok2str(icmp6_opt_values, "unknown", op->nd_opt_type), op->nd_opt_type, op->nd_opt_len << 3, op->nd_opt_len)); switch (op->nd_opt_type) { case ND_OPT_SOURCE_LINKADDR: l = (op->nd_opt_len << 3) - 2; print_lladdr(ndo, cp + 2, l); break; case ND_OPT_TARGET_LINKADDR: l = (op->nd_opt_len << 3) - 2; print_lladdr(ndo, cp + 2, l); break; case ND_OPT_PREFIX_INFORMATION: opp = (const struct nd_opt_prefix_info *)op; ND_TCHECK(opp->nd_opt_pi_prefix); ND_PRINT((ndo,"%s/%u%s, Flags [%s], valid time %s", ip6addr_string(ndo, &opp->nd_opt_pi_prefix), opp->nd_opt_pi_prefix_len, (op->nd_opt_len != 4) ? "badlen" : "", bittok2str(icmp6_opt_pi_flag_values, "none", opp->nd_opt_pi_flags_reserved), get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_valid_time)))); ND_PRINT((ndo,", pref. time %s", get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_preferred_time)))); break; case ND_OPT_REDIRECTED_HEADER: print_unknown_data(ndo, bp,"\n\t ",op->nd_opt_len<<3); /* xxx */ break; case ND_OPT_MTU: opm = (const struct nd_opt_mtu *)op; ND_TCHECK(opm->nd_opt_mtu_mtu); ND_PRINT((ndo," %u%s", EXTRACT_32BITS(&opm->nd_opt_mtu_mtu), (op->nd_opt_len != 1) ? "bad option length" : "" )); break; case ND_OPT_RDNSS: oprd = (const struct nd_opt_rdnss *)op; l = (op->nd_opt_len - 1) / 2; ND_PRINT((ndo," lifetime %us,", EXTRACT_32BITS(&oprd->nd_opt_rdnss_lifetime))); for (i = 0; i < l; i++) { ND_TCHECK(oprd->nd_opt_rdnss_addr[i]); ND_PRINT((ndo," addr: %s", ip6addr_string(ndo, &oprd->nd_opt_rdnss_addr[i]))); } break; case ND_OPT_DNSSL: opds = (const struct nd_opt_dnssl *)op; ND_PRINT((ndo," lifetime %us, domain(s):", EXTRACT_32BITS(&opds->nd_opt_dnssl_lifetime))); domp = cp + 8; /* domain names, variable-sized, RFC1035-encoded */ while (domp < cp + (op->nd_opt_len << 3) && *domp != '\0') { ND_PRINT((ndo, " ")); if ((domp = ns_nprint (ndo, domp, bp)) == NULL) goto trunc; } break; case ND_OPT_ADVINTERVAL: opa = (const struct nd_opt_advinterval *)op; ND_TCHECK(opa->nd_opt_adv_interval); ND_PRINT((ndo," %ums", EXTRACT_32BITS(&opa->nd_opt_adv_interval))); break; case ND_OPT_HOMEAGENT_INFO: oph = (const struct nd_opt_homeagent_info *)op; ND_TCHECK(oph->nd_opt_hai_lifetime); ND_PRINT((ndo," preference %u, lifetime %u", EXTRACT_16BITS(&oph->nd_opt_hai_preference), EXTRACT_16BITS(&oph->nd_opt_hai_lifetime))); break; case ND_OPT_ROUTE_INFO: opri = (const struct nd_opt_route_info *)op; ND_TCHECK(opri->nd_opt_rti_lifetime); memset(&in6, 0, sizeof(in6)); in6p = (const struct in6_addr *)(opri + 1); switch (op->nd_opt_len) { case 1: break; case 2: ND_TCHECK2(*in6p, 8); memcpy(&in6, opri + 1, 8); break; case 3: ND_TCHECK(*in6p); memcpy(&in6, opri + 1, sizeof(in6)); break; default: goto trunc; } ND_PRINT((ndo," %s/%u", ip6addr_string(ndo, &in6), opri->nd_opt_rti_prefixlen)); ND_PRINT((ndo,", pref=%s", get_rtpref(opri->nd_opt_rti_flags))); ND_PRINT((ndo,", lifetime=%s", get_lifetime(EXTRACT_32BITS(&opri->nd_opt_rti_lifetime)))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo,cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */ return; } break; } /* do we want to see an additional hexdump ? */ if (ndo->ndo_vflag> 1) print_unknown_data(ndo, cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */ cp += op->nd_opt_len << 3; resid -= op->nd_opt_len << 3; } return; trunc: ND_PRINT((ndo, "[ndp opt]")); return; #undef ECHECK } CWE ID: CWE-125 Target: 1 Example 2: Code: void BrowserWindowGtk::ResetCustomFrameCursor() { if (!frame_cursor_) return; frame_cursor_ = NULL; gdk_window_set_cursor(gtk_widget_get_window(GTK_WIDGET(window_)), NULL); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; } 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: static int iucv_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); unsigned int copied, rlen; struct sk_buff *skb, *rskb, *cskb; int err = 0; if ((sk->sk_state == IUCV_DISCONN) && skb_queue_empty(&iucv->backlog_skb_q) && skb_queue_empty(&sk->sk_receive_queue) && list_empty(&iucv->message_q.list)) return 0; if (flags & (MSG_OOB)) return -EOPNOTSUPP; /* receive/dequeue next skb: * the function understands MSG_PEEK and, thus, does not dequeue skb */ skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); if (!rlen) sk->sk_shutdown = sk->sk_shutdown | RCV_SHUTDOWN; cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } /* SOCK_SEQPACKET: set MSG_TRUNC if recv buf size is too small */ if (sk->sk_type == SOCK_SEQPACKET) { if (copied < rlen) msg->msg_flags |= MSG_TRUNC; /* each iucv message contains a complete record */ msg->msg_flags |= MSG_EOR; } /* create control message to store iucv msg target class: * get the trgcls from the control buffer of the skb due to * fragmentation of original iucv message. */ err = put_cmsg(msg, SOL_IUCV, SCM_IUCV_TRGCLS, CB_TRGCLS_LEN, CB_TRGCLS(skb)); if (err) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return err; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); if (iucv->transport == AF_IUCV_TRANS_HIPER) { atomic_inc(&iucv->msg_recv); if (atomic_read(&iucv->msg_recv) > iucv->msglimit) { WARN_ON(1); iucv_sock_close(sk); return -EFAULT; } } /* Queue backlog skbs */ spin_lock_bh(&iucv->message_q.lock); rskb = skb_dequeue(&iucv->backlog_skb_q); while (rskb) { if (sock_queue_rcv_skb(sk, rskb)) { skb_queue_head(&iucv->backlog_skb_q, rskb); break; } else { rskb = skb_dequeue(&iucv->backlog_skb_q); } } if (skb_queue_empty(&iucv->backlog_skb_q)) { if (!list_empty(&iucv->message_q.list)) iucv_process_message_q(sk); if (atomic_read(&iucv->msg_recv) >= iucv->msglimit / 2) { err = iucv_send_ctrl(sk, AF_IUCV_FLAG_WIN); if (err) { sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } } } spin_unlock_bh(&iucv->message_q.lock); } done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; } CWE ID: CWE-200 Target: 1 Example 2: Code: void WebKitTestController::RenderProcessGone(base::TerminationStatus status) { DCHECK(CalledOnValidThread()); if (current_pid_ != base::kNullProcessId) { printer_->AddErrorMessage(std::string("#CRASHED - renderer (pid ") + base::IntToString(current_pid_) + ")"); } else { printer_->AddErrorMessage("#CRASHED - renderer"); } DiscardMainWindow(); } 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 NaClProcessHost::OnProcessLaunched() { FilePath irt_path; const char* irt_path_var = getenv("NACL_IRT_LIBRARY"); if (irt_path_var != NULL) { FilePath::StringType string(irt_path_var, irt_path_var + strlen(irt_path_var)); irt_path = FilePath(string); } else { FilePath plugin_dir; if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) { LOG(ERROR) << "Failed to locate the plugins directory"; delete this; return; } irt_path = plugin_dir.Append(GetIrtLibraryFilename()); } base::FileUtilProxy::CreateOrOpenCallback* callback = callback_factory_.NewCallback(&NaClProcessHost::OpenIrtFileDone); if (!base::FileUtilProxy::CreateOrOpen( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), irt_path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ, callback)) { delete callback; delete this; } } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void svc_rdma_destroy_maps(struct svcxprt_rdma *xprt) { while (!list_empty(&xprt->sc_maps)) { struct svc_rdma_req_map *map; map = list_first_entry(&xprt->sc_maps, struct svc_rdma_req_map, free); list_del(&map->free); kfree(map); } } CWE ID: CWE-404 Target: 1 Example 2: Code: static bool nfs_fattr_map_owner_name(struct nfs_server *server, struct nfs_fattr *fattr) { struct nfs4_string *owner = fattr->owner_name; kuid_t uid; if (!(fattr->valid & NFS_ATTR_FATTR_OWNER_NAME)) return false; if (nfs_map_name_to_uid(server, owner->data, owner->len, &uid) == 0) { fattr->uid = uid; fattr->valid |= NFS_ATTR_FATTR_OWNER; } return true; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void md_new_event_inintr(struct mddev *mddev) { atomic_inc(&md_event_count); wake_up(&md_event_waiters); } CWE ID: CWE-200 Output:
0