prompt
stringlengths
799
20.4k
output
int64
0
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int asymmetric_key_match(const struct key *key, const struct key_match_data *match_data) { const struct asymmetric_key_subtype *subtype = asymmetric_key_subtype(key); const char *description = match_data->raw_data; const char *spec = description; const char *id; ptrdiff_t speclen; if (!subtype || !spec || !*spec) return 0; /* See if the full key description matches as is */ if (key->description && strcmp(key->description, description) == 0) return 1; /* All tests from here on break the criterion description into a * specifier, a colon and then an identifier. */ id = strchr(spec, ':'); if (!id) return 0; speclen = id - spec; id++; if (speclen == 2 && memcmp(spec, "id", 2) == 0) return asymmetric_keyid_match(asymmetric_key_id(key), id); if (speclen == subtype->name_len && memcmp(spec, subtype->name, speclen) == 0) return 1; return 0; } CWE ID: CWE-476 Target: 1 Example 2: Code: directory_count_stop (NautilusDirectory *directory) { NautilusFile *file; if (directory->details->count_in_progress != NULL) { file = directory->details->count_in_progress->count_file; if (file != NULL) { g_assert (NAUTILUS_IS_FILE (file)); g_assert (file->details->directory == directory); if (is_needy (file, should_get_directory_count_now, REQUEST_DIRECTORY_COUNT)) { return; } } /* The count is not wanted, so stop it. */ directory_count_cancel (directory); } } 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: socket_t *socket_accept(const socket_t *socket) { assert(socket != NULL); int fd = accept(socket->fd, NULL, NULL); if (fd == INVALID_FD) { LOG_ERROR("%s unable to accept socket: %s", __func__, strerror(errno)); return NULL; } socket_t *ret = (socket_t *)osi_calloc(sizeof(socket_t)); if (!ret) { close(fd); LOG_ERROR("%s unable to allocate memory for socket.", __func__); return NULL; } ret->fd = fd; return ret; } CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> postMessageCallback(const v8::Arguments& args) { INC_STATS("DOM.TestActiveDOMObject.postMessage"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, message, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->postMessage(message); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: BasePage* ThreadHeap::LookupPageForAddress(Address address) { DCHECK(thread_state_->InAtomicMarkingPause()); if (PageMemoryRegion* region = region_tree_->Lookup(address)) { return region->PageFromAddress(address); } return nullptr; } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) } 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: standard_info_part2(standard_display *dp, png_const_structp pp, png_const_infop pi, int nImages) { /* Record cbRow now that it can be found. */ dp->pixel_size = bit_size(pp, png_get_color_type(pp, pi), png_get_bit_depth(pp, pi)); dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size; dp->cbRow = png_get_rowbytes(pp, pi); /* Validate the rowbytes here again. */ if (dp->cbRow != (dp->bit_width+7)/8) png_error(pp, "bad png_get_rowbytes calculation"); /* Then ensure there is enough space for the output image(s). */ store_ensure_image(dp->ps, pp, nImages, dp->cbRow, dp->h); } CWE ID: Target: 1 Example 2: Code: ssh_packet_is_rekeying(struct ssh *ssh) { return compat20 && (ssh->state->rekeying || (ssh->kex != NULL && ssh->kex->done == 0)); } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: __u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr, __be16 sport, __be16 dport) { __u32 seq; __u32 hash[12]; struct keydata *keyptr = get_keyptr(); /* The procedure is the same as for IPv4, but addresses are longer. * Thus we must use twothirdsMD4Transform. */ memcpy(hash, saddr, 16); hash[4] = ((__force u16)sport << 16) + (__force u16)dport; memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7); seq = twothirdsMD4Transform((const __u32 *)daddr, hash) & HASH_MASK; seq += keyptr->count; seq += ktime_to_ns(ktime_get_real()); return seq; } 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 struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; __ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ if (np->opt) newnp->opt = ipv6_dup_options(newsk, np->opt); inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); if (tcp_sk(sk)->rx_opt.user_mss && tcp_sk(sk)->rx_opt.user_mss < newtp->advmss) newtp->advmss = tcp_sk(sk)->rx_opt.user_mss; tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_atomic(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_atomic(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } CWE ID: CWE-416 Target: 1 Example 2: Code: RenderThreadImpl::GetCompositorImplThreadTaskRunner() { return compositor_task_runner_; } CWE ID: CWE-310 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ath_tx_queue_tid(struct ath_txq *txq, struct ath_atx_tid *tid) { struct ath_atx_ac *ac = tid->ac; if (tid->paused) return; if (tid->sched) return; tid->sched = true; list_add_tail(&tid->list, &ac->tid_q); if (ac->sched) return; ac->sched = true; list_add_tail(&ac->list, &txq->axq_acq); } 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: GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context, const GURL& real_url) { if (real_url.SchemeIs(kGuestScheme)) return real_url; GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url); url::Origin origin = url::Origin::Create(url); auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); url::Origin isolated_origin; if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin)) return isolated_origin.GetURL(); if (!origin.host().empty() && origin.scheme() != url::kFileScheme) { std::string domain = net::registry_controlled_domains::GetDomainAndRegistry( origin.host(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); std::string site = origin.scheme(); site += url::kStandardSchemeSeparator; site += domain.empty() ? origin.host() : domain; return GURL(site); } if (!origin.unique()) { DCHECK(!origin.scheme().empty()); return GURL(origin.scheme() + ":"); } else if (url.has_scheme()) { if (url.SchemeIsBlob()) { if (url.has_ref()) { GURL::Replacements replacements; replacements.ClearRef(); url = url.ReplaceComponents(replacements); } return url; } DCHECK(!url.scheme().empty()); return GURL(url.scheme() + ":"); } DCHECK(!url.is_valid()) << url; return GURL(); } CWE ID: CWE-285 Target: 1 Example 2: Code: GetGeometry(ClientPtr client, xGetGeometryReply * rep) { DrawablePtr pDraw; int rc; REQUEST(xResourceReq); REQUEST_SIZE_MATCH(xResourceReq); rc = dixLookupDrawable(&pDraw, stuff->id, client, M_ANY, DixGetAttrAccess); if (rc != Success) return rc; rep->type = X_Reply; rep->length = 0; rep->sequenceNumber = client->sequence; rep->root = pDraw->pScreen->root->drawable.id; rep->depth = pDraw->depth; rep->width = pDraw->width; rep->height = pDraw->height; if (WindowDrawable(pDraw->type)) { WindowPtr pWin = (WindowPtr) pDraw; rep->x = pWin->origin.x - wBorderWidth(pWin); rep->y = pWin->origin.y - wBorderWidth(pWin); rep->borderWidth = pWin->borderWidth; } else { /* DRAWABLE_PIXMAP */ rep->x = rep->y = rep->borderWidth = 0; } return Success; } CWE ID: CWE-369 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: main(const int argc, const char * const * const argv) { /* For each file on the command line test it with a range of transforms */ int option_end, ilog = 0; struct display d; validate_T(); display_init(&d); for (option_end=1; option_end<argc; ++option_end) { const char *name = argv[option_end]; if (strcmp(name, "--verbose") == 0) d.options = (d.options & ~LEVEL_MASK) | VERBOSE; else if (strcmp(name, "--warnings") == 0) d.options = (d.options & ~LEVEL_MASK) | WARNINGS; else if (strcmp(name, "--errors") == 0) d.options = (d.options & ~LEVEL_MASK) | ERRORS; else if (strcmp(name, "--quiet") == 0) d.options = (d.options & ~LEVEL_MASK) | QUIET; else if (strcmp(name, "--exhaustive") == 0) d.options |= EXHAUSTIVE; else if (strcmp(name, "--fast") == 0) d.options &= ~EXHAUSTIVE; else if (strcmp(name, "--strict") == 0) d.options |= STRICT; else if (strcmp(name, "--relaxed") == 0) d.options &= ~STRICT; else if (strcmp(name, "--log") == 0) { ilog = option_end; /* prevent display */ d.options |= LOG; } else if (strcmp(name, "--nolog") == 0) d.options &= ~LOG; else if (strcmp(name, "--continue") == 0) d.options |= CONTINUE; else if (strcmp(name, "--stop") == 0) d.options &= ~CONTINUE; else if (strcmp(name, "--skip-bugs") == 0) d.options |= SKIP_BUGS; else if (strcmp(name, "--test-all") == 0) d.options &= ~SKIP_BUGS; else if (strcmp(name, "--log-skipped") == 0) d.options |= LOG_SKIPPED; else if (strcmp(name, "--nolog-skipped") == 0) d.options &= ~LOG_SKIPPED; else if (strcmp(name, "--find-bad-combos") == 0) d.options |= FIND_BAD_COMBOS; else if (strcmp(name, "--nofind-bad-combos") == 0) d.options &= ~FIND_BAD_COMBOS; else if (name[0] == '-' && name[1] == '-') { fprintf(stderr, "pngimage: %s: unknown option\n", name); return 99; } else break; /* Not an option */ } { int i; int errors = 0; for (i=option_end; i<argc; ++i) { { int ret = do_test(&d, argv[i]); if (ret > QUIET) /* abort on user or internal error */ return 99; } /* Here on any return, including failures, except user/internal issues */ { const int pass = (d.options & STRICT) ? RESULT_STRICT(d.results) : RESULT_RELAXED(d.results); if (!pass) ++errors; if (d.options & LOG) { int j; printf("%s: pngimage ", pass ? "PASS" : "FAIL"); for (j=1; j<option_end; ++j) if (j != ilog) printf("%s ", argv[j]); printf("%s\n", d.filename); } } display_clean(&d); } return errors != 0; } } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DownloadRequestLimiter::TabDownloadState::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; if (status_ == ALLOW_ONE_DOWNLOAD || (status_ == PROMPT_BEFORE_DOWNLOAD && !navigation_handle->IsRendererInitiated())) { NotifyCallbacks(false); host_->Remove(this, web_contents()); } } CWE ID: Target: 1 Example 2: Code: void FakeCentral::RemoveFakeDescriptor(const std::string& descriptor_id, const std::string& characteristic_id, const std::string& service_id, const std::string& peripheral_address, RemoveFakeDescriptorCallback callback) { FakeRemoteGattCharacteristic* fake_remote_gatt_characteristic = GetFakeRemoteGattCharacteristic(peripheral_address, service_id, characteristic_id); if (!fake_remote_gatt_characteristic) { std::move(callback).Run(false); return; } std::move(callback).Run( fake_remote_gatt_characteristic->RemoveFakeDescriptor(descriptor_id)); } 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 copy_cred(struct svc_cred *target, struct svc_cred *source) { int ret; ret = strdup_if_nonnull(&target->cr_principal, source->cr_principal); if (ret) return ret; ret = strdup_if_nonnull(&target->cr_raw_principal, source->cr_raw_principal); if (ret) return ret; target->cr_flavor = source->cr_flavor; target->cr_uid = source->cr_uid; target->cr_gid = source->cr_gid; target->cr_group_info = source->cr_group_info; get_group_info(target->cr_group_info); target->cr_gss_mech = source->cr_gss_mech; if (source->cr_gss_mech) gss_mech_get(source->cr_gss_mech); return 0; } CWE ID: CWE-404 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: SProcXIBarrierReleasePointer(ClientPtr client) { xXIBarrierReleasePointerInfo *info; REQUEST(xXIBarrierReleasePointerReq); int i; swaps(&stuff->length); REQUEST_AT_LEAST_SIZE(xXIBarrierReleasePointerReq); swapl(&stuff->num_barriers); REQUEST_FIXED_SIZE(xXIBarrierReleasePointerReq, stuff->num_barriers * sizeof(xXIBarrierReleasePointerInfo)); info = (xXIBarrierReleasePointerInfo*) &stuff[1]; swapl(&info->barrier); swapl(&info->eventid); } CWE ID: CWE-190 Target: 1 Example 2: Code: static FILE *msg_cache_get(struct ImapData *idata, struct Header *h) { if (!idata || !h) return NULL; idata->bcache = msg_cache_open(idata); char id[64]; snprintf(id, sizeof(id), "%u-%u", idata->uid_validity, HEADER_DATA(h)->uid); return mutt_bcache_get(idata->bcache, id); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void __init fork_init(void) { int i; #ifndef CONFIG_ARCH_TASK_STRUCT_ALLOCATOR #ifndef ARCH_MIN_TASKALIGN #define ARCH_MIN_TASKALIGN 0 #endif int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN); /* create a slab on which task_structs can be allocated */ task_struct_cachep = kmem_cache_create("task_struct", arch_task_struct_size, align, SLAB_PANIC|SLAB_NOTRACK|SLAB_ACCOUNT, NULL); #endif /* do the arch specific task caches init */ arch_task_cache_init(); set_max_threads(MAX_THREADS); init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2; init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2; init_task.signal->rlim[RLIMIT_SIGPENDING] = init_task.signal->rlim[RLIMIT_NPROC]; for (i = 0; i < UCOUNT_COUNTS; i++) { init_user_ns.ucount_max[i] = max_threads/2; } #ifdef CONFIG_VMAP_STACK cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache", NULL, free_vm_stack_cache); #endif } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int pop_fetch_message(struct Context *ctx, struct Message *msg, int msgno) { void *uidl = NULL; char buf[LONG_STRING]; char path[PATH_MAX]; struct Progress progressbar; struct PopData *pop_data = (struct PopData *) ctx->data; struct PopCache *cache = NULL; struct Header *h = ctx->hdrs[msgno]; unsigned short bcache = 1; /* see if we already have the message in body cache */ msg->fp = mutt_bcache_get(pop_data->bcache, h->data); if (msg->fp) return 0; /* * see if we already have the message in our cache in * case $message_cachedir is unset */ cache = &pop_data->cache[h->index % POP_CACHE_LEN]; if (cache->path) { if (cache->index == h->index) { /* yes, so just return a pointer to the message */ msg->fp = fopen(cache->path, "r"); if (msg->fp) return 0; mutt_perror(cache->path); return -1; } else { /* clear the previous entry */ unlink(cache->path); FREE(&cache->path); } } while (true) { if (pop_reconnect(ctx) < 0) return -1; /* verify that massage index is correct */ if (h->refno < 0) { mutt_error( _("The message index is incorrect. Try reopening the mailbox.")); return -1; } mutt_progress_init(&progressbar, _("Fetching message..."), MUTT_PROGRESS_SIZE, NetInc, h->content->length + h->content->offset - 1); /* see if we can put in body cache; use our cache as fallback */ msg->fp = mutt_bcache_put(pop_data->bcache, h->data); if (!msg->fp) { /* no */ bcache = 0; mutt_mktemp(path, sizeof(path)); msg->fp = mutt_file_fopen(path, "w+"); if (!msg->fp) { mutt_perror(path); return -1; } } snprintf(buf, sizeof(buf), "RETR %d\r\n", h->refno); const int ret = pop_fetch_data(pop_data, buf, &progressbar, fetch_message, msg->fp); if (ret == 0) break; mutt_file_fclose(&msg->fp); /* if RETR failed (e.g. connection closed), be sure to remove either * the file in bcache or from POP's own cache since the next iteration * of the loop will re-attempt to put() the message */ if (!bcache) unlink(path); if (ret == -2) { mutt_error("%s", pop_data->err_msg); return -1; } if (ret == -3) { mutt_error(_("Can't write message to temporary file!")); return -1; } } /* Update the header information. Previously, we only downloaded a * portion of the headers, those required for the main display. */ if (bcache) mutt_bcache_commit(pop_data->bcache, h->data); else { cache->index = h->index; cache->path = mutt_str_strdup(path); } rewind(msg->fp); uidl = h->data; /* we replace envelop, key in subj_hash has to be updated as well */ if (ctx->subj_hash && h->env->real_subj) mutt_hash_delete(ctx->subj_hash, h->env->real_subj, h); mutt_label_hash_remove(ctx, h); mutt_env_free(&h->env); h->env = mutt_rfc822_read_header(msg->fp, h, 0, 0); if (ctx->subj_hash && h->env->real_subj) mutt_hash_insert(ctx->subj_hash, h->env->real_subj, h); mutt_label_hash_add(ctx, h); h->data = uidl; h->lines = 0; fgets(buf, sizeof(buf), msg->fp); while (!feof(msg->fp)) { ctx->hdrs[msgno]->lines++; fgets(buf, sizeof(buf), msg->fp); } h->content->length = ftello(msg->fp) - h->content->offset; /* This needs to be done in case this is a multipart message */ if (!WithCrypto) h->security = crypt_query(h->content); mutt_clear_error(); rewind(msg->fp); return 0; } CWE ID: CWE-22 Target: 1 Example 2: Code: referenceDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name) { callbacks++; if (quiet) return; fprintf(SAXdebug, "SAX.reference(%s)\n", name); } 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: RenderFrameImpl::BuildServiceWorkerNetworkProviderForNavigation( blink::mojom::ControllerServiceWorkerInfoPtr controller_service_worker_info, blink::mojom::ServiceWorkerProviderInfoForWindowPtr provider_info) { if (!provider_info) { return ServiceWorkerNetworkProviderForFrame::CreateInvalidInstance(); } scoped_refptr<network::SharedURLLoaderFactory> fallback_factory = network::SharedURLLoaderFactory::Create( GetLoaderFactoryBundle()->CloneWithoutAppCacheFactory()); return ServiceWorkerNetworkProviderForFrame::Create( this, std::move(provider_info), std::move(controller_service_worker_info), std::move(fallback_factory)); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static PassRefPtr<CSSValue> getPositionOffsetValue(RenderStyle* style, CSSPropertyID propertyID, RenderView* renderView) { if (!style) return 0; Length l; switch (propertyID) { case CSSPropertyLeft: l = style->left(); break; case CSSPropertyRight: l = style->right(); break; case CSSPropertyTop: l = style->top(); break; case CSSPropertyBottom: l = style->bottom(); break; default: return 0; } if (style->position() == AbsolutePosition || style->position() == FixedPosition) { if (l.type() == WebCore::Fixed) return zoomAdjustedPixelValue(l.value(), style); else if (l.isViewportPercentage()) return zoomAdjustedPixelValue(valueForLength(l, 0, renderView), style); return cssValuePool().createValue(l); } if (style->position() == RelativePosition) return cssValuePool().createValue(l); return cssValuePool().createIdentifierValue(CSSValueAuto); } CWE ID: CWE-119 Target: 1 Example 2: Code: void WebRuntimeFeatures::EnableExperimentalFeatures(bool enable) { RuntimeEnabledFeatures::SetExperimentalFeaturesEnabled(enable); } 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 GpuProcessHost::DidFailInitialize() { UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", false); status_ = FAILURE; GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance(); gpu_data_manager->FallBackToNextGpuMode(); RunRequestGPUInfoCallbacks(gpu_data_manager->GetGPUInfo()); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int vt_reset_keyboard(int fd) { int kb; /* If we can't read the default, then default to unicode. It's 2017 after all. */ kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE; if (ioctl(fd, KDSKBMODE, kb) < 0) return -errno; return 0; } CWE ID: CWE-255 Target: 1 Example 2: Code: static void __always_inline vmx_enable_intercept_for_msr(unsigned long *msr_bitmap, u32 msr, int type) { int f = sizeof(unsigned long); if (!cpu_has_vmx_msr_bitmap()) return; if (static_branch_unlikely(&enable_evmcs)) evmcs_touch_msr_bitmap(); /* * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals * have the write-low and read-high bitmap offsets the wrong way round. * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff. */ if (msr <= 0x1fff) { if (type & MSR_TYPE_R) /* read-low */ __set_bit(msr, msr_bitmap + 0x000 / f); if (type & MSR_TYPE_W) /* write-low */ __set_bit(msr, msr_bitmap + 0x800 / f); } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) { msr &= 0x1fff; if (type & MSR_TYPE_R) /* read-high */ __set_bit(msr, msr_bitmap + 0x400 / f); if (type & MSR_TYPE_W) /* write-high */ __set_bit(msr, msr_bitmap + 0xc00 / f); } } 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 GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) { WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); if (!frame) { args.GetReturnValue().SetNull(); return; } WebDataSource* data_source = frame->dataSource(); if (!data_source) { args.GetReturnValue().SetNull(); return; } DocumentState* document_state = DocumentState::FromDataSource(data_source); if (!document_state) { args.GetReturnValue().SetNull(); return; } double request_time = document_state->request_time().ToDoubleT(); double start_load_time = document_state->start_load_time().ToDoubleT(); double commit_load_time = document_state->commit_load_time().ToDoubleT(); double finish_document_load_time = document_state->finish_document_load_time().ToDoubleT(); double finish_load_time = document_state->finish_load_time().ToDoubleT(); double first_paint_time = document_state->first_paint_time().ToDoubleT(); double first_paint_after_load_time = document_state->first_paint_after_load_time().ToDoubleT(); std::string navigation_type = GetNavigationType(data_source->navigationType()); bool was_fetched_via_spdy = document_state->was_fetched_via_spdy(); bool was_npn_negotiated = document_state->was_npn_negotiated(); std::string npn_negotiated_protocol = document_state->npn_negotiated_protocol(); bool was_alternate_protocol_available = document_state->was_alternate_protocol_available(); std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString( document_state->connection_info()); v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Object> load_times = v8::Object::New(isolate); load_times->Set(v8::String::NewFromUtf8(isolate, "requestTime"), v8::Number::New(isolate, request_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "startLoadTime"), v8::Number::New(isolate, start_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "commitLoadTime"), v8::Number::New(isolate, commit_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"), v8::Number::New(isolate, finish_document_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "finishLoadTime"), v8::Number::New(isolate, finish_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintTime"), v8::Number::New(isolate, first_paint_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"), v8::Number::New(isolate, first_paint_after_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "navigationType"), v8::String::NewFromUtf8(isolate, navigation_type.c_str())); load_times->Set(v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"), v8::Boolean::New(isolate, was_fetched_via_spdy)); load_times->Set(v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"), v8::Boolean::New(isolate, was_npn_negotiated)); load_times->Set( v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"), v8::String::NewFromUtf8(isolate, npn_negotiated_protocol.c_str())); load_times->Set( v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"), v8::Boolean::New(isolate, was_alternate_protocol_available)); load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"), v8::String::NewFromUtf8(isolate, connection_info.c_str())); args.GetReturnValue().Set(load_times); } 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: jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->ops = &boxinfo->ops; box->len = len; if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; } CWE ID: CWE-476 Target: 1 Example 2: Code: static inline struct page *alloc_slab_page(gfp_t flags, int node, struct kmem_cache_order_objects oo) { int order = oo_order(oo); if (node == -1) return alloc_pages(flags, order); else return alloc_pages_node(node, flags, order); } 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 InputHandler::cut() { executeTextEditCommand("Cut"); } 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: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8( "[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;" "[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;" "[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;" "[ҫင] > c; ұ > y; [χҳӽӿ] > x;" "ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;" "[зҙӡउওဒვპ] > 3; [บບ] > u"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } CWE ID: CWE-20 Target: 1 Example 2: Code: static MagickBooleanType load_hierarchy(Image *image,XCFDocInfo *inDocInfo, XCFLayerInfo *inLayer) { MagickOffsetType saved_pos, offset, junk; size_t width, height, bytes_per_pixel; width=ReadBlobMSBLong(image); (void) width; height=ReadBlobMSBLong(image); (void) height; bytes_per_pixel=inDocInfo->bytes_per_pixel=ReadBlobMSBLong(image); (void) bytes_per_pixel; /* load in the levels...we make sure that the number of levels * calculated when the TileManager was created is the same * as the number of levels found in the file. */ offset=(MagickOffsetType) ReadBlobMSBLong(image); /* top level */ /* discard offsets for layers below first, if any. */ do { junk=(MagickOffsetType) ReadBlobMSBLong(image); } while (junk != 0); /* save the current position as it is where the * next level offset is stored. */ saved_pos=TellBlob(image); /* seek to the level offset */ if (SeekBlob(image, offset, SEEK_SET) != offset) ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile", image->filename); /* read in the level */ if (load_level (image, inDocInfo, inLayer) == 0) return(MagickFalse); /* restore the saved position so we'll be ready to * read the next offset. */ offset=SeekBlob(image, saved_pos, SEEK_SET); return(MagickTrue); } 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 mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track) { int i; uint8_t leading, dependent, reference, redundancy; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "sdtp"); avio_wb32(pb, 0); // version & flags for (i = 0; i < track->entry; i++) { dependent = MOV_SAMPLE_DEPENDENCY_YES; leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN; if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) { reference = MOV_SAMPLE_DEPENDENCY_NO; } if (track->cluster[i].flags & MOV_SYNC_SAMPLE) { dependent = MOV_SAMPLE_DEPENDENCY_NO; } avio_w8(pb, (leading << 6) | (dependent << 4) | (reference << 2) | redundancy); } return update_size(pb, pos); } CWE ID: CWE-369 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 DataReductionProxyConfig::InitializeOnIOThread( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, WarmupURLFetcher::CreateCustomProxyConfigCallback create_custom_proxy_config_callback, NetworkPropertiesManager* manager) { DCHECK(thread_checker_.CalledOnValidThread()); network_properties_manager_ = manager; network_properties_manager_->ResetWarmupURLFetchMetrics(); secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory)); warmup_url_fetcher_.reset(new WarmupURLFetcher( url_loader_factory, create_custom_proxy_config_callback, base::BindRepeating( &DataReductionProxyConfig::HandleWarmupFetcherResponse, base::Unretained(this)), base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate, base::Unretained(this)), ui_task_runner_)); if (ShouldAddDefaultProxyBypassRules()) AddDefaultProxyBypassRules(); network_connection_tracker_->AddNetworkConnectionObserver(this); network_connection_tracker_->GetConnectionType( &connection_type_, base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged, weak_factory_.GetWeakPtr())); } CWE ID: CWE-20 Target: 1 Example 2: Code: static int lua_ap_exists_config_define(lua_State *L) { int returnValue; const char *name; luaL_checktype(L, 1, LUA_TSTRING); name = lua_tostring(L, 1); returnValue = ap_exists_config_define(name); lua_pushboolean(L, returnValue); return 1; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static const struct sys_reg_desc *get_target_table(unsigned target, bool mode_is_64, size_t *num) { struct kvm_sys_reg_target_table *table; table = target_tables[target]; if (mode_is_64) { *num = table->table64.num; return table->table64.table; } else { *num = table->table32.num; return table->table32.table; } } CWE ID: CWE-617 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int inotify_release(struct inode *ignored, struct file *file) { struct fsnotify_group *group = file->private_data; struct user_struct *user = group->inotify_data.user; pr_debug("%s: group=%p\n", __func__, group); fsnotify_clear_marks_by_group(group); /* free this group, matching get was inotify_init->fsnotify_obtain_group */ fsnotify_put_group(group); atomic_dec(&user->inotify_devs); return 0; } CWE ID: CWE-399 Target: 1 Example 2: Code: void Editor::SetBaseWritingDirection(WritingDirection direction) { Element* focused_element = GetFrame().GetDocument()->FocusedElement(); if (IsTextControlElement(focused_element)) { if (direction == NaturalWritingDirection) return; focused_element->setAttribute( dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl"); focused_element->DispatchInputEvent(); return; } MutableStylePropertySet* style = MutableStylePropertySet::Create(kHTMLQuirksMode); style->SetProperty( CSSPropertyDirection, direction == LeftToRightWritingDirection ? "ltr" : direction == RightToLeftWritingDirection ? "rtl" : "inherit", false); ApplyParagraphStyleToSelection( style, InputEvent::InputType::kFormatSetBlockTextDirection); } 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: open_patch_file (char const *filename) { file_offset file_pos = 0; file_offset pos; struct stat st; if (!filename || !*filename || strEQ (filename, "-")) pfp = stdin; else { pfp = fopen (filename, binary_transput ? "rb" : "r"); if (!pfp) pfatal ("Can't open patch file %s", quotearg (filename)); } #if HAVE_SETMODE_DOS if (binary_transput) { if (isatty (fileno (pfp))) fatal ("cannot read binary data from tty on this platform"); setmode (fileno (pfp), O_BINARY); } #endif if (fstat (fileno (pfp), &st) != 0) pfatal ("fstat"); if (S_ISREG (st.st_mode) && (pos = file_tell (pfp)) != -1) file_pos = pos; else { size_t charsread; int fd = make_tempfile (&TMPPATNAME, 'p', NULL, O_RDWR | O_BINARY, 0); FILE *read_pfp = pfp; TMPPATNAME_needs_removal = true; pfp = fdopen (fd, "w+b"); if (! pfp) pfatal ("Can't open stream for file %s", quotearg (TMPPATNAME)); for (st.st_size = 0; (charsread = fread (buf, 1, bufsize, read_pfp)) != 0; st.st_size += charsread) if (fwrite (buf, 1, charsread, pfp) != charsread) write_fatal (); if (ferror (read_pfp) || fclose (read_pfp) != 0) read_fatal (); if (fflush (pfp) != 0 || file_seek (pfp, (file_offset) 0, SEEK_SET) != 0) write_fatal (); } p_filesize = st.st_size; if (p_filesize != (file_offset) p_filesize) fatal ("patch file is too long"); next_intuit_at (file_pos, 1); set_hunkmax(); } 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 nf_ct_frag6_gather(struct net *net, struct sk_buff *skb, u32 user) { struct net_device *dev = skb->dev; int fhoff, nhoff, ret; struct frag_hdr *fhdr; struct frag_queue *fq; struct ipv6hdr *hdr; u8 prevhdr; /* Jumbo payload inhibits frag. header */ if (ipv6_hdr(skb)->payload_len == 0) { pr_debug("payload len = 0\n"); return -EINVAL; } if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0) return -EINVAL; if (!pskb_may_pull(skb, fhoff + sizeof(*fhdr))) return -ENOMEM; skb_set_transport_header(skb, fhoff); hdr = ipv6_hdr(skb); fhdr = (struct frag_hdr *)skb_transport_header(skb); fq = fq_find(net, fhdr->identification, user, &hdr->saddr, &hdr->daddr, skb->dev ? skb->dev->ifindex : 0, ip6_frag_ecn(hdr)); if (fq == NULL) { pr_debug("Can't find and can't create new queue\n"); return -ENOMEM; } spin_lock_bh(&fq->q.lock); if (nf_ct_frag6_queue(fq, skb, fhdr, nhoff) < 0) { ret = -EINVAL; goto out_unlock; } /* after queue has assumed skb ownership, only 0 or -EINPROGRESS * must be returned. */ ret = -EINPROGRESS; if (fq->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len && nf_ct_frag6_reasm(fq, skb, dev)) ret = 0; out_unlock: spin_unlock_bh(&fq->q.lock); inet_frag_put(&fq->q, &nf_frags); return ret; } CWE ID: CWE-787 Target: 1 Example 2: Code: int nfs_open(struct inode *inode, struct file *filp) { struct nfs_open_context *ctx; struct rpc_cred *cred; cred = rpc_lookup_cred(); if (IS_ERR(cred)) return PTR_ERR(cred); ctx = alloc_nfs_open_context(filp->f_path.mnt, filp->f_path.dentry, cred); put_rpccred(cred); if (ctx == NULL) return -ENOMEM; ctx->mode = filp->f_mode; nfs_file_set_open_context(filp, ctx); put_nfs_open_context(ctx); return 0; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: InstalledBubbleContent(Browser* browser, const Extension* extension, ExtensionInstalledBubble::BubbleType type, SkBitmap* icon, ExtensionInstalledBubble* bubble) : browser_(browser), extension_id_(extension->id()), bubble_(bubble), type_(type), info_(NULL) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::BaseFont); gfx::Size size(icon->width(), icon->height()); if (size.width() > kIconSize || size.height() > kIconSize) size = gfx::Size(kIconSize, kIconSize); icon_ = new views::ImageView(); icon_->SetImageSize(size); icon_->SetImage(*icon); AddChildView(icon_); string16 extension_name = UTF8ToUTF16(extension->name()); base::i18n::AdjustStringForLocaleDirection(&extension_name); heading_ = new views::Label(l10n_util::GetStringFUTF16( IDS_EXTENSION_INSTALLED_HEADING, extension_name, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME))); heading_->SetFont(rb.GetFont(ResourceBundle::MediumFont)); heading_->SetMultiLine(true); heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(heading_); switch (type_) { case ExtensionInstalledBubble::PAGE_ACTION: { info_ = new views::Label(l10n_util::GetStringUTF16( IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO)); info_->SetFont(font); info_->SetMultiLine(true); info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(info_); break; } case ExtensionInstalledBubble::OMNIBOX_KEYWORD: { info_ = new views::Label(l10n_util::GetStringFUTF16( IDS_EXTENSION_INSTALLED_OMNIBOX_KEYWORD_INFO, UTF8ToUTF16(extension->omnibox_keyword()))); info_->SetFont(font); info_->SetMultiLine(true); info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(info_); break; } case ExtensionInstalledBubble::APP: { views::Link* link = new views::Link( l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALLED_APP_INFO)); link->set_listener(this); manage_ = link; manage_->SetFont(font); manage_->SetMultiLine(true); manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(manage_); break; } default: break; } if (type_ != ExtensionInstalledBubble::APP) { manage_ = new views::Label( l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALLED_MANAGE_INFO)); manage_->SetFont(font); manage_->SetMultiLine(true); manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(manage_); } close_button_ = new views::ImageButton(this); close_button_->SetImage(views::CustomButton::BS_NORMAL, rb.GetBitmapNamed(IDR_CLOSE_BAR)); close_button_->SetImage(views::CustomButton::BS_HOT, rb.GetBitmapNamed(IDR_CLOSE_BAR_H)); close_button_->SetImage(views::CustomButton::BS_PUSHED, rb.GetBitmapNamed(IDR_CLOSE_BAR_P)); AddChildView(close_button_); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RilSapSocket::sendResponse(MsgHeader* hdr) { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; pthread_mutex_lock(&write_lock); if ((success = pb_get_encoded_size(&encoded_size, MsgHeader_fields, hdr)) && encoded_size <= INT32_MAX && commandFd != -1) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t buffer[buffer_size]; written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, MsgHeader_fields, hdr); if (success) { RLOGD("Size: %d (0x%x) Size as written: 0x%x", encoded_size, encoded_size, written_size); log_hex("onRequestComplete", &buffer[sizeof(written_size)], encoded_size); RLOGI("[%d] < SAP RESPONSE type: %d. id: %d. error: %d", hdr->token, hdr->type, hdr->id,hdr->error ); if ( 0 != blockingWrite_helper(commandFd, buffer, buffer_size)) { RLOGE("Error %d while writing to fd", errno); } else { RLOGD("Write successful"); } } else { RLOGE("Error while encoding response of type %d id %d buffer_size: %d: %s.", hdr->type, hdr->id, buffer_size, PB_GET_ERROR(&ostream)); } } else { RLOGE("Not sending response type %d: encoded_size: %u. commandFd: %d. encoded size result: %d", hdr->type, encoded_size, commandFd, success); } pthread_mutex_unlock(&write_lock); } CWE ID: CWE-264 Target: 1 Example 2: Code: void CStarter::getJobOwnerFQUOrDummy(MyString &result) { ClassAd *jobAd = jic ? jic->jobClassAd() : NULL; if( jobAd ) { jobAd->LookupString(ATTR_USER,result); } if( result.IsEmpty() ) { result = "job-owner@submit-domain"; } } CWE ID: CWE-134 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewImpl::DidFocus(blink::WebLocalFrame* calling_frame) { if (WebUserGestureIndicator::IsProcessingUserGesture(calling_frame) && !RenderThreadImpl::current()->layout_test_mode()) { Send(new ViewHostMsg_Focus(GetRoutingID())); RenderFrameImpl* calling_render_frame = RenderFrameImpl::FromWebFrame(calling_frame); if (calling_render_frame) calling_render_frame->FrameDidCallFocus(); } } 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: static void suffix_object( cJSON *prev, cJSON *item ) { prev->next = item; item->prev = prev; } CWE ID: CWE-119 Target: 1 Example 2: Code: cc::ScrollTree& PropertyTreeManager::GetScrollTree() { return property_trees_.scroll_tree; } 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: virtual status_t decrypt( const void *inData, size_t size, uint32_t streamCTR, uint64_t inputCTR, void *outData) { Parcel data, reply; data.writeInterfaceToken(IHDCP::getInterfaceDescriptor()); data.writeInt32(size); data.write(inData, size); data.writeInt32(streamCTR); data.writeInt64(inputCTR); remote()->transact(HDCP_DECRYPT, data, &reply); status_t err = reply.readInt32(); if (err != OK) { return err; } reply.read(outData, size); return err; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ResourcePrefetchPredictor::LearnOrigins( const std::string& host, const GURL& main_frame_origin, const std::map<GURL, OriginRequestSummary>& summaries) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (host.size() > ResourcePrefetchPredictorTables::kMaxStringLength) return; OriginData data; bool exists = origin_data_->TryGetData(host, &data); if (!exists) { data.set_host(host); data.set_last_visit_time(base::Time::Now().ToInternalValue()); size_t origins_size = summaries.size(); auto ordered_origins = std::vector<const OriginRequestSummary*>(origins_size); for (const auto& kv : summaries) { size_t index = kv.second.first_occurrence; DCHECK_LT(index, origins_size); ordered_origins[index] = &kv.second; } for (const OriginRequestSummary* summary : ordered_origins) { auto* origin_to_add = data.add_origins(); InitializeOriginStatFromOriginRequestSummary(origin_to_add, *summary); } } else { data.set_last_visit_time(base::Time::Now().ToInternalValue()); std::map<GURL, int> old_index; int old_size = static_cast<int>(data.origins_size()); for (int i = 0; i < old_size; ++i) { bool is_new = old_index.insert({GURL(data.origins(i).origin()), i}).second; DCHECK(is_new); } for (int i = 0; i < old_size; ++i) { auto* old_origin = data.mutable_origins(i); GURL origin(old_origin->origin()); auto it = summaries.find(origin); if (it == summaries.end()) { old_origin->set_number_of_misses(old_origin->number_of_misses() + 1); old_origin->set_consecutive_misses(old_origin->consecutive_misses() + 1); } else { const auto& new_origin = it->second; old_origin->set_always_access_network(new_origin.always_access_network); old_origin->set_accessed_network(new_origin.accessed_network); int position = new_origin.first_occurrence + 1; int total = old_origin->number_of_hits() + old_origin->number_of_misses(); old_origin->set_average_position( ((old_origin->average_position() * total) + position) / (total + 1)); old_origin->set_number_of_hits(old_origin->number_of_hits() + 1); old_origin->set_consecutive_misses(0); } } for (const auto& kv : summaries) { if (old_index.find(kv.first) != old_index.end()) continue; auto* origin_to_add = data.add_origins(); InitializeOriginStatFromOriginRequestSummary(origin_to_add, kv.second); } } ResourcePrefetchPredictorTables::TrimOrigins(&data, config_.max_consecutive_misses); ResourcePrefetchPredictorTables::SortOrigins(&data, main_frame_origin.spec()); if (data.origins_size() > static_cast<int>(config_.max_origins_per_entry)) { data.mutable_origins()->DeleteSubrange( config_.max_origins_per_entry, data.origins_size() - config_.max_origins_per_entry); } if (data.origins_size() == 0) origin_data_->DeleteData({host}); else origin_data_->UpdateData(host, data); } CWE ID: CWE-125 Target: 1 Example 2: Code: static void callWithScriptStateScriptArgumentsVoidMethodOptionalBooleanArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); if (UNLIKELY(info.Length() <= 0)) { ScriptState* currentState = ScriptState::current(); if (!currentState) return; ScriptState& state = *currentState; RefPtr<ScriptArguments> scriptArguments(createScriptArguments(info, 1)); imp->callWithScriptStateScriptArgumentsVoidMethodOptionalBooleanArg(&state, scriptArguments.release()); if (state.hadException()) { v8::Local<v8::Value> exception = state.exception(); state.clearException(); throwError(exception, info.GetIsolate()); return; } return; } V8TRYCATCH_VOID(bool, optionalBooleanArg, info[0]->BooleanValue()); ScriptState* currentState = ScriptState::current(); if (!currentState) return; ScriptState& state = *currentState; RefPtr<ScriptArguments> scriptArguments(createScriptArguments(info, 1)); imp->callWithScriptStateScriptArgumentsVoidMethodOptionalBooleanArg(&state, scriptArguments.release(), optionalBooleanArg); if (state.hadException()) { v8::Local<v8::Value> exception = state.exception(); state.clearException(); throwError(exception, info.GetIsolate()); return; } } 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 free_bprm(struct linux_binprm *bprm) { free_arg_pages(bprm); if (bprm->cred) { mutex_unlock(&current->signal->cred_guard_mutex); abort_creds(bprm->cred); } kfree(bprm); } 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 SecurityHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { host_ = frame_host; if (enabled_ && host_) AttachToRenderFrameHost(); } CWE ID: CWE-20 Target: 1 Example 2: Code: void PaintLayerScrollableArea::ComputeScrollbarExistence( bool& needs_horizontal_scrollbar, bool& needs_vertical_scrollbar, ComputeScrollbarExistenceOption option) const { DCHECK(GetLayoutBox()->GetFrame()->GetSettings()); if (VisualViewportSuppliesScrollbars() || !CanHaveOverflowScrollbars(*GetLayoutBox()) || GetLayoutBox()->GetFrame()->GetSettings()->GetHideScrollbars()) { needs_horizontal_scrollbar = false; needs_vertical_scrollbar = false; return; } needs_horizontal_scrollbar = GetLayoutBox()->ScrollsOverflowX(); needs_vertical_scrollbar = GetLayoutBox()->ScrollsOverflowY(); if (GetLayoutBox()->HasAutoHorizontalScrollbar()) { if (option == kForbidAddingAutoBars) needs_horizontal_scrollbar &= HasHorizontalScrollbar(); needs_horizontal_scrollbar &= GetLayoutBox()->IsRooted() && HasHorizontalOverflow() && VisibleContentRect(kIncludeScrollbars).Height(); } if (GetLayoutBox()->HasAutoVerticalScrollbar()) { if (option == kForbidAddingAutoBars) needs_vertical_scrollbar &= HasVerticalScrollbar(); needs_vertical_scrollbar &= GetLayoutBox()->IsRooted() && HasVerticalOverflow() && VisibleContentRect(kIncludeScrollbars).Width(); } if (GetLayoutBox()->IsLayoutView()) { ScrollbarMode h_mode; ScrollbarMode v_mode; ToLayoutView(GetLayoutBox())->CalculateScrollbarModes(h_mode, v_mode); if (h_mode == kScrollbarAlwaysOn) needs_horizontal_scrollbar = true; else if (h_mode == kScrollbarAlwaysOff) needs_horizontal_scrollbar = false; if (v_mode == kScrollbarAlwaysOn) needs_vertical_scrollbar = true; else if (v_mode == kScrollbarAlwaysOff) needs_vertical_scrollbar = false; } } CWE ID: CWE-79 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static v8::Local<v8::Value> handleMaxRecursionDepthExceeded() { V8Proxy::throwError(V8Proxy::RangeError, "Maximum call stack size exceeded."); return v8::Local<v8::Value>(); } 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 __init trap_init(void) { int i; #ifdef CONFIG_EISA void __iomem *p = early_ioremap(0x0FFFD9, 4); if (readl(p) == 'E' + ('I'<<8) + ('S'<<16) + ('A'<<24)) EISA_bus = 1; early_iounmap(p, 4); #endif set_intr_gate(X86_TRAP_DE, divide_error); set_intr_gate_ist(X86_TRAP_NMI, &nmi, NMI_STACK); /* int4 can be called from all */ set_system_intr_gate(X86_TRAP_OF, &overflow); set_intr_gate(X86_TRAP_BR, bounds); set_intr_gate(X86_TRAP_UD, invalid_op); set_intr_gate(X86_TRAP_NM, device_not_available); #ifdef CONFIG_X86_32 set_task_gate(X86_TRAP_DF, GDT_ENTRY_DOUBLEFAULT_TSS); #else set_intr_gate_ist(X86_TRAP_DF, &double_fault, DOUBLEFAULT_STACK); #endif set_intr_gate(X86_TRAP_OLD_MF, coprocessor_segment_overrun); set_intr_gate(X86_TRAP_TS, invalid_TSS); set_intr_gate(X86_TRAP_NP, segment_not_present); set_intr_gate_ist(X86_TRAP_SS, &stack_segment, STACKFAULT_STACK); set_intr_gate(X86_TRAP_GP, general_protection); set_intr_gate(X86_TRAP_SPURIOUS, spurious_interrupt_bug); set_intr_gate(X86_TRAP_MF, coprocessor_error); set_intr_gate(X86_TRAP_AC, alignment_check); #ifdef CONFIG_X86_MCE set_intr_gate_ist(X86_TRAP_MC, &machine_check, MCE_STACK); #endif set_intr_gate(X86_TRAP_XF, simd_coprocessor_error); /* Reserve all the builtin and the syscall vector: */ for (i = 0; i < FIRST_EXTERNAL_VECTOR; i++) set_bit(i, used_vectors); #ifdef CONFIG_IA32_EMULATION set_system_intr_gate(IA32_SYSCALL_VECTOR, ia32_syscall); set_bit(IA32_SYSCALL_VECTOR, used_vectors); #endif #ifdef CONFIG_X86_32 set_system_trap_gate(SYSCALL_VECTOR, &system_call); set_bit(SYSCALL_VECTOR, used_vectors); #endif /* * Set the IDT descriptor to a fixed read-only location, so that the * "sidt" instruction will not leak the location of the kernel, and * to defend the IDT against arbitrary memory write vulnerabilities. * It will be reloaded in cpu_init() */ __set_fixmap(FIX_RO_IDT, __pa_symbol(idt_table), PAGE_KERNEL_RO); idt_descr.address = fix_to_virt(FIX_RO_IDT); /* * Should be a barrier for any external CPU state: */ cpu_init(); x86_init.irqs.trap_init(); #ifdef CONFIG_X86_64 memcpy(&debug_idt_table, &idt_table, IDT_ENTRIES * 16); set_nmi_gate(X86_TRAP_DB, &debug); set_nmi_gate(X86_TRAP_BP, &int3); #endif } CWE ID: CWE-264 Target: 1 Example 2: Code: void ExtensionWebContentsObserver::InitializeRenderFrame( content::RenderFrameHost* render_frame_host) { DCHECK(render_frame_host); DCHECK(render_frame_host->IsRenderFrameLive()); render_frame_host->Send(new ExtensionMsg_NotifyRenderViewType( render_frame_host->GetRoutingID(), GetViewType(web_contents()))); const Extension* frame_extension = GetExtensionFromFrame(render_frame_host); if (frame_extension) { ExtensionsBrowserClient::Get()->RegisterMojoServices(render_frame_host, frame_extension); ProcessManager::Get(browser_context_) ->RegisterRenderFrameHost(web_contents(), render_frame_host, frame_extension); } } 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 trace_die_handler(struct notifier_block *self, unsigned long val, void *data) { switch (val) { case DIE_OOPS: if (ftrace_dump_on_oops) ftrace_dump(ftrace_dump_on_oops); break; default: break; } return NOTIFY_OK; } 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: v8::Local<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) { v8::EscapableHandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> v8_context = context()->v8_context(); v8::Context::Scope context_scope(v8_context); v8::Local<v8::Value> source(GetSource(module_name)); if (source.IsEmpty() || source->IsUndefined()) { Fatal(context_, "No source for require(" + module_name + ")"); return v8::Undefined(GetIsolate()); } v8::Local<v8::String> wrapped_source( WrapSource(v8::Local<v8::String>::Cast(source))); v8::Local<v8::String> v8_module_name; if (!ToV8String(GetIsolate(), module_name.c_str(), &v8_module_name)) { NOTREACHED() << "module_name is too long"; return v8::Undefined(GetIsolate()); } v8::Local<v8::Value> func_as_value = RunString(wrapped_source, v8_module_name); if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) { Fatal(context_, "Bad source for require(" + module_name + ")"); return v8::Undefined(GetIsolate()); } v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(func_as_value); v8::Local<v8::Object> define_object = v8::Object::New(GetIsolate()); gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object); v8::Local<v8::Value> exports = v8::Object::New(GetIsolate()); v8::Local<v8::Object> natives(NewInstance()); CHECK(!natives.IsEmpty()); // this can fail if v8 has issues v8::Local<v8::Value> args[] = { GetPropertyUnsafe(v8_context, define_object, "define"), GetPropertyUnsafe(v8_context, natives, "require", v8::NewStringType::kInternalized), GetPropertyUnsafe(v8_context, natives, "requireNative", v8::NewStringType::kInternalized), GetPropertyUnsafe(v8_context, natives, "requireAsync", v8::NewStringType::kInternalized), exports, console::AsV8Object(GetIsolate()), GetPropertyUnsafe(v8_context, natives, "privates", v8::NewStringType::kInternalized), context_->safe_builtins()->GetArray(), context_->safe_builtins()->GetFunction(), context_->safe_builtins()->GetJSON(), context_->safe_builtins()->GetObjekt(), context_->safe_builtins()->GetRegExp(), context_->safe_builtins()->GetString(), context_->safe_builtins()->GetError(), }; { v8::TryCatch try_catch(GetIsolate()); try_catch.SetCaptureMessage(true); context_->CallFunction(func, arraysize(args), args); if (try_catch.HasCaught()) { HandleException(try_catch); return v8::Undefined(GetIsolate()); } } return handle_scope.Escape(exports); } CWE ID: CWE-264 Target: 1 Example 2: Code: BrowserViewRenderer::RootLayerStateAsValue( const gfx::Vector2dF& total_scroll_offset_dip, const gfx::SizeF& scrollable_size_dip) { scoped_refptr<base::trace_event::TracedValue> state = new base::trace_event::TracedValue(); state->SetDouble("total_scroll_offset_dip.x", total_scroll_offset_dip.x()); state->SetDouble("total_scroll_offset_dip.y", total_scroll_offset_dip.y()); state->SetDouble("max_scroll_offset_dip.x", max_scroll_offset_dip_.x()); state->SetDouble("max_scroll_offset_dip.y", max_scroll_offset_dip_.y()); state->SetDouble("scrollable_size_dip.width", scrollable_size_dip.width()); state->SetDouble("scrollable_size_dip.height", scrollable_size_dip.height()); state->SetDouble("page_scale_factor", page_scale_factor_); return state; } 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 disable_progress_bar() { pthread_mutex_lock(&screen_mutex); if(progress_enabled) { progress_bar(sym_count + dev_count + fifo_count + cur_blocks, total_inodes - total_files + total_blocks, columns); printf("\n"); } progress_enabled = FALSE; pthread_mutex_unlock(&screen_mutex); } 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: MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) { assert(memory_info != (MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); if (memory_info->blob != (void *) NULL) switch (memory_info->type) { case AlignedVirtualMemory: { memory_info->blob=RelinquishAlignedMemory(memory_info->blob); RelinquishMagickResource(MemoryResource,memory_info->length); break; } case MapVirtualMemory: { (void) UnmapBlob(memory_info->blob,memory_info->length); memory_info->blob=NULL; RelinquishMagickResource(MapResource,memory_info->length); if (*memory_info->filename != '\0') (void) RelinquishUniqueFileResource(memory_info->filename); break; } case UnalignedVirtualMemory: default: { memory_info->blob=RelinquishMagickMemory(memory_info->blob); break; } } memory_info->signature=(~MagickSignature); memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info); return(memory_info); } CWE ID: CWE-189 Target: 1 Example 2: Code: xfs_queue_cowblocks( struct xfs_mount *mp) { rcu_read_lock(); if (radix_tree_tagged(&mp->m_perag_tree, XFS_ICI_COWBLOCKS_TAG)) queue_delayed_work(mp->m_eofblocks_workqueue, &mp->m_cowblocks_work, msecs_to_jiffies(xfs_cowb_secs * 1000)); rcu_read_unlock(); } 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: ui::MenuModel* AuthenticatorSheetModelBase::GetOtherTransportsMenuModel() { return nullptr; } 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 MagickBooleanType Get8BIMProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, format[MagickPathExtent], name[MagickPathExtent], *resource; const StringInfo *profile; const unsigned char *info; long start, stop; MagickBooleanType status; register ssize_t i; size_t length; ssize_t count, id, sub_number; /* There are no newlines in path names, so it's safe as terminator. */ profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return(MagickFalse); count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop, name,format); if ((count != 2) && (count != 3) && (count != 4)) return(MagickFalse); if (count < 4) (void) CopyMagickString(format,"SVG",MagickPathExtent); if (count < 3) *name='\0'; sub_number=1; if (*name == '#') sub_number=(ssize_t) StringToLong(&name[1]); sub_number=MagickMax(sub_number,1L); resource=(char *) NULL; status=MagickFalse; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while ((length > 0) && (status == MagickFalse)) { if (ReadPropertyByte(&info,&length) != (unsigned char) '8') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadPropertyMSBShort(&info,&length); if (id < (ssize_t) start) continue; if (id > (ssize_t) stop) continue; if (resource != (char *) NULL) resource=DestroyString(resource); count=(ssize_t) ReadPropertyByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { resource=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) resource=(char *) AcquireQuantumMemory((size_t) count+ MagickPathExtent,sizeof(*resource)); if (resource != (char *) NULL) { for (i=0; i < (ssize_t) count; i++) resource[i]=(char) ReadPropertyByte(&info,&length); resource[count]='\0'; } } if ((count & 0x01) == 0) (void) ReadPropertyByte(&info,&length); count=(ssize_t) ReadPropertyMSBLong(&info,&length); if ((*name != '\0') && (*name != '#')) if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) { /* No name match, scroll forward and try next. */ info+=count; length-=MagickMin(count,(ssize_t) length); continue; } if ((*name == '#') && (sub_number != 1)) { /* No numbered match, scroll forward and try next. */ sub_number--; info+=count; length-=MagickMin(count,(ssize_t) length); continue; } /* We have the resource of interest. */ attribute=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, sizeof(*attribute)); if (attribute != (char *) NULL) { (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); attribute[count]='\0'; info+=count; length-=MagickMin(count,(ssize_t) length); if ((id <= 1999) || (id >= 2999)) (void) SetImageProperty((Image *) image,key,(const char *) attribute,exception); else { char *path; if (LocaleCompare(format,"svg") == 0) path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, image->columns,image->rows); else path=TracePSClippath((unsigned char *) attribute,(size_t) count); (void) SetImageProperty((Image *) image,key,(const char *) path, exception); path=DestroyString(path); } attribute=DestroyString(attribute); status=MagickTrue; } } if (resource != (char *) NULL) resource=DestroyString(resource); return(status); } CWE ID: CWE-125 Target: 1 Example 2: Code: void usb_enable_ltm(struct usb_device *udev) { struct usb_hcd *hcd = bus_to_hcd(udev->bus); /* Check if the roothub and device supports LTM. */ if (!usb_device_supports_ltm(hcd->self.root_hub) || !usb_device_supports_ltm(udev)) return; /* Set Feature LTM Enable can only be sent if the device is * configured. */ if (!udev->actconfig) return; usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, USB_RECIP_DEVICE, USB_DEVICE_LTM_ENABLE, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); } 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 gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond) { PurpleXfer *xfer = data; struct im_connection *ic = purple_ic_by_pa(xfer->account); struct prpl_xfer_data *px = xfer->ui_data; PurpleBuddy *buddy; const char *who; buddy = purple_find_buddy(xfer->account, xfer->who); who = buddy ? purple_buddy_get_name(buddy) : xfer->who; /* TODO(wilmer): After spreading some more const goodness in BitlBee, remove the evil cast below. */ px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size); px->ft->data = px; px->ft->accept = prpl_xfer_accept; px->ft->canceled = prpl_xfer_canceled; px->ft->free = prpl_xfer_free; px->ft->write_request = prpl_xfer_write_request; return FALSE; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: gplotGenCommandFile(GPLOT *gplot) { char buf[L_BUF_SIZE]; char *cmdstr, *plottitle, *dataname; l_int32 i, plotstyle, nplots; FILE *fp; PROCNAME("gplotGenCommandFile"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); /* Remove any previous command data */ sarrayClear(gplot->cmddata); /* Generate command data instructions */ if (gplot->title) { /* set title */ snprintf(buf, L_BUF_SIZE, "set title '%s'", gplot->title); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->xlabel) { /* set xlabel */ snprintf(buf, L_BUF_SIZE, "set xlabel '%s'", gplot->xlabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->ylabel) { /* set ylabel */ snprintf(buf, L_BUF_SIZE, "set ylabel '%s'", gplot->ylabel); sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Set terminal type and output */ if (gplot->outformat == GPLOT_PNG) { snprintf(buf, L_BUF_SIZE, "set terminal png; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_PS) { snprintf(buf, L_BUF_SIZE, "set terminal postscript; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_EPS) { snprintf(buf, L_BUF_SIZE, "set terminal postscript eps; set output '%s'", gplot->outname); } else if (gplot->outformat == GPLOT_LATEX) { snprintf(buf, L_BUF_SIZE, "set terminal latex; set output '%s'", gplot->outname); } sarrayAddString(gplot->cmddata, buf, L_COPY); if (gplot->scaling == GPLOT_LOG_SCALE_X || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUF_SIZE, "set logscale x"); sarrayAddString(gplot->cmddata, buf, L_COPY); } if (gplot->scaling == GPLOT_LOG_SCALE_Y || gplot->scaling == GPLOT_LOG_SCALE_X_Y) { snprintf(buf, L_BUF_SIZE, "set logscale y"); sarrayAddString(gplot->cmddata, buf, L_COPY); } nplots = sarrayGetCount(gplot->datanames); for (i = 0; i < nplots; i++) { plottitle = sarrayGetString(gplot->plottitles, i, L_NOCOPY); dataname = sarrayGetString(gplot->datanames, i, L_NOCOPY); numaGetIValue(gplot->plotstyles, i, &plotstyle); if (nplots == 1) { snprintf(buf, L_BUF_SIZE, "plot '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } else { if (i == 0) snprintf(buf, L_BUF_SIZE, "plot '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else if (i < nplots - 1) snprintf(buf, L_BUF_SIZE, " '%s' title '%s' %s, \\", dataname, plottitle, gplotstylenames[plotstyle]); else snprintf(buf, L_BUF_SIZE, " '%s' title '%s' %s", dataname, plottitle, gplotstylenames[plotstyle]); } sarrayAddString(gplot->cmddata, buf, L_COPY); } /* Write command data to file */ cmdstr = sarrayToString(gplot->cmddata, 1); if ((fp = fopenWriteStream(gplot->cmdname, "w")) == NULL) { LEPT_FREE(cmdstr); return ERROR_INT("cmd stream not opened", procName, 1); } fwrite(cmdstr, 1, strlen(cmdstr), fp); fclose(fp); LEPT_FREE(cmdstr); return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void index_entry_adjust_namemask( git_index_entry *entry, size_t path_length) { entry->flags &= ~GIT_IDXENTRY_NAMEMASK; if (path_length < GIT_IDXENTRY_NAMEMASK) entry->flags |= path_length & GIT_IDXENTRY_NAMEMASK; else entry->flags |= GIT_IDXENTRY_NAMEMASK; } 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: cmsIntentsList* SearchIntent(cmsUInt32Number Intent) { cmsIntentsList* pt; for (pt = Intents; pt != NULL; pt = pt -> Next) if (pt ->Intent == Intent) return pt; return NULL; } 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 SandboxIPCHandler::HandleLocaltime( int fd, base::PickleIterator iter, const std::vector<base::ScopedFD>& fds) { std::string time_string; if (!iter.ReadString(&time_string) || time_string.size() != sizeof(time_t)) return; time_t time; memcpy(&time, time_string.data(), sizeof(time)); const struct tm* expanded_time = localtime(&time); std::string result_string; const char* time_zone_string = ""; if (expanded_time) { result_string = std::string(reinterpret_cast<const char*>(expanded_time), sizeof(struct tm)); time_zone_string = expanded_time->tm_zone; } base::Pickle reply; reply.WriteString(result_string); reply.WriteString(time_zone_string); SendRendererReply(fds, reply, -1); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int hfsplus_rmdir(struct inode *dir, struct dentry *dentry) { struct hfsplus_sb_info *sbi = HFSPLUS_SB(dir->i_sb); struct inode *inode = dentry->d_inode; int res; if (inode->i_size != 2) return -ENOTEMPTY; mutex_lock(&sbi->vh_mutex); res = hfsplus_delete_cat(inode->i_ino, dir, &dentry->d_name); if (res) goto out; clear_nlink(inode); inode->i_ctime = CURRENT_TIME_SEC; hfsplus_delete_inode(inode); mark_inode_dirty(inode); out: mutex_unlock(&sbi->vh_mutex); return res; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool highligh_words_in_textview(int page, GtkTextView *tev, GList *words, GList *ignored_words, bool case_insensitive) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(tev); gtk_text_buffer_set_modified(buffer, FALSE); GtkWidget *notebook_child = gtk_notebook_get_nth_page(g_notebook, page); GtkWidget *tab_lbl = gtk_notebook_get_tab_label(g_notebook, notebook_child); /* Remove old results */ bool buffer_removing = false; GtkTreeIter iter; gboolean valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_ls_sensitive_list), &iter); /* Turn off the changed callback during the update */ g_signal_handler_block(g_tv_sensitive_sel, g_tv_sensitive_sel_hndlr); while (valid) { char *text = NULL; search_item_t *word = NULL; gtk_tree_model_get(GTK_TREE_MODEL(g_ls_sensitive_list), &iter, SEARCH_COLUMN_TEXT, &text, SEARCH_COLUMN_ITEM, &word, -1); free(text); if (word->buffer == buffer) { buffer_removing = true; valid = gtk_list_store_remove(g_ls_sensitive_list, &iter); if (word == g_current_highlighted_word) g_current_highlighted_word = NULL; free(word); } else { if(buffer_removing) break; valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(g_ls_sensitive_list), &iter); } } /* Turn on the changed callback after the update */ g_signal_handler_unblock(g_tv_sensitive_sel, g_tv_sensitive_sel_hndlr); GtkTextIter start_find; gtk_text_buffer_get_start_iter(buffer, &start_find); GtkTextIter end_find; gtk_text_buffer_get_end_iter(buffer, &end_find); gtk_text_buffer_remove_tag_by_name(buffer, "search_result_bg", &start_find, &end_find); gtk_text_buffer_remove_tag_by_name(buffer, "current_result_bg", &start_find, &end_find); PangoAttrList *attrs = gtk_label_get_attributes(GTK_LABEL(tab_lbl)); gtk_label_set_attributes(GTK_LABEL(tab_lbl), NULL); pango_attr_list_unref(attrs); GList *result = NULL; GList *ignored_words_in_buffer = NULL; ignored_words_in_buffer = find_words_in_text_buffer(page, tev, ignored_words, NULL, start_find, end_find, /*case sensitive*/false); result = find_words_in_text_buffer(page, tev, words, ignored_words_in_buffer, start_find, end_find, case_insensitive ); for (GList *w = result; w; w = g_list_next(w)) { search_item_t *item = (search_item_t *)w->data; gtk_text_buffer_apply_tag_by_name(buffer, "search_result_bg", sitem_get_start_iter(item), sitem_get_end_iter(item)); } if (result) { PangoAttrList *attrs = pango_attr_list_new(); PangoAttribute *foreground_attr = pango_attr_foreground_new(65535, 0, 0); pango_attr_list_insert(attrs, foreground_attr); PangoAttribute *underline_attr = pango_attr_underline_new(PANGO_UNDERLINE_SINGLE); pango_attr_list_insert(attrs, underline_attr); gtk_label_set_attributes(GTK_LABEL(tab_lbl), attrs); /* The current order of the found words is defined by order of words in the * passed list. We have to order the words according to their occurrence in * the buffer. */ result = g_list_sort(result, (GCompareFunc)sitem_compare); GList *search_result = result; for ( ; search_result != NULL; search_result = g_list_next(search_result)) { search_item_t *word = (search_item_t *)search_result->data; const gchar *file_name = gtk_label_get_text(GTK_LABEL(tab_lbl)); /* Create a new row */ GtkTreeIter new_row; if (valid) /* iter variable is valid GtkTreeIter and it means that the results */ /* need to be inserted before this iterator, in this case iter points */ /* to the first word of another GtkTextView */ gtk_list_store_insert_before(g_ls_sensitive_list, &new_row, &iter); else /* the GtkTextView is the last one or the only one, insert the results */ /* at the end of the list store */ gtk_list_store_append(g_ls_sensitive_list, &new_row); /* Assign values to the new row */ search_item_to_list_store_item(g_ls_sensitive_list, &new_row, file_name, word); } } g_list_free_full(ignored_words_in_buffer, free); g_list_free(result); return result != NULL; } 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: bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload, FetchRequest::OriginRestriction originRestriction) const { SecurityOrigin* securityOrigin = options.securityOrigin.get(); if (!securityOrigin && document()) securityOrigin = document()->securityOrigin(); if (securityOrigin && !securityOrigin->canDisplay(url)) { if (!forPreload) context().reportLocalLoadFailed(url); WTF_LOG(ResourceLoading, "ResourceFetcher::requestResource URL was not allowed by SecurityOrigin::canDisplay"); return 0; } bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script().shouldBypassMainWorldContentSecurityPolicy()) || (options.contentSecurityPolicyOption == DoNotCheckContentSecurityPolicy); switch (type) { case Resource::MainResource: case Resource::Image: case Resource::CSSStyleSheet: case Resource::Script: case Resource::Font: case Resource::Raw: case Resource::LinkPrefetch: case Resource::LinkSubresource: case Resource::TextTrack: case Resource::ImportResource: case Resource::Media: if (originRestriction == FetchRequest::RestrictToSameOrigin && !securityOrigin->canRequest(url)) { printAccessDeniedMessage(url); return false; } break; case Resource::XSLStyleSheet: ASSERT(RuntimeEnabledFeatures::xsltEnabled()); case Resource::SVGDocument: if (!securityOrigin->canRequest(url)) { printAccessDeniedMessage(url); return false; } break; } ContentSecurityPolicy::ReportingStatus cspReporting = forPreload ? ContentSecurityPolicy::SuppressReport : ContentSecurityPolicy::SendReport; switch (type) { case Resource::XSLStyleSheet: ASSERT(RuntimeEnabledFeatures::xsltEnabled()); if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url, cspReporting)) return false; break; case Resource::Script: case Resource::ImportResource: if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url, cspReporting)) return false; if (frame()) { Settings* settings = frame()->settings(); if (!frame()->loader().client()->allowScriptFromSource(!settings || settings->scriptEnabled(), url)) { frame()->loader().client()->didNotAllowScript(); return false; } } break; case Resource::CSSStyleSheet: if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowStyleFromSource(url, cspReporting)) return false; break; case Resource::SVGDocument: case Resource::Image: if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowImageFromSource(url, cspReporting)) return false; break; case Resource::Font: { if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowFontFromSource(url, cspReporting)) return false; break; } case Resource::MainResource: case Resource::Raw: case Resource::LinkPrefetch: case Resource::LinkSubresource: break; case Resource::Media: case Resource::TextTrack: if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowMediaFromSource(url, cspReporting)) return false; break; } if (!checkInsecureContent(type, url, options.mixedContentBlockingTreatment)) return false; return true; } CWE ID: CWE-264 Target: 1 Example 2: Code: static u32 FFD_RegisterMimeTypes(const GF_InputService *plug) { u32 i; for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) gf_service_register_mime(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2]); return i/3; } 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 irda_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct irda_sock *self; if (net != &init_net) return -EAFNOSUPPORT; /* Check for valid socket type */ switch (sock->type) { case SOCK_STREAM: /* For TTP connections with SAR disabled */ case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */ case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */ break; default: return -ESOCKTNOSUPPORT; } /* Allocate networking socket */ sk = sk_alloc(net, PF_IRDA, GFP_KERNEL, &irda_proto, kern); if (sk == NULL) return -ENOMEM; self = irda_sk(sk); pr_debug("%s() : self is %p\n", __func__, self); init_waitqueue_head(&self->query_wait); switch (sock->type) { case SOCK_STREAM: sock->ops = &irda_stream_ops; self->max_sdu_size_rx = TTP_SAR_DISABLE; break; case SOCK_SEQPACKET: sock->ops = &irda_seqpacket_ops; self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; case SOCK_DGRAM: switch (protocol) { #ifdef CONFIG_IRDA_ULTRA case IRDAPROTO_ULTRA: sock->ops = &irda_ultra_ops; /* Initialise now, because we may send on unbound * sockets. Jean II */ self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER; self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER; break; #endif /* CONFIG_IRDA_ULTRA */ case IRDAPROTO_UNITDATA: sock->ops = &irda_dgram_ops; /* We let Unitdata conn. be like seqpack conn. */ self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } /* Initialise networking socket struct */ sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */ sk->sk_family = PF_IRDA; sk->sk_protocol = protocol; /* Register as a client with IrLMP */ self->ckey = irlmp_register_client(0, NULL, NULL, NULL); self->mask.word = 0xffff; self->rx_flow = self->tx_flow = FLOW_START; self->nslots = DISCOVERY_DEFAULT_SLOTS; self->daddr = DEV_ADDR_ANY; /* Until we get connected */ self->saddr = 0x0; /* so IrLMP assign us any link */ return 0; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize) { /* If this function is being called, the buffer should not have been initialized yet. */ assert(!stream->bufbase_); if (bufmode != JAS_STREAM_UNBUF) { /* The full- or line-buffered mode is being employed. */ if (!buf) { /* The caller has not specified a buffer to employ, so allocate one. */ if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE + JAS_STREAM_MAXPUTBACK))) { stream->bufmode_ |= JAS_STREAM_FREEBUF; stream->bufsize_ = JAS_STREAM_BUFSIZE; } else { /* The buffer allocation has failed. Resort to unbuffered operation. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } } else { /* The caller has specified a buffer to employ. */ /* The buffer must be large enough to accommodate maximum putback. */ assert(bufsize > JAS_STREAM_MAXPUTBACK); stream->bufbase_ = JAS_CAST(uchar *, buf); stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK; } } else { /* The unbuffered mode is being employed. */ /* A buffer should not have been supplied by the caller. */ assert(!buf); /* Use a trivial one-character buffer. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK]; stream->ptr_ = stream->bufstart_; stream->cnt_ = 0; stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK; } CWE ID: CWE-190 Target: 1 Example 2: Code: MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page) { MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); flags=ParseAbsoluteGeometry(page,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; image->page.width=geometry.width; image->page.height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) image->page.x+=geometry.x; if ((flags & YValue) != 0) image->page.y+=geometry.y; } else { if ((flags & XValue) != 0) { image->page.x=geometry.x; if ((image->page.width == 0) && (geometry.x > 0)) image->page.width=image->columns+geometry.x; } if ((flags & YValue) != 0) { image->page.y=geometry.y; if ((image->page.height == 0) && (geometry.y > 0)) image->page.height=image->rows+geometry.y; } } return(MagickTrue); } 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: const char *string_of_NPNVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPNVxDisplay); _(NPNVxtAppContext); _(NPNVnetscapeWindow); _(NPNVjavascriptEnabledBool); _(NPNVasdEnabledBool); _(NPNVisOfflineBool); _(NPNVserviceManager); _(NPNVDOMElement); _(NPNVDOMWindow); _(NPNVToolkit); _(NPNVSupportsXEmbedBool); _(NPNVWindowNPObject); _(NPNVPluginElementNPObject); _(NPNVSupportsWindowless); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPNVserviceManager); _(11, NPNVDOMElement); _(12, NPNVDOMWindow); _(13, NPNVToolkit); #undef _ default: str = "<unknown variable>"; break; } break; } return str; } 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: jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x) { jas_matrix_t *y; int i; int j; y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x)); assert(y); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; } CWE ID: CWE-190 Target: 1 Example 2: Code: void RecordOffliningPreviewsUMA(const ClientId& client_id, content::PreviewsState previews_state) { bool is_previews_enabled = (previews_state != content::PreviewsTypes::PREVIEWS_OFF && previews_state != content::PreviewsTypes::PREVIEWS_NO_TRANSFORM); base::UmaHistogramBoolean( AddHistogramSuffix(client_id, "OfflinePages.Background.OffliningPreviewStatus"), is_previews_enabled); } 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: DocumentLoader::~DocumentLoader() { ASSERT(!m_frame || frameLoader()->activeDocumentLoader() != this || !isLoading()); if (m_iconLoadDecisionCallback) m_iconLoadDecisionCallback->invalidate(); if (m_iconDataCallback) m_iconDataCallback->invalidate(); m_cachedResourceLoader->clearDocumentLoader(); if (m_mainResource) { m_mainResource->removeClient(this); m_mainResource = 0; } } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SYSCALL_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; struct user_struct *user; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; user = get_current_user(); if (unlikely(atomic_read(&user->inotify_devs) >= inotify_max_user_instances)) { ret = -EMFILE; goto out_free_uid; } /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(user, inotify_max_queued_events); if (IS_ERR(group)) { ret = PTR_ERR(group); goto out_free_uid; } atomic_inc(&user->inotify_devs); ret = anon_inode_getfd("inotify", &inotify_fops, group, O_RDONLY | flags); if (ret >= 0) return ret; fsnotify_put_group(group); atomic_dec(&user->inotify_devs); out_free_uid: free_uid(user); return ret; } CWE ID: CWE-399 Target: 1 Example 2: Code: int tty_unregister_ldisc(int disc) { unsigned long flags; int ret = 0; if (disc < N_TTY || disc >= NR_LDISCS) return -EINVAL; raw_spin_lock_irqsave(&tty_ldiscs_lock, flags); if (tty_ldiscs[disc]->refcount) ret = -EBUSY; else tty_ldiscs[disc] = NULL; raw_spin_unlock_irqrestore(&tty_ldiscs_lock, flags); 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: irc_server_get_pv_count (struct t_irc_server *server) { int count; struct t_irc_channel *ptr_channel; count = 0; for (ptr_channel = server->channels; ptr_channel; ptr_channel = ptr_channel->next_channel) { if (ptr_channel->type == IRC_CHANNEL_TYPE_PRIVATE) count++; } return count; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void __fput_sync(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; file_sb_list_del(file); BUG_ON(!(task->flags & PF_KTHREAD)); __fput(file); } } CWE ID: CWE-17 Target: 1 Example 2: Code: static int is_f00f_bug(struct pt_regs *regs, unsigned long address) { #ifdef CONFIG_X86_F00F_BUG unsigned long nr; /* * Pentium F0 0F C7 C8 bug workaround: */ if (boot_cpu_data.f00f_bug) { nr = (address - idt_descr.address) >> 3; if (nr == 6) { do_invalid_op(regs, 0); return 1; } } #endif return 0; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: InputDispatcher::CommandEntry::CommandEntry(Command command) : command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), seq(0), handled(false) { } 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: gss_export_sec_context(minor_status, context_handle, interprocess_token) OM_uint32 * minor_status; gss_ctx_id_t * context_handle; gss_buffer_t interprocess_token; { OM_uint32 status; OM_uint32 length; gss_union_ctx_id_t ctx = NULL; gss_mechanism mech; gss_buffer_desc token = GSS_C_EMPTY_BUFFER; char *buf; status = val_exp_sec_ctx_args(minor_status, context_handle, interprocess_token); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) *context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return GSS_S_BAD_MECH; if (!mech->gss_export_sec_context) return (GSS_S_UNAVAILABLE); status = mech->gss_export_sec_context(minor_status, &ctx->internal_ctx_id, &token); if (status != GSS_S_COMPLETE) { map_error(minor_status, mech); goto cleanup; } length = token.length + 4 + ctx->mech_type->length; interprocess_token->length = length; interprocess_token->value = malloc(length); if (interprocess_token->value == 0) { *minor_status = ENOMEM; status = GSS_S_FAILURE; goto cleanup; } buf = interprocess_token->value; length = ctx->mech_type->length; buf[3] = (unsigned char) (length & 0xFF); length >>= 8; buf[2] = (unsigned char) (length & 0xFF); length >>= 8; buf[1] = (unsigned char) (length & 0xFF); length >>= 8; buf[0] = (unsigned char) (length & 0xFF); memcpy(buf+4, ctx->mech_type->elements, (size_t) ctx->mech_type->length); memcpy(buf+4+ctx->mech_type->length, token.value, token.length); status = GSS_S_COMPLETE; cleanup: (void) gss_release_buffer(minor_status, &token); if (ctx != NULL && ctx->internal_ctx_id == GSS_C_NO_CONTEXT) { /* If the mech deleted its context, delete the union context. */ free(ctx->mech_type->elements); free(ctx->mech_type); free(ctx); *context_handle = GSS_C_NO_CONTEXT; } return status; } CWE ID: CWE-415 Target: 1 Example 2: Code: int ssl3_renegotiate_check(SSL *s) { int ret = 0; if (s->s3->renegotiate) { if ((s->s3->rbuf.left == 0) && (s->s3->wbuf.left == 0) && !SSL_in_init(s)) { /* * if we are the server, and we have sent a 'RENEGOTIATE' * message, we need to go to SSL_ST_ACCEPT. */ /* SSL_ST_ACCEPT */ s->state = SSL_ST_RENEGOTIATE; s->s3->renegotiate = 0; s->s3->num_renegotiations++; s->s3->total_renegotiations++; ret = 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: SPL_METHOD(Array, getChildren) { zval *object = getThis(), **entry, *flags; spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); HashTable *aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_array_object_verify_pos(intern, aht TSRMLS_CC) == FAILURE) { return; } if (zend_hash_get_current_data_ex(aht, (void **) &entry, &intern->pos) == FAILURE) { return; } if (Z_TYPE_PP(entry) == IS_OBJECT) { if ((intern->ar_flags & SPL_ARRAY_CHILD_ARRAYS_ONLY) != 0) { return; } if (instanceof_function(Z_OBJCE_PP(entry), Z_OBJCE_P(getThis()) TSRMLS_CC)) { RETURN_ZVAL(*entry, 1, 0); } } MAKE_STD_ZVAL(flags); ZVAL_LONG(flags, SPL_ARRAY_USE_OTHER | intern->ar_flags); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, *entry, flags TSRMLS_CC); zval_ptr_dtor(&flags); } 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_write_finish_row(png_structp png_ptr) { #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif int ret; png_debug(1, "in png_write_finish_row"); /* Next row */ png_ptr->row_number++; /* See if we are done */ if (png_ptr->row_number < png_ptr->num_rows) return; #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced, go to next pass */ if (png_ptr->interlaced) { png_ptr->row_number = 0; if (png_ptr->transformations & PNG_INTERLACE) { png_ptr->pass++; } else { /* Loop until we find a non-zero width or height pass */ do { png_ptr->pass++; if (png_ptr->pass >= 7) break; png_ptr->usr_width = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; png_ptr->num_rows = (png_ptr->height + png_pass_yinc[png_ptr->pass] - 1 - png_pass_ystart[png_ptr->pass]) / png_pass_yinc[png_ptr->pass]; if (png_ptr->transformations & PNG_INTERLACE) break; } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0); } /* Reset the row above the image for the next pass */ if (png_ptr->pass < 7) { if (png_ptr->prev_row != NULL) png_memset(png_ptr->prev_row, 0, (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels* png_ptr->usr_bit_depth, png_ptr->width)) + 1); return; } } #endif /* If we get here, we've just written the last row, so we need to flush the compressor */ do { /* Tell the compressor we are done */ ret = deflate(&png_ptr->zstream, Z_FINISH); /* Check for an error */ if (ret == Z_OK) { /* Check to see if we need more room */ if (!(png_ptr->zstream.avail_out)) { png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; } } else if (ret != Z_STREAM_END) { if (png_ptr->zstream.msg != NULL) png_error(png_ptr, png_ptr->zstream.msg); else png_error(png_ptr, "zlib error"); } } while (ret != Z_STREAM_END); /* Write any extra space */ if (png_ptr->zstream.avail_out < png_ptr->zbuf_size) { png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size - png_ptr->zstream.avail_out); } deflateReset(&png_ptr->zstream); png_ptr->zstream.data_type = Z_BINARY; } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderFrameDevToolsAgentHost::SynchronousSwapCompositorFrame( viz::CompositorFrameMetadata frame_metadata) { for (auto* page : protocol::PageHandler::ForAgentHost(this)) page->OnSynchronousSwapCompositorFrame(frame_metadata.Clone()); if (!frame_trace_recorder_) return; bool did_initiate_recording = false; for (auto* tracing : protocol::TracingHandler::ForAgentHost(this)) did_initiate_recording |= tracing->did_initiate_recording(); if (did_initiate_recording) { frame_trace_recorder_->OnSynchronousSwapCompositorFrame(frame_host_, frame_metadata); } } 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: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_ext_data(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_start_code; IMPEG2D_ERROR_CODES_T e_error; e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; ps_stream = &ps_dec->s_bit_stream; u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); while ( (u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) && (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE == e_error) { if(u4_start_code == USER_DATA_START_CODE) { impeg2d_dec_user_data(ps_dec); } else { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN); switch(u4_start_code) { case QUANT_MATRIX_EXT_ID: impeg2d_dec_quant_matrix_ext(ps_dec); break; case COPYRIGHT_EXT_ID: impeg2d_dec_copyright_ext(ps_dec); break; case PIC_DISPLAY_EXT_ID: impeg2d_dec_pic_disp_ext(ps_dec); break; case CAMERA_PARAM_EXT_ID: impeg2d_dec_cam_param_ext(ps_dec); break; case ITU_T_EXT_ID: impeg2d_dec_itu_t_ext(ps_dec); break; case PIC_SPATIAL_SCALABLE_EXT_ID: case PIC_TEMPORAL_SCALABLE_EXT_ID: e_error = IMPEG2D_SCALABLITY_NOT_SUP; break; default: /* In case its a reserved extension code */ impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN); impeg2d_next_start_code(ps_dec); break; } } u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); } return e_error; } CWE ID: CWE-254 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 nsv_parse_NSVf_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; unsigned int av_unused file_size; unsigned int size; int64_t duration; int strings_size; int table_entries; int table_entries_used; nsv->state = NSV_UNSYNC; /* in case we fail */ size = avio_rl32(pb); if (size < 28) return -1; nsv->NSVf_end = size; file_size = (uint32_t)avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size); av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size); nsv->duration = duration = avio_rl32(pb); /* in ms */ av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration); strings_size = avio_rl32(pb); table_entries = avio_rl32(pb); table_entries_used = avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n", strings_size, table_entries, table_entries_used); if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb)); if (strings_size > 0) { char *strings; /* last byte will be '\0' to play safe with str*() */ char *p, *endp; char *token, *value; char quote; p = strings = av_mallocz((size_t)strings_size + 1); if (!p) return AVERROR(ENOMEM); endp = strings + strings_size; avio_read(pb, strings, strings_size); while (p < endp) { while (*p == ' ') p++; /* strip out spaces */ if (p >= endp-2) break; token = p; p = strchr(p, '='); if (!p || p >= endp-2) break; *p++ = '\0'; quote = *p++; value = p; p = strchr(p, quote); if (!p || p >= endp) break; *p++ = '\0'; av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value); av_dict_set(&s->metadata, token, value, 0); } av_free(strings); } if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb)); if (table_entries_used > 0) { int i; nsv->index_entries = table_entries_used; if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t)) return -1; nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_file_offset) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) nsv->nsvs_file_offset[i] = avio_rl32(pb) + size; if(table_entries > table_entries_used && avio_rl32(pb) == MKTAG('T','O','C','2')) { nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_timestamps) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) { nsv->nsvs_timestamps[i] = avio_rl32(pb); } } } av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb)); avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */ if (avio_feof(pb)) return -1; nsv->state = NSV_HAS_READ_NSVF; return 0; } CWE ID: CWE-834 Target: 1 Example 2: Code: static jboolean Region_isComplex(JNIEnv* env, jobject region) { bool result = GetSkRegion(env, region)->isComplex(); return boolTojboolean(result); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static ssize_t __disk_events_show(unsigned int events, char *buf) { const char *delim = ""; ssize_t pos = 0; int i; for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++) if (events & (1 << i)) { pos += sprintf(buf + pos, "%s%s", delim, disk_events_strs[i]); delim = " "; } if (pos) pos += sprintf(buf + pos, "\n"); return pos; } 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: struct key *key_alloc(struct key_type *type, const char *desc, kuid_t uid, kgid_t gid, const struct cred *cred, key_perm_t perm, unsigned long flags, struct key_restriction *restrict_link) { struct key_user *user = NULL; struct key *key; size_t desclen, quotalen; int ret; key = ERR_PTR(-EINVAL); if (!desc || !*desc) goto error; if (type->vet_description) { ret = type->vet_description(desc); if (ret < 0) { key = ERR_PTR(ret); goto error; } } desclen = strlen(desc); quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ user = key_user_lookup(uid); if (!user) goto no_memory_1; /* check that the user's quota permits allocation of another key and * its description */ if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxkeys : key_quota_maxkeys; unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxbytes : key_quota_maxbytes; spin_lock(&user->lock); if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) { if (user->qnkeys + 1 >= maxkeys || user->qnbytes + quotalen >= maxbytes || user->qnbytes + quotalen < user->qnbytes) goto no_quota; } user->qnkeys++; user->qnbytes += quotalen; spin_unlock(&user->lock); } /* allocate and initialise the key and its description */ key = kmem_cache_zalloc(key_jar, GFP_KERNEL); if (!key) goto no_memory_2; key->index_key.desc_len = desclen; key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL); if (!key->index_key.description) goto no_memory_3; refcount_set(&key->usage, 1); init_rwsem(&key->sem); lockdep_set_class(&key->sem, &type->lock_class); key->index_key.type = type; key->user = user; key->quotalen = quotalen; key->datalen = type->def_datalen; key->uid = uid; key->gid = gid; key->perm = perm; key->restrict_link = restrict_link; if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) key->flags |= 1 << KEY_FLAG_IN_QUOTA; if (flags & KEY_ALLOC_BUILT_IN) key->flags |= 1 << KEY_FLAG_BUILTIN; #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC; #endif /* let the security module know about the key */ ret = security_key_alloc(key, cred, flags); if (ret < 0) goto security_error; /* publish the key by giving it a serial number */ atomic_inc(&user->nkeys); key_alloc_serial(key); error: return key; security_error: kfree(key->description); kmem_cache_free(key_jar, key); if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); key = ERR_PTR(ret); goto error; no_memory_3: kmem_cache_free(key_jar, key); no_memory_2: if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); no_memory_1: key = ERR_PTR(-ENOMEM); goto error; no_quota: spin_unlock(&user->lock); key_user_put(user); key = ERR_PTR(-EDQUOT); goto error; } CWE ID: Target: 1 Example 2: Code: notify_resource_release(void) { if (path_is_malloced) { FREE(path); path_is_malloced = false; path = NULL; } } CWE ID: CWE-59 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: my_object_recursive2 (MyObject *obj, guint32 reqlen, GArray **ret, GError **error) { guint32 val; GArray *array; array = g_array_new (FALSE, TRUE, sizeof (guint32)); while (reqlen > 0) { val = 42; g_array_append_val (array, val); val = 26; g_array_append_val (array, val); reqlen--; } val = 2; g_array_append_val (array, val); *ret = array; return TRUE; } 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: xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemForEachPtr comp = (xsltStyleItemForEachPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif int i; xmlXPathObjectPtr res = NULL; xmlNodePtr cur, curInst; xmlNodeSetPtr list = NULL; xmlNodeSetPtr oldList; int oldXPProximityPosition, oldXPContextSize; xmlNodePtr oldContextNode; xsltTemplatePtr oldCurTemplRule; xmlDocPtr oldXPDoc; xsltDocumentPtr oldDocInfo; xmlXPathContextPtr xpctxt; if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL)) { xsltGenericError(xsltGenericErrorContext, "xsltForEach(): Bad arguments.\n"); return; } if (comp == NULL) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltForEach(): " "The XSLT 'for-each' instruction was not compiled.\n"); return; } if ((comp->select == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltForEach(): " "The selecting expression of the XSLT 'for-each' " "instruction was not compiled correctly.\n"); return; } xpctxt = ctxt->xpathCtxt; #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select %s\n", comp->select)); #endif /* * Save context states. */ oldDocInfo = ctxt->document; oldList = ctxt->nodeList; oldContextNode = ctxt->node; /* * The "current template rule" is cleared for the instantiation of * xsl:for-each. */ oldCurTemplRule = ctxt->currentTemplateRule; ctxt->currentTemplateRule = NULL; oldXPDoc = xpctxt->doc; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; /* * Set up XPath. */ xpctxt->node = contextNode; #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif /* * Evaluate the 'select' expression. */ res = xmlXPathCompiledEval(comp->comp, ctxt->xpathCtxt); if (res != NULL) { if (res->type == XPATH_NODESET) list = res->nodesetval; else { xsltTransformError(ctxt, NULL, inst, "The 'select' expression does not evaluate to a node set.\n"); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select didn't evaluate to a node list\n")); #endif goto error; } } else { xsltTransformError(ctxt, NULL, inst, "Failed to evaluate the 'select' expression.\n"); ctxt->state = XSLT_STATE_STOPPED; goto error; } if ((list == NULL) || (list->nodeNr <= 0)) goto exit; #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_FOR_EACH,xsltGenericDebug(xsltGenericDebugContext, "xsltForEach: select evaluates to %d nodes\n", list->nodeNr)); #endif /* * Restore XPath states for the "current node". */ xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->node = contextNode; /* * Set the list; this has to be done already here for xsltDoSortFunction(). */ ctxt->nodeList = list; /* * Handle xsl:sort instructions and skip them for further processing. * BUG TODO: We are not using namespaced potentially defined on the * xsl:sort element; XPath expression might fail. */ curInst = inst->children; if (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) { int nbsorts = 0; xmlNodePtr sorts[XSLT_MAX_SORT]; sorts[nbsorts++] = curInst; #ifdef WITH_DEBUGGER if (xslDebugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(curInst, contextNode, NULL, ctxt); #endif curInst = curInst->next; while (IS_XSLT_ELEM(curInst) && IS_XSLT_NAME(curInst, "sort")) { if (nbsorts >= XSLT_MAX_SORT) { xsltTransformError(ctxt, NULL, curInst, "The number of xsl:sort instructions exceeds the " "maximum (%d) allowed by this processor.\n", XSLT_MAX_SORT); goto error; } else { sorts[nbsorts++] = curInst; } #ifdef WITH_DEBUGGER if (xslDebugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(curInst, contextNode, NULL, ctxt); #endif curInst = curInst->next; } xsltDoSortFunction(ctxt, sorts, nbsorts); } xpctxt->contextSize = list->nodeNr; /* * Instantiate the sequence constructor for each selected node. */ for (i = 0; i < list->nodeNr; i++) { cur = list->nodeTab[i]; /* * The selected node becomes the "current node". */ ctxt->node = cur; /* * An xsl:for-each can change the current context doc. * OPTIMIZE TODO: Get rid of the need to set the context doc. */ if ((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL)) xpctxt->doc = cur->doc; xpctxt->proximityPosition = i + 1; xsltApplySequenceConstructor(ctxt, cur, curInst, NULL); } exit: error: if (res != NULL) xmlXPathFreeObject(res); /* * Restore old states. */ ctxt->document = oldDocInfo; ctxt->nodeList = oldList; ctxt->node = oldContextNode; ctxt->currentTemplateRule = oldCurTemplRule; xpctxt->doc = oldXPDoc; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; } CWE ID: CWE-119 Target: 1 Example 2: Code: exsltDateDateTimeFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *ret; if (nargs != 0) { xmlXPathSetArityError(ctxt); return; } ret = exsltDateDateTime(); if (ret == NULL) xmlXPathReturnEmptyString(ctxt); else xmlXPathReturnString(ctxt, ret); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void free_groupnames(char **groupnames) { int i; if (!groupnames) return; for (i = 0; groupnames[i]; i++) free(groupnames[i]); free(groupnames); } CWE ID: CWE-862 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 HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionCode& ec) { RefPtr<DocumentFragment> fragment = document()->createDocumentFragment(); Element* contextElement = contextElementForInsertion(where, this, ec); if (!contextElement) return; if (document()->isHTMLDocument()) fragment->parseHTML(markup, contextElement); else { if (!fragment->parseXML(markup, contextElement)) return; } insertAdjacent(where, fragment.get(), ec); } CWE ID: CWE-264 Target: 1 Example 2: Code: static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){ int rc; /* Error code */ char *zErr = 0; /* Error message */ Vdbe *v = (Vdbe *)p->pStmt; /* Set the value of register r[1] in the SQL statement to integer iRow. ** This is done directly as a performance optimization */ v->aMem[1].flags = MEM_Int; v->aMem[1].u.i = iRow; /* If the statement has been run before (and is paused at the OP_ResultRow) ** then back it up to the point where it does the OP_SeekRowid. This could ** have been down with an extra OP_Goto, but simply setting the program ** counter is faster. */ if( v->pc>3 ){ v->pc = 3; rc = sqlite3VdbeExec(v); }else{ rc = sqlite3_step(p->pStmt); } if( rc==SQLITE_ROW ){ VdbeCursor *pC = v->apCsr[0]; u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0; testcase( pC->nHdrParsed==p->iCol ); testcase( pC->nHdrParsed==p->iCol+1 ); if( type<12 ){ zErr = sqlite3MPrintf(p->db, "cannot open value of type %s", type==0?"null": type==7?"real": "integer" ); rc = SQLITE_ERROR; sqlite3_finalize(p->pStmt); p->pStmt = 0; }else{ p->iOffset = pC->aType[p->iCol + pC->nField]; p->nByte = sqlite3VdbeSerialTypeLen(type); p->pCsr = pC->uc.pCursor; sqlite3BtreeIncrblobCursor(p->pCsr); } } if( rc==SQLITE_ROW ){ rc = SQLITE_OK; }else if( p->pStmt ){ rc = sqlite3_finalize(p->pStmt); p->pStmt = 0; if( rc==SQLITE_OK ){ zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow); rc = SQLITE_ERROR; }else{ zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db)); } } assert( rc!=SQLITE_OK || zErr==0 ); assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE ); *pzErr = zErr; return rc; } 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 __init ipc_ns_init(void) { shm_init_ns(&init_ipc_ns); return 0; } 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: DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) { int i; int ret = 0; DefragInit(); /* * Build the packets. */ int id = 1; Packet *packets[17]; memset(packets, 0x00, sizeof(packets)); /* * Original fragments. */ /* A*24 at 0. */ packets[0] = BuildTestPacket(id, 0, 1, 'A', 24); /* B*15 at 32. */ packets[1] = BuildTestPacket(id, 32 >> 3, 1, 'B', 16); /* C*24 at 48. */ packets[2] = BuildTestPacket(id, 48 >> 3, 1, 'C', 24); /* D*8 at 80. */ packets[3] = BuildTestPacket(id, 80 >> 3, 1, 'D', 8); /* E*16 at 104. */ packets[4] = BuildTestPacket(id, 104 >> 3, 1, 'E', 16); /* F*24 at 120. */ packets[5] = BuildTestPacket(id, 120 >> 3, 1, 'F', 24); /* G*16 at 144. */ packets[6] = BuildTestPacket(id, 144 >> 3, 1, 'G', 16); /* H*16 at 160. */ packets[7] = BuildTestPacket(id, 160 >> 3, 1, 'H', 16); /* I*8 at 176. */ packets[8] = BuildTestPacket(id, 176 >> 3, 1, 'I', 8); /* * Overlapping subsequent fragments. */ /* J*32 at 8. */ packets[9] = BuildTestPacket(id, 8 >> 3, 1, 'J', 32); /* K*24 at 48. */ packets[10] = BuildTestPacket(id, 48 >> 3, 1, 'K', 24); /* L*24 at 72. */ packets[11] = BuildTestPacket(id, 72 >> 3, 1, 'L', 24); /* M*24 at 96. */ packets[12] = BuildTestPacket(id, 96 >> 3, 1, 'M', 24); /* N*8 at 128. */ packets[13] = BuildTestPacket(id, 128 >> 3, 1, 'N', 8); /* O*8 at 152. */ packets[14] = BuildTestPacket(id, 152 >> 3, 1, 'O', 8); /* P*8 at 160. */ packets[15] = BuildTestPacket(id, 160 >> 3, 1, 'P', 8); /* Q*16 at 176. */ packets[16] = BuildTestPacket(id, 176 >> 3, 0, 'Q', 16); default_policy = policy; /* Send all but the last. */ for (i = 0; i < 9; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) { goto end; } } int overlap = 0; for (; i < 16; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV4_FRAG_OVERLAP)) { overlap++; } } if (!overlap) { goto end; } /* And now the last one. */ Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL); if (reassembled == NULL) { goto end; } if (IPV4_GET_HLEN(reassembled) != 20) { goto end; } if (IPV4_GET_IPLEN(reassembled) != 20 + 192) { goto end; } if (memcmp(GET_PKT_DATA(reassembled) + 20, expected, expected_len) != 0) { goto end; } SCFree(reassembled); /* Make sure all frags were returned back to the pool. */ if (defrag_context->frag_pool->outstanding != 0) { goto end; } ret = 1; end: for (i = 0; i < 17; i++) { SCFree(packets[i]); } DefragDestroy(); return ret; } CWE ID: CWE-358 Target: 1 Example 2: Code: static struct ath_buf *ath_tx_get_buffer(struct ath_softc *sc) { struct ath_buf *bf = NULL; spin_lock_bh(&sc->tx.txbuflock); if (unlikely(list_empty(&sc->tx.txbuf))) { spin_unlock_bh(&sc->tx.txbuflock); return NULL; } bf = list_first_entry(&sc->tx.txbuf, struct ath_buf, list); list_del(&bf->list); spin_unlock_bh(&sc->tx.txbuflock); return bf; } 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: Track::GetContentEncodingByIndex(unsigned long idx) const { const ptrdiff_t count = content_encoding_entries_end_ - content_encoding_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return content_encoding_entries_[idx]; } 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: ClassicScript* ClassicPendingScript::GetSource(const KURL& document_url, bool& error_occurred) const { CheckState(); DCHECK(IsReady()); error_occurred = ErrorOccurred(); if (!is_external_) { ScriptSourceCode source_code( GetElement()->TextFromChildren(), source_location_type_, nullptr /* cache_handler */, document_url, StartingPosition()); return ClassicScript::Create(source_code, base_url_for_inline_script_, options_, kSharableCrossOrigin); } DCHECK(GetResource()->IsLoaded()); ScriptResource* resource = ToScriptResource(GetResource()); bool streamer_ready = (ready_state_ == kReady) && streamer_ && !streamer_->StreamingSuppressed(); ScriptSourceCode source_code(streamer_ready ? streamer_ : nullptr, resource); const KURL& base_url = source_code.Url(); return ClassicScript::Create(source_code, base_url, options_, resource->CalculateAccessControlStatus()); } CWE ID: CWE-200 Target: 1 Example 2: Code: static HB_Error Load_ChainContextPos3( HB_ChainContextPosFormat3* ccpf3, HB_Stream stream ) { HB_Error error; HB_UShort n, nb, ni, nl, m, count; HB_UShort backtrack_count, input_count, lookahead_count; HB_UInt cur_offset, new_offset, base_offset; HB_Coverage* b; HB_Coverage* i; HB_Coverage* l; HB_PosLookupRecord* plr; base_offset = FILE_Pos() - 2L; if ( ACCESS_Frame( 2L ) ) return error; ccpf3->BacktrackGlyphCount = GET_UShort(); FORGET_Frame(); ccpf3->BacktrackCoverage = NULL; backtrack_count = ccpf3->BacktrackGlyphCount; if ( ALLOC_ARRAY( ccpf3->BacktrackCoverage, backtrack_count, HB_Coverage ) ) return error; b = ccpf3->BacktrackCoverage; for ( nb = 0; nb < backtrack_count; nb++ ) { if ( ACCESS_Frame( 2L ) ) goto Fail4; new_offset = GET_UShort() + base_offset; FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = _HB_OPEN_Load_Coverage( &b[nb], stream ) ) != HB_Err_Ok ) goto Fail4; (void)FILE_Seek( cur_offset ); } if ( ACCESS_Frame( 2L ) ) goto Fail4; ccpf3->InputGlyphCount = GET_UShort(); FORGET_Frame(); ccpf3->InputCoverage = NULL; input_count = ccpf3->InputGlyphCount; if ( ALLOC_ARRAY( ccpf3->InputCoverage, input_count, HB_Coverage ) ) goto Fail4; i = ccpf3->InputCoverage; for ( ni = 0; ni < input_count; ni++ ) { if ( ACCESS_Frame( 2L ) ) goto Fail3; new_offset = GET_UShort() + base_offset; FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = _HB_OPEN_Load_Coverage( &i[ni], stream ) ) != HB_Err_Ok ) goto Fail3; (void)FILE_Seek( cur_offset ); } if ( ACCESS_Frame( 2L ) ) goto Fail3; ccpf3->LookaheadGlyphCount = GET_UShort(); FORGET_Frame(); ccpf3->LookaheadCoverage = NULL; lookahead_count = ccpf3->LookaheadGlyphCount; if ( ALLOC_ARRAY( ccpf3->LookaheadCoverage, lookahead_count, HB_Coverage ) ) goto Fail3; l = ccpf3->LookaheadCoverage; for ( nl = 0; nl < lookahead_count; nl++ ) { if ( ACCESS_Frame( 2L ) ) goto Fail2; new_offset = GET_UShort() + base_offset; FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = _HB_OPEN_Load_Coverage( &l[nl], stream ) ) != HB_Err_Ok ) goto Fail2; (void)FILE_Seek( cur_offset ); } if ( ACCESS_Frame( 2L ) ) goto Fail2; ccpf3->PosCount = GET_UShort(); FORGET_Frame(); ccpf3->PosLookupRecord = NULL; count = ccpf3->PosCount; if ( ALLOC_ARRAY( ccpf3->PosLookupRecord, count, HB_PosLookupRecord ) ) goto Fail2; plr = ccpf3->PosLookupRecord; if ( ACCESS_Frame( count * 4L ) ) goto Fail1; for ( n = 0; n < count; n++ ) { plr[n].SequenceIndex = GET_UShort(); plr[n].LookupListIndex = GET_UShort(); } FORGET_Frame(); return HB_Err_Ok; Fail1: FREE( plr ); Fail2: for ( m = 0; m < nl; m++ ) _HB_OPEN_Free_Coverage( &l[m] ); FREE( l ); Fail3: for ( m = 0; m < ni; m++ ) _HB_OPEN_Free_Coverage( &i[m] ); FREE( i ); Fail4: for ( m = 0; m < nb; m++ ) _HB_OPEN_Free_Coverage( &b[m] ); FREE( b ); return error; } 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: BOOLEAN btif_hl_find_mdl_idx_using_handle(tBTA_HL_MDL_HANDLE mdl_handle, UINT8 *p_app_idx,UINT8 *p_mcl_idx, UINT8 *p_mdl_idx){ btif_hl_app_cb_t *p_acb; btif_hl_mcl_cb_t *p_mcb; btif_hl_mdl_cb_t *p_dcb; BOOLEAN found=FALSE; UINT8 i,j,k; *p_app_idx = 0; *p_mcl_idx =0; *p_mdl_idx = 0; for (i=0; i < BTA_HL_NUM_APPS ; i ++) { p_acb =BTIF_HL_GET_APP_CB_PTR(i); for (j=0; j< BTA_HL_NUM_MCLS; j++) { p_mcb =BTIF_HL_GET_MCL_CB_PTR(i,j); for (k=0; k< BTA_HL_NUM_MDLS_PER_MCL; k++) { p_dcb =BTIF_HL_GET_MDL_CB_PTR(i,j,k); if (p_acb->in_use && p_mcb->in_use && p_dcb->in_use && (p_dcb->mdl_handle == mdl_handle)) { found = TRUE; *p_app_idx = i; *p_mcl_idx =j; *p_mdl_idx = k; break; } } } } BTIF_TRACE_EVENT("%s found=%d app_idx=%d mcl_idx=%d mdl_idx=%d ", __FUNCTION__,found,i,j,k ); return found; } CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ServiceManagerContext::ServiceManagerContext() { service_manager::mojom::ServiceRequest packaged_services_request; if (service_manager::ServiceManagerIsRemote()) { auto invitation = mojo::edk::IncomingBrokerClientInvitation::AcceptFromCommandLine( mojo::edk::TransportProtocol::kLegacy); packaged_services_request = service_manager::GetServiceRequestFromCommandLine(invitation.get()); } else { std::unique_ptr<BuiltinManifestProvider> manifest_provider = base::MakeUnique<BuiltinManifestProvider>(); static const struct ManifestInfo { const char* name; int resource_id; } kManifests[] = { {mojom::kBrowserServiceName, IDR_MOJO_CONTENT_BROWSER_MANIFEST}, {mojom::kGpuServiceName, IDR_MOJO_CONTENT_GPU_MANIFEST}, {mojom::kPackagedServicesServiceName, IDR_MOJO_CONTENT_PACKAGED_SERVICES_MANIFEST}, {mojom::kPluginServiceName, IDR_MOJO_CONTENT_PLUGIN_MANIFEST}, {mojom::kRendererServiceName, IDR_MOJO_CONTENT_RENDERER_MANIFEST}, {mojom::kUtilityServiceName, IDR_MOJO_CONTENT_UTILITY_MANIFEST}, {catalog::mojom::kServiceName, IDR_MOJO_CATALOG_MANIFEST}, }; for (size_t i = 0; i < arraysize(kManifests); ++i) { manifest_provider->AddServiceManifest(kManifests[i].name, kManifests[i].resource_id); } for (const auto& manifest : GetContentClient()->browser()->GetExtraServiceManifests()) { manifest_provider->AddServiceManifest(manifest.name, manifest.resource_id); } in_process_context_ = new InProcessServiceManagerContext; service_manager::mojom::ServicePtr packaged_services_service; packaged_services_request = mojo::MakeRequest(&packaged_services_service); in_process_context_->Start(packaged_services_service.PassInterface(), std::move(manifest_provider)); } packaged_services_connection_ = ServiceManagerConnection::Create( std::move(packaged_services_request), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); service_manager::mojom::ServicePtr root_browser_service; ServiceManagerConnection::SetForProcess(ServiceManagerConnection::Create( mojo::MakeRequest(&root_browser_service), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO))); auto* browser_connection = ServiceManagerConnection::GetForProcess(); service_manager::mojom::PIDReceiverPtr pid_receiver; packaged_services_connection_->GetConnector()->StartService( service_manager::Identity(mojom::kBrowserServiceName, service_manager::mojom::kRootUserID), std::move(root_browser_service), mojo::MakeRequest(&pid_receiver)); pid_receiver->SetPID(base::GetCurrentProcId()); service_manager::EmbeddedServiceInfo device_info; #if defined(OS_ANDROID) JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaGlobalRef<jobject> java_nfc_delegate; java_nfc_delegate.Reset(Java_ContentNfcDelegate_create(env)); DCHECK(!java_nfc_delegate.is_null()); device_info.factory = base::Bind(&device::CreateDeviceService, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), base::Bind(&WakeLockContextHost::GetNativeViewForContext), std::move(java_nfc_delegate)); #else device_info.factory = base::Bind(&device::CreateDeviceService, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)); #endif device_info.task_runner = base::ThreadTaskRunnerHandle::Get(); packaged_services_connection_->AddEmbeddedService(device::mojom::kServiceName, device_info); if (base::FeatureList::IsEnabled(features::kGlobalResourceCoordinator)) { service_manager::EmbeddedServiceInfo resource_coordinator_info; resource_coordinator_info.factory = base::Bind(&resource_coordinator::ResourceCoordinatorService::Create); packaged_services_connection_->AddEmbeddedService( resource_coordinator::mojom::kServiceName, resource_coordinator_info); } ContentBrowserClient::StaticServiceMap services; GetContentClient()->browser()->RegisterInProcessServices(&services); for (const auto& entry : services) { packaged_services_connection_->AddEmbeddedService(entry.first, entry.second); } g_io_thread_connector.Get() = browser_connection->GetConnector()->Clone(); ContentBrowserClient::OutOfProcessServiceMap out_of_process_services; GetContentClient()->browser()->RegisterOutOfProcessServices( &out_of_process_services); out_of_process_services[data_decoder::mojom::kServiceName] = { base::ASCIIToUTF16("Data Decoder Service"), SANDBOX_TYPE_UTILITY}; bool network_service_enabled = base::FeatureList::IsEnabled(features::kNetworkService); if (network_service_enabled) { out_of_process_services[content::mojom::kNetworkServiceName] = { base::ASCIIToUTF16("Network Service"), SANDBOX_TYPE_NETWORK}; } if (base::FeatureList::IsEnabled(video_capture::kMojoVideoCapture)) { out_of_process_services[video_capture::mojom::kServiceName] = { base::ASCIIToUTF16("Video Capture Service"), SANDBOX_TYPE_NO_SANDBOX}; } #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_UTILITY_PROCESS) out_of_process_services[media::mojom::kMediaServiceName] = { base::ASCIIToUTF16("Media Service"), SANDBOX_TYPE_NO_SANDBOX}; #endif for (const auto& service : out_of_process_services) { packaged_services_connection_->AddServiceRequestHandler( service.first, base::Bind(&StartServiceInUtilityProcess, service.first, service.second.first, service.second.second)); } #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_GPU_PROCESS) packaged_services_connection_->AddServiceRequestHandler( media::mojom::kMediaServiceName, base::Bind(&StartServiceInGpuProcess, media::mojom::kMediaServiceName)); #endif packaged_services_connection_->AddServiceRequestHandler( shape_detection::mojom::kServiceName, base::Bind(&StartServiceInGpuProcess, shape_detection::mojom::kServiceName)); packaged_services_connection_->Start(); RegisterCommonBrowserInterfaces(browser_connection); browser_connection->Start(); if (network_service_enabled) { browser_connection->GetConnector()->StartService( mojom::kNetworkServiceName); } } CWE ID: CWE-119 Target: 1 Example 2: Code: void setJSTestObjStringAttrWithSetterException(ExecState* exec, JSObject* thisObject, JSValue value) { JSTestObj* castedThis = jsCast<JSTestObj*>(thisObject); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); ExceptionCode ec = 0; impl->setStringAttrWithSetterException(ustringToString(value.isEmpty() ? UString() : value.toString(exec)->value(exec)), ec); setDOMException(exec, ec); } 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: validate_group(struct perf_event *event) { struct perf_event *sibling, *leader = event->group_leader; struct pmu_hw_events fake_pmu; DECLARE_BITMAP(fake_used_mask, ARMPMU_MAX_HWEVENTS); /* * Initialise the fake PMU. We only need to populate the * used_mask for the purposes of validation. */ memset(fake_used_mask, 0, sizeof(fake_used_mask)); fake_pmu.used_mask = fake_used_mask; if (!validate_event(&fake_pmu, leader)) return -EINVAL; list_for_each_entry(sibling, &leader->sibling_list, group_entry) { if (!validate_event(&fake_pmu, sibling)) return -EINVAL; } if (!validate_event(&fake_pmu, event)) return -EINVAL; return 0; } 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: dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int sh_num) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; const char *interp = ""; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment 0x%lx", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; interp = (const char *)nbuf; } else interp = "*empty*"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; } CWE ID: CWE-399 Target: 1 Example 2: Code: xfs_da3_root_split( struct xfs_da_state *state, struct xfs_da_state_blk *blk1, struct xfs_da_state_blk *blk2) { struct xfs_da_intnode *node; struct xfs_da_intnode *oldroot; struct xfs_da_node_entry *btree; struct xfs_da3_icnode_hdr nodehdr; struct xfs_da_args *args; struct xfs_buf *bp; struct xfs_inode *dp; struct xfs_trans *tp; struct xfs_mount *mp; struct xfs_dir2_leaf *leaf; xfs_dablk_t blkno; int level; int error; int size; trace_xfs_da_root_split(state->args); /* * Copy the existing (incorrect) block from the root node position * to a free space somewhere. */ args = state->args; error = xfs_da_grow_inode(args, &blkno); if (error) return error; dp = args->dp; tp = args->trans; mp = state->mp; error = xfs_da_get_buf(tp, dp, blkno, -1, &bp, args->whichfork); if (error) return error; node = bp->b_addr; oldroot = blk1->bp->b_addr; if (oldroot->hdr.info.magic == cpu_to_be16(XFS_DA_NODE_MAGIC) || oldroot->hdr.info.magic == cpu_to_be16(XFS_DA3_NODE_MAGIC)) { struct xfs_da3_icnode_hdr nodehdr; dp->d_ops->node_hdr_from_disk(&nodehdr, oldroot); btree = dp->d_ops->node_tree_p(oldroot); size = (int)((char *)&btree[nodehdr.count] - (char *)oldroot); level = nodehdr.level; /* * we are about to copy oldroot to bp, so set up the type * of bp while we know exactly what it will be. */ xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DA_NODE_BUF); } else { struct xfs_dir3_icleaf_hdr leafhdr; struct xfs_dir2_leaf_entry *ents; leaf = (xfs_dir2_leaf_t *)oldroot; dp->d_ops->leaf_hdr_from_disk(&leafhdr, leaf); ents = dp->d_ops->leaf_ents_p(leaf); ASSERT(leafhdr.magic == XFS_DIR2_LEAFN_MAGIC || leafhdr.magic == XFS_DIR3_LEAFN_MAGIC); size = (int)((char *)&ents[leafhdr.count] - (char *)leaf); level = 0; /* * we are about to copy oldroot to bp, so set up the type * of bp while we know exactly what it will be. */ xfs_trans_buf_set_type(tp, bp, XFS_BLFT_DIR_LEAFN_BUF); } /* * we can copy most of the information in the node from one block to * another, but for CRC enabled headers we have to make sure that the * block specific identifiers are kept intact. We update the buffer * directly for this. */ memcpy(node, oldroot, size); if (oldroot->hdr.info.magic == cpu_to_be16(XFS_DA3_NODE_MAGIC) || oldroot->hdr.info.magic == cpu_to_be16(XFS_DIR3_LEAFN_MAGIC)) { struct xfs_da3_intnode *node3 = (struct xfs_da3_intnode *)node; node3->hdr.info.blkno = cpu_to_be64(bp->b_bn); } xfs_trans_log_buf(tp, bp, 0, size - 1); bp->b_ops = blk1->bp->b_ops; xfs_trans_buf_copy_type(bp, blk1->bp); blk1->bp = bp; blk1->blkno = blkno; /* * Set up the new root node. */ error = xfs_da3_node_create(args, (args->whichfork == XFS_DATA_FORK) ? mp->m_dirleafblk : 0, level + 1, &bp, args->whichfork); if (error) return error; node = bp->b_addr; dp->d_ops->node_hdr_from_disk(&nodehdr, node); btree = dp->d_ops->node_tree_p(node); btree[0].hashval = cpu_to_be32(blk1->hashval); btree[0].before = cpu_to_be32(blk1->blkno); btree[1].hashval = cpu_to_be32(blk2->hashval); btree[1].before = cpu_to_be32(blk2->blkno); nodehdr.count = 2; dp->d_ops->node_hdr_to_disk(node, &nodehdr); #ifdef DEBUG if (oldroot->hdr.info.magic == cpu_to_be16(XFS_DIR2_LEAFN_MAGIC) || oldroot->hdr.info.magic == cpu_to_be16(XFS_DIR3_LEAFN_MAGIC)) { ASSERT(blk1->blkno >= mp->m_dirleafblk && blk1->blkno < mp->m_dirfreeblk); ASSERT(blk2->blkno >= mp->m_dirleafblk && blk2->blkno < mp->m_dirfreeblk); } #endif /* Header is already logged by xfs_da_node_create */ xfs_trans_log_buf(tp, bp, XFS_DA_LOGRANGE(node, btree, sizeof(xfs_da_node_entry_t) * 2)); return 0; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameImpl::CancelBlockedRequests() { frame_request_blocker_->Cancel(); } 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: MediaStreamManagerTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) { audio_manager_ = std::make_unique<MockAudioManager>(); audio_system_ = std::make_unique<media::AudioSystemImpl>(audio_manager_.get()); auto video_capture_provider = std::make_unique<MockVideoCaptureProvider>(); video_capture_provider_ = video_capture_provider.get(); media_stream_manager_ = std::make_unique<MediaStreamManager>( audio_system_.get(), audio_manager_->GetTaskRunner(), std::move(video_capture_provider)); base::RunLoop().RunUntilIdle(); ON_CALL(*video_capture_provider_, DoGetDeviceInfosAsync(_)) .WillByDefault(Invoke( [](VideoCaptureProvider::GetDeviceInfosCallback& result_callback) { std::vector<media::VideoCaptureDeviceInfo> stub_results; base::ResetAndReturn(&result_callback).Run(stub_results); })); } CWE ID: CWE-20 Target: 1 Example 2: Code: pixman_image_create_bits (pixman_format_code_t format, int width, int height, uint32_t * bits, int rowstride_bytes) { return create_bits_image_internal ( format, width, height, bits, rowstride_bytes, 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: bool BluetoothDeviceChromeOS::RunPairingCallbacks(Status status) { if (!agent_.get()) return false; bool callback_run = false; if (!pincode_callback_.is_null()) { pincode_callback_.Run(status, ""); pincode_callback_.Reset(); callback_run = true; } if (!passkey_callback_.is_null()) { passkey_callback_.Run(status, 0); passkey_callback_.Reset(); callback_run = true; } if (!confirmation_callback_.is_null()) { confirmation_callback_.Run(status); confirmation_callback_.Reset(); callback_run = true; } return callback_run; } 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 Document::open() { ASSERT(!importLoader()); if (m_frame) { if (ScriptableDocumentParser* parser = scriptableDocumentParser()) { if (parser->isParsing()) { if (parser->isExecutingScript()) return; if (!parser->wasCreatedByScript() && parser->hasInsertionPoint()) return; } } if (m_frame->loader().provisionalDocumentLoader()) m_frame->loader().stopAllLoaders(); } removeAllEventListenersRecursively(); implicitOpen(ForceSynchronousParsing); if (ScriptableDocumentParser* parser = scriptableDocumentParser()) parser->setWasCreatedByScript(true); if (m_frame) m_frame->loader().didExplicitOpen(); if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress) m_loadEventProgress = LoadEventNotRun; } CWE ID: CWE-20 Target: 1 Example 2: Code: static const char *no_set_limit(cmd_parms *cmd, void *conf_, const char *arg, const char *arg2) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server, APLOGNO(00118) "%s not supported on this platform", cmd->cmd->name); return NULL; } 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 JSValueRef addTouchPointCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { if (argumentCount < 2) return JSValueMakeUndefined(context); int x = static_cast<int>(JSValueToNumber(context, arguments[0], exception)); ASSERT(!exception || !*exception); int y = static_cast<int>(JSValueToNumber(context, arguments[1], exception)); ASSERT(!exception || !*exception); BlackBerry::Platform::TouchPoint touch; touch.m_id = touches.isEmpty() ? 0 : touches.last().m_id + 1; IntPoint pos(x, y); touch.m_pos = pos; touch.m_screenPos = pos; touch.m_state = BlackBerry::Platform::TouchPoint::TouchPressed; touches.append(touch); return JSValueMakeUndefined(context); } 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: long Cluster::ParseSimpleBlock( long long block_size, long long& pos, long& len) { const long long block_start = pos; const long long block_stop = pos + block_size; IMkvReader* const pReader = m_pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((pos + len) > block_stop) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long track = ReadUInt(pReader, pos, len); if (track < 0) //error return static_cast<long>(track); if (track == 0) return E_FILE_FORMAT_INVALID; #if 0 const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast<long>(track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return E_FILE_FORMAT_INVALID; #endif pos += len; //consume track number if ((pos + 2) > block_stop) return E_FILE_FORMAT_INVALID; if ((pos + 2) > avail) { len = 2; return E_BUFFER_NOT_FULL; } pos += 2; //consume timecode if ((pos + 1) > block_stop) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } unsigned char flags; status = pReader->Read(pos, 1, &flags); if (status < 0) //error or underflow { len = 1; return status; } ++pos; //consume flags byte assert(pos <= avail); if (pos >= block_stop) return E_FILE_FORMAT_INVALID; const int lacing = int(flags & 0x06) >> 1; if ((lacing != 0) && (block_stop > avail)) { len = static_cast<long>(block_stop - pos); return E_BUFFER_NOT_FULL; } status = CreateBlock(0x23, //simple block id block_start, block_size, 0); //DiscardPadding if (status != 0) return status; m_pos = block_stop; return 0; //success } CWE ID: CWE-119 Target: 1 Example 2: Code: bool OmniboxViewWin::OnInlineAutocompleteTextMaybeChanged( const string16& display_text, size_t user_text_length) { if (display_text == GetText()) return false; ScopedFreeze freeze(this, GetTextObjectModel()); SetWindowText(display_text.c_str()); SetSelection(static_cast<LONG>(display_text.length()), static_cast<LONG>(user_text_length)); TextChanged(); return true; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: tt_cmap12_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p; FT_ULong length; FT_ULong num_groups; if ( table + 16 > valid->limit ) FT_INVALID_TOO_SHORT; p = table + 4; length = TT_NEXT_ULONG( p ); p = table + 12; p = table + 12; num_groups = TT_NEXT_ULONG( p ); if ( table + length > valid->limit || length < 16 + 12 * num_groups ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ for ( n = 0; n < num_groups; n++ ) { start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; } last = end; } } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DevToolsUIBindings::CallClientFunction(const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { if (!web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme)) return; std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); web_contents_->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript)); } CWE ID: CWE-200 Target: 1 Example 2: Code: void PPB_URLLoader_Impl::UpdateStatus() { if (status_callback_ && (RecordDownloadProgress() || RecordUploadProgress())) { PP_Resource pp_resource = GetReferenceNoAddRef(); if (pp_resource) { status_callback_( instance()->pp_instance(), pp_resource, RecordUploadProgress() ? bytes_sent_ : -1, RecordUploadProgress() ? total_bytes_to_be_sent_ : -1, RecordDownloadProgress() ? bytes_received_ : -1, RecordDownloadProgress() ? total_bytes_to_be_received_ : -1); } } } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsSecure && !audio) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; } 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: my_object_increment_retval (MyObject *obj, gint32 x) { return x + 1; } CWE ID: CWE-264 Target: 1 Example 2: Code: int dm_suspended(struct dm_target *ti) { return dm_suspended_md(dm_table_get_md(ti->table)); } 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 MediaStreamDispatcherHost::CancelAllRequests() { if (!bindings_.empty()) return; media_stream_manager_->CancelAllRequests(render_process_id_, render_frame_id_); } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void prefetch_table(const void *tab, size_t len) { const volatile byte *vtab = tab; size_t i; for (i = 0; i < len; i += 8 * 32) { (void)vtab[i + 0 * 32]; (void)vtab[i + 1 * 32]; (void)vtab[i + 2 * 32]; (void)vtab[i + 3 * 32]; (void)vtab[i + 4 * 32]; (void)vtab[i + 5 * 32]; (void)vtab[i + 6 * 32]; (void)vtab[i + 7 * 32]; } (void)vtab[len - 1]; } CWE ID: CWE-310 Target: 1 Example 2: Code: cmppixel(Transform *transform, png_const_voidp in, png_const_voidp out, png_uint_32 x, png_uint_32 y/*or palette index*/) { int maxerr; png_const_charp errmsg; Pixel pixel_in, pixel_calc, pixel_out; transform->in_gp(&pixel_in, in); if (transform->from_linear == NULL) transform->transform(&pixel_calc, &pixel_in, transform->background); else { transform->transform(&pixel_out, &pixel_in, transform->background); transform->from_linear(&pixel_calc, &pixel_out, NULL); } transform->out_gp(&pixel_out, out); /* Eliminate the case where the input and output values match exactly. */ if (pixel_calc.a == pixel_out.a && pixel_calc.r == pixel_out.r && pixel_calc.g == pixel_out.g && pixel_calc.b == pixel_out.b) return 1; /* Eliminate the case where the output pixel is transparent and the output * is 8-bit - any component values are valid. Don't check the input alpha * here to also skip the 16-bit small alpha cases. */ if (transform->output_8bit && pixel_calc.a == 0 && pixel_out.a == 0) return 1; /* Check for alpha errors first; an alpha error can damage the components too * so avoid spurious checks on components if one is found. */ errmsg = NULL; { int err_a = abs(pixel_calc.a-pixel_out.a); if (err_a > transform->error[3]) { /* If accumulating check the components too */ if (transform->accumulate) transform->error[3] = (png_uint_16)err_a; else errmsg = "alpha"; } } /* Now if *either* of the output alphas are 0 but alpha is within tolerance * eliminate the 8-bit component comparison. */ if (errmsg == NULL && transform->output_8bit && (pixel_calc.a == 0 || pixel_out.a == 0)) return 1; if (errmsg == NULL) /* else just signal an alpha error */ { int err_r = abs(pixel_calc.r - pixel_out.r); int err_g = abs(pixel_calc.g - pixel_out.g); int err_b = abs(pixel_calc.b - pixel_out.b); int limit; if ((err_r | err_g | err_b) == 0) return 1; /* exact match */ /* Mismatch on a component, check the input alpha */ if (pixel_in.a >= transform->in_opaque) { errmsg = "opaque component"; limit = 2; /* opaque */ } else if (pixel_in.a > 0) { errmsg = "alpha component"; limit = 1; /* partially transparent */ } else { errmsg = "transparent component (background)"; limit = 0; /* transparent */ } maxerr = err_r; if (maxerr < err_g) maxerr = err_g; if (maxerr < err_b) maxerr = err_b; if (maxerr <= transform->error[limit]) return 1; /* within the error limits */ /* Handle a component mis-match; log it, just return an error code, or * accumulate it. */ if (transform->accumulate) { transform->error[limit] = (png_uint_16)maxerr; return 1; /* to cause the caller to keep going */ } } /* Failure to match and not accumulating, so the error must be logged. */ return logpixel(transform, x, y, &pixel_in, &pixel_calc, &pixel_out, errmsg); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int nfc_llcp_send_connect(struct nfc_llcp_sock *sock) { struct nfc_llcp_local *local; struct sk_buff *skb; u8 *service_name_tlv = NULL, service_name_tlv_length; u8 *miux_tlv = NULL, miux_tlv_length; u8 *rw_tlv = NULL, rw_tlv_length, rw; int err; u16 size = 0; __be16 miux; pr_debug("Sending CONNECT\n"); local = sock->local; if (local == NULL) return -ENODEV; if (sock->service_name != NULL) { service_name_tlv = nfc_llcp_build_tlv(LLCP_TLV_SN, sock->service_name, sock->service_name_len, &service_name_tlv_length); size += service_name_tlv_length; } /* If the socket parameters are not set, use the local ones */ miux = be16_to_cpu(sock->miux) > LLCP_MAX_MIUX ? local->miux : sock->miux; rw = sock->rw > LLCP_MAX_RW ? local->rw : sock->rw; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&miux, 0, &miux_tlv_length); size += miux_tlv_length; rw_tlv = nfc_llcp_build_tlv(LLCP_TLV_RW, &rw, 0, &rw_tlv_length); size += rw_tlv_length; pr_debug("SKB size %d SN length %zu\n", size, sock->service_name_len); skb = llcp_allocate_pdu(sock, LLCP_PDU_CONNECT, size); if (skb == NULL) { err = -ENOMEM; goto error_tlv; } llcp_add_tlv(skb, service_name_tlv, service_name_tlv_length); llcp_add_tlv(skb, miux_tlv, miux_tlv_length); llcp_add_tlv(skb, rw_tlv, rw_tlv_length); skb_queue_tail(&local->tx_queue, skb); err = 0; error_tlv: if (err) pr_err("error %d\n", err); kfree(service_name_tlv); kfree(miux_tlv); kfree(rw_tlv); return err; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WebContentsImpl::DidCallFocus() { if (IsFullscreenForCurrentTab()) ExitFullscreen(true); } CWE ID: CWE-20 Target: 1 Example 2: Code: PHP_FUNCTION(curl_exec) { CURLcode error; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zid) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ch, php_curl *, zid, -1, le_curl_name, le_curl); _php_curl_verify_handlers(ch, 1); _php_curl_cleanup_handle(ch); error = curl_easy_perform(ch->cp); SAVE_CURL_ERROR(ch, error); /* CURLE_PARTIAL_FILE is returned by HEAD requests */ if (error != CURLE_OK && error != CURLE_PARTIAL_FILE) { smart_str_free(&ch->handlers->write->buf); RETURN_FALSE; } if (!Z_ISUNDEF(ch->handlers->std_err)) { php_stream *stream; stream = zend_fetch_resource(&ch->handlers->std_err, -1, NULL, NULL, 2, php_file_le_stream(), php_file_le_pstream()); if (stream) { php_stream_flush(stream); } } if (ch->handlers->write->method == PHP_CURL_RETURN && ch->handlers->write->buf.s) { smart_str_0(&ch->handlers->write->buf); RETURN_STR(zend_string_copy(ch->handlers->write->buf.s)); } /* flush the file handle, so any remaining data is synched to disk */ if (ch->handlers->write->method == PHP_CURL_FILE && ch->handlers->write->fp) { fflush(ch->handlers->write->fp); } if (ch->handlers->write_header->method == PHP_CURL_FILE && ch->handlers->write_header->fp) { fflush(ch->handlers->write_header->fp); } if (ch->handlers->write->method == PHP_CURL_RETURN) { RETURN_EMPTY_STRING(); } else { RETURN_TRUE; } } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WARN_UNUSED_RESULT bool VerifyRecordedSamplesForHistogram( const size_t num_samples, const std::string& histogram_name) const { return num_samples == histogram_tester_.GetAllSamples(histogram_name).size(); } CWE ID: CWE-281 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 __u8 *nci_extract_rf_params_nfcb_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfcb_poll *nfcb_poll, __u8 *data) { nfcb_poll->sensb_res_len = *data++; pr_debug("sensb_res_len %d\n", nfcb_poll->sensb_res_len); memcpy(nfcb_poll->sensb_res, data, nfcb_poll->sensb_res_len); data += nfcb_poll->sensb_res_len; return data; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int __init vhost_init(void) { return 0; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t CameraClient::checkPidAndHardware() const { status_t result = checkPid(); if (result != NO_ERROR) return result; if (mHardware == 0) { ALOGE("attempt to use a camera after disconnect() (pid %d)", getCallingPid()); return INVALID_OPERATION; } return NO_ERROR; } 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: xsltStylesheetPtr XSLStyleSheet::compileStyleSheet() { if (m_embedded) return xsltLoadStylesheetPI(document()); ASSERT(!m_stylesheetDocTaken); xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc); if (result) m_stylesheetDocTaken = true; return result; } CWE ID: CWE-399 Target: 1 Example 2: Code: content::Visibility TabLifecycleUnitSource::TabLifecycleUnit::GetVisibility() const { return GetWebContents()->GetVisibility(); } 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 perf_mmap_close(struct vm_area_struct *vma) { struct perf_event *event = vma->vm_file->private_data; if (atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) { unsigned long size = perf_data_size(event->rb); struct user_struct *user = event->mmap_user; struct ring_buffer *rb = event->rb; atomic_long_sub((size >> PAGE_SHIFT) + 1, &user->locked_vm); vma->vm_mm->locked_vm -= event->mmap_locked; rcu_assign_pointer(event->rb, NULL); mutex_unlock(&event->mmap_mutex); ring_buffer_put(rb); free_uid(user); } } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int equalizer_get_parameter(effect_context_t *context, effect_param_t *p, uint32_t *size) { equalizer_context_t *eq_ctxt = (equalizer_context_t *)context; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); int32_t *param_tmp = (int32_t *)p->data; int32_t param = *param_tmp++; int32_t param2; char *name; void *value = p->data + voffset; int i; ALOGV("%s", __func__); p->status = 0; switch (param) { case EQ_PARAM_NUM_BANDS: case EQ_PARAM_CUR_PRESET: case EQ_PARAM_GET_NUM_OF_PRESETS: case EQ_PARAM_BAND_LEVEL: case EQ_PARAM_GET_BAND: if (p->vsize < sizeof(int16_t)) p->status = -EINVAL; p->vsize = sizeof(int16_t); break; case EQ_PARAM_LEVEL_RANGE: if (p->vsize < 2 * sizeof(int16_t)) p->status = -EINVAL; p->vsize = 2 * sizeof(int16_t); break; case EQ_PARAM_BAND_FREQ_RANGE: if (p->vsize < 2 * sizeof(int32_t)) p->status = -EINVAL; p->vsize = 2 * sizeof(int32_t); break; case EQ_PARAM_CENTER_FREQ: if (p->vsize < sizeof(int32_t)) p->status = -EINVAL; p->vsize = sizeof(int32_t); break; case EQ_PARAM_GET_PRESET_NAME: break; case EQ_PARAM_PROPERTIES: if (p->vsize < (2 + NUM_EQ_BANDS) * sizeof(uint16_t)) p->status = -EINVAL; p->vsize = (2 + NUM_EQ_BANDS) * sizeof(uint16_t); break; default: p->status = -EINVAL; } *size = sizeof(effect_param_t) + voffset + p->vsize; if (p->status != 0) return 0; switch (param) { case EQ_PARAM_NUM_BANDS: ALOGV("%s: EQ_PARAM_NUM_BANDS", __func__); *(uint16_t *)value = (uint16_t)NUM_EQ_BANDS; break; case EQ_PARAM_LEVEL_RANGE: ALOGV("%s: EQ_PARAM_LEVEL_RANGE", __func__); *(int16_t *)value = -1500; *((int16_t *)value + 1) = 1500; break; case EQ_PARAM_BAND_LEVEL: ALOGV("%s: EQ_PARAM_BAND_LEVEL", __func__); param2 = *param_tmp; if (param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; break; } *(int16_t *)value = (int16_t)equalizer_get_band_level(eq_ctxt, param2); break; case EQ_PARAM_CENTER_FREQ: ALOGV("%s: EQ_PARAM_CENTER_FREQ", __func__); param2 = *param_tmp; if (param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; break; } *(int32_t *)value = equalizer_get_center_frequency(eq_ctxt, param2); break; case EQ_PARAM_BAND_FREQ_RANGE: ALOGV("%s: EQ_PARAM_BAND_FREQ_RANGE", __func__); param2 = *param_tmp; if (param2 >= NUM_EQ_BANDS) { p->status = -EINVAL; break; } equalizer_get_band_freq_range(eq_ctxt, param2, (uint32_t *)value, ((uint32_t *)value + 1)); break; case EQ_PARAM_GET_BAND: ALOGV("%s: EQ_PARAM_GET_BAND", __func__); param2 = *param_tmp; *(uint16_t *)value = (uint16_t)equalizer_get_band(eq_ctxt, param2); break; case EQ_PARAM_CUR_PRESET: ALOGV("%s: EQ_PARAM_CUR_PRESET", __func__); *(uint16_t *)value = (uint16_t)equalizer_get_preset(eq_ctxt); break; case EQ_PARAM_GET_NUM_OF_PRESETS: ALOGV("%s: EQ_PARAM_GET_NUM_OF_PRESETS", __func__); *(uint16_t *)value = (uint16_t)equalizer_get_num_presets(eq_ctxt); break; case EQ_PARAM_GET_PRESET_NAME: ALOGV("%s: EQ_PARAM_GET_PRESET_NAME", __func__); param2 = *param_tmp; ALOGV("param2: %d", param2); if (param2 >= equalizer_get_num_presets(eq_ctxt)) { p->status = -EINVAL; break; } name = (char *)value; strlcpy(name, equalizer_get_preset_name(eq_ctxt, param2), p->vsize - 1); name[p->vsize - 1] = 0; p->vsize = strlen(name) + 1; break; case EQ_PARAM_PROPERTIES: { ALOGV("%s: EQ_PARAM_PROPERTIES", __func__); int16_t *prop = (int16_t *)value; prop[0] = (int16_t)equalizer_get_preset(eq_ctxt); prop[1] = (int16_t)NUM_EQ_BANDS; for (i = 0; i < NUM_EQ_BANDS; i++) { prop[2 + i] = (int16_t)equalizer_get_band_level(eq_ctxt, i); } } break; default: p->status = -EINVAL; break; } return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: void OomInterventionTabHelper::OnHighMemoryUsage() { auto* config = OomInterventionConfig::GetInstance(); if (config->is_renderer_pause_enabled() || config->is_navigate_ads_enabled()) { NearOomReductionInfoBar::Show(web_contents(), this); intervention_state_ = InterventionState::UI_SHOWN; if (!last_navigation_timestamp_.is_null()) { base::TimeDelta time_since_last_navigation = base::TimeTicks::Now() - last_navigation_timestamp_; UMA_HISTOGRAM_COUNTS_1M( "Memory.Experimental.OomIntervention." "RendererTimeSinceLastNavigationAtIntervention", time_since_last_navigation.InSeconds()); } } near_oom_detected_time_ = base::TimeTicks::Now(); renderer_detection_timer_.AbandonAndStop(); } 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 inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb, APERice *rice) { unsigned int x, overflow; overflow = get_unary(gb, 1, get_bits_left(gb)); if (ctx->fileversion > 3880) { while (overflow >= 16) { overflow -= 16; rice->k += 4; } } if (!rice->k) x = overflow; else if(rice->k <= MIN_CACHE_BITS) { x = (overflow << rice->k) + get_bits(gb, rice->k); } else { av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k); return AVERROR_INVALIDDATA; } rice->ksum += x - (rice->ksum + 8 >> 4); if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0)) rice->k--; else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24) rice->k++; /* Convert to signed */ return ((x >> 1) ^ ((x & 1) - 1)) + 1; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WORD32 ixheaacd_real_synth_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer, WORD32 num_columns, FLOAT32 qmf_buf_real[][64], FLOAT32 qmf_buf_imag[][64]) { WORD32 i, j, k, l, idx; FLOAT32 g[640]; FLOAT32 w[640]; FLOAT32 synth_out[128]; FLOAT32 accu_r; WORD32 synth_size = ptr_hbe_txposer->synth_size; FLOAT32 *ptr_cos_tab_trans_qmf = (FLOAT32 *)&ixheaacd_cos_table_trans_qmf[0][0] + ptr_hbe_txposer->k_start * 32; FLOAT32 *buffer = ptr_hbe_txposer->synth_buf; for (idx = 0; idx < num_columns; idx++) { FLOAT32 loc_qmf_buf[64]; FLOAT32 *synth_buf_r = loc_qmf_buf; FLOAT32 *out_buf = ptr_hbe_txposer->ptr_input_buf + (idx + 1) * ptr_hbe_txposer->synth_size; FLOAT32 *synth_cos_tab = ptr_hbe_txposer->synth_cos_tab; const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->synth_wind_coeff; if (ptr_hbe_txposer->k_start < 0) return -1; for (k = 0; k < synth_size; k++) { WORD32 ki = ptr_hbe_txposer->k_start + k; synth_buf_r[k] = (FLOAT32)( ptr_cos_tab_trans_qmf[(k << 1) + 0] * qmf_buf_real[idx][ki] + ptr_cos_tab_trans_qmf[(k << 1) + 1] * qmf_buf_imag[idx][ki]); synth_buf_r[k + ptr_hbe_txposer->synth_size] = 0; } for (l = (20 * synth_size - 1); l >= 2 * synth_size; l--) { buffer[l] = buffer[l - 2 * synth_size]; } if (synth_size == 20) { FLOAT32 *psynth_cos_tab = synth_cos_tab; for (l = 0; l < (synth_size + 1); l++) { accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[0 + l] = accu_r; buffer[synth_size - l] = accu_r; psynth_cos_tab = psynth_cos_tab + synth_size; } for (l = (synth_size + 1); l < (2 * synth_size - synth_size / 2); l++) { accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[0 + l] = accu_r; buffer[3 * synth_size - l] = -accu_r; psynth_cos_tab = psynth_cos_tab + synth_size; } accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[3 * synth_size >> 1] = accu_r; } else { FLOAT32 tmp; FLOAT32 *ptr_u = synth_out; WORD32 kmax = (synth_size >> 1); FLOAT32 *syn_buf = &buffer[kmax]; kmax += synth_size; if (ixheaacd_real_synth_fft != NULL) (*ixheaacd_real_synth_fft)(synth_buf_r, synth_out, synth_size * 2); else return -1; for (k = 0; k < kmax; k++) { tmp = ((*ptr_u++) * (*synth_cos_tab++)); tmp -= ((*ptr_u++) * (*synth_cos_tab++)); *syn_buf++ = tmp; } syn_buf = &buffer[0]; kmax -= synth_size; for (k = 0; k < kmax; k++) { tmp = ((*ptr_u++) * (*synth_cos_tab++)); tmp -= ((*ptr_u++) * (*synth_cos_tab++)); *syn_buf++ = tmp; } } for (i = 0; i < 5; i++) { memcpy(&g[(2 * i + 0) * synth_size], &buffer[(4 * i + 0) * synth_size], sizeof(FLOAT32) * synth_size); memcpy(&g[(2 * i + 1) * synth_size], &buffer[(4 * i + 3) * synth_size], sizeof(FLOAT32) * synth_size); } for (k = 0; k < 10 * synth_size; k++) { w[k] = g[k] * interp_window_coeff[k]; } for (i = 0; i < synth_size; i++) { accu_r = 0.0; for (j = 0; j < 10; j++) { accu_r = accu_r + w[synth_size * j + i]; } out_buf[i] = (FLOAT32)accu_r; } } return 0; } CWE ID: CWE-787 Target: 1 Example 2: Code: static size_t ZSTD_compressLiterals (ZSTD_hufCTables_t const* prevHuf, ZSTD_hufCTables_t* nextHuf, ZSTD_strategy strategy, int disableLiteralCompression, void* dst, size_t dstCapacity, const void* src, size_t srcSize, void* workspace, size_t wkspSize, const int bmi2) { size_t const minGain = ZSTD_minGain(srcSize, strategy); size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB); BYTE* const ostart = (BYTE*)dst; U32 singleStream = srcSize < 256; symbolEncodingType_e hType = set_compressed; size_t cLitSize; DEBUGLOG(5,"ZSTD_compressLiterals (disableLiteralCompression=%i)", disableLiteralCompression); /* Prepare nextEntropy assuming reusing the existing table */ memcpy(nextHuf, prevHuf, sizeof(*prevHuf)); if (disableLiteralCompression) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize); /* small ? don't even attempt compression (speed opt) */ # define COMPRESS_LITERALS_SIZE_MIN 63 { size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN; if (srcSize <= minLitSize) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize); } if (dstCapacity < lhSize+1) return ERROR(dstSize_tooSmall); /* not enough space for compression */ { HUF_repeat repeat = prevHuf->repeatMode; int const preferRepeat = strategy < ZSTD_lazy ? srcSize <= 1024 : 0; if (repeat == HUF_repeat_valid && lhSize == 3) singleStream = 1; cLitSize = singleStream ? HUF_compress1X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11, workspace, wkspSize, (HUF_CElt*)nextHuf->CTable, &repeat, preferRepeat, bmi2) : HUF_compress4X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11, workspace, wkspSize, (HUF_CElt*)nextHuf->CTable, &repeat, preferRepeat, bmi2); if (repeat != HUF_repeat_none) { /* reused the existing table */ hType = set_repeat; } } if ((cLitSize==0) | (cLitSize >= srcSize - minGain) | ERR_isError(cLitSize)) { memcpy(nextHuf, prevHuf, sizeof(*prevHuf)); return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize); } if (cLitSize==1) { memcpy(nextHuf, prevHuf, sizeof(*prevHuf)); return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize); } if (hType == set_compressed) { /* using a newly constructed table */ nextHuf->repeatMode = HUF_repeat_check; } /* Build header */ switch(lhSize) { case 3: /* 2 - 2 - 10 - 10 */ { U32 const lhc = hType + ((!singleStream) << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<14); MEM_writeLE24(ostart, lhc); break; } case 4: /* 2 - 2 - 14 - 14 */ { U32 const lhc = hType + (2 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<18); MEM_writeLE32(ostart, lhc); break; } case 5: /* 2 - 2 - 18 - 18 */ { U32 const lhc = hType + (3 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<22); MEM_writeLE32(ostart, lhc); ostart[4] = (BYTE)(cLitSize >> 10); break; } default: /* not possible : lhSize is {3,4,5} */ assert(0); } return lhSize+cLitSize; } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } CWE ID: CWE-59 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool MediaStreamDevicesController::ShouldAlwaysAllowOrigin() const { return profile_->GetHostContentSettingsMap()->ShouldAllowAllContent( request_.security_origin, request_.security_origin, CONTENT_SETTINGS_TYPE_MEDIASTREAM); } 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: err_t verify_signed_hash(const struct RSA_public_key *k , u_char *s, unsigned int s_max_octets , u_char **psig , size_t hash_len , const u_char *sig_val, size_t sig_len) { unsigned int padlen; /* actual exponentiation; see PKCS#1 v2.0 5.1 */ { chunk_t temp_s; MP_INT c; n_to_mpz(&c, sig_val, sig_len); oswcrypto.mod_exp(&c, &c, &k->e, &k->n); temp_s = mpz_to_n(&c, sig_len); /* back to octets */ if(s_max_octets < sig_len) { return "2""exponentiation failed; too many octets"; } memcpy(s, temp_s.ptr, sig_len); pfree(temp_s.ptr); mpz_clear(&c); } /* check signature contents */ /* verify padding (not including any DER digest info! */ padlen = sig_len - 3 - hash_len; /* now check padding */ DBG(DBG_CRYPT, DBG_dump("verify_sh decrypted SIG1:", s, sig_len)); DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len)); /* skip padding */ if(s[0] != 0x00 || s[1] != 0x01 || s[padlen+2] != 0x00) { return "3""SIG padding does not check out"; } s += padlen + 3; (*psig) = s; /* return SUCCESS */ return NULL; } CWE ID: CWE-347 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: ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } CWE ID: CWE-125 Target: 1 Example 2: Code: sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g) { return sshbuf_get_ec(ssh->state->incoming_packet, v, g); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PrintPreviewUI::ClearAllPreviewData() { print_preview_data_service()->RemoveEntry(preview_ui_addr_str_); } 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: RenderProcessImpl::RenderProcessImpl() : ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_( FROM_HERE, base::TimeDelta::FromSeconds(5), this, &RenderProcessImpl::ClearTransportDIBCache)), transport_dib_next_sequence_number_(0) { in_process_plugins_ = InProcessPlugins(); for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) shared_mem_cache_[i] = NULL; #if defined(OS_WIN) if (GetModuleHandle(L"LPK.DLL") == NULL) { typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs); GdiInitializeLanguagePack gdi_init_lpk = reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress( GetModuleHandle(L"GDI32.DLL"), "GdiInitializeLanguagePack")); DCHECK(gdi_init_lpk); if (gdi_init_lpk) { gdi_init_lpk(0); } } #endif webkit_glue::SetJavaScriptFlags( "--debugger-auto-break" " --prof --prof-lazy"); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kJavaScriptFlags)) { webkit_glue::SetJavaScriptFlags( command_line.GetSwitchValueASCII(switches::kJavaScriptFlags)); } } CWE ID: CWE-264 Target: 1 Example 2: Code: static inline void slave_disable_netpoll(struct slave *slave) { } 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 dccp_v6_conn_request(struct sock *sk, struct sk_buff *skb) { struct request_sock *req; struct dccp_request_sock *dreq; struct inet_request_sock *ireq; struct ipv6_pinfo *np = inet6_sk(sk); const __be32 service = dccp_hdr_request(skb)->dccph_req_service; struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb); if (skb->protocol == htons(ETH_P_IP)) return dccp_v4_conn_request(sk, skb); if (!ipv6_unicast_destination(skb)) return 0; /* discard, don't send a reset here */ if (dccp_bad_service_code(sk, service)) { dcb->dccpd_reset_code = DCCP_RESET_CODE_BAD_SERVICE_CODE; goto drop; } /* * There are no SYN attacks on IPv6, yet... */ dcb->dccpd_reset_code = DCCP_RESET_CODE_TOO_BUSY; if (inet_csk_reqsk_queue_is_full(sk)) goto drop; if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) goto drop; req = inet_reqsk_alloc(&dccp6_request_sock_ops, sk, true); if (req == NULL) goto drop; if (dccp_reqsk_init(req, dccp_sk(sk), skb)) goto drop_and_free; dreq = dccp_rsk(req); if (dccp_parse_options(sk, dreq, skb)) goto drop_and_free; if (security_inet_conn_request(sk, skb, req)) goto drop_and_free; ireq = inet_rsk(req); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; ireq->ireq_family = AF_INET6; if (ipv6_opt_accepted(sk, skb, IP6CB(skb)) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = inet6_iif(skb); /* * Step 3: Process LISTEN state * * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookie * * Setting S.SWL/S.SWH to is deferred to dccp_create_openreq_child(). */ dreq->dreq_isr = dcb->dccpd_seq; dreq->dreq_gsr = dreq->dreq_isr; dreq->dreq_iss = dccp_v6_init_sequence(skb); dreq->dreq_gss = dreq->dreq_iss; dreq->dreq_service = service; if (dccp_v6_send_response(sk, req)) goto drop_and_free; inet_csk_reqsk_queue_hash_add(sk, req, DCCP_TIMEOUT_INIT); return 0; drop_and_free: reqsk_free(req); drop: DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS); return -1; } 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: v8::Local<v8::Object> V8SchemaRegistry::GetSchema(const std::string& api) { if (schema_cache_ != NULL) { v8::Local<v8::Object> cached_schema = schema_cache_->Get(api); if (!cached_schema.IsEmpty()) { return cached_schema; } } v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::EscapableHandleScope handle_scope(isolate); v8::Local<v8::Context> context = GetOrCreateContext(isolate); v8::Context::Scope context_scope(context); const base::DictionaryValue* schema = ExtensionAPI::GetSharedInstance()->GetSchema(api); CHECK(schema) << api; std::unique_ptr<V8ValueConverter> v8_value_converter( V8ValueConverter::create()); v8::Local<v8::Value> value = v8_value_converter->ToV8Value(schema, context); CHECK(!value.IsEmpty()); v8::Local<v8::Object> v8_schema(v8::Local<v8::Object>::Cast(value)); v8_schema->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen); schema_cache_->Set(api, v8_schema); return handle_scope.Escape(v8_schema); } CWE ID: CWE-200 Target: 1 Example 2: Code: static void user_free_payload_rcu(struct rcu_head *head) { struct user_key_payload *payload; payload = container_of(head, struct user_key_payload, rcu); kzfree(payload); } 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 vbe_ioport_write_data(void *opaque, uint32_t addr, uint32_t val) { VGACommonState *s = opaque; if (s->vbe_index <= VBE_DISPI_INDEX_NB) { trace_vga_vbe_write(s->vbe_index, val); switch(s->vbe_index) { case VBE_DISPI_INDEX_ID: if (val == VBE_DISPI_ID0 || val == VBE_DISPI_ID1 || val == VBE_DISPI_ID2 || val == VBE_DISPI_ID3 || val == VBE_DISPI_ID4) { s->vbe_regs[s->vbe_index] = val; } break; case VBE_DISPI_INDEX_XRES: case VBE_DISPI_INDEX_YRES: case VBE_DISPI_INDEX_BPP: case VBE_DISPI_INDEX_VIRT_WIDTH: case VBE_DISPI_INDEX_X_OFFSET: case VBE_DISPI_INDEX_Y_OFFSET: s->vbe_regs[s->vbe_index] = val; vbe_fixup_regs(s); vbe_update_vgaregs(s); break; case VBE_DISPI_INDEX_BANK: val &= s->vbe_bank_mask; s->vbe_regs[s->vbe_index] = val; s->bank_offset = (val << 16); vga_update_memory_access(s); break; case VBE_DISPI_INDEX_ENABLE: if ((val & VBE_DISPI_ENABLED) && !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) { s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] = 0; s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0; s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0; s->vbe_regs[VBE_DISPI_INDEX_ENABLE] |= VBE_DISPI_ENABLED; vbe_fixup_regs(s); vbe_update_vgaregs(s); /* clear the screen */ if (!(val & VBE_DISPI_NOCLEARMEM)) { memset(s->vram_ptr, 0, s->vbe_regs[VBE_DISPI_INDEX_YRES] * s->vbe_line_offset); } } else { s->bank_offset = 0; } s->dac_8bit = (val & VBE_DISPI_8BIT_DAC) > 0; s->vbe_regs[s->vbe_index] = val; vga_update_memory_access(s); break; default: break; } } } CWE ID: CWE-617 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last) { const char *s = name; while (1) { const char *s0 = s; char *dirname; /* Find a directory component, if any. */ while (1) { if (*s == 0) { if (last && s != s0) break; else return dir; } /* This is deliberately slash-only. */ if (*s == '/') break; s++; } dirname = g_strndup (s0, s - s0); while (*s == '/') s++; if (strcmp (dirname, ".") != 0) { GsfInput *subdir = gsf_infile_child_by_name (GSF_INFILE (dir), dirname); if (subdir) { /* Undo the ref. */ g_object_unref (subdir); dir = GSF_INFILE_TAR (subdir); } else dir = tar_create_dir (dir, dirname); } g_free (dirname); } } CWE ID: CWE-476 Target: 1 Example 2: Code: const views::ProgressBar* MediaControlsProgressView::progress_bar_for_testing() const { return progress_bar_; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: image_transform_png_set_expand_gray_1_2_4_to_8_set( PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_gray_1_2_4_to_8(pp); this->next->set(this->next, that, pp, pi); } 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 __exit ipgre_fini(void) { rtnl_link_unregister(&ipgre_tap_ops); rtnl_link_unregister(&ipgre_link_ops); unregister_pernet_device(&ipgre_net_ops); if (inet_del_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) printk(KERN_INFO "ipgre close: can't remove protocol\n"); } CWE ID: Target: 1 Example 2: Code: static inline void rcu_copy_process(struct task_struct *p) { #ifdef CONFIG_PREEMPT_RCU p->rcu_read_lock_nesting = 0; p->rcu_read_unlock_special.s = 0; p->rcu_blocked_node = NULL; INIT_LIST_HEAD(&p->rcu_node_entry); #endif /* #ifdef CONFIG_PREEMPT_RCU */ #ifdef CONFIG_TASKS_RCU p->rcu_tasks_holdout = false; INIT_LIST_HEAD(&p->rcu_tasks_holdout_list); p->rcu_tasks_idle_cpu = -1; #endif /* #ifdef CONFIG_TASKS_RCU */ } 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: grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) { struct grub_ext2_data *data = node->data; struct grub_ext2_inode *inode = &node->inode; int blknr = -1; unsigned int blksz = EXT2_BLOCK_SIZE (data); int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data); if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG) { #ifndef _MSC_VER char buf[EXT2_BLOCK_SIZE (data)]; #else char * buf = grub_malloc (EXT2_BLOCK_SIZE(data)); #endif struct grub_ext4_extent_header *leaf; struct grub_ext4_extent *ext; int i; leaf = grub_ext4_find_leaf (data, buf, (struct grub_ext4_extent_header *) inode->blocks.dir_blocks, fileblock); if (! leaf) { grub_error (GRUB_ERR_BAD_FS, "invalid extent"); return -1; } ext = (struct grub_ext4_extent *) (leaf + 1); for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++) { if (fileblock < grub_le_to_cpu32 (ext[i].block)) break; } if (--i >= 0) { fileblock -= grub_le_to_cpu32 (ext[i].block); if (fileblock >= grub_le_to_cpu16 (ext[i].len)) return 0; else { grub_disk_addr_t start; start = grub_le_to_cpu16 (ext[i].start_hi); start = (start << 32) + grub_le_to_cpu32 (ext[i].start); return fileblock + start; } } else { grub_error (GRUB_ERR_BAD_FS, "something wrong with extent"); return -1; } } /* Direct blocks. */ if (fileblock < INDIRECT_BLOCKS) blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]); /* Indirect. */ else if (fileblock < INDIRECT_BLOCKS + blksz / 4) { grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.indir_block)) << log2_blksz, 0, blksz, indir)) return grub_errno; blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]); grub_free (indir); } /* Double indirect. */ else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \ * (grub_disk_addr_t)(blksz / 4 + 1)) { unsigned int perblock = blksz / 4; unsigned int rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4); grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.double_indir_block)) << log2_blksz, 0, blksz, indir)) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (indir[rblock / perblock])) << log2_blksz, 0, blksz, indir)) return grub_errno; blknr = grub_le_to_cpu32 (indir[rblock % perblock]); grub_free (indir); } /* triple indirect. */ else { grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, "ext2fs doesn't support triple indirect blocks"); } return blknr; } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps) { return -1; } if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); return -1; } return 0; } CWE ID: CWE-369 Target: 1 Example 2: Code: static void bsg_kref_release_function(struct kref *kref) { struct bsg_class_device *bcd = container_of(kref, struct bsg_class_device, ref); struct device *parent = bcd->parent; if (bcd->release) bcd->release(bcd->parent); put_device(parent); } 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: isoent_cmp_node_iso9660(const struct archive_rb_node *n1, const struct archive_rb_node *n2) { const struct idrent *e1 = (const struct idrent *)n1; const struct idrent *e2 = (const struct idrent *)n2; return (isoent_cmp_iso9660_identifier(e2->isoent, e1->isoent)); } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; if (cid <= 0) continue; dctx->remaining = avpriv_dnxhd_get_frame_size(cid); if (dctx->remaining <= 0) { dctx->remaining = ff_dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (dctx->remaining <= 0) return dctx->remaining; } if (buf_size - i + 47 >= dctx->remaining) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; return END_NOT_FOUND; } CWE ID: CWE-476 Target: 1 Example 2: Code: static inline bool cpu_has_vmx_virtualize_x2apic_mode(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void flush_tmregs_to_thread(struct task_struct *tsk) { /* * If task is not current, it will have been flushed already to * it's thread_struct during __switch_to(). * * A reclaim flushes ALL the state or if not in TM save TM SPRs * in the appropriate thread structures from live. */ if (tsk != current) return; if (MSR_TM_SUSPENDED(mfmsr())) { tm_reclaim_current(TM_CAUSE_SIGNAL); } else { tm_enable(); tm_save_sprs(&(tsk->thread)); } } 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 Image *ReadOTBImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define GetBit(a,i) (((a) >> (i)) & 1L) Image *image; int byte; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; ssize_t y; unsigned char bit, info, depth; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ info=(unsigned char) ReadBlobByte(image); if (GetBit(info,4) == 0) { image->columns=(size_t) ReadBlobByte(image); image->rows=(size_t) ReadBlobByte(image); } else { image->columns=(size_t) ReadBlobMSBShort(image); image->rows=(size_t) ReadBlobMSBShort(image); } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); depth=(unsigned char) ReadBlobByte(image); if (depth != 1) ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported"); if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert bi-level image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) { byte=ReadBlobByte(image); if (byte == EOF) ThrowReaderException(CorruptImageError,"CorruptImage"); } SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 0x00 : 0x01); bit++; if (bit == 8) bit=0; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } CWE ID: CWE-119 Target: 1 Example 2: Code: static struct page *alloc_buddy_huge_page(struct hstate *h, int nid) { struct page *page; unsigned int r_nid; if (h->order >= MAX_ORDER) return NULL; /* * Assume we will successfully allocate the surplus page to * prevent racing processes from causing the surplus to exceed * overcommit * * This however introduces a different race, where a process B * tries to grow the static hugepage pool while alloc_pages() is * called by process A. B will only examine the per-node * counters in determining if surplus huge pages can be * converted to normal huge pages in adjust_pool_surplus(). A * won't be able to increment the per-node counter, until the * lock is dropped by B, but B doesn't drop hugetlb_lock until * no more huge pages can be converted from surplus to normal * state (and doesn't try to convert again). Thus, we have a * case where a surplus huge page exists, the pool is grown, and * the surplus huge page still exists after, even though it * should just have been converted to a normal huge page. This * does not leak memory, though, as the hugepage will be freed * once it is out of use. It also does not allow the counters to * go out of whack in adjust_pool_surplus() as we don't modify * the node values until we've gotten the hugepage and only the * per-node value is checked there. */ spin_lock(&hugetlb_lock); if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) { spin_unlock(&hugetlb_lock); return NULL; } else { h->nr_huge_pages++; h->surplus_huge_pages++; } spin_unlock(&hugetlb_lock); if (nid == NUMA_NO_NODE) page = alloc_pages(htlb_alloc_mask|__GFP_COMP| __GFP_REPEAT|__GFP_NOWARN, huge_page_order(h)); else page = alloc_pages_exact_node(nid, htlb_alloc_mask|__GFP_COMP|__GFP_THISNODE| __GFP_REPEAT|__GFP_NOWARN, huge_page_order(h)); if (page && arch_prepare_hugepage(page)) { __free_pages(page, huge_page_order(h)); page = NULL; } spin_lock(&hugetlb_lock); if (page) { r_nid = page_to_nid(page); set_compound_page_dtor(page, free_huge_page); /* * We incremented the global counters already */ h->nr_huge_pages_node[r_nid]++; h->surplus_huge_pages_node[r_nid]++; __count_vm_event(HTLB_BUDDY_PGALLOC); } else { h->nr_huge_pages--; h->surplus_huge_pages--; __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL); } spin_unlock(&hugetlb_lock); return page; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int apic_has_pending_timer(struct kvm_vcpu *vcpu) { struct kvm_lapic *apic = vcpu->arch.apic; if (kvm_vcpu_has_lapic(vcpu) && apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT)) return atomic_read(&apic->lapic_timer.pending); return 0; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) { assert(pCluster); assert(pCluster->m_index < 0); assert(idx >= m_clusterCount); const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); if (count >= size) { const long n = (size <= 0) ? 2048 : 2*size; Cluster** const qq = new Cluster*[n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } assert(m_clusters); Cluster** const p = m_clusters + idx; Cluster** q = m_clusters + count; assert(q >= p); assert(q < (m_clusters + size)); while (q > p) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; } m_clusters[idx] = pCluster; ++m_clusterPreloadCount; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int hci_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int len) { struct hci_ufilter uf = { .opcode = 0 }; struct sock *sk = sock->sk; int err = 0, opt = 0; BT_DBG("sk %p, opt %d", sk, optname); lock_sock(sk); if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) { err = -EBADFD; goto done; } switch (optname) { case HCI_DATA_DIR: if (get_user(opt, (int __user *)optval)) { err = -EFAULT; break; } if (opt) hci_pi(sk)->cmsg_mask |= HCI_CMSG_DIR; else hci_pi(sk)->cmsg_mask &= ~HCI_CMSG_DIR; break; case HCI_TIME_STAMP: if (get_user(opt, (int __user *)optval)) { err = -EFAULT; break; } if (opt) hci_pi(sk)->cmsg_mask |= HCI_CMSG_TSTAMP; else hci_pi(sk)->cmsg_mask &= ~HCI_CMSG_TSTAMP; break; case HCI_FILTER: { struct hci_filter *f = &hci_pi(sk)->filter; uf.type_mask = f->type_mask; uf.opcode = f->opcode; uf.event_mask[0] = *((u32 *) f->event_mask + 0); uf.event_mask[1] = *((u32 *) f->event_mask + 1); } len = min_t(unsigned int, len, sizeof(uf)); if (copy_from_user(&uf, optval, len)) { err = -EFAULT; break; } if (!capable(CAP_NET_RAW)) { uf.type_mask &= hci_sec_filter.type_mask; uf.event_mask[0] &= *((u32 *) hci_sec_filter.event_mask + 0); uf.event_mask[1] &= *((u32 *) hci_sec_filter.event_mask + 1); } { struct hci_filter *f = &hci_pi(sk)->filter; f->type_mask = uf.type_mask; f->opcode = uf.opcode; *((u32 *) f->event_mask + 0) = uf.event_mask[0]; *((u32 *) f->event_mask + 1) = uf.event_mask[1]; } break; default: err = -ENOPROTOOPT; break; } done: release_sock(sk); return err; } 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 inline void __d_clear_type_and_inode(struct dentry *dentry) { unsigned flags = READ_ONCE(dentry->d_flags); flags &= ~(DCACHE_ENTRY_TYPE | DCACHE_FALLTHRU); WRITE_ONCE(dentry->d_flags, flags); dentry->d_inode = NULL; } 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: void ChromeDownloadManagerDelegate::CheckIfSuggestedPathExists( int32 download_id, const FilePath& unverified_path, bool should_prompt, bool is_forced_path, content::DownloadDangerType danger_type, const FilePath& default_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath target_path(unverified_path); file_util::CreateDirectory(default_path); FilePath dir = target_path.DirName(); FilePath filename = target_path.BaseName(); if (!file_util::PathIsWritable(dir)) { VLOG(1) << "Unable to write to directory \"" << dir.value() << "\""; should_prompt = true; PathService::Get(chrome::DIR_USER_DOCUMENTS, &dir); target_path = dir.Append(filename); } bool should_uniquify = (!is_forced_path && (danger_type == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || should_prompt)); bool should_overwrite = (should_uniquify || is_forced_path); bool should_create_marker = (should_uniquify && !should_prompt); if (should_uniquify) { int uniquifier = download_util::GetUniquePathNumberWithCrDownload(target_path); if (uniquifier > 0) { target_path = target_path.InsertBeforeExtensionASCII( StringPrintf(" (%d)", uniquifier)); } else if (uniquifier == -1) { VLOG(1) << "Unable to find a unique path for suggested path \"" << target_path.value() << "\""; should_prompt = true; } } if (should_create_marker) file_util::WriteFile(download_util::GetCrDownloadPath(target_path), "", 0); DownloadItem::TargetDisposition disposition; if (should_prompt) disposition = DownloadItem::TARGET_DISPOSITION_PROMPT; else if (should_overwrite) disposition = DownloadItem::TARGET_DISPOSITION_OVERWRITE; else disposition = DownloadItem::TARGET_DISPOSITION_UNIQUIFY; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ChromeDownloadManagerDelegate::OnPathExistenceAvailable, this, download_id, target_path, disposition, danger_type)); } CWE ID: CWE-119 Target: 1 Example 2: Code: static jboolean JNI_ChromeFeatureList_GetFieldTrialParamByFeatureAsBoolean( JNIEnv* env, const JavaParamRef<jstring>& jfeature_name, const JavaParamRef<jstring>& jparam_name, const jboolean jdefault_value) { const base::Feature* feature = FindFeatureExposedToJava(ConvertJavaStringToUTF8(env, jfeature_name)); const std::string& param_name = ConvertJavaStringToUTF8(env, jparam_name); return base::GetFieldTrialParamByFeatureAsBool(*feature, param_name, jdefault_value); } 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 Ins_WS( INS_ARG ) { if ( BOUNDS( args[0], CUR.storeSize ) ) { CUR.error = TT_Err_Invalid_Reference; return; } CUR.storage[args[0]] = args[1]; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void mark_commit(struct commit *c, void *data) { mark_object(&c->object, NULL, NULL, data); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void set_texcoords_in_vertices(const float coord[4], float *out, unsigned stride) { out[0] = coord[0]; /*t0.s*/ out[1] = coord[1]; /*t0.t*/ out += stride; out[0] = coord[2]; /*t1.s*/ out[1] = coord[1]; /*t1.t*/ out += stride; out[0] = coord[2]; /*t2.s*/ out[1] = coord[3]; /*t2.t*/ out += stride; out[0] = coord[0]; /*t3.s*/ out[1] = coord[3]; /*t3.t*/ } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void removeEventListenerMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectV8Internal::removeEventListenerMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Reinitialize(ReinitTestCase test_case) { feature_list_.InitAndEnableFeature(network::features::kNetworkService); ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index")); EXPECT_TRUE(db.LazyOpen(true)); if (test_case == CORRUPT_CACHE_ON_INSTALL || test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) { const std::string kCorruptData("deadbeef"); base::FilePath disk_cache_directory = temp_directory_.GetPath().AppendASCII("Cache"); ASSERT_TRUE(base::CreateDirectory(disk_cache_directory)); base::FilePath index_file = disk_cache_directory.AppendASCII("index"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(index_file, kCorruptData.data(), kCorruptData.length())); base::FilePath entry_file = disk_cache_directory.AppendASCII("01234567_0"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(entry_file, kCorruptData.data(), kCorruptData.length())); } if (test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) { AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index")); GURL manifest_url = GetMockUrl("manifest"); AppCacheDatabase::GroupRecord group_record; group_record.group_id = 1; group_record.manifest_url = manifest_url; group_record.origin = url::Origin::Create(manifest_url); EXPECT_TRUE(db.InsertGroup(&group_record)); AppCacheDatabase::CacheRecord cache_record; cache_record.cache_id = 1; cache_record.group_id = 1; cache_record.online_wildcard = false; cache_record.update_time = kZeroTime; cache_record.cache_size = kDefaultEntrySize; EXPECT_TRUE(db.InsertCache(&cache_record)); AppCacheDatabase::EntryRecord entry_record; entry_record.cache_id = 1; entry_record.url = manifest_url; entry_record.flags = AppCacheEntry::MANIFEST; entry_record.response_id = 1; entry_record.response_size = kDefaultEntrySize; EXPECT_TRUE(db.InsertEntry(&entry_record)); } service_.reset(new AppCacheServiceImpl(nullptr)); auto loader_factory_getter = base::MakeRefCounted<URLLoaderFactoryGetter>(); loader_factory_getter->SetNetworkFactoryForTesting( &mock_url_loader_factory_, /* is_corb_enabled = */ true); service_->set_url_loader_factory_getter(loader_factory_getter.get()); service_->Initialize(temp_directory_.GetPath()); mock_quota_manager_proxy_ = new MockQuotaManagerProxy(); service_->quota_manager_proxy_ = mock_quota_manager_proxy_; delegate_.reset(new MockStorageDelegate(this)); observer_.reset(new MockServiceObserver(this)); service_->AddObserver(observer_.get()); FlushAllTasks(); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&AppCacheStorageImplTest::Continue_Reinitialize, base::Unretained(this), test_case)); } CWE ID: CWE-200 Target: 1 Example 2: Code: static int encode_rename(struct xdr_stream *xdr, const struct qstr *oldname, const struct qstr *newname) { __be32 *p; RESERVE_SPACE(8 + oldname->len); WRITE32(OP_RENAME); WRITE32(oldname->len); WRITEMEM(oldname->name, oldname->len); RESERVE_SPACE(4 + newname->len); WRITE32(newname->len); WRITEMEM(newname->name, newname->len); return 0; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host, DevToolsAgentHostClient* client) : binding_(this), agent_host_(agent_host), client_(client), process_(nullptr), host_(nullptr), dispatcher_(new protocol::UberDispatcher(this)), weak_factory_(this) { dispatcher_->setFallThroughForNotFound(true); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) { struct sctp_association *asoc = sctp_id2assoc(sk, id); struct sctp_sock *sp = sctp_sk(sk); struct socket *sock; int err = 0; if (!asoc) return -EINVAL; /* If there is a thread waiting on more sndbuf space for * sending on this asoc, it cannot be peeled. */ if (waitqueue_active(&asoc->wait)) return -EBUSY; /* An association cannot be branched off from an already peeled-off * socket, nor is this supported for tcp style sockets. */ if (!sctp_style(sk, UDP)) return -EINVAL; /* Create a new socket. */ err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock); if (err < 0) return err; sctp_copy_sock(sock->sk, sk, asoc); /* Make peeled-off sockets more like 1-1 accepted sockets. * Set the daddr and initialize id to something more random */ sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk); /* Populate the fields of the newsk from the oldsk and migrate the * asoc to the newsk. */ sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH); *sockp = sock; return err; } CWE ID: CWE-416 Target: 1 Example 2: Code: RenderLayerCompositor::CompositingStateTransitionType RenderLayerCompositor::computeCompositedLayerUpdate(const RenderLayer* layer) { CompositingStateTransitionType update = NoCompositingStateChange; if (needsOwnBacking(layer)) { if (!layer->hasCompositedLayerMapping()) { update = AllocateOwnCompositedLayerMapping; } } else { if (layer->hasCompositedLayerMapping()) update = RemoveOwnCompositedLayerMapping; if (layerSquashingEnabled()) { if (requiresSquashing(layer->compositingReasons())) { update = AddToSquashingLayer; } else if (layer->groupedMapping()) { update = RemoveFromSquashingLayer; } } } return update; } 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 TEE_Result set_rmem_param(const struct optee_msg_param_rmem *rmem, struct param_mem *mem) { uint64_t shm_ref = READ_ONCE(rmem->shm_ref); mem->mobj = mobj_reg_shm_get_by_cookie(shm_ref); if (!mem->mobj) return TEE_ERROR_BAD_PARAMETERS; mem->offs = READ_ONCE(rmem->offs); mem->size = READ_ONCE(rmem->size); return TEE_SUCCESS; } 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: ExtensionFunction::ResponseAction UsbFindDevicesFunction::Run() { scoped_ptr<extensions::core_api::usb::FindDevices::Params> parameters = FindDevices::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(parameters.get()); vendor_id_ = parameters->options.vendor_id; product_id_ = parameters->options.product_id; interface_id_ = parameters->options.interface_id.get() ? *parameters->options.interface_id.get() : UsbDevicePermissionData::ANY_INTERFACE; UsbDevicePermission::CheckParam param(vendor_id_, product_id_, interface_id_); if (!extension()->permissions_data()->CheckAPIPermissionWithParam( APIPermission::kUsbDevice, &param)) { return RespondNow(Error(kErrorPermissionDenied)); } UsbService* service = device::DeviceClient::Get()->GetUsbService(); if (!service) { return RespondNow(Error(kErrorInitService)); } service->GetDevices( base::Bind(&UsbFindDevicesFunction::OnGetDevicesComplete, this)); return RespondLater(); } CWE ID: CWE-399 Target: 1 Example 2: Code: void VerifyPagesPrinted(bool printed) { #if defined(OS_CHROMEOS) bool did_print_msg = (render_thread_->sink().GetUniqueMessageMatching( PrintHostMsg_TempFileForPrintingWritten::ID) != NULL); ASSERT_EQ(printed, did_print_msg); #else const IPC::Message* print_msg = render_thread_->sink().GetUniqueMessageMatching( PrintHostMsg_DidPrintPage::ID); bool did_print_msg = (NULL != print_msg); ASSERT_EQ(printed, did_print_msg); if (printed) { PrintHostMsg_DidPrintPage::Param post_did_print_page_param; PrintHostMsg_DidPrintPage::Read(print_msg, &post_did_print_page_param); EXPECT_EQ(0, post_did_print_page_param.a.page_number); } #endif // defined(OS_CHROMEOS) } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool MockRenderThread::Send(IPC::Message* msg) { if (msg->is_reply()) { if (reply_deserializer_.get()) { reply_deserializer_->SerializeOutputParameters(*msg); reply_deserializer_.reset(); } } else { if (msg->is_sync()) { reply_deserializer_.reset( static_cast<IPC::SyncMessage*>(msg)->GetReplyDeserializer()); } OnMessageReceived(*msg); } delete msg; return true; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char *argv[]) { opj_dinfo_t* dinfo; opj_event_mgr_t event_mgr; /* event manager */ int tnum; unsigned int snum; opj_mj2_t *movie; mj2_tk_t *track; mj2_sample_t *sample; unsigned char* frame_codestream; FILE *file, *outfile; char outfilename[50]; mj2_dparameters_t parameters; if (argc != 3) { printf("Usage: %s mj2filename output_location\n", argv[0]); printf("Example: %s foreman.mj2 output/foreman\n", argv[0]); return 1; } file = fopen(argv[1], "rb"); if (!file) { fprintf(stderr, "failed to open %s for reading\n", argv[1]); return 1; } /* configure the event callbacks (not required) setting of each callback is optional */ memset(&event_mgr, 0, sizeof(opj_event_mgr_t)); event_mgr.error_handler = error_callback; event_mgr.warning_handler = warning_callback; event_mgr.info_handler = info_callback; /* get a MJ2 decompressor handle */ dinfo = mj2_create_decompress(); /* catch events using our callbacks and give a local context */ opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr); /* setup the decoder decoding parameters using user parameters */ memset(&parameters, 0, sizeof(mj2_dparameters_t)); movie = (opj_mj2_t*) dinfo->mj2_handle; mj2_setup_decoder(movie, &parameters); if (mj2_read_struct(file, movie)) { /* Creating the movie structure*/ return 1; } /* Decode first video track */ tnum = 0; while (movie->tk[tnum].track_type != 0) { tnum ++; } track = &movie->tk[tnum]; fprintf(stdout, "Extracting %d frames from file...\n", track->num_samples); for (snum = 0; snum < track->num_samples; snum++) { sample = &track->sample[snum]; frame_codestream = (unsigned char*) malloc(sample->sample_size - 8); /* Skipping JP2C marker*/ fseek(file, sample->offset + 8, SEEK_SET); fread(frame_codestream, sample->sample_size - 8, 1, file); /* Assuming that jp and ftyp markers size do*/ sprintf(outfilename, "%s_%05d.j2k", argv[2], snum); outfile = fopen(outfilename, "wb"); if (!outfile) { fprintf(stderr, "failed to open %s for writing\n", outfilename); return 1; } fwrite(frame_codestream, sample->sample_size - 8, 1, outfile); fclose(outfile); free(frame_codestream); } fclose(file); fprintf(stdout, "%d frames correctly extracted\n", snum); /* free remaining structures */ if (dinfo) { mj2_destroy_decompress((opj_mj2_t*)dinfo->mj2_handle); } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: accept_new_connection(const struct socket *listener, struct mg_context *ctx) { struct socket so; char src_addr[IP_ADDR_STR_LEN]; socklen_t len = sizeof(so.rsa); int on = 1; if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) { } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) { sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa); mg_cry_internal(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr); closesocket(so.sock); } else { /* Put so socket structure into the queue */ DEBUG_TRACE("Accepted socket %d", (int)so.sock); set_close_on_exec(so.sock, fc(ctx)); so.is_ssl = listener->is_ssl; so.ssl_redir = listener->ssl_redir; if (getsockname(so.sock, &so.lsa.sa, &len) != 0) { mg_cry_internal(fc(ctx), "%s: getsockname() failed: %s", __func__, strerror(ERRNO)); } /* Set TCP keep-alive. This is needed because if HTTP-level * keep-alive * is enabled, and client resets the connection, server won't get * TCP FIN or RST and will keep the connection open forever. With * TCP keep-alive, next keep-alive handshake will figure out that * the client is down and will close the server end. * Thanks to Igor Klopov who suggested the patch. */ if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (SOCK_OPT_TYPE)&on, sizeof(on)) != 0) { mg_cry_internal( fc(ctx), "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s", __func__, strerror(ERRNO)); } /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced * to effectively fill up the underlying IP packet payload and * reduce the overhead of sending lots of small buffers. However * this hurts the server's throughput (ie. operations per second) * when HTTP 1.1 persistent connections are used and the responses * are relatively small (eg. less than 1400 bytes). */ if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL) && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) { if (set_tcp_nodelay(so.sock, 1) != 0) { mg_cry_internal( fc(ctx), "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s", __func__, strerror(ERRNO)); } } /* We are using non-blocking sockets. Thus, the * set_sock_timeout(so.sock, timeout); * call is no longer required. */ /* The "non blocking" property should already be * inherited from the parent socket. Set it for * non-compliant socket implementations. */ set_non_blocking_mode(so.sock); so.in_use = 0; produce_socket(ctx, &so); } } 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 parse_csum_name(const char *name, int len) { if (len < 0 && name) len = strlen(name); if (!name || (len == 4 && strncasecmp(name, "auto", 4) == 0)) { if (protocol_version >= 30) return CSUM_MD5; if (protocol_version >= 27) return CSUM_MD4_OLD; if (protocol_version >= 21) return CSUM_MD4_BUSTED; return CSUM_ARCHAIC; } if (len == 3 && strncasecmp(name, "md4", 3) == 0) return CSUM_MD4; if (len == 3 && strncasecmp(name, "md5", 3) == 0) return CSUM_MD5; if (len == 4 && strncasecmp(name, "none", 4) == 0) return CSUM_NONE; rprintf(FERROR, "unknown checksum name: %s\n", name); exit_cleanup(RERR_UNSUPPORTED); } CWE ID: CWE-354 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ShellBrowserMain(const content::MainFunctionParams& parameters) { bool layout_test_mode = CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree); base::ScopedTempDir browser_context_path_for_layout_tests; if (layout_test_mode) { CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir()); CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kContentShellDataPath, browser_context_path_for_layout_tests.path().MaybeAsASCII()); } scoped_ptr<content::BrowserMainRunner> main_runner_( content::BrowserMainRunner::Create()); int exit_code = main_runner_->Initialize(parameters); if (exit_code >= 0) return exit_code; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kCheckLayoutTestSysDeps)) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); main_runner_->Shutdown(); return 0; } if (layout_test_mode) { content::WebKitTestController test_controller; std::string test_string; CommandLine::StringVector args = CommandLine::ForCurrentProcess()->GetArgs(); size_t command_line_position = 0; bool ran_at_least_once = false; #if defined(OS_ANDROID) std::cout << "#READY\n"; std::cout.flush(); #endif while (GetNextTest(args, &command_line_position, &test_string)) { if (test_string.empty()) continue; if (test_string == "QUIT") break; bool enable_pixel_dumps; std::string pixel_hash; FilePath cwd; GURL test_url = GetURLForLayoutTest( test_string, &cwd, &enable_pixel_dumps, &pixel_hash); if (!content::WebKitTestController::Get()->PrepareForLayoutTest( test_url, cwd, enable_pixel_dumps, pixel_hash)) { break; } ran_at_least_once = true; main_runner_->Run(); if (!content::WebKitTestController::Get()->ResetAfterLayoutTest()) break; } if (!ran_at_least_once) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); } exit_code = 0; } else { exit_code = main_runner_->Run(); } main_runner_->Shutdown(); return exit_code; } CWE ID: CWE-200 Target: 1 Example 2: Code: internalSubsetDebug(void *ctx ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { callbacks++; if (quiet) return; fprintf(SAXdebug, "SAX.internalSubset(%s,", name); if (ExternalID == NULL) fprintf(SAXdebug, " ,"); else fprintf(SAXdebug, " %s,", ExternalID); if (SystemID == NULL) fprintf(SAXdebug, " )\n"); else fprintf(SAXdebug, " %s)\n", SystemID); } 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 udf_get_filename(struct super_block *sb, uint8_t *sname, uint8_t *dname, int flen) { struct ustr *filename, *unifilename; int len = 0; filename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!filename) return 0; unifilename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!unifilename) goto out1; if (udf_build_ustr_exact(unifilename, sname, flen)) goto out2; if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) { if (!udf_CS0toUTF8(filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) { if (!udf_CS0toNLS(UDF_SB(sb)->s_nls_map, filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else goto out2; len = udf_translate_to_linux(dname, filename->u_name, filename->u_len, unifilename->u_name, unifilename->u_len); out2: kfree(unifilename); out1: kfree(filename); return len; } 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: void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = joinbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int hstartcol; /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide. */ abort(); } } hstartcol = (numrows + 1 - parity) >> 1; /* Save the samples from the lowpass channel. */ n = hstartcol; srcptr = &a[0]; dstptr = buf; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } srcptr += stride; dstptr += JPC_QMFB_COLGRPSIZE; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol * stride]; dstptr = &a[(1 - parity) * stride]; n = numrows - hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += stride; } /* Copy the samples from the lowpass channel into place. */ srcptr = buf; dstptr = &a[parity * stride]; n = hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += JPC_QMFB_COLGRPSIZE; } /* If the join buffer was allocated on the heap, free this memory. */ if (buf != joinbuf) { jas_free(buf); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static struct fuse_conn *fuse_get_conn(struct file *file) { /* * Lockless access is OK, because file->private data is set * once during mount and is valid until the file is released. */ return file->private_data; } 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: XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) { if (parser != NULL) parser->m_entityDeclHandler = handler; } CWE ID: CWE-611 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 CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "TIME")) return; reply(nickFromMask(prefix), "TIME", QDateTime::currentDateTime().toString()); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2") .arg(nickFromMask(prefix)).arg(param)); } } CWE ID: CWE-399 Target: 1 Example 2: Code: RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() { WebContentsImpl* contents = this; FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame(); if (!focused_node) return nullptr; while (true) { contents = contents->node_.GetInnerWebContentsInFrame(focused_node); if (!contents) return focused_node->current_frame_host(); focused_node = contents->frame_tree_.GetFocusedFrame(); if (!focused_node) return contents->GetMainFrame(); } } 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 Initialize() { client_.reset(new FakeMidiManagerClient(&logger_)); manager_->StartSession(client_.get()); } 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 inet_sock_destruct(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); __skb_queue_purge(&sk->sk_receive_queue); __skb_queue_purge(&sk->sk_error_queue); sk_mem_reclaim(sk); if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) { pr_err("Attempt to release TCP socket in state %d %p\n", sk->sk_state, sk); return; } if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive inet socket %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); WARN_ON(sk->sk_wmem_queued); WARN_ON(sk->sk_forward_alloc); kfree(inet->opt); dst_release(rcu_dereference_check(sk->sk_dst_cache, 1)); sk_refcnt_debug_dec(sk); } CWE ID: CWE-362 Target: 1 Example 2: Code: send_channel_info_cmd(struct ipmi_smi *intf, int chan) { struct kernel_ipmi_msg msg; unsigned char data[1]; struct ipmi_system_interface_addr si; si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE; si.channel = IPMI_BMC_CHANNEL; si.lun = 0; msg.netfn = IPMI_NETFN_APP_REQUEST; msg.cmd = IPMI_GET_CHANNEL_INFO_CMD; msg.data = data; msg.data_len = 1; data[0] = chan; return i_ipmi_request(NULL, intf, (struct ipmi_addr *) &si, 0, &msg, intf, NULL, NULL, 0, intf->addrinfo[0].address, intf->addrinfo[0].lun, -1, 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: void WebLocalFrameImpl::SetTextDirection(WebTextDirection direction) { Editor& editor = frame_->GetEditor(); if (!editor.CanEdit()) return; switch (direction) { case kWebTextDirectionDefault: editor.SetBaseWritingDirection(WritingDirection::kNatural); break; case kWebTextDirectionLeftToRight: editor.SetBaseWritingDirection(WritingDirection::kLeftToRight); break; case kWebTextDirectionRightToLeft: editor.SetBaseWritingDirection(WritingDirection::kRightToLeft); break; default: NOTIMPLEMENTED(); break; } } 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: stringprep_utf8_nfkc_normalize (const char *str, ssize_t len) { return g_utf8_normalize (str, len, G_NORMALIZE_NFKC); } CWE ID: CWE-125 Target: 1 Example 2: Code: cf2_glyphpath_computeOffset( CF2_GlyphPath glyphpath, CF2_Fixed x1, CF2_Fixed y1, CF2_Fixed x2, CF2_Fixed y2, CF2_Fixed* x, CF2_Fixed* y ) { CF2_Fixed dx = x2 - x1; CF2_Fixed dy = y2 - y1; /* note: negative offsets don't work here; negate deltas to change */ /* quadrants, below */ if ( glyphpath->font->reverseWinding ) { dx = -dx; dy = -dy; } *x = *y = 0; if ( !glyphpath->darken ) return; /* add momentum for this path element */ glyphpath->callbacks->windingMomentum += cf2_getWindingMomentum( x1, y1, x2, y2 ); /* note: allow mixed integer and fixed multiplication here */ if ( dx >= 0 ) { if ( dy >= 0 ) { /* first quadrant, +x +y */ if ( dx > 2 * dy ) { /* +x */ *x = 0; *y = 0; } else if ( dy > 2 * dx ) { /* +y */ *x = glyphpath->xOffset; *y = glyphpath->yOffset; } else { /* +x +y */ *x = FT_MulFix( cf2_floatToFixed( 0.7 ), glyphpath->xOffset ); *y = FT_MulFix( cf2_floatToFixed( 1.0 - 0.7 ), glyphpath->yOffset ); } } else { /* fourth quadrant, +x -y */ if ( dx > -2 * dy ) { /* +x */ *x = 0; *y = 0; } else if ( -dy > 2 * dx ) { /* -y */ *x = -glyphpath->xOffset; *y = glyphpath->yOffset; } else { /* +x -y */ *x = FT_MulFix( cf2_floatToFixed( -0.7 ), glyphpath->xOffset ); *y = FT_MulFix( cf2_floatToFixed( 1.0 - 0.7 ), glyphpath->yOffset ); } } } else { if ( dy >= 0 ) { /* second quadrant, -x +y */ if ( -dx > 2 * dy ) { /* -x */ *x = 0; *y = 2 * glyphpath->yOffset; } else if ( dy > -2 * dx ) { /* +y */ *x = glyphpath->xOffset; *y = glyphpath->yOffset; } else { /* -x +y */ *x = FT_MulFix( cf2_floatToFixed( 0.7 ), glyphpath->xOffset ); *y = FT_MulFix( cf2_floatToFixed( 1.0 + 0.7 ), glyphpath->yOffset ); } } else { /* third quadrant, -x -y */ if ( -dx > -2 * dy ) { /* -x */ *x = 0; *y = 2 * glyphpath->yOffset; } else if ( -dy > -2 * dx ) { /* -y */ *x = -glyphpath->xOffset; *y = glyphpath->yOffset; } else { /* -x -y */ *x = FT_MulFix( cf2_floatToFixed( -0.7 ), glyphpath->xOffset ); *y = FT_MulFix( cf2_floatToFixed( 1.0 + 0.7 ), glyphpath->yOffset ); } } } } 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: zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */ { spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC); if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) { method = "_bad_state_ex"; method_len = sizeof("_bad_state_ex") - 1; key = NULL; } return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC); } /* }}} */ CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MediaStreamDispatcherHost::DoGenerateStream( int32_t page_request_id, const StreamControls& controls, bool user_gesture, GenerateStreamCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(MEDIA_DEVICE_INVALID_SECURITY_ORIGIN, std::string(), MediaStreamDevices(), MediaStreamDevices()); return; } media_stream_manager_->GenerateStream( render_process_id_, render_frame_id_, page_request_id, controls, std::move(salt_and_origin), user_gesture, std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr()), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceChanged, weak_factory_.GetWeakPtr())); } CWE ID: CWE-189 Target: 1 Example 2: Code: static void nfs4_reclaim_complete_done(struct rpc_task *task, void *data) { struct nfs4_reclaim_complete_data *calldata = data; struct nfs_client *clp = calldata->clp; struct nfs4_sequence_res *res = &calldata->res.seq_res; dprintk("--> %s\n", __func__); if (!nfs41_sequence_done(task, res)) return; trace_nfs4_reclaim_complete(clp, task->tk_status); if (nfs41_reclaim_complete_handle_errors(task, clp) == -EAGAIN) { rpc_restart_call_prepare(task); return; } dprintk("<-- %s\n", __func__); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool NuMediaExtractor::getTotalBitrate(int64_t *bitrate) const { if (mTotalBitrate >= 0) { *bitrate = mTotalBitrate; return true; } off64_t size; if (mDurationUs >= 0 && mDataSource->getSize(&size) == OK) { *bitrate = size * 8000000ll / mDurationUs; // in bits/sec return true; } return false; } 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: bool GesturePoint::IsInsideManhattanSquare(const TouchEvent& event) const { int manhattanDistance = abs(event.x() - first_touch_position_.x()) + abs(event.y() - first_touch_position_.y()); return manhattanDistance < kMaximumTouchMoveInPixelsForClick; } CWE ID: CWE-20 Target: 1 Example 2: Code: static ssize_t map_addr_show(struct uio_mem *mem, char *buf) { return sprintf(buf, "0x%llx\n", (unsigned long long)mem->addr); } 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: s32 gf_net_get_ntp_diff_ms(u64 ntp) { u32 remote_s, remote_f, local_s, local_f; s64 local, remote; remote_s = (ntp >> 32); remote_f = (u32) (ntp & 0xFFFFFFFFULL); gf_net_get_ntp(&local_s, &local_f); local = local_s; local *= 1000; local += ((u64) local_f)*1000 / 0xFFFFFFFFULL; remote = remote_s; remote *= 1000; remote += ((u64) remote_f)*1000 / 0xFFFFFFFFULL; return (s32) (local - remote); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void setup_test_dir(char *tmp_dir, const char *files, ...) { va_list ap; assert_se(mkdtemp(tmp_dir) != NULL); va_start(ap, files); while (files != NULL) { _cleanup_free_ char *path = strappend(tmp_dir, files); assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0) == 0); files = va_arg(ap, const char *); } va_end(ap); } CWE ID: CWE-264 Target: 1 Example 2: Code: static void ga_wait_child(pid_t pid, int *status, Error **err) { pid_t rpid; *status = 0; do { rpid = waitpid(pid, status, 0); } while (rpid == -1 && errno == EINTR); if (rpid == -1) { error_setg_errno(err, errno, "failed to wait for child (pid: %d)", pid); return; } g_assert(rpid == pid); } 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: PanoramiXRenderCreateLinearGradient(ClientPtr client) { REQUEST(xRenderCreateLinearGradientReq); PanoramiXRes *newPict; int result = Success, j; REQUEST_AT_LEAST_SIZE(xRenderCreateLinearGradientReq); if (!(newPict = (PanoramiXRes *) malloc(sizeof(PanoramiXRes)))) return BadAlloc; newPict->type = XRT_PICTURE; panoramix_setup_ids(newPict, client, stuff->pid); newPict->u.pict.root = FALSE; FOR_NSCREENS_BACKWARD(j) { stuff->pid = newPict->info[j].id; result = (*PanoramiXSaveRenderVector[X_RenderCreateLinearGradient]) (client); if (result != Success) break; } if (result == Success) AddResource(newPict->info[0].id, XRT_PICTURE, newPict); else free(newPict); return result; } CWE ID: CWE-20 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 impeg2d_dec_p_mb_params(dec_state_t *ps_dec) { stream_t *ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_mb_addr_incr; UWORD16 u2_total_len; UWORD16 u2_len; UWORD16 u2_mb_type; UWORD32 u4_next_word; const dec_mb_params_t *ps_dec_mb_params; if(impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,1); } else { u2_mb_addr_incr = impeg2d_get_mb_addr_incr(ps_stream); if(0 == ps_dec->u2_first_mb) { /****************************************************************/ /* If the 2nd member of a field picture pair is a P picture and */ /* the first one was an I picture, there cannot be any skipped */ /* MBs in the second field picture */ /****************************************************************/ /* if((dec->picture_structure != FRAME_PICTURE) && (dec->f->FieldFuncCall != 0) && (dec->las->u1_last_coded_vop_type == I)) { core0_err_handler((void *)(VOLParams), ITTMPEG2_ERR_INVALID_MB_SKIP); } */ /****************************************************************/ /* In MPEG-2, the last MB of the row cannot be skipped and the */ /* MBAddrIncr cannot be such that it will take the current MB */ /* beyond the current row */ /* In MPEG-1, the slice could start and end anywhere and is not */ /* restricted to a row like in MPEG-2. Hence this check should */ /* not be done for MPEG-1 streams. */ /****************************************************************/ if(ps_dec->u2_is_mpeg2 && ((ps_dec->u2_mb_x + u2_mb_addr_incr) > ps_dec->u2_num_horiz_mb) ) { u2_mb_addr_incr = ps_dec->u2_num_horiz_mb - ps_dec->u2_mb_x; } impeg2d_dec_skip_mbs(ps_dec, (UWORD16)(u2_mb_addr_incr - 1)); } } u4_next_word = (UWORD16)impeg2d_bit_stream_nxt(ps_stream,16); /*-----------------------------------------------------------------------*/ /* MB type */ /*-----------------------------------------------------------------------*/ { u2_mb_type = ps_dec->pu2_mb_type[BITS((UWORD16)u4_next_word,15,10)]; u2_len = BITS(u2_mb_type,15,8); u2_total_len = u2_len; u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << u2_len); } /*-----------------------------------------------------------------------*/ /* motion type */ /*-----------------------------------------------------------------------*/ { if((u2_mb_type & MB_FORW_OR_BACK) && ps_dec->u2_read_motion_type) { WORD32 i4_motion_type; ps_dec->u2_motion_type = BITS((UWORD16)u4_next_word,15,14); u2_total_len += MB_MOTION_TYPE_LEN; u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << MB_MOTION_TYPE_LEN); i4_motion_type = ps_dec->u2_motion_type; if((i4_motion_type == 0) || (i4_motion_type == 4) || (i4_motion_type > 7)) { i4_motion_type = 1; } } } /*-----------------------------------------------------------------------*/ /* dct type */ /*-----------------------------------------------------------------------*/ { if((u2_mb_type & MB_CODED) && ps_dec->u2_read_dct_type) { ps_dec->u2_field_dct = BIT((UWORD16)u4_next_word,15); u2_total_len += MB_DCT_TYPE_LEN; u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << MB_DCT_TYPE_LEN); } } /*-----------------------------------------------------------------------*/ /* Quant scale code */ /*-----------------------------------------------------------------------*/ if(u2_mb_type & MB_QUANT) { UWORD16 u2_quant_scale_code; u2_quant_scale_code = BITS((UWORD16)u4_next_word,15,11); ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); u2_total_len += MB_QUANT_SCALE_CODE_LEN; } impeg2d_bit_stream_flush(ps_stream,u2_total_len); /*-----------------------------------------------------------------------*/ /* Set the function pointers */ /*-----------------------------------------------------------------------*/ ps_dec->u2_coded_mb = (UWORD16)(u2_mb_type & MB_CODED); if(u2_mb_type & MB_FORW_OR_BACK) { UWORD16 refPic = !(u2_mb_type & MB_MV_FORW); UWORD16 index = (ps_dec->u2_motion_type); ps_dec->u2_prev_intra_mb = 0; ps_dec->e_mb_pred = (e_pred_direction_t)refPic; ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index]; ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; ps_dec_mb_params->pf_func_mb_params(ps_dec); } else if(u2_mb_type & MB_TYPE_INTRA) { ps_dec->u2_prev_intra_mb = 1; impeg2d_dec_intra_mb(ps_dec); } else { ps_dec->u2_prev_intra_mb = 0; ps_dec->e_mb_pred = FORW; ps_dec->u2_motion_type = 0; impeg2d_dec_0mv_coded_mb(ps_dec); } /*-----------------------------------------------------------------------*/ /* decode cbp */ /*-----------------------------------------------------------------------*/ if((u2_mb_type & MB_TYPE_INTRA)) { ps_dec->u2_cbp = 0x3f; ps_dec->u2_prev_intra_mb = 1; } else { ps_dec->u2_prev_intra_mb = 0; ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; if((ps_dec->u2_coded_mb)) { UWORD16 cbpValue; cbpValue = gau2_impeg2d_cbp_code[impeg2d_bit_stream_nxt(ps_stream,MB_CBP_LEN)]; ps_dec->u2_cbp = cbpValue & 0xFF; impeg2d_bit_stream_flush(ps_stream,(cbpValue >> 8) & 0x0FF); } else { ps_dec->u2_cbp = 0; } } } CWE ID: CWE-119 Target: 1 Example 2: Code: virtual status_t signRSA(Vector<uint8_t> const &sessionId, String8 const &algorithm, Vector<uint8_t> const &message, Vector<uint8_t> const &wrappedKey, Vector<uint8_t> &signature) { Parcel data, reply; data.writeInterfaceToken(IDrm::getInterfaceDescriptor()); writeVector(data, sessionId); data.writeString8(algorithm); writeVector(data, message); writeVector(data, wrappedKey); status_t status = remote()->transact(SIGN_RSA, data, &reply); if (status != OK) { return status; } readVector(reply, signature); return reply.readInt32(); } 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 init_nss_hash(struct crypto_instance *instance) { PK11SlotInfo* hash_slot = NULL; SECItem hash_param; if (!hash_to_nss[instance->crypto_hash_type]) { return 0; } hash_param.type = siBuffer; hash_param.data = 0; hash_param.len = 0; hash_slot = PK11_GetBestSlot(hash_to_nss[instance->crypto_hash_type], NULL); if (hash_slot == NULL) { log_printf(instance->log_level_security, "Unable to find security slot (err %d)", PR_GetError()); return -1; } instance->nss_sym_key_sign = PK11_ImportSymKey(hash_slot, hash_to_nss[instance->crypto_hash_type], PK11_OriginUnwrap, CKA_SIGN, &hash_param, NULL); if (instance->nss_sym_key_sign == NULL) { log_printf(instance->log_level_security, "Failure to import key into NSS (err %d)", PR_GetError()); return -1; } PK11_FreeSlot(hash_slot); return 0; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SProcXFixesCreatePointerBarrier(ClientPtr client) { REQUEST(xXFixesCreatePointerBarrierReq); int i; int i; CARD16 *in_devices = (CARD16 *) &stuff[1]; swaps(&stuff->length); swaps(&stuff->num_devices); REQUEST_FIXED_SIZE(xXFixesCreatePointerBarrierReq, pad_to_int32(stuff->num_devices)); swaps(&stuff->x1); swaps(&stuff->y1); swaps(&stuff->x2); swaps(&stuff->y2); swapl(&stuff->directions); for (i = 0; i < stuff->num_devices; i++) { swaps(in_devices + i); } return ProcXFixesVector[stuff->xfixesReqType] (client); } CWE ID: CWE-20 Target: 1 Example 2: Code: request_remove_header (struct request *req, const char *name) { int i; for (i = 0; i < req->hcount; i++) { struct request_header *hdr = &req->headers[i]; if (0 == c_strcasecmp (name, hdr->name)) { release_header (hdr); /* Move the remaining headers by one. */ if (i < req->hcount - 1) memmove (hdr, hdr + 1, (req->hcount - i - 1) * sizeof (*hdr)); --req->hcount; return true; } } return false; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DatabaseImpl::IDBThreadHelper::SetIndexKeys( int64_t transaction_id, int64_t object_store_id, const IndexedDBKey& primary_key, const std::vector<IndexedDBIndexKeys>& index_keys) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; IndexedDBTransaction* transaction = connection_->GetTransaction(transaction_id); if (!transaction) return; connection_->database()->SetIndexKeys( transaction, object_store_id, base::MakeUnique<IndexedDBKey>(primary_key), index_keys); } 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: bool GestureProviderAura::OnTouchEvent(const TouchEvent& event) { last_touch_event_flags_ = event.flags(); bool pointer_id_is_active = false; for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) { if (event.touch_id() != pointer_state_.GetPointerId(i)) continue; pointer_id_is_active = true; break; } if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) { return false; } else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) { return false; } pointer_state_.OnTouch(event); bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_); pointer_state_.CleanupRemovedTouchPoints(event); return result; } CWE ID: Target: 1 Example 2: Code: static bool jslIsToken(const char *token, int startOffset) { int i; for (i=startOffset;i<lex->tokenl;i++) { if (lex->token[i]!=token[i]) return false; } return token[lex->tokenl] == 0; // only match if token ends now } 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: EAS_BOOL WT_CheckSampleEnd (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame, EAS_BOOL update) { EAS_U32 endPhaseAccum; EAS_U32 endPhaseFrac; EAS_I32 numSamples; EAS_BOOL done = EAS_FALSE; /* check to see if we hit the end of the waveform this time */ /*lint -e{703} use shift for performance */ endPhaseFrac = pWTVoice->phaseFrac + (pWTIntFrame->frame.phaseIncrement << SYNTH_UPDATE_PERIOD_IN_BITS); endPhaseAccum = pWTVoice->phaseAccum + GET_PHASE_INT_PART(endPhaseFrac); if (endPhaseAccum >= pWTVoice->loopEnd) { /* calculate how far current ptr is from end */ numSamples = (EAS_I32) (pWTVoice->loopEnd - pWTVoice->phaseAccum); /* now account for the fractional portion */ /*lint -e{703} use shift for performance */ numSamples = (EAS_I32) ((numSamples << NUM_PHASE_FRAC_BITS) - pWTVoice->phaseFrac); if (pWTIntFrame->frame.phaseIncrement) { pWTIntFrame->numSamples = 1 + (numSamples / pWTIntFrame->frame.phaseIncrement); } else { pWTIntFrame->numSamples = numSamples; } if (pWTIntFrame->numSamples < 0) { ALOGE("b/26366256"); pWTIntFrame->numSamples = 0; } /* sound will be done this frame */ done = EAS_TRUE; } /* update data for off-chip synth */ if (update) { pWTVoice->phaseFrac = endPhaseFrac; pWTVoice->phaseAccum = endPhaseAccum; } return done; } 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 SniffMimeType(const char* content, size_t content_size, const GURL& url, const std::string& type_hint, std::string* result) { DCHECK_LT(content_size, 1000000U); // sanity check DCHECK(content); DCHECK(result); bool have_enough_content = true; result->assign(type_hint); if (IsOfficeType(type_hint)) return SniffForInvalidOfficeDocs(content, content_size, url, result); const bool hint_is_unknown_mime_type = IsUnknownMimeType(type_hint); if (hint_is_unknown_mime_type && !url.SchemeIsFile() && SniffForHTML(content, content_size, &have_enough_content, result)) { return true; } const bool hint_is_text_plain = (type_hint == "text/plain"); if (hint_is_unknown_mime_type || hint_is_text_plain) { if (!SniffBinary(content, content_size, &have_enough_content, result)) { if (hint_is_text_plain) { return have_enough_content; } } } if (type_hint == "text/xml" || type_hint == "application/xml") { if (SniffXML(content, content_size, &have_enough_content, result)) return true; return have_enough_content; } if (SniffCRX(content, content_size, url, type_hint, &have_enough_content, result)) return true; if (SniffForOfficeDocs(content, content_size, url, &have_enough_content, result)) return true; // We've matched a magic number. No more content needed. if (type_hint == "application/octet-stream") return have_enough_content; if (SniffForMagicNumbers(content, content_size, &have_enough_content, result)) return true; // We've matched a magic number. No more content needed. return have_enough_content; } CWE ID: Target: 1 Example 2: Code: static void reg_combine_min_max(struct bpf_reg_state *true_src, struct bpf_reg_state *true_dst, struct bpf_reg_state *false_src, struct bpf_reg_state *false_dst, u8 opcode) { switch (opcode) { case BPF_JEQ: __reg_combine_min_max(true_src, true_dst); break; case BPF_JNE: __reg_combine_min_max(false_src, false_dst); break; } } 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 BrowserView::TabDetachedAt(TabContents* contents, int index) { if (index == browser_->active_index()) { contents_container_->SetWebContents(NULL); infobar_container_->ChangeTabContents(NULL); UpdateDevToolsForContents(NULL); } } 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: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode) { struct sshbuf *b = NULL; struct sshcomp *comp; struct sshenc *enc; struct sshmac *mac; struct newkeys *newkey = NULL; size_t keylen, ivlen, maclen; int r; if ((newkey = calloc(1, sizeof(*newkey))) == NULL) { r = SSH_ERR_ALLOC_FAIL; goto out; } if ((r = sshbuf_froms(m, &b)) != 0) goto out; #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif enc = &newkey->enc; mac = &newkey->mac; comp = &newkey->comp; if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 || (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 || (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 || (r = sshbuf_get_u32(b, &enc->block_size)) != 0 || (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 || (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0) goto out; if (cipher_authlen(enc->cipher) == 0) { if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0) goto out; if ((r = mac_setup(mac, mac->name)) != 0) goto out; if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 || (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0) goto out; if (maclen > mac->key_len) { r = SSH_ERR_INVALID_FORMAT; goto out; } mac->key_len = maclen; } if ((r = sshbuf_get_u32(b, &comp->type)) != 0 || (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 || (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0) goto out; if (enc->name == NULL || cipher_by_name(enc->name) != enc->cipher) { r = SSH_ERR_INVALID_FORMAT; goto out; } if (sshbuf_len(b) != 0) { r = SSH_ERR_INVALID_FORMAT; goto out; } enc->key_len = keylen; enc->iv_len = ivlen; ssh->kex->newkeys[mode] = newkey; newkey = NULL; r = 0; out: free(newkey); sshbuf_free(b); return r; } CWE ID: CWE-119 Target: 1 Example 2: Code: void Camera3Device::setErrorStateLocked(const char *fmt, ...) { va_list args; va_start(args, fmt); setErrorStateLockedV(fmt, args); va_end(args); } 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: ScopedTextureBinder::ScopedTextureBinder(ContextState* state, GLuint id, GLenum target) : state_(state), target_(target) { ScopedGLErrorSuppressor suppressor( "ScopedTextureBinder::ctor", state_->GetErrorState()); glActiveTexture(GL_TEXTURE0); glBindTexture(target, id); } 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 irqreturn_t i8042_interrupt(int irq, void *dev_id) { struct i8042_port *port; struct serio *serio; unsigned long flags; unsigned char str, data; unsigned int dfl; unsigned int port_no; bool filtered; int ret = 1; spin_lock_irqsave(&i8042_lock, flags); str = i8042_read_status(); if (unlikely(~str & I8042_STR_OBF)) { spin_unlock_irqrestore(&i8042_lock, flags); if (irq) dbg("Interrupt %d, without any data\n", irq); ret = 0; goto out; } data = i8042_read_data(); if (i8042_mux_present && (str & I8042_STR_AUXDATA)) { static unsigned long last_transmit; static unsigned char last_str; dfl = 0; if (str & I8042_STR_MUXERR) { dbg("MUX error, status is %02x, data is %02x\n", str, data); /* * When MUXERR condition is signalled the data register can only contain * 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately * it is not always the case. Some KBCs also report 0xfc when there is * nothing connected to the port while others sometimes get confused which * port the data came from and signal error leaving the data intact. They * _do not_ revert to legacy mode (actually I've never seen KBC reverting * to legacy mode yet, when we see one we'll add proper handling). * Anyway, we process 0xfc, 0xfd, 0xfe and 0xff as timeouts, and for the * rest assume that the data came from the same serio last byte * was transmitted (if transmission happened not too long ago). */ switch (data) { default: if (time_before(jiffies, last_transmit + HZ/10)) { str = last_str; break; } /* fall through - report timeout */ case 0xfc: case 0xfd: case 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break; case 0xff: dfl = SERIO_PARITY; data = 0xfe; break; } } port_no = I8042_MUX_PORT_NO + ((str >> 6) & 3); last_str = str; last_transmit = jiffies; } else { dfl = ((str & I8042_STR_PARITY) ? SERIO_PARITY : 0) | ((str & I8042_STR_TIMEOUT && !i8042_notimeout) ? SERIO_TIMEOUT : 0); port_no = (str & I8042_STR_AUXDATA) ? I8042_AUX_PORT_NO : I8042_KBD_PORT_NO; } port = &i8042_ports[port_no]; serio = port->exists ? port->serio : NULL; filter_dbg(port->driver_bound, data, "<- i8042 (interrupt, %d, %d%s%s)\n", port_no, irq, dfl & SERIO_PARITY ? ", bad parity" : "", dfl & SERIO_TIMEOUT ? ", timeout" : ""); filtered = i8042_filter(data, str, serio); spin_unlock_irqrestore(&i8042_lock, flags); if (likely(port->exists && !filtered)) serio_interrupt(serio, data, dfl); out: return IRQ_RETVAL(ret); } CWE ID: CWE-476 Target: 1 Example 2: Code: void RenderFrameImpl::DispatchLoad() { Send(new FrameHostMsg_DispatchLoad(routing_id_)); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void server_connect_ref(SERVER_CONNECT_REC *conn) { conn->refcount++; } 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 find_high_bit(unsigned int x) { int i; for(i=31;i>=0;i--) { if(x&(1<<i)) return i; } return 0; } CWE ID: CWE-682 Target: 1 Example 2: Code: void LayoutBlockFlow::positionSpannerDescendant(LayoutMultiColumnSpannerPlaceholder& child) { LayoutBox& spanner = *child.layoutObjectInFlowThread(); setLogicalTopForChild(spanner, child.logicalTop()); determineLogicalLeftPositionForChild(spanner); } CWE ID: CWE-22 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ip_vs_lookup_dest(struct ip_vs_service *svc, const union nf_inet_addr *daddr, __be16 dport) { struct ip_vs_dest *dest; /* * Find the destination for the given service */ list_for_each_entry(dest, &svc->destinations, n_list) { if ((dest->af == svc->af) && ip_vs_addr_equal(svc->af, &dest->addr, daddr) && (dest->port == dport)) { /* HIT */ return dest; } } return NULL; } 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: PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_TD_ARG array_init(return_value); key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); } CWE ID: CWE-190 Target: 1 Example 2: Code: mrb_mod_const_get(mrb_state *mrb, mrb_value mod) { mrb_value path; mrb_sym id; char *ptr; mrb_int off, end, len; mrb_get_args(mrb, "o", &path); if (mrb_symbol_p(path)) { /* const get with symbol */ id = mrb_symbol(path); return mrb_const_get_sym(mrb, mod, id); } /* const get with class path string */ path = mrb_string_type(mrb, path); ptr = RSTRING_PTR(path); len = RSTRING_LEN(path); off = 0; while (off < len) { end = mrb_str_index_lit(mrb, path, "::", off); end = (end == -1) ? len : end; id = mrb_intern(mrb, ptr+off, end-off); mod = mrb_const_get_sym(mrb, mod, id); off = (end == len) ? end : end+2; } return mod; } 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: check_rpcsec_auth(struct svc_req *rqstp) { gss_ctx_id_t ctx; krb5_context kctx; OM_uint32 maj_stat, min_stat; gss_name_t name; krb5_principal princ; int ret, success; krb5_data *c1, *c2, *realm; gss_buffer_desc gss_str; kadm5_server_handle_t handle; size_t slen; char *sdots; success = 0; handle = (kadm5_server_handle_t)global_server_handle; if (rqstp->rq_cred.oa_flavor != RPCSEC_GSS) return 0; ctx = rqstp->rq_svccred; maj_stat = gss_inquire_context(&min_stat, ctx, NULL, &name, NULL, NULL, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) { krb5_klog_syslog(LOG_ERR, _("check_rpcsec_auth: failed " "inquire_context, stat=%u"), maj_stat); log_badauth(maj_stat, min_stat, rqstp->rq_xprt, NULL); goto fail_name; } kctx = handle->context; ret = gss_to_krb5_name_1(rqstp, kctx, name, &princ, &gss_str); if (ret == 0) goto fail_name; slen = gss_str.length; trunc_name(&slen, &sdots); /* * Since we accept with GSS_C_NO_NAME, the client can authenticate * against the entire kdb. Therefore, ensure that the service * name is something reasonable. */ if (krb5_princ_size(kctx, princ) != 2) goto fail_princ; c1 = krb5_princ_component(kctx, princ, 0); c2 = krb5_princ_component(kctx, princ, 1); realm = krb5_princ_realm(kctx, princ); if (strncmp(handle->params.realm, realm->data, realm->length) == 0 && strncmp("kadmin", c1->data, c1->length) == 0) { if (strncmp("history", c2->data, c2->length) == 0) goto fail_princ; else success = 1; } fail_princ: if (!success) { krb5_klog_syslog(LOG_ERR, _("bad service principal %.*s%s"), (int) slen, (char *) gss_str.value, sdots); } gss_release_buffer(&min_stat, &gss_str); krb5_free_principal(kctx, princ); fail_name: gss_release_name(&min_stat, &name); return success; } CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, int64_t i0, int i1, int w0, int w1, int w2) { pdf_xref_entry *table; pdf_xref_entry *table; int i, n; if (i0 < 0 || i1 < 0 || i0 > INT_MAX - i1) fz_throw(ctx, FZ_ERROR_GENERIC, "negative xref stream entry index"); table = pdf_xref_find_subsection(ctx, doc, i0, i1); for (i = i0; i < i0 + i1; i++) for (i = i0; i < i0 + i1; i++) { pdf_xref_entry *entry = &table[i-i0]; int a = 0; int64_t b = 0; int c = 0; if (fz_is_eof(ctx, stm)) fz_throw(ctx, FZ_ERROR_GENERIC, "truncated xref stream"); for (n = 0; n < w0; n++) a = (a << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w1; n++) b = (b << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w2; n++) c = (c << 8) + fz_read_byte(ctx, stm); if (!entry->type) { int t = w0 ? a : 1; entry->type = t == 0 ? 'f' : t == 1 ? 'n' : t == 2 ? 'o' : 0; entry->ofs = w1 ? b : 0; entry->gen = w2 ? c : 0; entry->num = i; } } doc->has_xref_streams = 1; } CWE ID: CWE-119 Target: 1 Example 2: Code: void HTMLInputElement::setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionCode& ec) { if (!canHaveSelection()) { ec = INVALID_STATE_ERR; return; } HTMLTextFormControlElement::setSelectionRange(start, end, direction); } 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 RenderViewHostImpl::LostCapture() { RenderWidgetHostImpl::LostCapture(); delegate_->LostCapture(); } 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 NavigateToUrlWithEdge(const base::string16& url) { base::string16 protocol_url = L"microsoft-edge:" + url; SHELLEXECUTEINFO info = { sizeof(info) }; info.fMask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI; info.lpVerb = L"open"; info.lpFile = protocol_url.c_str(); info.nShow = SW_SHOWNORMAL; if (::ShellExecuteEx(&info)) return true; PLOG(ERROR) << "Failed to launch Edge for uninstall survey"; return false; } CWE ID: CWE-20 Target: 1 Example 2: Code: bool ExtensionInstallDialogView::Cancel() { if (handled_result_) return true; handled_result_ = true; UpdateInstallResultHistogram(false); if (sampling_event_) sampling_event_->CreateUserDecisionEvent(ExperienceSamplingEvent::kDeny); base::ResetAndReturn(&done_callback_) .Run(ExtensionInstallPrompt::Result::USER_CANCELED); return true; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); } 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 uhid_write(int fd, const struct uhid_event *ev) { ssize_t ret = write(fd, ev, sizeof(*ev)); if (ret < 0){ int rtn = -errno; APPL_TRACE_ERROR("%s: Cannot write to uhid:%s", __FUNCTION__, strerror(errno)); return rtn; } else if (ret != (ssize_t)sizeof(*ev)) { APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu", __FUNCTION__, ret, sizeof(*ev)); return -EFAULT; } return 0; } CWE ID: CWE-284 Target: 1 Example 2: Code: bgr2g(fz_context *ctx, fz_color_converter *cc, float *dv, const float *sv) { dv[0] = sv[0] * 0.11f + sv[1] * 0.59f + sv[2] * 0.3f; } 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 ehci_trace_itd(EHCIState *s, hwaddr addr, EHCIitd *itd) { trace_usb_ehci_itd(addr, itd->next, get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT), get_field(itd->bufptr[2], ITD_BUFPTR_MULT), get_field(itd->bufptr[0], ITD_BUFPTR_EP), get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR)); } CWE ID: CWE-772 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; } CWE ID: CWE-20 Target: 1 Example 2: Code: void vrend_set_blend_color(struct vrend_context *ctx, struct pipe_blend_color *color) { ctx->sub->blend_color = *color; glBlendColor(color->color[0], color->color[1], color->color[2], color->color[3]); } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WORK_STATE ossl_statem_server_pre_work(SSL *s, WORK_STATE wst) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { case TLS_ST_SW_HELLO_REQ: s->shutdown = 0; if (SSL_IS_DTLS(s)) dtls1_clear_record_buffer(s); break; case DTLS_ST_SW_HELLO_VERIFY_REQUEST: s->shutdown = 0; if (SSL_IS_DTLS(s)) { dtls1_clear_record_buffer(s); /* We don't buffer this message so don't use the timer */ st->use_timer = 0; } break; case TLS_ST_SW_SRVR_HELLO: if (SSL_IS_DTLS(s)) { /* * Messages we write from now on should be bufferred and * retransmitted if necessary, so we need to use the timer now */ st->use_timer = 1; } break; case TLS_ST_SW_SRVR_DONE: #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) return dtls_wait_for_dry(s); #endif return WORK_FINISHED_CONTINUE; case TLS_ST_SW_SESSION_TICKET: if (SSL_IS_DTLS(s)) { /* * We're into the last flight. We don't retransmit the last flight * unless we need to, so we don't use the timer */ st->use_timer = 0; } break; case TLS_ST_SW_CHANGE: s->session->cipher = s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ossl_statem_set_error(s); return WORK_ERROR; } if (SSL_IS_DTLS(s)) { /* * We're into the last flight. We don't retransmit the last flight * unless we need to, so we don't use the timer. This might have * already been set to 0 if we sent a NewSessionTicket message, * but we'll set it again here in case we didn't. */ st->use_timer = 0; } return WORK_FINISHED_CONTINUE; case TLS_ST_OK: return tls_finish_handshake(s, wst); default: /* No pre work to be done */ break; } return WORK_FINISHED_CONTINUE; } 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 numtostr(js_State *J, const char *fmt, int w, double n) { char buf[32], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, "e%+d", exp); } js_pushstring(J, buf); } CWE ID: CWE-119 Target: 1 Example 2: Code: WebString WebLocalFrameImpl::SelectionAsText() const { DCHECK(GetFrame()); WebPluginContainerImpl* plugin_container = GetFrame()->GetWebPluginContainer(); if (plugin_container) return plugin_container->Plugin()->SelectionAsText(); GetFrame()->GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); String text = GetFrame()->Selection().SelectedText( TextIteratorBehavior::EmitsObjectReplacementCharacterBehavior()); #if defined(OS_WIN) ReplaceNewlinesWithWindowsStyleNewlines(text); #endif ReplaceNBSPWithSpace(text); return text; } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: fn_printn(netdissect_options *ndo, register const u_char *s, register u_int n, register const u_char *ep) { register u_char c; while (n > 0 && (ep == NULL || s < ep)) { n--; c = *s++; if (!ND_ISASCII(c)) { c = ND_TOASCII(c); ND_PRINT((ndo, "M-")); } if (!ND_ISPRINT(c)) { c ^= 0x40; /* DEL to ?, others to alpha */ ND_PRINT((ndo, "^")); } ND_PRINT((ndo, "%c", c)); } return (n == 0) ? 0 : 1; } 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: read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof, char *errbuf) { size_t amt_read; amt_read = fread(buf, 1, bytes_to_read, fp); if (amt_read != bytes_to_read) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); } else { if (amt_read == 0 && !fail_on_eof) return (0); /* EOF */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "truncated dump file; tried to read %" PRIsize " bytes, only got %" PRIsize, bytes_to_read, amt_read); } return (-1); } return (1); } CWE ID: CWE-20 Target: 1 Example 2: Code: static struct sk_buff *tun_alloc_skb(struct tun_file *tfile, size_t prepad, size_t len, size_t linear, int noblock) { struct sock *sk = tfile->socket.sk; struct sk_buff *skb; int err; /* Under a page? Don't bother with paged skb. */ if (prepad + len < PAGE_SIZE || !linear) linear = len; skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock, &err, 0); if (!skb) return ERR_PTR(err); skb_reserve(skb, prepad); skb_put(skb, linear); skb->data_len = len - linear; skb->len += len - linear; return skb; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) { visitor->Trace(factory_); visitor->Trace(resolver_); visitor->Trace(options_); } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct rds_connection *__rds_conn_create(struct net *net, __be32 laddr, __be32 faddr, struct rds_transport *trans, gfp_t gfp, int is_outgoing) { struct rds_connection *conn, *parent = NULL; struct hlist_head *head = rds_conn_bucket(laddr, faddr); struct rds_transport *loop_trans; unsigned long flags; int ret; struct rds_transport *otrans = trans; if (!is_outgoing && otrans->t_type == RDS_TRANS_TCP) goto new_conn; rcu_read_lock(); conn = rds_conn_lookup(net, head, laddr, faddr, trans); if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport && laddr == faddr && !is_outgoing) { /* This is a looped back IB connection, and we're * called by the code handling the incoming connect. * We need a second connection object into which we * can stick the other QP. */ parent = conn; conn = parent->c_passive; } rcu_read_unlock(); if (conn) goto out; new_conn: conn = kmem_cache_zalloc(rds_conn_slab, gfp); if (!conn) { conn = ERR_PTR(-ENOMEM); goto out; } INIT_HLIST_NODE(&conn->c_hash_node); conn->c_laddr = laddr; conn->c_faddr = faddr; spin_lock_init(&conn->c_lock); conn->c_next_tx_seq = 1; rds_conn_net_set(conn, net); init_waitqueue_head(&conn->c_waitq); INIT_LIST_HEAD(&conn->c_send_queue); INIT_LIST_HEAD(&conn->c_retrans); ret = rds_cong_get_maps(conn); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } /* * This is where a connection becomes loopback. If *any* RDS sockets * can bind to the destination address then we'd rather the messages * flow through loopback rather than either transport. */ loop_trans = rds_trans_get_preferred(net, faddr); if (loop_trans) { rds_trans_put(loop_trans); conn->c_loopback = 1; if (is_outgoing && trans->t_prefer_loopback) { /* "outgoing" connection - and the transport * says it wants the connection handled by the * loopback transport. This is what TCP does. */ trans = &rds_loop_transport; } } conn->c_trans = trans; ret = trans->conn_alloc(conn, gfp); if (ret) { kmem_cache_free(rds_conn_slab, conn); conn = ERR_PTR(ret); goto out; } atomic_set(&conn->c_state, RDS_CONN_DOWN); conn->c_send_gen = 0; conn->c_reconnect_jiffies = 0; INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker); INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker); INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker); INIT_WORK(&conn->c_down_w, rds_shutdown_worker); mutex_init(&conn->c_cm_lock); conn->c_flags = 0; rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n", conn, &laddr, &faddr, trans->t_name ? trans->t_name : "[unknown]", is_outgoing ? "(outgoing)" : ""); /* * Since we ran without holding the conn lock, someone could * have created the same conn (either normal or passive) in the * interim. We check while holding the lock. If we won, we complete * init and return our conn. If we lost, we rollback and return the * other one. */ spin_lock_irqsave(&rds_conn_lock, flags); if (parent) { /* Creating passive conn */ if (parent->c_passive) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = parent->c_passive; } else { parent->c_passive = conn; rds_cong_add_conn(conn); rds_conn_count++; } } else { /* Creating normal conn */ struct rds_connection *found; if (!is_outgoing && otrans->t_type == RDS_TRANS_TCP) found = NULL; else found = rds_conn_lookup(net, head, laddr, faddr, trans); if (found) { trans->conn_free(conn->c_transport_data); kmem_cache_free(rds_conn_slab, conn); conn = found; } else { if ((is_outgoing && otrans->t_type == RDS_TRANS_TCP) || (otrans->t_type != RDS_TRANS_TCP)) { /* Only the active side should be added to * reconnect list for TCP. */ hlist_add_head_rcu(&conn->c_hash_node, head); } rds_cong_add_conn(conn); rds_conn_count++; } } spin_unlock_irqrestore(&rds_conn_lock, flags); out: return conn; } CWE ID: Target: 1 Example 2: Code: static _Bool check_notify_received (const notification_t *n) /* {{{ */ { notification_meta_t *ptr; for (ptr = n->meta; ptr != NULL; ptr = ptr->next) if ((strcmp ("network:received", ptr->name) == 0) && (ptr->type == NM_TYPE_BOOLEAN)) return ((_Bool) ptr->nm_value.nm_boolean); return (0); } /* }}} _Bool check_notify_received */ CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BluetoothOptionsHandler::GenerateFakeDeviceList() { GenerateFakeDiscoveredDevice( "Fake Wireless Keyboard", "01-02-03-04-05-06", "input-keyboard", true, true); GenerateFakeDiscoveredDevice( "Fake Wireless Mouse", "02-03-04-05-06-01", "input-mouse", true, false); GenerateFakeDiscoveredDevice( "Fake Wireless Headset", "03-04-05-06-01-02", "headset", false, false); GenerateFakePairing( "Fake Connecting Keyboard", "04-05-06-01-02-03", "input-keyboard", "bluetoothRemotePasskey"); GenerateFakePairing( "Fake Connecting Phone", "05-06-01-02-03-04", "phone", "bluetoothConfirmPasskey"); GenerateFakePairing( "Fake Connecting Headset", "06-01-02-03-04-05", "headset", "bluetoothEnterPasskey"); web_ui_->CallJavascriptFunction( "options.SystemOptions.notifyBluetoothSearchComplete"); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct sco_options opts; struct sco_conninfo cinfo; int len, err = 0; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case SCO_OPTIONS: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } opts.mtu = sco_pi(sk)->conn->mtu; BT_DBG("mtu %d", opts.mtu); len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *)&opts, len)) err = -EFAULT; break; case SCO_CONNINFO: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } cinfo.hci_handle = sco_pi(sk)->conn->hcon->handle; memcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *)&cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } CWE ID: CWE-200 Target: 1 Example 2: Code: static HashTable *row_get_properties(zval *object TSRMLS_DC) { pdo_stmt_t * stmt = (pdo_stmt_t *) zend_object_store_get_object(object TSRMLS_CC); int i; if (stmt == NULL) { return NULL; } if (!stmt->std.properties) { rebuild_object_properties(&stmt->std); } for (i = 0; i < stmt->column_count; i++) { zval *val; MAKE_STD_ZVAL(val); fetch_value(stmt, val, i, NULL TSRMLS_CC); zend_hash_update(stmt->std.properties, stmt->columns[i].name, stmt->columns[i].namelen + 1, (void *)&val, sizeof(zval *), NULL); } return stmt->std.properties; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void handle_ld_nf(u32 insn, struct pt_regs *regs) { int rd = ((insn >> 25) & 0x1f); int from_kernel = (regs->tstate & TSTATE_PRIV) != 0; unsigned long *reg; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); maybe_flush_windows(0, 0, rd, from_kernel); reg = fetch_reg_addr(rd, regs); if (from_kernel || rd < 16) { reg[0] = 0; if ((insn & 0x780000) == 0x180000) reg[1] = 0; } else if (test_thread_flag(TIF_32BIT)) { put_user(0, (int __user *) reg); if ((insn & 0x780000) == 0x180000) put_user(0, ((int __user *) reg) + 1); } else { put_user(0, (unsigned long __user *) reg); if ((insn & 0x780000) == 0x180000) put_user(0, (unsigned long __user *) reg + 1); } advance(regs); } 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 PrintPreviewUI::GetPrintPreviewDataForIndex( int index, scoped_refptr<base::RefCountedBytes>* data) { print_preview_data_service()->GetDataEntry(preview_ui_addr_str_, index, data); } CWE ID: CWE-200 Target: 1 Example 2: Code: X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx) { return ctx->param; } 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: xsltCopyTextString(xsltTransformContextPtr ctxt, xmlNodePtr target, const xmlChar *string, int noescape) { xmlNodePtr copy; int len; if (string == NULL) return(NULL); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_TEXT,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyTextString: copy text %s\n", string)); #endif /* * Play safe and reset the merging mechanism for every new * target node. */ if ((target == NULL) || (target->children == NULL)) { ctxt->lasttext = NULL; } /* handle coalescing of text nodes here */ len = xmlStrlen(string); if ((ctxt->type == XSLT_OUTPUT_XML) && (ctxt->style->cdataSection != NULL) && (target != NULL) && (target->type == XML_ELEMENT_NODE) && (((target->ns == NULL) && (xmlHashLookup2(ctxt->style->cdataSection, target->name, NULL) != NULL)) || ((target->ns != NULL) && (xmlHashLookup2(ctxt->style->cdataSection, target->name, target->ns->href) != NULL)))) { /* * Process "cdata-section-elements". */ if ((target->last != NULL) && (target->last->type == XML_CDATA_SECTION_NODE)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewCDataBlock(ctxt->output, string, len); } else if (noescape) { /* * Process "disable-output-escaping". */ if ((target != NULL) && (target->last != NULL) && (target->last->type == XML_TEXT_NODE) && (target->last->name == xmlStringTextNoenc)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewTextLen(string, len); if (copy != NULL) copy->name = xmlStringTextNoenc; } else { /* * Default processing. */ if ((target != NULL) && (target->last != NULL) && (target->last->type == XML_TEXT_NODE) && (target->last->name == xmlStringText)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewTextLen(string, len); } if (copy != NULL) { if (target != NULL) copy = xsltAddChild(target, copy); ctxt->lasttext = copy->content; ctxt->lasttsize = len; ctxt->lasttuse = len; } else { xsltTransformError(ctxt, NULL, target, "xsltCopyTextString: text copy failed\n"); ctxt->lasttext = NULL; } return(copy); } 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 ssl_set_client_disabled(SSL *s) { CERT *c = s->cert; c->mask_a = 0; c->mask_k = 0; /* Don't allow TLS 1.2 only ciphers if we don't suppport them */ if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s)) c->mask_ssl = SSL_TLSV1_2; else c->mask_ssl = 0; ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK); /* Disable static DH if we don't include any appropriate * signature algorithms. */ if (c->mask_a & SSL_aRSA) c->mask_k |= SSL_kDHr|SSL_kECDHr; if (c->mask_a & SSL_aDSS) c->mask_k |= SSL_kDHd; if (c->mask_a & SSL_aECDSA) c->mask_k |= SSL_kECDHe; #ifndef OPENSSL_NO_KRB5 if (!kssl_tgt_is_available(s->kssl_ctx)) { c->mask_a |= SSL_aKRB5; c->mask_k |= SSL_kKRB5; } #endif #ifndef OPENSSL_NO_PSK /* with PSK there must be client callback set */ if (!s->psk_client_callback) { c->mask_a |= SSL_aPSK; c->mask_k |= SSL_kPSK; } #endif /* OPENSSL_NO_PSK */ c->valid = 1; } CWE ID: Target: 1 Example 2: Code: static int test_same_origin(const char *src, const char *ref) { char src_proto[64]; char ref_proto[64]; char src_auth[256]; char ref_auth[256]; char src_host[256]; char ref_host[256]; int src_port=-1; int ref_port=-1; av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src); av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref); if (strlen(src) == 0) { return -1; } else if (strlen(src_auth) + 1 >= sizeof(src_auth) || strlen(ref_auth) + 1 >= sizeof(ref_auth) || strlen(src_host) + 1 >= sizeof(src_host) || strlen(ref_host) + 1 >= sizeof(ref_host)) { return 0; } else if (strcmp(src_proto, ref_proto) || strcmp(src_auth, ref_auth) || strcmp(src_host, ref_host) || src_port != ref_port) { return 0; } else return 1; } CWE ID: CWE-834 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameImpl::OnFindMatchRects(int current_version) { std::vector<gfx::RectF> match_rects; int rects_version = frame_->FindMatchMarkersVersion(); if (current_version != rects_version) { WebVector<WebFloatRect> web_match_rects; frame_->FindMatchRects(web_match_rects); match_rects.reserve(web_match_rects.size()); for (size_t i = 0; i < web_match_rects.size(); ++i) match_rects.push_back(gfx::RectF(web_match_rects[i])); } gfx::RectF active_rect = frame_->ActiveFindMatchRect(); Send(new FrameHostMsg_FindMatchRects_Reply(routing_id_, rects_version, match_rects, active_rect)); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BluetoothDeviceChromeOS::OnPairError( const ConnectErrorCallback& error_callback, const std::string& error_name, const std::string& error_message) { if (--num_connecting_calls_ == 0) adapter_->NotifyDeviceChanged(this); DCHECK(num_connecting_calls_ >= 0); LOG(WARNING) << object_path_.value() << ": Failed to pair device: " << error_name << ": " << error_message; VLOG(1) << object_path_.value() << ": " << num_connecting_calls_ << " still in progress"; UnregisterAgent(); ConnectErrorCode error_code = ERROR_UNKNOWN; if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationFailed) { error_code = ERROR_AUTH_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) { error_code = ERROR_AUTH_CANCELED; } else if (error_name == bluetooth_device::kErrorAuthenticationRejected) { error_code = ERROR_AUTH_REJECTED; } else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) { error_code = ERROR_AUTH_TIMEOUT; } RecordPairingResult(error_code); error_callback.Run(error_code); } CWE ID: Target: 1 Example 2: Code: void MediaStreamManager::HandleAccessRequestResponse( const std::string& label, const media::AudioParameters& output_parameters, const MediaStreamDevices& devices, MediaStreamRequestResult result) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "HandleAccessRequestResponse(" << ", {label = " << label << "})"; DeviceRequest* request = FindRequest(label); if (!request) { return; } if (request->request_type == MEDIA_DEVICE_ACCESS) { FinalizeMediaAccessRequest(label, request, devices); return; } if (result != MEDIA_DEVICE_OK) { FinalizeRequestFailed(label, request, result); return; } DCHECK(!devices.empty()); bool found_audio = false; bool found_video = false; for (const MediaStreamDevice& media_stream_device : devices) { MediaStreamDevice device = media_stream_device; if (device.type == MEDIA_TAB_VIDEO_CAPTURE || device.type == MEDIA_TAB_AUDIO_CAPTURE) { device.id = request->tab_capture_device_id; } if (device.type == MEDIA_TAB_AUDIO_CAPTURE || device.type == MEDIA_DESKTOP_AUDIO_CAPTURE) { int sample_rate = output_parameters.sample_rate(); if (sample_rate <= 0 || sample_rate > 96000) sample_rate = 44100; media::AudioParameters params( device.input.format(), media::CHANNEL_LAYOUT_STEREO, sample_rate, device.input.bits_per_sample(), device.input.frames_per_buffer()); params.set_effects(device.input.effects()); params.set_mic_positions(device.input.mic_positions()); DCHECK(params.IsValid()); device.input = params; } if (device.type == request->audio_type()) found_audio = true; else if (device.type == request->video_type()) found_video = true; if (request->request_type == MEDIA_GENERATE_STREAM) { MediaRequestState state; if (FindExistingRequestedDevice(*request, device, &device, &state)) { request->devices.push_back(device); request->SetState(device.type, state); DVLOG(1) << "HandleAccessRequestResponse - device already opened " << ", {label = " << label << "}" << ", device_id = " << device.id << "}"; continue; } } device.session_id = GetDeviceManager(device.type)->Open(device); TranslateDeviceIdToSourceId(request, &device); request->devices.push_back(device); request->SetState(device.type, MEDIA_REQUEST_STATE_OPENING); DVLOG(1) << "HandleAccessRequestResponse - opening device " << ", {label = " << label << "}" << ", {device_id = " << device.id << "}" << ", {session_id = " << device.session_id << "}"; } 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: u32 h264bsdActivateParamSets(storage_t *pStorage, u32 ppsId, u32 isIdr) { /* Variables */ u32 tmp; u32 flag; /* Code */ ASSERT(pStorage); ASSERT(ppsId < MAX_NUM_PIC_PARAM_SETS); /* check that pps and corresponding sps exist */ if ( (pStorage->pps[ppsId] == NULL) || (pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId] == NULL) ) { return(HANTRO_NOK); } /* check that pps parameters do not violate picture size constraints */ tmp = CheckPps(pStorage->pps[ppsId], pStorage->sps[pStorage->pps[ppsId]->seqParameterSetId]); if (tmp != HANTRO_OK) return(tmp); /* first activation part1 */ if (pStorage->activePpsId == MAX_NUM_PIC_PARAM_SETS) { pStorage->activePpsId = ppsId; pStorage->activePps = pStorage->pps[ppsId]; pStorage->activeSpsId = pStorage->activePps->seqParameterSetId; pStorage->activeSps = pStorage->sps[pStorage->activeSpsId]; pStorage->picSizeInMbs = pStorage->activeSps->picWidthInMbs * pStorage->activeSps->picHeightInMbs; pStorage->currImage->width = pStorage->activeSps->picWidthInMbs; pStorage->currImage->height = pStorage->activeSps->picHeightInMbs; pStorage->pendingActivation = HANTRO_TRUE; } /* first activation part2 */ else if (pStorage->pendingActivation) { pStorage->pendingActivation = HANTRO_FALSE; FREE(pStorage->mb); FREE(pStorage->sliceGroupMap); ALLOCATE(pStorage->mb, pStorage->picSizeInMbs, mbStorage_t); ALLOCATE(pStorage->sliceGroupMap, pStorage->picSizeInMbs, u32); if (pStorage->mb == NULL || pStorage->sliceGroupMap == NULL) return(MEMORY_ALLOCATION_ERROR); H264SwDecMemset(pStorage->mb, 0, pStorage->picSizeInMbs * sizeof(mbStorage_t)); h264bsdInitMbNeighbours(pStorage->mb, pStorage->activeSps->picWidthInMbs, pStorage->picSizeInMbs); /* dpb output reordering disabled if * 1) application set noReordering flag * 2) POC type equal to 2 * 3) num_reorder_frames in vui equal to 0 */ if ( pStorage->noReordering || pStorage->activeSps->picOrderCntType == 2 || (pStorage->activeSps->vuiParametersPresentFlag && pStorage->activeSps->vuiParameters->bitstreamRestrictionFlag && !pStorage->activeSps->vuiParameters->numReorderFrames) ) flag = HANTRO_TRUE; else flag = HANTRO_FALSE; tmp = h264bsdResetDpb(pStorage->dpb, pStorage->activeSps->picWidthInMbs * pStorage->activeSps->picHeightInMbs, pStorage->activeSps->maxDpbSize, pStorage->activeSps->numRefFrames, pStorage->activeSps->maxFrameNum, flag); if (tmp != HANTRO_OK) return(tmp); } else if (ppsId != pStorage->activePpsId) { /* sequence parameter set shall not change but before an IDR picture */ if (pStorage->pps[ppsId]->seqParameterSetId != pStorage->activeSpsId) { DEBUG(("SEQ PARAM SET CHANGING...\n")); if (isIdr) { pStorage->activePpsId = ppsId; pStorage->activePps = pStorage->pps[ppsId]; pStorage->activeSpsId = pStorage->activePps->seqParameterSetId; pStorage->activeSps = pStorage->sps[pStorage->activeSpsId]; pStorage->picSizeInMbs = pStorage->activeSps->picWidthInMbs * pStorage->activeSps->picHeightInMbs; pStorage->currImage->width = pStorage->activeSps->picWidthInMbs; pStorage->currImage->height = pStorage->activeSps->picHeightInMbs; pStorage->pendingActivation = HANTRO_TRUE; } else { DEBUG(("TRYING TO CHANGE SPS IN NON-IDR SLICE\n")); return(HANTRO_NOK); } } else { pStorage->activePpsId = ppsId; pStorage->activePps = pStorage->pps[ppsId]; } } return(HANTRO_OK); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_d_slice(dec_state_t *ps_dec) { UWORD32 i; yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; stream_t *ps_stream = &ps_dec->s_bit_stream; UWORD8 *pu1_vld_buf; WORD16 i2_dc_diff; UWORD32 u4_frame_width = ps_dec->u2_frame_width; UWORD32 u4_frm_offset = 0; if(ps_dec->u2_picture_structure != FRAME_PICTURE) { u4_frame_width <<= 1; if(ps_dec->u2_picture_structure == BOTTOM_FIELD) { u4_frm_offset = ps_dec->u2_frame_width; } } do { UWORD32 u4_x_offset, u4_y_offset; UWORD32 u4_blk_pos; WORD16 i2_dc_val; UWORD32 u4_dst_x_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); UWORD32 u4_dst_y_offset = (ps_dec->u2_mb_y << 4) * u4_frame_width; UWORD8 *pu1_vld_buf8 = ps_cur_frm_buf->pu1_y + u4_dst_x_offset + u4_dst_y_offset; UWORD32 u4_dst_wd = u4_frame_width; /*------------------------------------------------------------------*/ /* Discard the Macroblock stuffing in case of MPEG-1 stream */ /*------------------------------------------------------------------*/ while(impeg2d_bit_stream_nxt(ps_stream,MB_STUFFING_CODE_LEN) == MB_STUFFING_CODE) impeg2d_bit_stream_flush(ps_stream,MB_STUFFING_CODE_LEN); /*------------------------------------------------------------------*/ /* Flush 2 bits from bitstream [MB_Type and MacroBlockAddrIncrement]*/ /*------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,1); if(impeg2d_bit_stream_get(ps_stream, 1) != 0x01) { /* Ignore and continue decoding. */ } /* Process LUMA blocks of the MB */ for(i = 0; i < NUM_LUMA_BLKS; ++i) { u4_x_offset = gai2_impeg2_blk_x_off[i]; u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; u4_blk_pos = (u4_y_offset * u4_dst_wd) + u4_x_offset; pu1_vld_buf = pu1_vld_buf8 + u4_blk_pos; i2_dc_diff = impeg2d_get_luma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[Y_LUMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[Y_LUMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); } /* Process U block of the MB */ u4_dst_x_offset >>= 1; u4_dst_y_offset >>= 2; u4_dst_wd >>= 1; pu1_vld_buf = ps_cur_frm_buf->pu1_u + u4_dst_x_offset + u4_dst_y_offset; i2_dc_diff = impeg2d_get_chroma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[U_CHROMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[U_CHROMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); /* Process V block of the MB */ pu1_vld_buf = ps_cur_frm_buf->pu1_v + u4_dst_x_offset + u4_dst_y_offset; i2_dc_diff = impeg2d_get_chroma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[V_CHROMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[V_CHROMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); /* Common MB processing Steps */ ps_dec->u2_num_mbs_left--; ps_dec->u2_mb_x++; if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) { return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; } else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) { ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y++; } /* Flush end of macro block */ impeg2d_bit_stream_flush(ps_stream,1); } while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }/* End of impeg2d_dec_d_slice() */ CWE ID: CWE-254 Target: 1 Example 2: Code: static int ptrace_getwmmxregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); if (!test_ti_thread_flag(thread, TIF_USING_IWMMXT)) return -ENODATA; iwmmxt_task_disable(thread); /* force it to ram */ return copy_to_user(ufp, &thread->fpstate.iwmmxt, IWMMXT_SIZE) ? -EFAULT : 0; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; if (ps_stream->u4_offset < ps_stream->u4_max_offset) { FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) } return; } 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: AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required) : field_types_(field_types), upload_required_(upload_required) { DCHECK(upload_required_); } CWE ID: CWE-399 Target: 1 Example 2: Code: static LayoutPoint ComputeRelativeOffset(const LayoutObject* layout_object, const ScrollableArea* scroller, Corner corner) { return CornerPointOfRect(RelativeBounds(layout_object, scroller), corner); } 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: std::vector<FilePath> GDataCache::GetCachePaths( const FilePath& cache_root_path) { std::vector<FilePath> cache_paths; cache_paths.push_back(cache_root_path.Append(kGDataCacheMetaDir)); cache_paths.push_back(cache_root_path.Append(kGDataCachePinnedDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheOutgoingDir)); cache_paths.push_back(cache_root_path.Append(kGDataCachePersistentDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDownloadsDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDocumentsDir)); return cache_paths; } 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 LockScreenMediaControlsView::SetArtwork( base::Optional<gfx::ImageSkia> img) { if (!img.has_value()) { session_artwork_->SetImage(nullptr); return; } session_artwork_->SetImageSize(ScaleSizeToFitView( img->size(), gfx::Size(kArtworkViewWidth, kArtworkViewHeight))); session_artwork_->SetImage(*img); } CWE ID: CWE-200 Target: 1 Example 2: Code: static void anyAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValue(info, imp->anyAttribute().v8Value()); } 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: virtual ~PanelWindowResizerTextDirectionTest() {} 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: SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } } CWE ID: CWE-190 Target: 1 Example 2: Code: void GLES2Implementation::DrawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glDrawArraysInstancedANGLE(" << GLES2Util::GetStringDrawMode(mode) << ", " << first << ", " << count << ", " << primcount << ")"); if (count < 0) { SetGLError(GL_INVALID_VALUE, "glDrawArraysInstancedANGLE", "count < 0"); return; } if (primcount < 0) { SetGLError(GL_INVALID_VALUE, "glDrawArraysInstancedANGLE", "primcount < 0"); return; } if (primcount == 0) { return; } bool simulated = false; if (vertex_array_object_manager_->SupportsClientSideBuffers()) { GLsizei num_elements; if (!base::CheckAdd(first, count).AssignIfValid(&num_elements)) { SetGLError(GL_INVALID_VALUE, "glDrawArraysInstancedANGLE", "first+count overflow"); return; } if (!vertex_array_object_manager_->SetupSimulatedClientSideBuffers( "glDrawArraysInstancedANGLE", this, helper_, num_elements, primcount, &simulated)) { return; } } helper_->DrawArraysInstancedANGLE(mode, first, count, primcount); RestoreArrayBuffer(simulated); CheckGLError(); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: cfm_network_addr_print(netdissect_options *ndo, register const u_char *tptr) { u_int network_addr_type; u_int hexdump = FALSE; /* * Altough AFIs are tpically 2 octects wide, * 802.1ab specifies that this field width * is only once octet */ network_addr_type = *tptr; ND_PRINT((ndo, "\n\t Network Address Type %s (%u)", tok2str(af_values, "Unknown", network_addr_type), network_addr_type)); /* * Resolve the passed in Address. */ switch(network_addr_type) { case AFNUM_INET: ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1))); break; case AFNUM_INET6: ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1))); break; default: hexdump = TRUE; break; } return hexdump; } 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 snd_seq_ioctl_remove_events(struct snd_seq_client *client, void __user *arg) { struct snd_seq_remove_events info; if (copy_from_user(&info, arg, sizeof(info))) return -EFAULT; /* * Input mostly not implemented XXX. */ if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) { /* * No restrictions so for a user client we can clear * the whole fifo */ if (client->type == USER_CLIENT) snd_seq_fifo_clear(client->data.user.fifo); } if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT) snd_seq_queue_remove_cells(client->number, &info); return 0; } CWE ID: Target: 1 Example 2: Code: SVGElementSet* SVGElement::SetOfIncomingReferences() const { if (!HasSVGRareData()) return nullptr; return &SvgRareData()->IncomingReferences(); } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t OMXNodeInstance::configureVideoTunnelMode( OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync, native_handle_t **sidebandHandle) { Mutex::Autolock autolock(mLock); CLOG_CONFIG(configureVideoTunnelMode, "%s:%u tun=%d sync=%u", portString(portIndex), portIndex, tunneled, audioHwSync); OMX_INDEXTYPE index; OMX_STRING name = const_cast<OMX_STRING>( "OMX.google.android.index.configureVideoTunnelMode"); OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err != OMX_ErrorNone) { CLOG_ERROR_IF(tunneled, getExtensionIndex, err, "%s", name); return StatusFromOMXError(err); } ConfigureVideoTunnelModeParams tunnelParams; InitOMXParams(&tunnelParams); tunnelParams.nPortIndex = portIndex; tunnelParams.bTunneled = tunneled; tunnelParams.nAudioHwSync = audioHwSync; err = OMX_SetParameter(mHandle, index, &tunnelParams); if (err != OMX_ErrorNone) { CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index, portString(portIndex), portIndex, tunneled, audioHwSync); return StatusFromOMXError(err); } err = OMX_GetParameter(mHandle, index, &tunnelParams); if (err != OMX_ErrorNone) { CLOG_ERROR(getParameter, err, "%s(%#x): %s:%u tun=%d sync=%u", name, index, portString(portIndex), portIndex, tunneled, audioHwSync); return StatusFromOMXError(err); } if (sidebandHandle) { *sidebandHandle = (native_handle_t*)tunnelParams.pSidebandWindow; } return OK; } 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: zephyr_print(netdissect_options *ndo, const u_char *cp, int length) { struct z_packet z; const char *parse = (const char *) cp; int parselen = length; const char *s; int lose = 0; /* squelch compiler warnings */ z.kind = 0; z.class = 0; z.inst = 0; z.opcode = 0; z.sender = 0; z.recipient = 0; #define PARSE_STRING \ s = parse_field(ndo, &parse, &parselen); \ if (!s) lose = 1; #define PARSE_FIELD_INT(field) \ PARSE_STRING \ if (!lose) field = strtol(s, 0, 16); #define PARSE_FIELD_STR(field) \ PARSE_STRING \ if (!lose) field = s; PARSE_FIELD_STR(z.version); if (lose) return; if (strncmp(z.version, "ZEPH", 4)) return; PARSE_FIELD_INT(z.numfields); PARSE_FIELD_INT(z.kind); PARSE_FIELD_STR(z.uid); PARSE_FIELD_INT(z.port); PARSE_FIELD_INT(z.auth); PARSE_FIELD_INT(z.authlen); PARSE_FIELD_STR(z.authdata); PARSE_FIELD_STR(z.class); PARSE_FIELD_STR(z.inst); PARSE_FIELD_STR(z.opcode); PARSE_FIELD_STR(z.sender); PARSE_FIELD_STR(z.recipient); PARSE_FIELD_STR(z.format); PARSE_FIELD_INT(z.cksum); PARSE_FIELD_INT(z.multi); PARSE_FIELD_STR(z.multi_uid); if (lose) { ND_PRINT((ndo, " [|zephyr] (%d)", length)); return; } ND_PRINT((ndo, " zephyr")); if (strncmp(z.version+4, "0.2", 3)) { ND_PRINT((ndo, " v%s", z.version+4)); return; } ND_PRINT((ndo, " %s", tok2str(z_types, "type %d", z.kind))); if (z.kind == Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *ackdata = NULL; PARSE_FIELD_STR(ackdata); if (!lose && strcmp(ackdata, "SENT")) ND_PRINT((ndo, "/%s", str_to_lower(ackdata))); } if (*z.sender) ND_PRINT((ndo, " %s", z.sender)); if (!strcmp(z.class, "USER_LOCATE")) { if (!strcmp(z.opcode, "USER_HIDE")) ND_PRINT((ndo, " hide")); else if (!strcmp(z.opcode, "USER_UNHIDE")) ND_PRINT((ndo, " unhide")); else ND_PRINT((ndo, " locate %s", z.inst)); return; } if (!strcmp(z.class, "ZEPHYR_ADMIN")) { ND_PRINT((ndo, " zephyr-admin %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "ZEPHYR_CTL")) { if (!strcmp(z.inst, "CLIENT")) { if (!strcmp(z.opcode, "SUBSCRIBE") || !strcmp(z.opcode, "SUBSCRIBE_NODEFS") || !strcmp(z.opcode, "UNSUBSCRIBE")) { ND_PRINT((ndo, " %ssub%s", strcmp(z.opcode, "SUBSCRIBE") ? "un" : "", strcmp(z.opcode, "SUBSCRIBE_NODEFS") ? "" : "-nodefs")); if (z.kind != Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *c = NULL, *i = NULL, *r = NULL; PARSE_FIELD_STR(c); PARSE_FIELD_STR(i); PARSE_FIELD_STR(r); if (!lose) ND_PRINT((ndo, " %s", z_triple(c, i, r))); } return; } if (!strcmp(z.opcode, "GIMME")) { ND_PRINT((ndo, " ret")); return; } if (!strcmp(z.opcode, "GIMMEDEFS")) { ND_PRINT((ndo, " gimme-defs")); return; } if (!strcmp(z.opcode, "CLEARSUB")) { ND_PRINT((ndo, " clear-subs")); return; } ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "HM")) { ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "REALM")) { if (!strcmp(z.opcode, "ADD_SUBSCRIBE")) ND_PRINT((ndo, " realm add-subs")); if (!strcmp(z.opcode, "REQ_SUBSCRIBE")) ND_PRINT((ndo, " realm req-subs")); if (!strcmp(z.opcode, "RLM_SUBSCRIBE")) ND_PRINT((ndo, " realm rlm-sub")); if (!strcmp(z.opcode, "RLM_UNSUBSCRIBE")) ND_PRINT((ndo, " realm rlm-unsub")); return; } } if (!strcmp(z.class, "HM_CTL")) { ND_PRINT((ndo, " hm_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "HM_STAT")) { if (!strcmp(z.inst, "HMST_CLIENT") && !strcmp(z.opcode, "GIMMESTATS")) { ND_PRINT((ndo, " get-client-stats")); return; } } if (!strcmp(z.class, "WG_CTL")) { ND_PRINT((ndo, " wg_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "LOGIN")) { if (!strcmp(z.opcode, "USER_FLUSH")) { ND_PRINT((ndo, " flush_locs")); return; } if (!strcmp(z.opcode, "NONE") || !strcmp(z.opcode, "OPSTAFF") || !strcmp(z.opcode, "REALM-VISIBLE") || !strcmp(z.opcode, "REALM-ANNOUNCED") || !strcmp(z.opcode, "NET-VISIBLE") || !strcmp(z.opcode, "NET-ANNOUNCED")) { ND_PRINT((ndo, " set-exposure %s", str_to_lower(z.opcode))); return; } } if (!*z.recipient) z.recipient = "*"; ND_PRINT((ndo, " to %s", z_triple(z.class, z.inst, z.recipient))); if (*z.opcode) ND_PRINT((ndo, " op %s", z.opcode)); } CWE ID: CWE-125 Target: 1 Example 2: Code: static void rcu_free_slab(struct rcu_head *h) { struct page *page; page = container_of((struct list_head *)h, struct page, lru); __free_slab(page->slab, page); } 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 GURL ToAndFromOriginIdentifier(const GURL origin_url) { string16 id = DatabaseUtil::GetOriginIdentifier(origin_url); return DatabaseUtil::GetOriginFromIdentifier(id); } CWE ID: CWE-22 Output:
0