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 inline void VectorClamp(DDSVector4 *value) { value->x = MinF(1.0f,MaxF(0.0f,value->x)); value->y = MinF(1.0f,MaxF(0.0f,value->y)); value->z = MinF(1.0f,MaxF(0.0f,value->z)); value->w = MinF(1.0f,MaxF(0.0f,value->w)); } CWE ID: CWE-20 Target: 1 Example 2: Code: static int index_entry_dup_nocache( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy_nocache(*out, src); return 0; } CWE ID: CWE-415 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __free_session(struct nfsd4_session *ses) { free_session_slots(ses); kfree(ses); } CWE ID: CWE-404 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: crypto_retrieve_X509_sans(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, X509 *cert, krb5_principal **princs_ret, krb5_principal **upn_ret, unsigned char ***dns_ret) { krb5_error_code retval = EINVAL; char buf[DN_BUF_LEN]; int p = 0, u = 0, d = 0, ret = 0, l; krb5_principal *princs = NULL; krb5_principal *upns = NULL; unsigned char **dnss = NULL; unsigned int i, num_found = 0, num_sans = 0; X509_EXTENSION *ext = NULL; GENERAL_NAMES *ialt = NULL; GENERAL_NAME *gen = NULL; if (princs_ret != NULL) *princs_ret = NULL; if (upn_ret != NULL) *upn_ret = NULL; if (dns_ret != NULL) *dns_ret = NULL; if (princs_ret == NULL && upn_ret == NULL && dns_ret == NULL) { pkiDebug("%s: nowhere to return any values!\n", __FUNCTION__); return retval; } if (cert == NULL) { pkiDebug("%s: no certificate!\n", __FUNCTION__); return retval; } X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); pkiDebug("%s: looking for SANs in cert = %s\n", __FUNCTION__, buf); l = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1); if (l < 0) return 0; if (!(ext = X509_get_ext(cert, l)) || !(ialt = X509V3_EXT_d2i(ext))) { pkiDebug("%s: found no subject alt name extensions\n", __FUNCTION__); retval = ENOENT; goto cleanup; } num_sans = sk_GENERAL_NAME_num(ialt); pkiDebug("%s: found %d subject alt name extension(s)\n", __FUNCTION__, num_sans); /* OK, we're likely returning something. Allocate return values */ if (princs_ret != NULL) { princs = calloc(num_sans + 1, sizeof(krb5_principal)); if (princs == NULL) { retval = ENOMEM; goto cleanup; } } if (upn_ret != NULL) { upns = calloc(num_sans + 1, sizeof(krb5_principal)); if (upns == NULL) { retval = ENOMEM; goto cleanup; } } if (dns_ret != NULL) { dnss = calloc(num_sans + 1, sizeof(*dnss)); if (dnss == NULL) { retval = ENOMEM; goto cleanup; } } for (i = 0; i < num_sans; i++) { krb5_data name = { 0, 0, NULL }; gen = sk_GENERAL_NAME_value(ialt, i); switch (gen->type) { case GEN_OTHERNAME: name.length = gen->d.otherName->value->value.sequence->length; name.data = (char *)gen->d.otherName->value->value.sequence->data; if (princs != NULL && OBJ_cmp(plgctx->id_pkinit_san, gen->d.otherName->type_id) == 0) { #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)name.data, name.length, "/tmp/pkinit_san"); #endif ret = k5int_decode_krb5_principal_name(&name, &princs[p]); if (ret) { pkiDebug("%s: failed decoding pkinit san value\n", __FUNCTION__); } else { p++; num_found++; } } else if (upns != NULL && OBJ_cmp(plgctx->id_ms_san_upn, gen->d.otherName->type_id) == 0) { /* Prevent abuse of embedded null characters. */ if (memchr(name.data, '\0', name.length)) break; ret = krb5_parse_name_flags(context, name.data, KRB5_PRINCIPAL_PARSE_ENTERPRISE, &upns[u]); if (ret) { pkiDebug("%s: failed parsing ms-upn san value\n", __FUNCTION__); } else { u++; num_found++; } } else { pkiDebug("%s: unrecognized othername oid in SAN\n", __FUNCTION__); continue; } break; case GEN_DNS: if (dnss != NULL) { /* Prevent abuse of embedded null characters. */ if (memchr(gen->d.dNSName->data, '\0', gen->d.dNSName->length)) break; pkiDebug("%s: found dns name = %s\n", __FUNCTION__, gen->d.dNSName->data); dnss[d] = (unsigned char *) strdup((char *)gen->d.dNSName->data); if (dnss[d] == NULL) { pkiDebug("%s: failed to duplicate dns name\n", __FUNCTION__); } else { d++; num_found++; } } break; default: pkiDebug("%s: SAN type = %d expecting %d\n", __FUNCTION__, gen->type, GEN_OTHERNAME); } } sk_GENERAL_NAME_pop_free(ialt, GENERAL_NAME_free); retval = 0; if (princs) *princs_ret = princs; if (upns) *upn_ret = upns; if (dnss) *dns_ret = dnss; cleanup: if (retval) { if (princs != NULL) { for (i = 0; princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); } if (upns != NULL) { for (i = 0; upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); } if (dnss != NULL) { for (i = 0; dnss[i] != NULL; i++) free(dnss[i]); free(dnss); } } return retval; } CWE ID: CWE-287 Target: 1 Example 2: Code: ExtensionFunction::ResponseAction UsbControlTransferFunction::Run() { scoped_ptr<extensions::core_api::usb::ControlTransfer::Params> parameters = ControlTransfer::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(parameters.get()); scoped_refptr<UsbDeviceHandle> device_handle = GetDeviceHandle(parameters->handle); if (!device_handle.get()) { return RespondNow(Error(kErrorNoConnection)); } const ControlTransferInfo& transfer = parameters->transfer_info; UsbEndpointDirection direction; UsbDeviceHandle::TransferRequestType request_type; UsbDeviceHandle::TransferRecipient recipient; size_t size = 0; if (!ConvertDirectionFromApi(transfer.direction, &direction)) { return RespondNow(Error(kErrorConvertDirection)); } if (!ConvertRequestTypeFromApi(transfer.request_type, &request_type)) { return RespondNow(Error(kErrorConvertRequestType)); } if (!ConvertRecipientFromApi(transfer.recipient, &recipient)) { return RespondNow(Error(kErrorConvertRecipient)); } if (!GetTransferSize(transfer, &size)) { return RespondNow(Error(kErrorInvalidTransferLength)); } scoped_refptr<net::IOBuffer> buffer = CreateBufferForTransfer(transfer, direction, size); if (!buffer.get()) { return RespondNow(Error(kErrorMalformedParameters)); } int timeout = transfer.timeout ? *transfer.timeout : 0; if (timeout < 0) { return RespondNow(Error(kErrorInvalidTimeout)); } device_handle->ControlTransfer( direction, request_type, recipient, transfer.request, transfer.value, transfer.index, buffer.get(), size, timeout, base::Bind(&UsbControlTransferFunction::OnCompleted, this)); return RespondLater(); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool __skb_csum_offload_chk(struct sk_buff *skb, const struct skb_csum_offl_spec *spec, bool *csum_encapped, bool csum_help) { struct iphdr *iph; struct ipv6hdr *ipv6; void *nhdr; int protocol; u8 ip_proto; if (skb->protocol == htons(ETH_P_8021Q) || skb->protocol == htons(ETH_P_8021AD)) { if (!spec->vlan_okay) goto need_help; } /* We check whether the checksum refers to a transport layer checksum in * the outermost header or an encapsulated transport layer checksum that * corresponds to the inner headers of the skb. If the checksum is for * something else in the packet we need help. */ if (skb_checksum_start_offset(skb) == skb_transport_offset(skb)) { /* Non-encapsulated checksum */ protocol = eproto_to_ipproto(vlan_get_protocol(skb)); nhdr = skb_network_header(skb); *csum_encapped = false; if (spec->no_not_encapped) goto need_help; } else if (skb->encapsulation && spec->encap_okay && skb_checksum_start_offset(skb) == skb_inner_transport_offset(skb)) { /* Encapsulated checksum */ *csum_encapped = true; switch (skb->inner_protocol_type) { case ENCAP_TYPE_ETHER: protocol = eproto_to_ipproto(skb->inner_protocol); break; case ENCAP_TYPE_IPPROTO: protocol = skb->inner_protocol; break; } nhdr = skb_inner_network_header(skb); } else { goto need_help; } switch (protocol) { case IPPROTO_IP: if (!spec->ipv4_okay) goto need_help; iph = nhdr; ip_proto = iph->protocol; if (iph->ihl != 5 && !spec->ip_options_okay) goto need_help; break; case IPPROTO_IPV6: if (!spec->ipv6_okay) goto need_help; if (spec->no_encapped_ipv6 && *csum_encapped) goto need_help; ipv6 = nhdr; nhdr += sizeof(*ipv6); ip_proto = ipv6->nexthdr; break; default: goto need_help; } ip_proto_again: switch (ip_proto) { case IPPROTO_TCP: if (!spec->tcp_okay || skb->csum_offset != offsetof(struct tcphdr, check)) goto need_help; break; case IPPROTO_UDP: if (!spec->udp_okay || skb->csum_offset != offsetof(struct udphdr, check)) goto need_help; break; case IPPROTO_SCTP: if (!spec->sctp_okay || skb->csum_offset != offsetof(struct sctphdr, checksum)) goto cant_help; break; case NEXTHDR_HOP: case NEXTHDR_ROUTING: case NEXTHDR_DEST: { u8 *opthdr = nhdr; if (protocol != IPPROTO_IPV6 || !spec->ext_hdrs_okay) goto need_help; ip_proto = opthdr[0]; nhdr += (opthdr[1] + 1) << 3; goto ip_proto_again; } default: goto need_help; } /* Passed the tests for offloading checksum */ return true; need_help: if (csum_help && !skb_shinfo(skb)->gso_size) skb_checksum_help(skb); cant_help: return false; } CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); #if ARCH_X86 || ARCH_X86_64 const int simd_caps = x86_simd_caps(); if (!(simd_caps & HAS_MMX)) append_negative_gtest_filter(":MMX/*"); if (!(simd_caps & HAS_SSE)) append_negative_gtest_filter(":SSE/*"); if (!(simd_caps & HAS_SSE2)) append_negative_gtest_filter(":SSE2/*"); if (!(simd_caps & HAS_SSE3)) append_negative_gtest_filter(":SSE3/*"); if (!(simd_caps & HAS_SSSE3)) append_negative_gtest_filter(":SSSE3/*"); if (!(simd_caps & HAS_SSE4_1)) append_negative_gtest_filter(":SSE4_1/*"); if (!(simd_caps & HAS_AVX)) append_negative_gtest_filter(":AVX/*"); if (!(simd_caps & HAS_AVX2)) append_negative_gtest_filter(":AVX2/*"); #endif #if !CONFIG_SHARED #if CONFIG_VP8 vp8_rtcd(); #endif #if CONFIG_VP9 vp9_rtcd(); #endif #endif return RUN_ALL_TESTS(); } CWE ID: CWE-119 Target: 1 Example 2: Code: void Gfx::restoreState() { if (stackHeight <= bottomGuard() || !state->hasSaves()) { error(-1, "Restoring state when no valid states to pop"); commandAborted = gTrue; return; } state = state->restore(); out->restoreState(state); stackHeight--; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels, enum AVSampleFormat sample_fmt, const uint8_t *buf, int buf_size, int align) { int ch, planar, needed_size, ret = 0; needed_size = av_samples_get_buffer_size(NULL, nb_channels, frame->nb_samples, sample_fmt, align); if (buf_size < needed_size) return AVERROR(EINVAL); planar = av_sample_fmt_is_planar(sample_fmt); if (planar && nb_channels > AV_NUM_DATA_POINTERS) { if (!(frame->extended_data = av_mallocz_array(nb_channels, sizeof(*frame->extended_data)))) return AVERROR(ENOMEM); } else { frame->extended_data = frame->data; } if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0], (uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples, sample_fmt, align)) < 0) { if (frame->extended_data != frame->data) av_freep(&frame->extended_data); return ret; } if (frame->extended_data != frame->data) { for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++) frame->data[ch] = frame->extended_data[ch]; } return ret; } CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderProcessHostImpl::CreateSharedRendererHistogramAllocator() { if (!base::GlobalHistogramAllocator::Get()) { if (is_initialized_) { HistogramController::GetInstance()->SetHistogramMemory<RenderProcessHost>( this, mojo::ScopedSharedBufferHandle()); } return; } base::ProcessHandle destination = GetHandle(); if (destination == base::kNullProcessHandle) return; if (!metrics_allocator_) { std::unique_ptr<base::SharedMemory> shm(new base::SharedMemory()); if (!shm->CreateAndMapAnonymous(2 << 20)) // 2 MiB return; metrics_allocator_.reset(new base::SharedPersistentMemoryAllocator( std::move(shm), GetID(), "RendererMetrics", /*readonly=*/false)); } HistogramController::GetInstance()->SetHistogramMemory<RenderProcessHost>( this, mojo::WrapSharedMemoryHandle( metrics_allocator_->shared_memory()->handle().Duplicate(), metrics_allocator_->shared_memory()->mapped_size(), false)); } CWE ID: CWE-787 Target: 1 Example 2: Code: void credssp_buffer_free(rdpCredssp* credssp) { sspi_SecBufferFree(&credssp->negoToken); sspi_SecBufferFree(&credssp->pubKeyAuth); sspi_SecBufferFree(&credssp->authInfo); } 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: MagickExport ssize_t WriteBlobMSBLongLong(Image *image, const MagickSizeType value) { unsigned char buffer[8]; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); buffer[0]=(unsigned char) (value >> 56); buffer[1]=(unsigned char) (value >> 48); buffer[2]=(unsigned char) (value >> 40); buffer[3]=(unsigned char) (value >> 32); buffer[4]=(unsigned char) (value >> 24); buffer[5]=(unsigned char) (value >> 16); buffer[6]=(unsigned char) (value >> 8); buffer[7]=(unsigned char) value; return(WriteBlobStream(image,8,buffer)); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChromeNetworkDelegate::OnCompleted(net::URLRequest* request, bool started) { TRACE_EVENT_ASYNC_END0("net", "URLRequest", request); if (request->status().status() == net::URLRequestStatus::SUCCESS) { int64 received_content_length = request->received_response_content_length(); bool is_http = request->url().SchemeIs("http"); bool is_https = request->url().SchemeIs("https"); if (!request->was_cached() && // Don't record cached content received_content_length && // Zero-byte responses aren't useful. (is_http || is_https)) { // Only record for HTTP or HTTPS urls. int64 original_content_length = request->response_info().headers->GetInt64HeaderValue( "x-original-content-length"); bool via_data_reduction_proxy = request->response_info().headers->HasHeaderValue( "via", "1.1 Chrome Compression Proxy"); int64 adjusted_original_content_length = original_content_length; if (adjusted_original_content_length == -1) adjusted_original_content_length = received_content_length; base::TimeDelta freshness_lifetime = request->response_info().headers->GetFreshnessLifetime( request->response_info().response_time); AccumulateContentLength(received_content_length, adjusted_original_content_length, via_data_reduction_proxy); RecordContentLengthHistograms(received_content_length, original_content_length, freshness_lifetime); DVLOG(2) << __FUNCTION__ << " received content length: " << received_content_length << " original content length: " << original_content_length << " url: " << request->url(); } bool is_redirect = request->response_headers() && net::HttpResponseHeaders::IsRedirectResponseCode( request->response_headers()->response_code()); if (!is_redirect) { ExtensionWebRequestEventRouter::GetInstance()->OnCompleted( profile_, extension_info_map_.get(), request); } } else if (request->status().status() == net::URLRequestStatus::FAILED || request->status().status() == net::URLRequestStatus::CANCELED) { ExtensionWebRequestEventRouter::GetInstance()->OnErrorOccurred( profile_, extension_info_map_.get(), request, started); } else { NOTREACHED(); } ForwardProxyErrors(request, event_router_.get(), profile_); ForwardRequestStatus(REQUEST_DONE, request, profile_); } CWE ID: CWE-416 Target: 1 Example 2: Code: static void x86_pmu_enable(struct pmu *pmu) { struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events); struct perf_event *event; struct hw_perf_event *hwc; int i, added = cpuc->n_added; if (!x86_pmu_initialized()) return; if (cpuc->enabled) return; if (cpuc->n_added) { int n_running = cpuc->n_events - cpuc->n_added; /* * apply assignment obtained either from * hw_perf_group_sched_in() or x86_pmu_enable() * * step1: save events moving to new counters * step2: reprogram moved events into new counters */ for (i = 0; i < n_running; i++) { event = cpuc->event_list[i]; hwc = &event->hw; /* * we can avoid reprogramming counter if: * - assigned same counter as last time * - running on same CPU as last time * - no other event has used the counter since */ if (hwc->idx == -1 || match_prev_assignment(hwc, cpuc, i)) continue; /* * Ensure we don't accidentally enable a stopped * counter simply because we rescheduled. */ if (hwc->state & PERF_HES_STOPPED) hwc->state |= PERF_HES_ARCH; x86_pmu_stop(event, PERF_EF_UPDATE); } for (i = 0; i < cpuc->n_events; i++) { event = cpuc->event_list[i]; hwc = &event->hw; if (!match_prev_assignment(hwc, cpuc, i)) x86_assign_hw_event(event, cpuc, i); else if (i < n_running) continue; if (hwc->state & PERF_HES_ARCH) continue; x86_pmu_start(event, PERF_EF_RELOAD); } cpuc->n_added = 0; perf_events_lapic_init(); } cpuc->enabled = 1; barrier(); x86_pmu.enable_all(added); } 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: struct ipv6_txoptions *ipv6_update_options(struct sock *sk, struct ipv6_txoptions *opt) { if (inet_sk(sk)->is_icsk) { if (opt && !((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) && inet_sk(sk)->inet_daddr != LOOPBACK4_IPV6) { struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen; icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie); } } opt = xchg(&inet6_sk(sk)->opt, opt); sk_dst_reset(sk); return opt; } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintPreviewUI::OnPrintPreviewRequest(int request_id) { g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, request_id); } CWE ID: CWE-200 Target: 1 Example 2: Code: UsbReleaseInterfaceFunction::UsbReleaseInterfaceFunction() { } 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 Image *ReadCLIPBOARDImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; register ssize_t x; register PixelPacket *q; ssize_t y; 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); { HBITMAP bitmapH; HPALETTE hPal; OpenClipboard(NULL); bitmapH=(HBITMAP) GetClipboardData(CF_BITMAP); hPal=(HPALETTE) GetClipboardData(CF_PALETTE); CloseClipboard(); if ( bitmapH == NULL ) ThrowReaderException(CoderError,"NoBitmapOnClipboard"); { BITMAPINFO DIBinfo; BITMAP bitmap; HBITMAP hBitmap, hOldBitmap; HDC hDC, hMemDC; RGBQUAD *pBits, *ppBits; /* create an offscreen DC for the source */ hMemDC=CreateCompatibleDC(NULL); hOldBitmap=(HBITMAP) SelectObject(hMemDC,bitmapH); GetObject(bitmapH,sizeof(BITMAP),(LPSTR) &bitmap); if ((image->columns == 0) || (image->rows == 0)) { image->rows=bitmap.bmHeight; image->columns=bitmap.bmWidth; } /* Initialize the bitmap header info. */ (void) ResetMagickMemory(&DIBinfo,0,sizeof(BITMAPINFO)); DIBinfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); DIBinfo.bmiHeader.biWidth=(LONG) image->columns; DIBinfo.bmiHeader.biHeight=(-1)*(LONG) image->rows; DIBinfo.bmiHeader.biPlanes=1; DIBinfo.bmiHeader.biBitCount=32; DIBinfo.bmiHeader.biCompression=BI_RGB; hDC=GetDC(NULL); if (hDC == 0) ThrowReaderException(CoderError,"UnableToCreateADC"); hBitmap=CreateDIBSection(hDC,&DIBinfo,DIB_RGB_COLORS,(void **) &ppBits, NULL,0); ReleaseDC(NULL,hDC); if (hBitmap == 0) ThrowReaderException(CoderError,"UnableToCreateBitmap"); /* create an offscreen DC */ hDC=CreateCompatibleDC(NULL); if (hDC == 0) { DeleteObject(hBitmap); ThrowReaderException(CoderError,"UnableToCreateADC"); } hOldBitmap=(HBITMAP) SelectObject(hDC,hBitmap); if (hOldBitmap == 0) { DeleteDC(hDC); DeleteObject(hBitmap); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } if (hPal != NULL) { /* Kenichi Masuko says this needed */ SelectPalette(hDC, hPal, FALSE); RealizePalette(hDC); } /* bitblt from the memory to the DIB-based one */ BitBlt(hDC,0,0,(int) image->columns,(int) image->rows,hMemDC,0,0,SRCCOPY); /* finally copy the pixels! */ pBits=ppBits; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(pBits->rgbRed)); SetPixelGreen(q,ScaleCharToQuantum(pBits->rgbGreen)); SetPixelBlue(q,ScaleCharToQuantum(pBits->rgbBlue)); SetPixelOpacity(q,OpaqueOpacity); pBits++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } DeleteDC(hDC); DeleteObject(hBitmap); } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int usbip_recv_xbuff(struct usbip_device *ud, struct urb *urb) { int ret; int size; if (ud->side == USBIP_STUB) { /* the direction of urb must be OUT. */ if (usb_pipein(urb->pipe)) return 0; size = urb->transfer_buffer_length; } else { /* the direction of urb must be IN. */ if (usb_pipeout(urb->pipe)) return 0; size = urb->actual_length; } /* no need to recv xbuff */ if (!(size > 0)) return 0; ret = usbip_recv(ud->tcp_socket, urb->transfer_buffer, size); if (ret != size) { dev_err(&urb->dev->dev, "recv xbuf, %d\n", ret); if (ud->side == USBIP_STUB) { usbip_event_add(ud, SDEV_EVENT_ERROR_TCP); } else { usbip_event_add(ud, VDEV_EVENT_ERROR_TCP); return -EPIPE; } } return ret; } CWE ID: CWE-119 Target: 1 Example 2: Code: void CSoundFile::PanningSlide(ModChannel *pChn, ModCommand::PARAM param, bool memory) { if(memory) { if(param) pChn->nOldPanSlide = param; else param = pChn->nOldPanSlide; } if((GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { if((param & 0xF0) != 0) { param &= 0xF0; } else { param &= 0x0F; } } int32 nPanSlide = 0; if(!(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { if(m_SongFlags[SONG_FIRSTTICK]) { param = (param & 0xF0) / 4u; nPanSlide = - (int)param; } } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { if(m_SongFlags[SONG_FIRSTTICK]) { nPanSlide = (param & 0x0F) * 4u; } } else if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0x0F) { if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (param & 0xF0) == 0) nPanSlide = (int)((param & 0x0F) * 4u); } else { nPanSlide = -(int)((param & 0xF0) / 4u); } } } else { if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0xF0) { nPanSlide = (int)((param & 0xF0) / 4u); } else { nPanSlide = -(int)((param & 0x0F) * 4u); } if(m_playBehaviour[kFT2PanSlide]) nPanSlide /= 4; } } if (nPanSlide) { nPanSlide += pChn->nPan; nPanSlide = Clamp(nPanSlide, 0, 256); pChn->nPan = nPanSlide; pChn->nRestorePanOnNewNote = 0; } } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long elements; elements = parse_iv2((*p) + 2, p); (*p) += 2; if (ce->serialize == NULL) { object_init_ex(*rval, ce); } else { /* If this class implements Serializable, it should not land here but in object_custom(). The passed string obviously doesn't descend from the regular serializer. */ zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ce->name); return 0; } return elements; } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; UINT32 extra = 0; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; } CWE ID: CWE-119 Target: 1 Example 2: Code: int json_integer_set(json_t *json, json_int_t value) { if(!json_is_integer(json)) return -1; json_to_integer(json)->value = value; return 0; } 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: xmlParsePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_PEREF_NO_NAME, "PEReference: no name\n"); return; } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "PEReference: %s\n", name); if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL); return; } NEXT; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (ctxt->instate == XML_PARSER_EOF) return; if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) { xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); } else xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } xmlParserEntityCheck(ctxt, 0, NULL, 0); } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "Internal: %%%s; is not a parameter entity\n", name, NULL); } else { xmlChar start[4]; xmlCharEncoding enc; if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && ((ctxt->options & XML_PARSE_NOENT) == 0) && ((ctxt->options & XML_PARSE_DTDVALID) == 0) && ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && ((ctxt->options & XML_PARSE_DTDATTR) == 0) && (ctxt->replaceEntities == 0) && (ctxt->validate == 0)) return; input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. * Note that, since we may have some non-UTF8 * encoding (like UTF16, bug 135229), the 'length' * is not known, but we can calculate based upon * the amount of data in the buffer. */ GROW if (ctxt->instate == XML_PARSER_EOF) return; if ((ctxt->input->end - ctxt->input->cur)>=4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); } } } } ctxt->hasPErefs = 1; } CWE ID: CWE-835 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 faultin_page(struct task_struct *tsk, struct vm_area_struct *vma, unsigned long address, unsigned int *flags, int *nonblocking) { unsigned int fault_flags = 0; int ret; /* mlock all present pages, but do not fault in new pages */ if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK) return -ENOENT; /* For mm_populate(), just skip the stack guard page. */ if ((*flags & FOLL_POPULATE) && (stack_guard_page_start(vma, address) || stack_guard_page_end(vma, address + PAGE_SIZE))) return -ENOENT; if (*flags & FOLL_WRITE) fault_flags |= FAULT_FLAG_WRITE; if (*flags & FOLL_REMOTE) fault_flags |= FAULT_FLAG_REMOTE; if (nonblocking) fault_flags |= FAULT_FLAG_ALLOW_RETRY; if (*flags & FOLL_NOWAIT) fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT; if (*flags & FOLL_TRIED) { VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY); fault_flags |= FAULT_FLAG_TRIED; } ret = handle_mm_fault(vma, address, fault_flags); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return -ENOMEM; if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE)) return *flags & FOLL_HWPOISON ? -EHWPOISON : -EFAULT; if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV)) return -EFAULT; BUG(); } if (tsk) { if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; } if (ret & VM_FAULT_RETRY) { if (nonblocking) *nonblocking = 0; return -EBUSY; } /* * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when * necessary, even if maybe_mkwrite decided not to set pte_write. We * can thus safely do subsequent page lookups as if they were reads. * But only do so when looping for pte_write is futile: in some cases * userspace may also be wanting to write to the gotten user page, * which a read fault here might prevent (a readonly page might get * reCOWed by userspace write). */ if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE)) *flags &= ~FOLL_WRITE; return 0; } CWE ID: CWE-362 Target: 1 Example 2: Code: infinite_recursive_call_check_trav(Node* node, ScanEnv* env) { int r; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: do { r = infinite_recursive_call_check_trav(NODE_CAR(node), env); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ANCHOR: if (! ANCHOR_HAS_BODY(ANCHOR_(node))) { r = 0; break; } /* fall */ case NODE_QUANT: r = infinite_recursive_call_check_trav(NODE_BODY(node), env); break; case NODE_BAG: { BagNode* en = BAG_(node); if (en->type == BAG_MEMORY) { if (NODE_IS_RECURSION(node) && NODE_IS_CALLED(node)) { int ret; NODE_STATUS_ADD(node, MARK1); ret = infinite_recursive_call_check(NODE_BODY(node), env, 1); if (ret < 0) return ret; else if ((ret & (RECURSION_MUST | RECURSION_INFINITE)) != 0) return ONIGERR_NEVER_ENDING_RECURSION; NODE_STATUS_REMOVE(node, MARK1); } } else if (en->type == BAG_IF_ELSE) { if (IS_NOT_NULL(en->te.Then)) { r = infinite_recursive_call_check_trav(en->te.Then, env); if (r != 0) return r; } if (IS_NOT_NULL(en->te.Else)) { r = infinite_recursive_call_check_trav(en->te.Else, env); if (r != 0) return r; } } } r = infinite_recursive_call_check_trav(NODE_BODY(node), env); break; default: r = 0; break; } return r; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int pppol2tp_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; int val, len; int err; struct pppol2tp_session *ps; if (level != SOL_PPPOL2TP) return udp_prot.getsockopt(sk, level, optname, optval, optlen); if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get the session context */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_getsockopt(sk, tunnel, optname, &val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_getsockopt(sk, session, optname, &val); err = -EFAULT; if (put_user(len, optlen)) goto end_put_sess; if (copy_to_user((void __user *) optval, &val, len)) goto end_put_sess; err = 0; end_put_sess: sock_put(sk); end: return err; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: my_object_many_args (MyObject *obj, guint32 x, const char *str, double trouble, double *d_ret, char **str_ret, GError **error) { *d_ret = trouble + (x * 2); *str_ret = g_ascii_strup (str, -1); return TRUE; } CWE ID: CWE-264 Target: 1 Example 2: Code: void BluetoothSocketListenUsingRfcommFunction::CreateService( scoped_refptr<device::BluetoothAdapter> adapter, const device::BluetoothUUID& uuid, std::unique_ptr<std::string> name, const device::BluetoothAdapter::CreateServiceCallback& callback, const device::BluetoothAdapter::CreateServiceErrorCallback& error_callback) { device::BluetoothAdapter::ServiceOptions service_options; service_options.name = std::move(name); ListenOptions* options = params_->options.get(); if (options) { if (options->channel.get()) service_options.channel.reset(new int(*(options->channel))); } adapter->CreateRfcommService(uuid, service_options, callback, error_callback); } 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 v8::Handle<v8::Value> methodWithCallbackArgCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.methodWithCallbackArg"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); if (args.Length() <= 0 || !args[0]->IsFunction()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); RefPtr<TestCallback> callback = V8TestCallback::create(args[0], getScriptExecutionContext()); imp->methodWithCallbackArg(callback); return v8::Handle<v8::Value>(); } 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: Block::Block(long long start, long long size_, long long discard_padding) : m_start(start), m_size(size_), m_track(0), m_timecode(-1), m_flags(0), m_frames(NULL), m_frame_count(-1), m_discard_padding(discard_padding) { } CWE ID: CWE-119 Target: 1 Example 2: Code: int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len) { ext4_lblk_t start_blk; int error = 0; /* fallback to generic here if not in extents fmt */ if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) return generic_block_fiemap(inode, fieinfo, start, len, ext4_get_block); if (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS)) return -EBADR; if (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) { error = ext4_xattr_fiemap(inode, fieinfo); } else { ext4_lblk_t len_blks; __u64 last_blk; start_blk = start >> inode->i_sb->s_blocksize_bits; last_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits; if (last_blk >= EXT_MAX_BLOCK) last_blk = EXT_MAX_BLOCK-1; len_blks = ((ext4_lblk_t) last_blk) - start_blk + 1; /* * Walk the extent tree gathering extent information. * ext4_ext_fiemap_cb will push extents back to user. */ error = ext4_ext_walk_space(inode, start_blk, len_blks, ext4_ext_fiemap_cb, fieinfo); } return error; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: v8::Handle<v8::Value> V8TestEventConstructor::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestEventConstructor.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, args[0]); TestEventConstructorInit eventInit; if (args.Length() >= 2) { EXCEPTION_BLOCK(Dictionary, options, args[1]); if (!fillTestEventConstructorInit(eventInit, options)) return v8::Undefined(); } RefPtr<TestEventConstructor> event = TestEventConstructor::create(type, eventInit); V8DOMWrapper::setDOMWrapper(args.Holder(), &info, event.get()); V8DOMWrapper::setJSWrapperForDOMObject(event.release(), v8::Persistent<v8::Object>::New(args.Holder()), args.GetIsolate()); return args.Holder(); } 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 SoftAVC::drainAllOutputBuffers(bool eos) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); H264SwDecPicture decodedPicture; if (mHeadersDecoded) { while (!outQueue.empty() && H264SWDEC_PIC_RDY == H264SwDecNextPicture( mHandle, &decodedPicture, eos /* flush */)) { int32_t picId = decodedPicture.picId; uint8_t *data = (uint8_t *) decodedPicture.pOutputPicture; drainOneOutputBuffer(picId, data); } } if (!eos) { return; } while (!outQueue.empty()) { BufferInfo *outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; outHeader->nTimeStamp = 0; outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); mEOSStatus = OUTPUT_FRAMES_FLUSHED; } } CWE ID: CWE-20 Target: 1 Example 2: Code: leave_sysex(int dev) { int orig_dev = synth_devs[dev]->midi_dev; int timeout = 0; if (!sysex_state[dev]) return; sysex_state[dev] = 0; while (!midi_devs[orig_dev]->outputc(orig_dev, 0xf7) && timeout < 1000) timeout++; sysex_state[dev] = 0; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer) { if (buffer == 0) { return; } Mutex::Autolock autoLock(mBufferIDLock); mBufferHeaderToBufferID.removeItem(mBufferIDToBufferHeader.valueFor(buffer)); mBufferIDToBufferHeader.removeItem(buffer); } 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: VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::CreateVP8Picture() { scoped_refptr<VaapiDecodeSurface> va_surface = vaapi_dec_->CreateSurface(); if (!va_surface) return nullptr; return new VaapiVP8Picture(std::move(va_surface)); } CWE ID: CWE-362 Target: 1 Example 2: Code: cff_get_glyph_data( TT_Face face, FT_UInt glyph_index, FT_Byte** pointer, FT_ULong* length ) { #ifdef FT_CONFIG_OPTION_INCREMENTAL /* For incremental fonts get the character data using the */ /* callback function. */ if ( face->root.internal->incremental_interface ) { FT_Data data; FT_Error error = face->root.internal->incremental_interface->funcs->get_glyph_data( face->root.internal->incremental_interface->object, glyph_index, &data ); *pointer = (FT_Byte*)data.pointer; *length = data.length; return error; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { CFF_Font cff = (CFF_Font)(face->extra.data); return cff_index_access_element( &cff->charstrings_index, glyph_index, pointer, length ); } } 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 CURLcode nss_fail_connect(struct ssl_connect_data *connssl, struct Curl_easy *data, CURLcode curlerr) { PRErrorCode err = 0; if(is_nss_error(curlerr)) { /* read NSPR error code */ err = PR_GetError(); if(is_cc_error(err)) curlerr = CURLE_SSL_CERTPROBLEM; /* print the error number and error string */ infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err)); /* print a human-readable message describing the error if available */ nss_print_error_message(data, err); } /* cleanup on connection failure */ Curl_llist_destroy(connssl->obj_list, NULL); connssl->obj_list = NULL; return curlerr; } CWE ID: CWE-287 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); /* Flush temporal reference */ impeg2d_bit_stream_get(ps_stream,10); /* Picture type */ ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3); if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC)) { impeg2d_next_code(ps_dec, PICTURE_START_CODE); return IMPEG2D_INVALID_PIC_TYPE; } /* Flush vbv_delay */ impeg2d_bit_stream_get(ps_stream,16); if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC) { ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3); } if(ps_dec->e_pic_type == B_PIC) { ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3); } if(ps_dec->u2_is_mpeg2 == 0) { ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code; ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code; } /*-----------------------------------------------------------------------*/ /* Flush the extra bit value */ /* */ /* while(impeg2d_bit_stream_nxt() == '1') */ /* { */ /* extra_bit_picture 1 */ /* extra_information_picture 8 */ /* } */ /* extra_bit_picture 1 */ /*-----------------------------------------------------------------------*/ while (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_get(ps_stream,9); } impeg2d_bit_stream_get_bit(ps_stream); impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } CWE ID: CWE-254 Target: 1 Example 2: Code: static struct xfrm_state *xfrm_state_construct(struct net *net, struct xfrm_usersa_info *p, struct nlattr **attrs, int *errp) { struct xfrm_state *x = xfrm_state_alloc(net); int err = -ENOMEM; if (!x) goto error_no_put; copy_from_user_state(x, p); if (attrs[XFRMA_SA_EXTRA_FLAGS]) x->props.extra_flags = nla_get_u32(attrs[XFRMA_SA_EXTRA_FLAGS]); if ((err = attach_aead(x, attrs[XFRMA_ALG_AEAD]))) goto error; if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo, attrs[XFRMA_ALG_AUTH_TRUNC]))) goto error; if (!x->props.aalgo) { if ((err = attach_auth(&x->aalg, &x->props.aalgo, attrs[XFRMA_ALG_AUTH]))) goto error; } if ((err = attach_crypt(x, attrs[XFRMA_ALG_CRYPT]))) goto error; if ((err = attach_one_algo(&x->calg, &x->props.calgo, xfrm_calg_get_byname, attrs[XFRMA_ALG_COMP]))) goto error; if (attrs[XFRMA_ENCAP]) { x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]), sizeof(*x->encap), GFP_KERNEL); if (x->encap == NULL) goto error; } if (attrs[XFRMA_TFCPAD]) x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]); if (attrs[XFRMA_COADDR]) { x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]), sizeof(*x->coaddr), GFP_KERNEL); if (x->coaddr == NULL) goto error; } xfrm_mark_get(attrs, &x->mark); if (attrs[XFRMA_OUTPUT_MARK]) x->props.output_mark = nla_get_u32(attrs[XFRMA_OUTPUT_MARK]); err = __xfrm_init_state(x, false, attrs[XFRMA_OFFLOAD_DEV]); if (err) goto error; if (attrs[XFRMA_SEC_CTX]) { err = security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX])); if (err) goto error; } if (attrs[XFRMA_OFFLOAD_DEV]) { err = xfrm_dev_state_add(net, x, nla_data(attrs[XFRMA_OFFLOAD_DEV])); if (err) goto error; } if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn, attrs[XFRMA_REPLAY_ESN_VAL]))) goto error; x->km.seq = p->seq; x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth; /* sysctl_xfrm_aevent_etime is in 100ms units */ x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M; if ((err = xfrm_init_replay(x))) goto error; /* override default values from above */ xfrm_update_ae_params(x, attrs, 0); return x; error: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); error_no_put: *errp = err; 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 PHP_METHOD(PDOStatement, bindValue) { struct pdo_bound_param_data param = {0}; long param_type = PDO_PARAM_STR; PHP_STMT_GET_OBJ; param.paramno = -1; if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "lz/|l", &param.paramno, &param.parameter, &param_type)) { if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz/|l", &param.name, &param.namelen, &param.parameter, &param_type)) { RETURN_FALSE; } } param.param_type = (int) param_type; if (param.paramno > 0) { --param.paramno; /* make it zero-based internally */ } else if (!param.name) { pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "Columns/Parameters are 1-based" TSRMLS_CC); RETURN_FALSE; } Z_ADDREF_P(param.parameter); if (!really_register_bound_param(&param, stmt, TRUE TSRMLS_CC)) { if (param.parameter) { zval_ptr_dtor(&(param.parameter)); param.parameter = NULL; } RETURN_FALSE; } RETURN_TRUE; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int unshare_userns(unsigned long unshare_flags, struct cred **new_cred) { struct cred *cred; if (!(unshare_flags & CLONE_NEWUSER)) return 0; cred = prepare_creds(); if (!cred) return -ENOMEM; *new_cred = cred; return create_user_ns(cred); } CWE ID: CWE-399 Target: 1 Example 2: Code: sysapi_translate_opsys( const char *sysname, const char *release, const char *version, int append_version) { char tmp[64]; char ver[24]; const char * pver=""; char *tmpopsys; if( !strcmp(sysname, "Linux") ) { sprintf( tmp, "LINUX" ); } else if( !strcmp(sysname, "linux") ) { //LDAP entry sprintf( tmp, "LINUX" ); } else if( !strcmp(sysname, "SunOS") || !strcmp(sysname, "solaris" ) ) //LDAP entry { sprintf( tmp, "SOLARIS" ); if ( !strcmp(release, "2.10") //LDAP entry || !strcmp(release, "5.10") ) { pver = "210"; } else if ( !strcmp(release, "2.9") //LDAP entry || !strcmp(release, "5.9") ) { pver = "29"; } else if ( !strcmp(release, "2.8") //LDAP entry || !strcmp(release, "5.8") ) { pver = "28"; } else if ( !strcmp(release, "2.7") //LDAP entry || !strcmp(release, "5.7") ) { pver = "27"; } else if( !strcmp(release, "5.6") || !strcmp(release, "2.6") ) //LDAP entry { pver = "26"; } else if ( !strcmp(release, "5.5.1") || !strcmp(release, "2.5.1") ) //LDAP entry { pver = "251"; } else if ( !strcmp(release, "5.5") || !strcmp(release, "2.5") ) //LDAP entry { pver = "25"; } else { pver = release; } } else if( !strcmp(sysname, "HP-UX") ) { sprintf( tmp, "HPUX" ); if( !strcmp(release, "B.10.20") ) { pver = "10"; } else if( !strcmp(release, "B.11.00") ) { pver = "11"; } else if( !strcmp(release, "B.11.11") ) { pver = "11"; } else { pver = release; } } else if ( !strncmp(sysname, "Darwin", 6) ) { sprintf( tmp, "OSX"); } else if ( !strncmp(sysname, "AIX", 3) ) { sprintf(tmp, "%s", sysname); if ( !strcmp(version, "5") ) { sprintf(ver, "%s%s", version, release); pver = ver; } } else if ( !strncmp(sysname, "FreeBSD", 7) ) { sprintf( tmp, "FREEBSD" ); sprintf( ver, "%c", release[0]); pver = ver; } else { sprintf( tmp, "%s", sysname); pver = release; } if (append_version && pver) { strcat( tmp, pver ); } tmpopsys = strdup( tmp ); if( !tmpopsys ) { EXCEPT( "Out of memory!" ); } return( tmpopsys ); } 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: static int php_ifd_get32s(void *value, int motorola_intel) { if (motorola_intel) { return (((char *)value)[0] << 24) | (((uchar *)value)[1] << 16) | (((uchar *)value)[2] << 8 ) | (((uchar *)value)[3] ); } else { return (((char *)value)[3] << 24) | (((uchar *)value)[2] << 16) | (((uchar *)value)[1] << 8 ) | (((uchar *)value)[0] ); } } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool IsValidSymbolicLink(const FilePath& file_path, GDataCache::CacheSubDirectoryType sub_dir_type, const std::vector<FilePath>& cache_paths, std::string* reason) { DCHECK(sub_dir_type == GDataCache::CACHE_TYPE_PINNED || sub_dir_type == GDataCache::CACHE_TYPE_OUTGOING); FilePath destination; if (!file_util::ReadSymbolicLink(file_path, &destination)) { *reason = "failed to read the symlink (maybe not a symlink)"; return false; } if (!file_util::PathExists(destination)) { *reason = "pointing to a non-existent file"; return false; } if (sub_dir_type == GDataCache::CACHE_TYPE_PINNED && destination == FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull)) { return true; } if (!cache_paths[GDataCache::CACHE_TYPE_PERSISTENT].IsParent(destination)) { *reason = "pointing to a file outside of persistent directory"; return false; } return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: decode_OFPAT_RAW11_SET_VLAN_VID(uint16_t vid, enum ofp_version ofp_version OVS_UNUSED, struct ofpbuf *out) { return decode_set_vlan_vid(vid, false, out); } 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 tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb) { /* unprotected vars, we dont care of overwrites */ static u32 challenge_timestamp; static unsigned int challenge_count; struct tcp_sock *tp = tcp_sk(sk); u32 now; /* First check our per-socket dupack rate limit. */ if (tcp_oow_rate_limited(sock_net(sk), skb, LINUX_MIB_TCPACKSKIPPEDCHALLENGE, &tp->last_oow_ack_time)) return; /* Then check the check host-wide RFC 5961 rate limit. */ now = jiffies / HZ; if (now != challenge_timestamp) { challenge_timestamp = now; challenge_count = 0; } if (++challenge_count <= sysctl_tcp_challenge_ack_limit) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK); tcp_send_ack(sk); } } 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 * calloc(size_t n, size_t lb) { # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); } CWE ID: CWE-189 Target: 1 Example 2: Code: void Layer::SetBackgroundFilters(const FilterOperations& filters) { DCHECK(IsPropertyChangeAllowed()); if (background_filters_ == filters) return; background_filters_ = filters; SetNeedsCommit(); SetNeedsFilterContextIfNeeded(); } 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 DocumentThreadableLoader::loadRequest(const ResourceRequest& request, ResourceLoaderOptions resourceLoaderOptions) { const KURL& requestURL = request.url(); ASSERT(m_sameOriginRequest || requestURL.user().isEmpty()); ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty()); if (m_forceDoNotAllowStoredCredentials) resourceLoaderOptions.allowCredentials = DoNotAllowStoredCredentials; resourceLoaderOptions.securityOrigin = m_securityOrigin; if (m_async) { if (!m_actualRequest.isNull()) resourceLoaderOptions.dataBufferingPolicy = BufferData; if (m_options.timeoutMilliseconds > 0) m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0, BLINK_FROM_HERE); FetchRequest newRequest(request, m_options.initiator, resourceLoaderOptions); if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) newRequest.setOriginRestriction(FetchRequest::NoOriginRestriction); ASSERT(!resource()); if (request.requestContext() == WebURLRequest::RequestContextVideo || request.requestContext() == WebURLRequest::RequestContextAudio) setResource(RawResource::fetchMedia(newRequest, document().fetcher())); else if (request.requestContext() == WebURLRequest::RequestContextManifest) setResource(RawResource::fetchManifest(newRequest, document().fetcher())); else setResource(RawResource::fetch(newRequest, document().fetcher())); if (!resource()) { InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client); ThreadableLoaderClient* client = m_client; clear(); client->didFail(ResourceError(errorDomainBlinkInternal, 0, requestURL.getString(), "Failed to start loading.")); return; } if (resource()->loader()) { unsigned long identifier = resource()->identifier(); InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client); } else { InspectorInstrumentation::documentThreadableLoaderFailedToStartLoadingForClient(m_document, m_client); } return; } FetchRequest fetchRequest(request, m_options.initiator, resourceLoaderOptions); if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) fetchRequest.setOriginRestriction(FetchRequest::NoOriginRestriction); Resource* resource = RawResource::fetchSynchronously(fetchRequest, document().fetcher()); ResourceResponse response = resource ? resource->response() : ResourceResponse(); unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max(); ResourceError error = resource ? resource->resourceError() : ResourceError(); InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client); if (!resource) { m_client->didFail(error); return; } if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) { m_client->didFail(error); return; } if (requestURL != response.url() && !isAllowedRedirect(response.url())) { m_client->didFailRedirectCheck(); return; } handleResponse(identifier, response, nullptr); if (!m_client) return; SharedBuffer* data = resource->resourceBuffer(); if (data) handleReceivedData(data->data(), data->size()); if (!m_client) return; handleSuccessfulFinish(identifier, 0.0); } 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: JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { base::android::InitVM(vm); if (!content::android::OnJNIOnLoadInit()) return -1; content::SetContentMainDelegate(new content::ShellMainDelegate()); return JNI_VERSION_1_4; } CWE ID: CWE-264 Target: 1 Example 2: Code: static int is_sqp(enum ib_qp_type qp_type) { return is_qp0(qp_type) || is_qp1(qp_type); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool ShouldQuicRetryOnAlternateNetworkBeforeHandshake( const VariationParameters& quic_trial_params) { return base::LowerCaseEqualsASCII( GetVariationParam(quic_trial_params, "retry_on_alternate_network_before_handshake"), "true"); } CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DOMWindow::focus(LocalDOMWindow* incumbent_window) { if (!GetFrame()) return; Page* page = GetFrame()->GetPage(); if (!page) return; DCHECK(incumbent_window); ExecutionContext* incumbent_execution_context = incumbent_window->GetExecutionContext(); bool allow_focus = incumbent_execution_context->IsWindowInteractionAllowed(); if (allow_focus) { incumbent_execution_context->ConsumeWindowInteraction(); } else { DCHECK(IsMainThread()); allow_focus = opener() && (opener() != this) && (ToDocument(incumbent_execution_context)->domWindow() == opener()); } if (GetFrame()->IsMainFrame() && allow_focus) page->GetChromeClient().Focus(); page->GetFocusController().FocusDocumentView(GetFrame(), true /* notifyEmbedder */); } CWE ID: Target: 1 Example 2: Code: R_API int r_config_toggle(RConfig *cfg, const char *name) { RConfigNode *node = r_config_node_get (cfg, name); if (node && node->flags & CN_BOOL) { (void)r_config_set_i (cfg, name, !node->i_value); return true; } return false; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ConnectionInfoPopupAndroid::ConnectionInfoPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); } 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 destroy_super(struct super_block *s) { int i; list_lru_destroy(&s->s_dentry_lru); list_lru_destroy(&s->s_inode_lru); #ifdef CONFIG_SMP free_percpu(s->s_files); #endif for (i = 0; i < SB_FREEZE_LEVELS; i++) percpu_counter_destroy(&s->s_writers.counter[i]); security_sb_free(s); WARN_ON(!list_empty(&s->s_mounts)); kfree(s->s_subtype); kfree(s->s_options); kfree_rcu(s, rcu); } CWE ID: CWE-17 Target: 1 Example 2: Code: CameraService::Client::~Client() { ALOGV("~Client"); mDestructionStarted = true; mCameraService->releaseSound(); Client::disconnect(); } 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: virtual void SetDeferImeStartup(bool defer) {} 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: MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } CWE ID: CWE-125 Target: 1 Example 2: Code: construct_le_tlv(struct sc_apdu *apdu, unsigned char *apdu_buf, size_t data_tlv_len, unsigned char *le_tlv, size_t * le_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); *(apdu_buf + block_size + data_tlv_len) = 0x97; if (apdu->le > 0x7F) { /* Le' > 0x7E, use extended APDU */ *(apdu_buf + block_size + data_tlv_len + 1) = 2; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)(apdu->le / 0x100); *(apdu_buf + block_size + data_tlv_len + 3) = (unsigned char)(apdu->le % 0x100); memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 4); *le_tlv_len = 4; } else { *(apdu_buf + block_size + data_tlv_len + 1) = 1; *(apdu_buf + block_size + data_tlv_len + 2) = (unsigned char)apdu->le; memcpy(le_tlv, apdu_buf + block_size + data_tlv_len, 3); *le_tlv_len = 3; } return 0; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ims_pcu_verify_block(struct ims_pcu *pcu, u32 addr, u8 len, const u8 *data) { struct ims_pcu_flash_fmt *fragment; int error; fragment = (void *)&pcu->cmd_buf[1]; put_unaligned_le32(addr, &fragment->addr); fragment->len = len; error = ims_pcu_execute_bl_command(pcu, READ_APP, NULL, 5, IMS_PCU_CMD_RESPONSE_TIMEOUT); if (error) { dev_err(pcu->dev, "Failed to retrieve block at 0x%08x, len %d, error: %d\n", addr, len, error); return error; } fragment = (void *)&pcu->cmd_buf[IMS_PCU_BL_DATA_OFFSET]; if (get_unaligned_le32(&fragment->addr) != addr || fragment->len != len) { dev_err(pcu->dev, "Wrong block when retrieving 0x%08x (0x%08x), len %d (%d)\n", addr, get_unaligned_le32(&fragment->addr), len, fragment->len); return -EINVAL; } if (memcmp(fragment->data, data, len)) { dev_err(pcu->dev, "Mismatch in block at 0x%08x, len %d\n", addr, len); return -EINVAL; } return 0; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path, const char *name, V9fsPath *target) { if (dir_path) { v9fs_path_sprintf(target, "%s/%s", dir_path->data, name); } else { v9fs_path_sprintf(target, "%s", name); } return 0; } CWE ID: CWE-732 Target: 1 Example 2: Code: void HTMLElement::setTabIndex(int value) { setAttribute(tabindexAttr, String::number(value)); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void sctp_association_hold(struct sctp_association *asoc) { atomic_inc(&asoc->base.refcnt); } 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 WT_Interpolate (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 phaseFrac; EAS_I32 acc0; const EAS_SAMPLE *pSamples; const EAS_SAMPLE *loopEnd; EAS_I32 samp1; EAS_I32 samp2; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; pOutputBuffer = pWTIntFrame->pAudioBuffer; loopEnd = (const EAS_SAMPLE*) pWTVoice->loopEnd + 1; pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum; /*lint -e{713} truncation is OK */ phaseFrac = pWTVoice->phaseFrac; phaseInc = pWTIntFrame->frame.phaseIncrement; /* fetch adjacent samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif while (numSamples--) { /* linear interpolation */ acc0 = samp2 - samp1; acc0 = acc0 * phaseFrac; /*lint -e{704} <avoid divide>*/ acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS); /* save new output sample in buffer */ /*lint -e{704} <avoid divide>*/ *pOutputBuffer++ = (EAS_I16)(acc0 >> 2); /* increment phase */ phaseFrac += phaseInc; /*lint -e{704} <avoid divide>*/ acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS; /* next sample */ if (acc0 > 0) { /* advance sample pointer */ pSamples += acc0; phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK); /* check for loop end */ acc0 = (EAS_I32) (pSamples - loopEnd); if (acc0 >= 0) pSamples = (const EAS_SAMPLE*) pWTVoice->loopStart + acc0; /* fetch new samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif } } /* save pointer and phase */ pWTVoice->phaseAccum = (EAS_U32) pSamples; pWTVoice->phaseFrac = (EAS_U32) phaseFrac; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void ReflectedNameAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); TestObject* impl = V8TestObject::ToImpl(holder); V8SetReturnValueString(info, impl->GetNameAttribute(), info.GetIsolate()); } 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 TestRenderWidgetHostView::Destroy() { delete this; } 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: xmlStopParser(xmlParserCtxtPtr ctxt) { if (ctxt == NULL) return; ctxt->instate = XML_PARSER_EOF; ctxt->disableSAX = 1; if (ctxt->input != NULL) { ctxt->input->cur = BAD_CAST""; ctxt->input->base = ctxt->input->cur; } } CWE ID: CWE-119 Target: 1 Example 2: Code: void ist_end_non_atomic(void) { preempt_disable(); } 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 InitSkBitmapDataForTransfer(const SkBitmap& bitmap) { const SkImageInfo& info = bitmap.info(); color_type = info.colorType(); alpha_type = info.alphaType(); width = info.width(); height = info.height(); } 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: xfs_attr_calc_size( struct xfs_inode *ip, int namelen, int valuelen, int *local) { struct xfs_mount *mp = ip->i_mount; int size; int nblks; /* * Determine space new attribute will use, and if it would be * "local" or "remote" (note: local != inline). */ size = xfs_attr_leaf_newentsize(namelen, valuelen, mp->m_sb.sb_blocksize, local); nblks = XFS_DAENTER_SPACE_RES(mp, XFS_ATTR_FORK); if (*local) { if (size > (mp->m_sb.sb_blocksize >> 1)) { /* Double split possible */ nblks *= 2; } } else { /* * Out of line attribute, cannot double split, but * make room for the attribute value itself. */ uint dblocks = XFS_B_TO_FSB(mp, valuelen); nblks += dblocks; nblks += XFS_NEXTENTADD_SPACE_RES(mp, dblocks, XFS_ATTR_FORK); } return nblks; } CWE ID: CWE-19 Target: 1 Example 2: Code: profPop(xsltTransformContextPtr ctxt) { long ret; if (ctxt->profNr <= 0) return (0); ctxt->profNr--; if (ctxt->profNr > 0) ctxt->prof = ctxt->profTab[ctxt->profNr - 1]; else ctxt->prof = (long) 0; ret = ctxt->profTab[ctxt->profNr]; ctxt->profTab[ctxt->profNr] = 0; return (ret); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BeginInstallWithManifestFunction::OnParseSuccess( const SkBitmap& icon, DictionaryValue* parsed_manifest) { CHECK(parsed_manifest); icon_ = icon; parsed_manifest_.reset(parsed_manifest); std::string init_errors; dummy_extension_ = Extension::Create( FilePath(), Extension::INTERNAL, *static_cast<DictionaryValue*>(parsed_manifest_.get()), Extension::NO_FLAGS, &init_errors); if (!dummy_extension_.get()) { OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError)); return; } if (icon_.empty()) icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app()); ShowExtensionInstallDialog(profile(), this, dummy_extension_.get(), &icon_, dummy_extension_->GetPermissionMessageStrings(), ExtensionInstallUI::INSTALL_PROMPT); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int snd_timer_user_params(struct file *file, struct snd_timer_params __user *_params) { struct snd_timer_user *tu; struct snd_timer_params params; struct snd_timer *t; struct snd_timer_read *tr; struct snd_timer_tread *ttr; int err; tu = file->private_data; if (!tu->timeri) return -EBADFD; t = tu->timeri->timer; if (!t) return -EBADFD; if (copy_from_user(&params, _params, sizeof(params))) return -EFAULT; if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE) && params.ticks < 1) { err = -EINVAL; goto _end; } if (params.queue_size > 0 && (params.queue_size < 32 || params.queue_size > 1024)) { err = -EINVAL; goto _end; } if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)| (1<<SNDRV_TIMER_EVENT_TICK)| (1<<SNDRV_TIMER_EVENT_START)| (1<<SNDRV_TIMER_EVENT_STOP)| (1<<SNDRV_TIMER_EVENT_CONTINUE)| (1<<SNDRV_TIMER_EVENT_PAUSE)| (1<<SNDRV_TIMER_EVENT_SUSPEND)| (1<<SNDRV_TIMER_EVENT_RESUME)| (1<<SNDRV_TIMER_EVENT_MSTART)| (1<<SNDRV_TIMER_EVENT_MSTOP)| (1<<SNDRV_TIMER_EVENT_MCONTINUE)| (1<<SNDRV_TIMER_EVENT_MPAUSE)| (1<<SNDRV_TIMER_EVENT_MSUSPEND)| (1<<SNDRV_TIMER_EVENT_MRESUME))) { err = -EINVAL; goto _end; } snd_timer_stop(tu->timeri); spin_lock_irq(&t->lock); tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO| SNDRV_TIMER_IFLG_EXCLUSIVE| SNDRV_TIMER_IFLG_EARLY_EVENT); if (params.flags & SNDRV_TIMER_PSFLG_AUTO) tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO; if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE) tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE; if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT) tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT; spin_unlock_irq(&t->lock); if (params.queue_size > 0 && (unsigned int)tu->queue_size != params.queue_size) { if (tu->tread) { ttr = kmalloc(params.queue_size * sizeof(*ttr), GFP_KERNEL); if (ttr) { kfree(tu->tqueue); tu->queue_size = params.queue_size; tu->tqueue = ttr; } } else { tr = kmalloc(params.queue_size * sizeof(*tr), GFP_KERNEL); if (tr) { kfree(tu->queue); tu->queue_size = params.queue_size; tu->queue = tr; } } } tu->qhead = tu->qtail = tu->qused = 0; if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) { if (tu->tread) { struct snd_timer_tread tread; tread.event = SNDRV_TIMER_EVENT_EARLY; tread.tstamp.tv_sec = 0; tread.tstamp.tv_nsec = 0; tread.val = 0; snd_timer_user_append_to_tqueue(tu, &tread); } else { struct snd_timer_read *r = &tu->queue[0]; r->resolution = 0; r->ticks = 0; tu->qused++; tu->qtail++; } } tu->filter = params.filter; tu->ticks = params.ticks; err = 0; _end: if (copy_to_user(_params, &params, sizeof(params))) return -EFAULT; return err; } CWE ID: CWE-200 Target: 1 Example 2: Code: static void setup_rw_floppy(void) { int i; int r; int flags; unsigned long ready_date; void (*function)(void); flags = raw_cmd->flags; if (flags & (FD_RAW_READ | FD_RAW_WRITE)) flags |= FD_RAW_INTR; if ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)) { ready_date = DRS->spinup_date + DP->spinup; /* If spinup will take a long time, rerun scandrives * again just before spinup completion. Beware that * after scandrives, we must again wait for selection. */ if (time_after(ready_date, jiffies + DP->select_delay)) { ready_date -= DP->select_delay; function = floppy_start; } else function = setup_rw_floppy; /* wait until the floppy is spinning fast enough */ if (fd_wait_for_completion(ready_date, function)) return; } if ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE)) setup_DMA(); if (flags & FD_RAW_INTR) do_floppy = main_command_interrupt; r = 0; for (i = 0; i < raw_cmd->cmd_count; i++) r |= output_byte(raw_cmd->cmd[i]); debugt(__func__, "rw_command"); if (r) { cont->error(); reset_fdc(); return; } if (!(flags & FD_RAW_INTR)) { inr = result(); cont->interrupt(); } else if (flags & FD_RAW_NEED_DISK) fd_watchdog(); } 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: FakeOneGoogleBarFetcher* one_google_bar_fetcher() { return static_cast<FakeOneGoogleBarFetcher*>( OneGoogleBarServiceFactory::GetForProfile(browser()->profile()) ->fetcher_for_testing()); } 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 sas_init_disc(struct sas_discovery *disc, struct asd_sas_port *port) { int i; static const work_func_t sas_event_fns[DISC_NUM_EVENTS] = { [DISCE_DISCOVER_DOMAIN] = sas_discover_domain, [DISCE_REVALIDATE_DOMAIN] = sas_revalidate_domain, [DISCE_PROBE] = sas_probe_devices, [DISCE_SUSPEND] = sas_suspend_devices, [DISCE_RESUME] = sas_resume_devices, [DISCE_DESTRUCT] = sas_destruct_devices, }; disc->pending = 0; for (i = 0; i < DISC_NUM_EVENTS; i++) { INIT_SAS_WORK(&disc->disc_work[i].work, sas_event_fns[i]); disc->disc_work[i].port = port; } } CWE ID: Target: 1 Example 2: Code: void WebBluetoothServiceImpl::OnDescriptorWriteValueSuccess( RemoteDescriptorWriteValueCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::move(callback).Run(blink::mojom::WebBluetoothResult::SUCCESS); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PlatformSensorAndroid::PlatformSensorAndroid( mojom::SensorType type, mojo::ScopedSharedBufferMapping mapping, PlatformSensorProvider* provider, const JavaRef<jobject>& java_sensor) : PlatformSensor(type, std::move(mapping), provider) { JNIEnv* env = AttachCurrentThread(); j_object_.Reset(java_sensor); Java_PlatformSensor_initPlatformSensorAndroid(env, j_object_, reinterpret_cast<jlong>(this)); } CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void sas_destruct_devices(struct work_struct *work) { struct domain_device *dev, *n; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; clear_bit(DISCE_DESTRUCT, &port->disc.pending); list_for_each_entry_safe(dev, n, &port->destroy_list, disco_list_node) { list_del_init(&dev->disco_list_node); sas_remove_children(&dev->rphy->dev); sas_rphy_delete(dev->rphy); sas_unregister_common_dev(port, dev); } } CWE ID: Target: 1 Example 2: Code: bool SharedMemory::Lock(uint32 timeout_ms, SECURITY_ATTRIBUTES* sec_attr) { if (lock_ == NULL) { std::wstring name = name_; name.append(L"lock"); lock_ = CreateMutex(sec_attr, FALSE, name.c_str()); if (lock_ == NULL) { DPLOG(ERROR) << "Could not create mutex."; return false; // there is nothing good we can do here. } } DWORD result = WaitForSingleObject(lock_, timeout_ms); return (result == WAIT_OBJECT_0); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WebContentsImpl::FocusLocationBarByDefault() { NavigationEntry* entry = controller_.GetVisibleEntry(); if (entry && entry->GetURL() == GURL(url::kAboutBlankURL)) return true; return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this); } 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 WebPage::touchPointAsMouseEvent(const Platform::TouchPoint& point, unsigned modifiers) { if (d->m_page->defersLoading()) return; if (d->m_fullScreenPluginView.get()) return; d->m_lastUserEventTimestamp = currentTime(); Platform::TouchPoint tPoint = point; tPoint.m_pos = d->mapFromTransformed(tPoint.m_pos); d->m_touchEventHandler->handleTouchPoint(tPoint, modifiers); } CWE ID: Target: 1 Example 2: Code: void SetShelfVisibilityState(aura::Window* window, ShelfVisibilityState visibility_state) { Shelf* shelf = GetShelfForWindow(window); shelf->shelf_layout_manager()->SetState(visibility_state); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void V8Console::groupCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { ConsoleHelper(info).reportCallWithDefaultArgument(ConsoleAPIType::kStartGroup, String16("console.group")); } CWE ID: CWE-79 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: error::Error GLES2DecoderPassthroughImpl::DoEndQueryEXT(GLenum target, uint32_t submit_count) { if (IsEmulatedQueryTarget(target)) { auto active_query_iter = active_queries_.find(target); if (active_query_iter == active_queries_.end()) { InsertError(GL_INVALID_OPERATION, "No active query on target."); return error::kNoError; } if (target == GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM && !pending_read_pixels_.empty()) { GLuint query_service_id = active_query_iter->second.service_id; pending_read_pixels_.back().waiting_async_pack_queries.insert( query_service_id); } } else { CheckErrorCallbackState(); api()->glEndQueryFn(target); if (CheckErrorCallbackState()) { return error::kNoError; } } DCHECK(active_queries_.find(target) != active_queries_.end()); ActiveQuery active_query = std::move(active_queries_[target]); active_queries_.erase(target); PendingQuery pending_query; pending_query.target = target; pending_query.service_id = active_query.service_id; pending_query.shm = std::move(active_query.shm); pending_query.sync = active_query.sync; pending_query.submit_count = submit_count; switch (target) { case GL_COMMANDS_COMPLETED_CHROMIUM: pending_query.commands_completed_fence = gl::GLFence::Create(); break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: pending_query.buffer_shadow_update_fence = gl::GLFence::Create(); pending_query.buffer_shadow_updates = std::move(buffer_shadow_updates_); buffer_shadow_updates_.clear(); break; default: break; } pending_queries_.push_back(std::move(pending_query)); return ProcessQueries(false); } CWE ID: CWE-416 Target: 1 Example 2: Code: static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { unsigned error = 0; char *key = 0, *str = 0; unsigned i; while(!error) /*not really a while loop, only used to break on error*/ { unsigned length, string2_begin; length = 0; while(length < chunkLength && data[length] != 0) length++; /*even though it's not allowed by the standard, no error is thrown if there's no null termination char, if the text is empty*/ if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ key = (char*)malloc(length + 1); if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ key[length] = 0; for(i = 0; i < length; i++) key[i] = (char)data[i]; string2_begin = length + 1; /*skip keyword null terminator*/ length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin; str = (char*)malloc(length + 1); if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ str[length] = 0; for(i = 0; i < length; i++) str[i] = (char)data[string2_begin + i]; error = lodepng_add_text(info, key, str); break; } free(key); free(str); return error; } 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: cf2_getBlueMetrics( CFF_Decoder* decoder, CF2_Fixed* blueScale, CF2_Fixed* blueShift, CF2_Fixed* blueFuzz ) { FT_ASSERT( decoder && decoder->current_subfont ); *blueScale = FT_DivFix( decoder->current_subfont->private_dict.blue_scale, cf2_intToFixed( 1000 ) ); *blueShift = cf2_intToFixed( decoder->current_subfont->private_dict.blue_shift ); *blueFuzz = cf2_intToFixed( decoder->current_subfont->private_dict.blue_fuzz ); } 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: iperf_on_connect(struct iperf_test *test) { time_t now_secs; const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT"; char now_str[100]; char ipr[INET6_ADDRSTRLEN]; int port; struct sockaddr_storage sa; struct sockaddr_in *sa_inP; struct sockaddr_in6 *sa_in6P; socklen_t len; int opt; now_secs = time((time_t*) 0); (void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs)); if (test->json_output) cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s timesecs: %d", now_str, (int64_t) now_secs)); else if (test->verbose) iprintf(test, report_time, now_str); if (test->role == 'c') { if (test->json_output) cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s port: %d", test->server_hostname, (int64_t) test->server_port)); else { iprintf(test, report_connecting, test->server_hostname, test->server_port); if (test->reverse) iprintf(test, report_reverse, test->server_hostname); } } else { len = sizeof(sa); getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len); if (getsockdomain(test->ctrl_sck) == AF_INET) { sa_inP = (struct sockaddr_in *) &sa; inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr)); port = ntohs(sa_inP->sin_port); } else { sa_in6P = (struct sockaddr_in6 *) &sa; inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr)); port = ntohs(sa_in6P->sin6_port); } mapped_v4_to_regular_v4(ipr); if (test->json_output) cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s port: %d", ipr, (int64_t) port)); else iprintf(test, report_accepted, ipr, port); } if (test->json_output) { cJSON_AddStringToObject(test->json_start, "cookie", test->cookie); if (test->protocol->id == SOCK_STREAM) { if (test->settings->mss) cJSON_AddIntToObject(test->json_start, "tcp_mss", test->settings->mss); else { len = sizeof(opt); getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len); cJSON_AddIntToObject(test->json_start, "tcp_mss_default", opt); } } } else if (test->verbose) { iprintf(test, report_cookie, test->cookie); if (test->protocol->id == SOCK_STREAM) { if (test->settings->mss) iprintf(test, " TCP MSS: %d\n", test->settings->mss); else { len = sizeof(opt); getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len); iprintf(test, " TCP MSS: %d (default)\n", opt); } } } } CWE ID: CWE-119 Target: 1 Example 2: Code: TargetHandler::TargetHandler() : DevToolsDomainHandler(Target::Metainfo::domainName), auto_attacher_( base::Bind(&TargetHandler::AutoAttach, base::Unretained(this)), base::Bind(&TargetHandler::AutoDetach, base::Unretained(this))), discover_(false), weak_factory_(this) {} 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 bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) { u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO); struct vcpu_vmx *vmx = to_vmx(vcpu); struct vmcs12 *vmcs12 = get_vmcs12(vcpu); u32 exit_reason = vmx->exit_reason; trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason, vmcs_readl(EXIT_QUALIFICATION), vmx->idt_vectoring_info, intr_info, vmcs_read32(VM_EXIT_INTR_ERROR_CODE), KVM_ISA_VMX); if (vmx->nested.nested_run_pending) return 0; if (unlikely(vmx->fail)) { pr_info_ratelimited("%s failed vm entry %x\n", __func__, vmcs_read32(VM_INSTRUCTION_ERROR)); return 1; } switch (exit_reason) { case EXIT_REASON_EXCEPTION_NMI: if (!is_exception(intr_info)) return 0; else if (is_page_fault(intr_info)) return enable_ept; else if (is_no_device(intr_info) && !(vmcs12->guest_cr0 & X86_CR0_TS)) return 0; return vmcs12->exception_bitmap & (1u << (intr_info & INTR_INFO_VECTOR_MASK)); case EXIT_REASON_EXTERNAL_INTERRUPT: return 0; case EXIT_REASON_TRIPLE_FAULT: return 1; case EXIT_REASON_PENDING_INTERRUPT: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING); case EXIT_REASON_NMI_WINDOW: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING); case EXIT_REASON_TASK_SWITCH: return 1; case EXIT_REASON_CPUID: if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa) return 0; return 1; case EXIT_REASON_HLT: return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING); case EXIT_REASON_INVD: return 1; case EXIT_REASON_INVLPG: return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING); case EXIT_REASON_RDPMC: return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING); case EXIT_REASON_RDTSC: return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING); case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR: case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD: case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD: case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE: case EXIT_REASON_VMOFF: case EXIT_REASON_VMON: case EXIT_REASON_INVEPT: /* * VMX instructions trap unconditionally. This allows L1 to * emulate them for its L2 guest, i.e., allows 3-level nesting! */ return 1; case EXIT_REASON_CR_ACCESS: return nested_vmx_exit_handled_cr(vcpu, vmcs12); case EXIT_REASON_DR_ACCESS: return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING); case EXIT_REASON_IO_INSTRUCTION: return nested_vmx_exit_handled_io(vcpu, vmcs12); case EXIT_REASON_MSR_READ: case EXIT_REASON_MSR_WRITE: return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason); case EXIT_REASON_INVALID_STATE: return 1; case EXIT_REASON_MWAIT_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING); case EXIT_REASON_MONITOR_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING); case EXIT_REASON_PAUSE_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) || nested_cpu_has2(vmcs12, SECONDARY_EXEC_PAUSE_LOOP_EXITING); case EXIT_REASON_MCE_DURING_VMENTRY: return 0; case EXIT_REASON_TPR_BELOW_THRESHOLD: return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW); case EXIT_REASON_APIC_ACCESS: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES); case EXIT_REASON_EPT_VIOLATION: /* * L0 always deals with the EPT violation. If nested EPT is * used, and the nested mmu code discovers that the address is * missing in the guest EPT table (EPT12), the EPT violation * will be injected with nested_ept_inject_page_fault() */ return 0; case EXIT_REASON_EPT_MISCONFIG: /* * L2 never uses directly L1's EPT, but rather L0's own EPT * table (shadow on EPT) or a merged EPT table that L0 built * (EPT on EPT). So any problems with the structure of the * table is L0's fault. */ return 0; case EXIT_REASON_WBINVD: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING); case EXIT_REASON_XSETBV: return 1; default: return 1; } } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data[big_key_path]; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_instantiated(key) && (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); } CWE ID: CWE-20 Target: 1 Example 2: Code: int avpriv_unlock_avformat(void) { if (lockmgr_cb) { if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE)) return -1; } return 0; } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int efx_ethtool_set_settings(struct net_device *net_dev, struct ethtool_cmd *ecmd) { struct efx_nic *efx = netdev_priv(net_dev); int rc; /* GMAC does not support 1000Mbps HD */ if ((ethtool_cmd_speed(ecmd) == SPEED_1000) && (ecmd->duplex != DUPLEX_FULL)) { netif_dbg(efx, drv, efx->net_dev, "rejecting unsupported 1000Mbps HD setting\n"); return -EINVAL; } mutex_lock(&efx->mac_lock); rc = efx->phy_op->set_settings(efx, ecmd); mutex_unlock(&efx->mac_lock); return rc; } 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: check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: xfs_buf_read_map( struct xfs_buftarg *target, struct xfs_buf_map *map, int nmaps, xfs_buf_flags_t flags, const struct xfs_buf_ops *ops) { struct xfs_buf *bp; flags |= XBF_READ; bp = xfs_buf_get_map(target, map, nmaps, flags); if (bp) { trace_xfs_buf_read(bp, flags, _RET_IP_); if (!XFS_BUF_ISDONE(bp)) { XFS_STATS_INC(xb_get_read); bp->b_ops = ops; _xfs_buf_read(bp, flags); } else if (flags & XBF_ASYNC) { /* * Read ahead call which is already satisfied, * drop the buffer */ xfs_buf_relse(bp); return NULL; } else { /* We do not want read in the flags */ bp->b_flags &= ~XBF_READ; } } return bp; } 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: HandleCacheRedirectRequest(const net::test_server::HttpRequest& request) { if (!base::StartsWith(request.relative_url, "/cached-redirect?", base::CompareCase::INSENSITIVE_ASCII)) { return std::unique_ptr<net::test_server::HttpResponse>(); } GURL request_url = request.GetURL(); std::string dest = net::UnescapeBinaryURLComponent(request_url.query_piece()); auto http_response = std::make_unique<net::test_server::BasicHttpResponse>(); http_response->set_code(net::HTTP_MOVED_PERMANENTLY); http_response->AddCustomHeader("Location", dest); http_response->set_content_type("text/html"); http_response->set_content(base::StringPrintf( "<html><head></head><body>Redirecting to %s</body></html>", dest.c_str())); http_response->AddCustomHeader("Cache-Control", "max-age=6000"); return http_response; } 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: long mkvparser::UnserializeFloat( IMkvReader* pReader, long long pos, long long size_, double& result) { assert(pReader); assert(pos >= 0); if ((size_ != 4) && (size_ != 8)) return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); unsigned char buf[8]; const int status = pReader->Read(pos, size, buf); if (status < 0) //error return status; if (size == 4) { union { float f; unsigned long ff; }; ff = 0; for (int i = 0;;) { ff |= buf[i]; if (++i >= 4) break; ff <<= 8; } result = f; } else { assert(size == 8); union { double d; unsigned long long dd; }; dd = 0; for (int i = 0;;) { dd |= buf[i]; if (++i >= 8) break; dd <<= 8; } result = d; } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline u64 evmcs_read64(unsigned long field) { 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: upnp_event_create_notify(struct subscriber * sub) { struct upnp_event_notify * obj; /*struct timeval sock_timeout;*/ obj = calloc(1, sizeof(struct upnp_event_notify)); if(!obj) { syslog(LOG_ERR, "%s: calloc(): %m", "upnp_event_create_notify"); return; } obj->sub = sub; obj->state = ECreated; #ifdef ENABLE_IPV6 obj->s = socket((obj->sub->callback[7] == '[') ? PF_INET6 : PF_INET, SOCK_STREAM, 0); #else obj->s = socket(PF_INET, SOCK_STREAM, 0); #endif if(obj->s<0) { syslog(LOG_ERR, "%s: socket(): %m", "upnp_event_create_notify"); goto error; } #if 0 /* does not work for non blocking connect() */ /* set timeout to 3 seconds */ sock_timeout.tv_sec = 3; sock_timeout.tv_usec = 0; if(setsockopt(obj->s, SOL_SOCKET, SO_RCVTIMEO, &sock_timeout, sizeof(struct timeval)) < 0) { syslog(LOG_WARNING, "%s: setsockopt(SO_RCVTIMEO): %m", "upnp_event_create_notify"); } sock_timeout.tv_sec = 3; sock_timeout.tv_usec = 0; if(setsockopt(obj->s, SOL_SOCKET, SO_SNDTIMEO, &sock_timeout, sizeof(struct timeval)) < 0) { syslog(LOG_WARNING, "%s: setsockopt(SO_SNDTIMEO): %m", "upnp_event_create_notify"); } #endif /* set socket non blocking */ if(!set_non_blocking(obj->s)) { syslog(LOG_ERR, "%s: set_non_blocking(): %m", "upnp_event_create_notify"); goto error; } if(sub) sub->notify = obj; LIST_INSERT_HEAD(&notifylist, obj, entries); return; error: if(obj->s >= 0) close(obj->s); free(obj); } 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: evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen) { int port; char buf[128]; const char *cp, *addr_part, *port_part; int is_ipv6; /* recognized formats are: * [ipv6]:port * ipv6 * [ipv6] * ipv4:port * ipv4 */ cp = strchr(ip_as_string, ':'); if (*ip_as_string == '[') { int len; if (!(cp = strchr(ip_as_string, ']'))) { return -1; } len = (int) ( cp-(ip_as_string + 1) ); if (len > (int)sizeof(buf)-1) { return -1; } memcpy(buf, ip_as_string+1, len); buf[len] = '\0'; addr_part = buf; if (cp[1] == ':') port_part = cp+2; else port_part = NULL; is_ipv6 = 1; } else if (cp && strchr(cp+1, ':')) { is_ipv6 = 1; addr_part = ip_as_string; port_part = NULL; } else if (cp) { is_ipv6 = 0; if (cp - ip_as_string > (int)sizeof(buf)-1) { return -1; } memcpy(buf, ip_as_string, cp-ip_as_string); buf[cp-ip_as_string] = '\0'; addr_part = buf; port_part = cp+1; } else { addr_part = ip_as_string; port_part = NULL; is_ipv6 = 0; } if (port_part == NULL) { port = 0; } else { port = atoi(port_part); if (port <= 0 || port > 65535) { return -1; } } if (!addr_part) return -1; /* Should be impossible. */ #ifdef AF_INET6 if (is_ipv6) { struct sockaddr_in6 sin6; memset(&sin6, 0, sizeof(sin6)); #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN sin6.sin6_len = sizeof(sin6); #endif sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(port); if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr)) return -1; if ((int)sizeof(sin6) > *outlen) return -1; memset(out, 0, *outlen); memcpy(out, &sin6, sizeof(sin6)); *outlen = sizeof(sin6); return 0; } else #endif { struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN sin.sin_len = sizeof(sin); #endif sin.sin_family = AF_INET; sin.sin_port = htons(port); if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr)) return -1; if ((int)sizeof(sin) > *outlen) return -1; memset(out, 0, *outlen); memcpy(out, &sin, sizeof(sin)); *outlen = sizeof(sin); return 0; } } CWE ID: CWE-119 Target: 1 Example 2: Code: ptaaWrite(const char *filename, PTAA *ptaa, l_int32 type) { l_int32 ret; FILE *fp; PROCNAME("ptaaWrite"); if (!filename) return ERROR_INT("filename not defined", procName, 1); if (!ptaa) return ERROR_INT("ptaa not defined", procName, 1); if ((fp = fopenWriteStream(filename, "w")) == NULL) return ERROR_INT("stream not opened", procName, 1); ret = ptaaWriteStream(fp, ptaa, type); fclose(fp); if (ret) return ERROR_INT("ptaa not written to stream", procName, 1); return 0; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: HRESULT CGaiaCredentialBase::GetBitmapValueImpl(DWORD field_id, HBITMAP* phbmp) { HRESULT hr = E_INVALIDARG; switch (field_id) { case FID_PROVIDER_LOGO: *phbmp = ::LoadBitmap(CURRENT_MODULE(), MAKEINTRESOURCE(IDB_GOOGLE_LOGO_SMALL)); if (*phbmp) hr = S_OK; break; default: break; } return hr; } 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: VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::VaapiVP9Accelerator( VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper) : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { DCHECK(vaapi_wrapper_); DCHECK(vaapi_dec_); } CWE ID: CWE-362 Target: 1 Example 2: Code: size_t mptsas_config_io_unit_0(MPTSASState *s, uint8_t **data, int address) { PCIDevice *pci = PCI_DEVICE(s); uint64_t unique_value = 0x53504D554D4551LL; /* "QEMUMPTx" */ unique_value |= (uint64_t)pci->devfn << 56; return MPTSAS_CONFIG_PACK(0, MPI_CONFIG_PAGETYPE_IO_UNIT, 0x00, "q", unique_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: void GraphicsContext::drawFocusRing(const Path& path, int width, int offset, const Color& color) { } 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: SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } CWE ID: CWE-190 Target: 1 Example 2: Code: static int __tipc_nl_add_sk_publ(struct sk_buff *skb, struct netlink_callback *cb, struct publication *publ) { void *hdr; struct nlattr *attrs; hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, &tipc_genl_family, NLM_F_MULTI, TIPC_NL_PUBL_GET); if (!hdr) goto msg_cancel; attrs = nla_nest_start(skb, TIPC_NLA_PUBL); if (!attrs) goto genlmsg_cancel; if (nla_put_u32(skb, TIPC_NLA_PUBL_KEY, publ->key)) goto attr_msg_cancel; if (nla_put_u32(skb, TIPC_NLA_PUBL_TYPE, publ->type)) goto attr_msg_cancel; if (nla_put_u32(skb, TIPC_NLA_PUBL_LOWER, publ->lower)) goto attr_msg_cancel; if (nla_put_u32(skb, TIPC_NLA_PUBL_UPPER, publ->upper)) goto attr_msg_cancel; nla_nest_end(skb, attrs); genlmsg_end(skb, hdr); return 0; attr_msg_cancel: nla_nest_cancel(skb, attrs); genlmsg_cancel: genlmsg_cancel(skb, hdr); msg_cancel: return -EMSGSIZE; } 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: HarfBuzzShaper::HarfBuzzShaper(const Font* font, const TextRun& run, const GlyphData* emphasisData, HashSet<const SimpleFontData*>* fallbackFonts, FloatRect* bounds) : Shaper(font, run, emphasisData, fallbackFonts, bounds) , m_normalizedBufferLength(0) , m_wordSpacingAdjustment(font->fontDescription().wordSpacing()) , m_letterSpacing(font->fontDescription().letterSpacing()) , m_expansionOpportunityCount(0) , m_fromIndex(0) , m_toIndex(m_run.length()) { m_normalizedBuffer = adoptArrayPtr(new UChar[m_run.length() + 1]); normalizeCharacters(m_run, m_run.length(), m_normalizedBuffer.get(), &m_normalizedBufferLength); setExpansion(m_run.expansion()); setFontFeatures(); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sclp_ctl_ioctl_sccb(void __user *user_area) { struct sclp_ctl_sccb ctl_sccb; struct sccb_header *sccb; int rc; if (copy_from_user(&ctl_sccb, user_area, sizeof(ctl_sccb))) return -EFAULT; if (!sclp_ctl_cmdw_supported(ctl_sccb.cmdw)) return -EOPNOTSUPP; sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA); if (!sccb) return -ENOMEM; if (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sizeof(*sccb))) { rc = -EFAULT; goto out_free; } if (sccb->length > PAGE_SIZE || sccb->length < 8) return -EINVAL; if (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sccb->length)) { rc = -EFAULT; goto out_free; } rc = sclp_sync_request(ctl_sccb.cmdw, sccb); if (rc) goto out_free; if (copy_to_user(u64_to_uptr(ctl_sccb.sccb), sccb, sccb->length)) rc = -EFAULT; out_free: free_page((unsigned long) sccb); return rc; } CWE ID: CWE-362 Target: 1 Example 2: Code: void AccessibilityUIElement::getChildren(Vector<RefPtr<AccessibilityUIElement> >& children) { if (!m_element || !ATK_IS_OBJECT(m_element)) return; int count = childrenCount(); for (int i = 0; i < count; i++) { AtkObject* child = atk_object_ref_accessible_child(ATK_OBJECT(m_element), i); children.append(AccessibilityUIElement::create(child)); } } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int tls12_shared_sigalgs(SSL *s, TLS_SIGALGS *shsig, const unsigned char *pref, size_t preflen, const unsigned char *allow, size_t allowlen) { const unsigned char *ptmp, *atmp; size_t i, j, nmatch = 0; for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) { /* Skip disabled hashes or signature algorithms */ if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SHARED, ptmp)) continue; for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) { if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) { nmatch++; if (shsig) { shsig->rhash = ptmp[0]; shsig->rsign = ptmp[1]; tls1_lookup_sigalg(&shsig->hash_nid, &shsig->sign_nid, &shsig->signandhash_nid, ptmp); shsig++; } break; } } } return nmatch; } 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 ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id, int route_id) { ProcessRouteIDs key(child_id, route_id); DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) << "BlockRequestsForRoute called multiple time for the same RVH"; blocked_loaders_map_[key] = new BlockedLoadersList(); } CWE ID: CWE-399 Target: 1 Example 2: Code: static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot) { unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot); memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes); if (!memslot->dirty_bitmap) return -ENOMEM; return 0; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int jp2_ihdr_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_ihdr_t *ihdr = &box->data.ihdr; if (jp2_getuint32(in, &ihdr->height) || jp2_getuint32(in, &ihdr->width) || jp2_getuint16(in, &ihdr->numcmpts) || jp2_getuint8(in, &ihdr->bpc) || jp2_getuint8(in, &ihdr->comptype) || jp2_getuint8(in, &ihdr->csunk) || jp2_getuint8(in, &ihdr->ipr)) { return -1; } return 0; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: AppCacheUpdateJob::~AppCacheUpdateJob() { if (service_) service_->RemoveObserver(this); if (internal_state_ != COMPLETED) Cancel(); DCHECK(!manifest_fetcher_); DCHECK(pending_url_fetches_.empty()); DCHECK(!inprogress_cache_.get()); DCHECK(pending_master_entries_.empty()); DCHECK(master_entry_fetches_.empty()); if (group_) group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE); } CWE ID: Target: 1 Example 2: Code: int i2d_ECPrivateKey(EC_KEY *a, unsigned char **out) { int ret = 0, ok = 0; unsigned char *buffer = NULL; size_t buf_len = 0, tmp_len; EC_PRIVATEKEY *priv_key = NULL; if (a == NULL || a->group == NULL || a->priv_key == NULL) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_PASSED_NULL_PARAMETER); goto err; } if ((priv_key = EC_PRIVATEKEY_new()) == NULL) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); goto err; } priv_key->version = a->version; buf_len = (size_t)BN_num_bytes(a->priv_key); buffer = OPENSSL_malloc(buf_len); if (buffer == NULL) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); goto err; } if (!BN_bn2bin(a->priv_key, buffer)) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_BN_LIB); goto err; } if (!M_ASN1_OCTET_STRING_set(priv_key->privateKey, buffer, buf_len)) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_ASN1_LIB); goto err; } if (!(a->enc_flag & EC_PKEY_NO_PARAMETERS)) { if ((priv_key->parameters = ec_asn1_group2pkparameters(a->group, priv_key->parameters)) == NULL) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } } if (!(a->enc_flag & EC_PKEY_NO_PUBKEY)) { priv_key->publicKey = M_ASN1_BIT_STRING_new(); if (priv_key->publicKey == NULL) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); goto err; } tmp_len = EC_POINT_point2oct(a->group, a->pub_key, a->conv_form, NULL, 0, NULL); if (tmp_len > buf_len) { unsigned char *tmp_buffer = OPENSSL_realloc(buffer, tmp_len); if (!tmp_buffer) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); goto err; } buffer = tmp_buffer; buf_len = tmp_len; } if (!EC_POINT_point2oct(a->group, a->pub_key, a->conv_form, buffer, buf_len, NULL)) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } priv_key->publicKey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); priv_key->publicKey->flags |= ASN1_STRING_FLAG_BITS_LEFT; if (!M_ASN1_BIT_STRING_set(priv_key->publicKey, buffer, buf_len)) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_ASN1_LIB); goto err; } } if ((ret = i2d_EC_PRIVATEKEY(priv_key, out)) == 0) { ECerr(EC_F_I2D_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } ok = 1; err: if (buffer) OPENSSL_free(buffer); if (priv_key) EC_PRIVATEKEY_free(priv_key); return (ok ? ret : 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: get_html_data (MAPI_Attr *a) { VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1); int j; for (j = 0; j < a->num_values; j++) { body[j] = XMALLOC(VarLenData, 1); body[j]->len = a->values[j].len; body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len); memmove (body[j]->data, a->values[j].data.buf, body[j]->len); } return body; } 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: int perf_output_begin(struct perf_output_handle *handle, struct perf_event *event, unsigned int size, int nmi, int sample) { struct ring_buffer *rb; unsigned long tail, offset, head; int have_lost; struct perf_sample_data sample_data; struct { struct perf_event_header header; u64 id; u64 lost; } lost_event; rcu_read_lock(); /* * For inherited events we send all the output towards the parent. */ if (event->parent) event = event->parent; rb = rcu_dereference(event->rb); if (!rb) goto out; handle->rb = rb; handle->event = event; handle->nmi = nmi; handle->sample = sample; if (!rb->nr_pages) goto out; have_lost = local_read(&rb->lost); if (have_lost) { lost_event.header.size = sizeof(lost_event); perf_event_header__init_id(&lost_event.header, &sample_data, event); size += lost_event.header.size; } perf_output_get_handle(handle); do { /* * Userspace could choose to issue a mb() before updating the * tail pointer. So that all reads will be completed before the * write is issued. */ tail = ACCESS_ONCE(rb->user_page->data_tail); smp_rmb(); offset = head = local_read(&rb->head); head += size; if (unlikely(!perf_output_space(rb, tail, offset, head))) goto fail; } while (local_cmpxchg(&rb->head, offset, head) != offset); if (head - local_read(&rb->wakeup) > rb->watermark) local_add(rb->watermark, &rb->wakeup); handle->page = offset >> (PAGE_SHIFT + page_order(rb)); handle->page &= rb->nr_pages - 1; handle->size = offset & ((PAGE_SIZE << page_order(rb)) - 1); handle->addr = rb->data_pages[handle->page]; handle->addr += handle->size; handle->size = (PAGE_SIZE << page_order(rb)) - handle->size; if (have_lost) { lost_event.header.type = PERF_RECORD_LOST; lost_event.header.misc = 0; lost_event.id = event->id; lost_event.lost = local_xchg(&rb->lost, 0); perf_output_put(handle, lost_event); perf_event__output_id_sample(event, handle, &sample_data); } return 0; fail: local_inc(&rb->lost); perf_output_put_handle(handle); out: rcu_read_unlock(); return -ENOSPC; } CWE ID: CWE-399 Target: 1 Example 2: Code: dbus_service_name_handler(vector_t *strvec) { FREE_PTR(global_data->dbus_service_name); global_data->dbus_service_name = set_value(strvec); } 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: IW_IMPL(int) iw_get_input_density(struct iw_context *ctx, double *px, double *py, int *pcode) { *px = 1.0; *py = 1.0; *pcode = ctx->img1.density_code; if(ctx->img1.density_code!=IW_DENSITY_UNKNOWN) { *px = ctx->img1.density_x; *py = ctx->img1.density_y; return 1; } return 0; } CWE ID: CWE-369 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void NavigationRequest::OnRequestRedirected( const net::RedirectInfo& redirect_info, const scoped_refptr<network::ResourceResponse>& response) { response_ = response; ssl_info_ = response->head.ssl_info; #if defined(OS_ANDROID) base::WeakPtr<NavigationRequest> this_ptr(weak_factory_.GetWeakPtr()); bool should_override_url_loading = false; if (!GetContentClient()->browser()->ShouldOverrideUrlLoading( frame_tree_node_->frame_tree_node_id(), browser_initiated_, redirect_info.new_url, redirect_info.new_method, false, true, frame_tree_node_->IsMainFrame(), common_params_.transition, &should_override_url_loading)) { return; } if (!this_ptr) return; if (should_override_url_loading) { navigation_handle_->set_net_error_code(net::ERR_ABORTED); common_params_.url = redirect_info.new_url; common_params_.method = redirect_info.new_method; navigation_handle_->UpdateStateFollowingRedirect( GURL(redirect_info.new_referrer), base::Bind(&NavigationRequest::OnRedirectChecksComplete, base::Unretained(this))); frame_tree_node_->ResetNavigationRequest(false, true); return; } #endif if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRedirectToURL( redirect_info.new_url)) { DVLOG(1) << "Denied redirect for " << redirect_info.new_url.possibly_invalid_spec(); navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT); frame_tree_node_->ResetNavigationRequest(false, true); return; } if (!browser_initiated_ && source_site_instance() && !ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL( source_site_instance()->GetProcess()->GetID(), redirect_info.new_url)) { DVLOG(1) << "Denied unauthorized redirect for " << redirect_info.new_url.possibly_invalid_spec(); navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT); frame_tree_node_->ResetNavigationRequest(false, true); return; } if (redirect_info.new_method != "POST") common_params_.post_data = nullptr; if (commit_params_.navigation_timing.redirect_start.is_null()) { commit_params_.navigation_timing.redirect_start = commit_params_.navigation_timing.fetch_start; } commit_params_.navigation_timing.redirect_end = base::TimeTicks::Now(); commit_params_.navigation_timing.fetch_start = base::TimeTicks::Now(); commit_params_.redirect_response.push_back(response->head); commit_params_.redirect_infos.push_back(redirect_info); if (commit_params_.origin_to_commit) commit_params_.origin_to_commit.reset(); commit_params_.redirects.push_back(common_params_.url); common_params_.url = redirect_info.new_url; common_params_.method = redirect_info.new_method; common_params_.referrer.url = GURL(redirect_info.new_referrer); common_params_.referrer = Referrer::SanitizeForRequest(common_params_.url, common_params_.referrer); net::Error net_error = CheckContentSecurityPolicy(true /* has_followed_redirect */, redirect_info.insecure_scheme_was_upgraded, false /* is_response_check */); if (net_error != net::OK) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net_error), false /*skip_throttles*/, base::nullopt /*error_page_content*/, false /*collapse_frame*/); return; } if (CheckCredentialedSubresource() == CredentialedSubresourceCheckResult::BLOCK_REQUEST || CheckLegacyProtocolInSubresource() == LegacyProtocolInSubresourceCheckResult::BLOCK_REQUEST) { OnRequestFailedInternal( network::URLLoaderCompletionStatus(net::ERR_ABORTED), false /*skip_throttles*/, base::nullopt /*error_page_content*/, false /*collapse_frame*/); return; } scoped_refptr<SiteInstance> site_instance = frame_tree_node_->render_manager()->GetSiteInstanceForNavigationRequest( *this); speculative_site_instance_ = site_instance->HasProcess() ? site_instance : nullptr; if (!site_instance->HasProcess()) { RenderProcessHostImpl::NotifySpareManagerAboutRecentlyUsedBrowserContext( site_instance->GetBrowserContext()); } common_params_.previews_state = GetContentClient()->browser()->DetermineAllowedPreviews( common_params_.previews_state, navigation_handle_.get(), common_params_.url); RenderProcessHost* expected_process = site_instance->HasProcess() ? site_instance->GetProcess() : nullptr; navigation_handle_->WillRedirectRequest( common_params_.referrer.url, expected_process, base::Bind(&NavigationRequest::OnRedirectChecksComplete, base::Unretained(this))); } CWE ID: CWE-20 Target: 1 Example 2: Code: param_functions* get_param_functions() { config_p_funcs.set_param_func(&param); config_p_funcs.set_param_bool_int_func(&param_boolean_int); config_p_funcs.set_param_wo_default_func(&param_without_default); return &config_p_funcs; } 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: int deny_write_access(struct file * file) { struct inode *inode = file->f_path.dentry->d_inode; spin_lock(&inode->i_lock); if (atomic_read(&inode->i_writecount) > 0) { spin_unlock(&inode->i_lock); return -ETXTBSY; } atomic_dec(&inode->i_writecount); spin_unlock(&inode->i_lock); return 0; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ScreenOrientationDispatcherHost::OnUnlockRequest( RenderFrameHost* render_frame_host) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_.get()) return; provider_->UnlockOrientation(); } CWE ID: CWE-362 Target: 1 Example 2: Code: sp<MetaData> OggSource::getFormat() { return mExtractor->mImpl->getFormat(); } 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 skb_entail(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); skb->csum = 0; tcb->seq = tcb->end_seq = tp->write_seq; tcb->tcp_flags = TCPHDR_ACK; tcb->sacked = 0; __skb_header_release(skb); tcp_add_write_queue_tail(sk, skb); sk->sk_wmem_queued += skb->truesize; sk_mem_charge(sk, skb->truesize); if (tp->nonagle & TCP_NAGLE_PUSH) tp->nonagle &= ~TCP_NAGLE_PUSH; tcp_slow_start_after_idle_check(sk); } 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: static void rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data) { memset(task, 0, sizeof(*task)); atomic_set(&task->tk_count, 1); task->tk_flags = task_setup_data->flags; task->tk_ops = task_setup_data->callback_ops; task->tk_calldata = task_setup_data->callback_data; INIT_LIST_HEAD(&task->tk_task); /* Initialize retry counters */ task->tk_garb_retry = 2; task->tk_cred_retry = 2; task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW; task->tk_owner = current->tgid; /* Initialize workqueue for async tasks */ task->tk_workqueue = task_setup_data->workqueue; if (task->tk_ops->rpc_call_prepare != NULL) task->tk_action = rpc_prepare_task; /* starting timestamp */ task->tk_start = ktime_get(); dprintk("RPC: new task initialized, procpid %u\n", task_pid_nr(current)); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void ion_buffer_add(struct ion_device *dev, struct ion_buffer *buffer) { struct rb_node **p = &dev->buffers.rb_node; struct rb_node *parent = NULL; struct ion_buffer *entry; while (*p) { parent = *p; entry = rb_entry(parent, struct ion_buffer, node); if (buffer < entry) { p = &(*p)->rb_left; } else if (buffer > entry) { p = &(*p)->rb_right; } else { pr_err("%s: buffer already found.", __func__); BUG(); } } rb_link_node(&buffer->node, parent, p); rb_insert_color(&buffer->node, &dev->buffers); } 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: LowBatteryObserver::LowBatteryObserver(Profile* profile) : notification_(profile, "battery.chromeos", IDR_NOTIFICATION_LOW_BATTERY, l10n_util::GetStringUTF16(IDS_LOW_BATTERY_TITLE)), remaining_(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: static void DidDownloadImage(const WebContents::ImageDownloadCallback& callback, int id, const GURL& image_url, image_downloader::DownloadResultPtr result) { DCHECK(result); const std::vector<SkBitmap> images = result->images.To<std::vector<SkBitmap>>(); const std::vector<gfx::Size> original_image_sizes = result->original_image_sizes.To<std::vector<gfx::Size>>(); callback.Run(id, result->http_status_code, image_url, images, original_image_sizes); } CWE ID: Target: 1 Example 2: Code: void OnTimeout() { ASSERT(m_workerThread->workerGlobalScope()); m_lastQueuedTask = nullptr; if (m_sharedTimerFunction && m_running && !m_workerThread->workerGlobalScope()->isClosing()) m_sharedTimerFunction(); } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int flush_completed_IO(struct inode *inode) { ext4_io_end_t *io; int ret = 0; int ret2 = 0; if (list_empty(&EXT4_I(inode)->i_completed_io_list)) return ret; dump_completed_IO(inode); while (!list_empty(&EXT4_I(inode)->i_completed_io_list)){ io = list_entry(EXT4_I(inode)->i_completed_io_list.next, ext4_io_end_t, list); /* * Calling ext4_end_io_nolock() to convert completed * IO to written. * * When ext4_sync_file() is called, run_queue() may already * about to flush the work corresponding to this io structure. * It will be upset if it founds the io structure related * to the work-to-be schedule is freed. * * Thus we need to keep the io structure still valid here after * convertion finished. The io structure has a flag to * avoid double converting from both fsync and background work * queue work. */ ret = ext4_end_io_nolock(io); if (ret < 0) ret2 = ret; else list_del_init(&io->list); } return (ret2 < 0) ? ret2 : 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: int vp8dx_receive_compressed_data(VP8D_COMP *pbi, size_t size, const uint8_t *source, int64_t time_stamp) { VP8_COMMON *cm = &pbi->common; int retcode = -1; (void)size; (void)source; pbi->common.error.error_code = VPX_CODEC_OK; retcode = check_fragments_for_errors(pbi); if(retcode <= 0) return retcode; cm->new_fb_idx = get_free_fb (cm); /* setup reference frames for vp8_decode_frame */ pbi->dec_fb_ref[INTRA_FRAME] = &cm->yv12_fb[cm->new_fb_idx]; pbi->dec_fb_ref[LAST_FRAME] = &cm->yv12_fb[cm->lst_fb_idx]; pbi->dec_fb_ref[GOLDEN_FRAME] = &cm->yv12_fb[cm->gld_fb_idx]; pbi->dec_fb_ref[ALTREF_FRAME] = &cm->yv12_fb[cm->alt_fb_idx]; if (setjmp(pbi->common.error.jmp)) { /* We do not know if the missing frame(s) was supposed to update * any of the reference buffers, but we act conservative and * mark only the last buffer as corrupted. */ cm->yv12_fb[cm->lst_fb_idx].corrupted = 1; if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; goto decode_exit; } pbi->common.error.setjmp = 1; retcode = vp8_decode_frame(pbi); if (retcode < 0) { if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } if (swap_frame_buffers (cm)) { pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } vp8_clear_system_state(); if (cm->show_frame) { cm->current_video_frame++; cm->show_frame_mi = cm->mi; } #if CONFIG_ERROR_CONCEALMENT /* swap the mode infos to storage for future error concealment */ if (pbi->ec_enabled && pbi->common.prev_mi) { MODE_INFO* tmp = pbi->common.prev_mi; int row, col; pbi->common.prev_mi = pbi->common.mi; pbi->common.mi = tmp; /* Propagate the segment_ids to the next frame */ for (row = 0; row < pbi->common.mb_rows; ++row) { for (col = 0; col < pbi->common.mb_cols; ++col) { const int i = row*pbi->common.mode_info_stride + col; pbi->common.mi[i].mbmi.segment_id = pbi->common.prev_mi[i].mbmi.segment_id; } } } #endif pbi->ready_for_new_data = 0; pbi->last_time_stamp = time_stamp; decode_exit: pbi->common.error.setjmp = 0; vp8_clear_system_state(); return retcode; } CWE ID: Target: 1 Example 2: Code: void AppCacheUpdateJob::ClearPendingMasterEntries() { for (auto& pair : pending_master_entries_) { PendingHosts& hosts = pair.second; for (AppCacheHost* host : hosts) host->RemoveObserver(this); } pending_master_entries_.clear(); } 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: gss_wrap_aead (minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; gss_buffer_t input_assoc_buffer; gss_buffer_t input_payload_buffer; int * conf_state; gss_buffer_t output_message_buffer; { OM_uint32 status; gss_mechanism mech; gss_union_ctx_id_t ctx; status = val_wrap_aead_args(minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t)context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return (GSS_S_BAD_MECH); return gssint_wrap_aead(mech, minor_status, ctx, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); } CWE ID: CWE-415 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int svc_rdma_init(void) { dprintk("SVCRDMA Module Init, register RPC RDMA transport\n"); dprintk("\tsvcrdma_ord : %d\n", svcrdma_ord); dprintk("\tmax_requests : %u\n", svcrdma_max_requests); dprintk("\tsq_depth : %u\n", svcrdma_max_requests * RPCRDMA_SQ_DEPTH_MULT); dprintk("\tmax_bc_requests : %u\n", svcrdma_max_bc_requests); dprintk("\tmax_inline : %d\n", svcrdma_max_req_size); svc_rdma_wq = alloc_workqueue("svc_rdma", 0, 0); if (!svc_rdma_wq) return -ENOMEM; if (!svcrdma_table_header) svcrdma_table_header = register_sysctl_table(svcrdma_root_table); /* Register RDMA with the SVC transport switch */ svc_reg_xprt_class(&svc_rdma_class); #if defined(CONFIG_SUNRPC_BACKCHANNEL) svc_reg_xprt_class(&svc_rdma_bc_class); #endif return 0; } CWE ID: CWE-404 Target: 1 Example 2: Code: ~MockFetchContext() { } CWE ID: CWE-310 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; 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: void VRDisplay::ProcessScheduledWindowAnimations(double timestamp) { TRACE_EVENT1("gpu", "VRDisplay::window.rAF", "frame", vr_frame_id_); auto doc = navigator_vr_->GetDocument(); if (!doc) return; auto page = doc->GetPage(); if (!page) return; page->Animator().ServiceScriptedAnimations(timestamp); } CWE ID: Target: 1 Example 2: Code: static int vrend_decode_set_sub_ctx(struct vrend_decode_ctx *ctx, int length) { if (length != 1) return EINVAL; uint32_t ctx_sub_id = get_buf_entry(ctx, 1); vrend_renderer_set_sub_ctx(ctx->grctx, ctx_sub_id); return 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: static int __get_device_id(struct ipmi_smi *intf, struct bmc_device *bmc) { int rv; bmc->dyn_id_set = 2; intf->null_user_handler = bmc_device_id_handler; rv = send_get_device_id_cmd(intf); if (rv) return rv; wait_event(intf->waitq, bmc->dyn_id_set != 2); if (!bmc->dyn_id_set) rv = -EIO; /* Something went wrong in the fetch. */ /* dyn_id_set makes the id data available. */ smp_rmb(); intf->null_user_handler = NULL; return rv; } 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 v8::Handle<v8::Value> methodCallback(const v8::Arguments& args) { INC_STATS("DOM.TestMediaQueryListListener.method"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestMediaQueryListListener* imp = V8TestMediaQueryListListener::toNative(args.Holder()); EXCEPTION_BLOCK(RefPtr<MediaQueryListListener>, listener, MediaQueryListListener::create(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->method(listener); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: bool OmniboxViewWin::DeleteAtEndPressed() { return delete_at_end_pressed_; } 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_cmap6_get_info( TT_CMap cmap, TT_CMapInfo *cmap_info ) { FT_Byte* p = cmap->data + 4; cmap_info->format = 6; cmap_info->language = (FT_ULong)TT_PEEK_USHORT( p ); return SFNT_Err_Ok; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ip4_datagram_release_cb(struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; struct flowi4 fl4; struct rtable *rt; if (! __sk_dst_get(sk) || __sk_dst_check(sk, 0)) return; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; rt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (!IS_ERR(rt)) __sk_dst_set(sk, &rt->dst); rcu_read_unlock(); } CWE ID: CWE-416 Target: 1 Example 2: Code: static void op32_poke_tx(struct b43_dmaring *ring, int slot) { b43_dma_write(ring, B43_DMA32_TXINDEX, (u32) (slot * sizeof(struct b43_dmadesc32))); } 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 jobject Bitmap_createFromParcel(JNIEnv* env, jobject, jobject parcel) { if (parcel == NULL) { SkDebugf("-------- unparcel parcel is NULL\n"); return NULL; } android::Parcel* p = android::parcelForJavaObject(env, parcel); const bool isMutable = p->readInt32() != 0; const SkColorType colorType = (SkColorType)p->readInt32(); const SkAlphaType alphaType = (SkAlphaType)p->readInt32(); const int width = p->readInt32(); const int height = p->readInt32(); const int rowBytes = p->readInt32(); const int density = p->readInt32(); if (kN32_SkColorType != colorType && kRGB_565_SkColorType != colorType && kARGB_4444_SkColorType != colorType && kIndex_8_SkColorType != colorType && kAlpha_8_SkColorType != colorType) { SkDebugf("Bitmap_createFromParcel unknown colortype: %d\n", colorType); return NULL; } SkBitmap* bitmap = new SkBitmap; bitmap->setInfo(SkImageInfo::Make(width, height, colorType, alphaType), rowBytes); SkColorTable* ctable = NULL; if (colorType == kIndex_8_SkColorType) { int count = p->readInt32(); if (count > 0) { size_t size = count * sizeof(SkPMColor); const SkPMColor* src = (const SkPMColor*)p->readInplace(size); ctable = new SkColorTable(src, count); } } jbyteArray buffer = GraphicsJNI::allocateJavaPixelRef(env, bitmap, ctable); if (NULL == buffer) { SkSafeUnref(ctable); delete bitmap; return NULL; } SkSafeUnref(ctable); size_t size = bitmap->getSize(); android::Parcel::ReadableBlob blob; android::status_t status = p->readBlob(size, &blob); if (status) { doThrowRE(env, "Could not read bitmap from parcel blob."); delete bitmap; return NULL; } bitmap->lockPixels(); memcpy(bitmap->getPixels(), blob.data(), size); bitmap->unlockPixels(); blob.release(); return GraphicsJNI::createBitmap(env, bitmap, buffer, getPremulBitmapCreateFlags(isMutable), NULL, NULL, density); } 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: ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, const ExtensionInstallPrompt::DoneCallback& done_callback, std::unique_ptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), done_callback_(done_callback), prompt_(std::move(prompt)), container_(NULL), scroll_view_(NULL), handled_result_(false) { InitView(); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void cm_destroy_id(struct ib_cm_id *cm_id, int err) { struct cm_id_private *cm_id_priv; struct cm_work *work; cm_id_priv = container_of(cm_id, struct cm_id_private, id); retest: spin_lock_irq(&cm_id_priv->lock); switch (cm_id->state) { case IB_CM_LISTEN: cm_id->state = IB_CM_IDLE; spin_unlock_irq(&cm_id_priv->lock); spin_lock_irq(&cm.lock); rb_erase(&cm_id_priv->service_node, &cm.listen_service_table); spin_unlock_irq(&cm.lock); break; case IB_CM_SIDR_REQ_SENT: cm_id->state = IB_CM_IDLE; ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg); spin_unlock_irq(&cm_id_priv->lock); break; case IB_CM_SIDR_REQ_RCVD: spin_unlock_irq(&cm_id_priv->lock); cm_reject_sidr_req(cm_id_priv, IB_SIDR_REJECT); break; case IB_CM_REQ_SENT: ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg); spin_unlock_irq(&cm_id_priv->lock); ib_send_cm_rej(cm_id, IB_CM_REJ_TIMEOUT, &cm_id_priv->id.device->node_guid, sizeof cm_id_priv->id.device->node_guid, NULL, 0); break; case IB_CM_REQ_RCVD: if (err == -ENOMEM) { /* Do not reject to allow future retries. */ cm_reset_to_idle(cm_id_priv); spin_unlock_irq(&cm_id_priv->lock); } else { spin_unlock_irq(&cm_id_priv->lock); ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0, NULL, 0); } break; case IB_CM_MRA_REQ_RCVD: case IB_CM_REP_SENT: case IB_CM_MRA_REP_RCVD: ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg); /* Fall through */ case IB_CM_MRA_REQ_SENT: case IB_CM_REP_RCVD: case IB_CM_MRA_REP_SENT: spin_unlock_irq(&cm_id_priv->lock); ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0, NULL, 0); break; case IB_CM_ESTABLISHED: spin_unlock_irq(&cm_id_priv->lock); if (cm_id_priv->qp_type == IB_QPT_XRC_TGT) break; ib_send_cm_dreq(cm_id, NULL, 0); goto retest; case IB_CM_DREQ_SENT: ib_cancel_mad(cm_id_priv->av.port->mad_agent, cm_id_priv->msg); cm_enter_timewait(cm_id_priv); spin_unlock_irq(&cm_id_priv->lock); break; case IB_CM_DREQ_RCVD: spin_unlock_irq(&cm_id_priv->lock); ib_send_cm_drep(cm_id, NULL, 0); break; default: spin_unlock_irq(&cm_id_priv->lock); break; } cm_free_id(cm_id->local_id); cm_deref_id(cm_id_priv); wait_for_completion(&cm_id_priv->comp); while ((work = cm_dequeue_work(cm_id_priv)) != NULL) cm_free_work(work); kfree(cm_id_priv->compare_data); kfree(cm_id_priv->private_data); kfree(cm_id_priv); } 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: find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { guchar *match; int i; /* First try to match any leftover at the start */ if (client->auth_end_offset > 0) { gsize left = strlen (AUTH_END_STRING) - client->auth_end_offset; gsize to_match = MIN (left, buffer->pos); /* Matched at least up to to_match */ if (memcmp (buffer->data, &AUTH_END_STRING[client->auth_end_offset], to_match) == 0) { client->auth_end_offset += to_match; /* Matched all */ if (client->auth_end_offset == strlen (AUTH_END_STRING)) return to_match; /* Matched to end of buffer */ return -1; } /* Did not actually match at start */ client->auth_end_offset = -1; } /* Look for whole match inside buffer */ match = memmem (buffer, buffer->pos, AUTH_END_STRING, strlen (AUTH_END_STRING)); if (match != NULL) return match - buffer->data + strlen (AUTH_END_STRING); /* Record longest prefix match at the end */ for (i = MIN (strlen (AUTH_END_STRING) - 1, buffer->pos); i > 0; i--) { if (memcmp (buffer->data + buffer->pos - i, AUTH_END_STRING, i) == 0) { client->auth_end_offset = i; break; } } return -1; } CWE ID: CWE-436 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: ZEND_API void zend_ts_hash_graceful_destroy(TsHashTable *ht) { begin_write(ht); zend_hash_graceful_destroy(TS_HASH(ht)); end_write(ht); #ifdef ZTS tsrm_mutex_free(ht->mx_reader); tsrm_mutex_free(ht->mx_reader); #endif } CWE ID: Target: 1 Example 2: Code: PHP_RINIT_FUNCTION(pgsql) { PGG(default_link)=-1; PGG(num_links) = PGG(num_persistent); return SUCCESS; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int fib_multipath_hash(const struct fib_info *fi, const struct flowi4 *fl4, const struct sk_buff *skb) { struct net *net = fi->fib_net; struct flow_keys hash_keys; u32 mhash; switch (net->ipv4.sysctl_fib_multipath_hash_policy) { case 0: memset(&hash_keys, 0, sizeof(hash_keys)); hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; if (skb) { ip_multipath_l3_keys(skb, &hash_keys); } else { hash_keys.addrs.v4addrs.src = fl4->saddr; hash_keys.addrs.v4addrs.dst = fl4->daddr; } break; case 1: /* skb is currently provided only when forwarding */ if (skb) { unsigned int flag = FLOW_DISSECTOR_F_STOP_AT_ENCAP; struct flow_keys keys; /* short-circuit if we already have L4 hash present */ if (skb->l4_hash) return skb_get_hash_raw(skb) >> 1; memset(&hash_keys, 0, sizeof(hash_keys)); skb_flow_dissect_flow_keys(skb, &keys, flag); hash_keys.addrs.v4addrs.src = keys.addrs.v4addrs.src; hash_keys.addrs.v4addrs.dst = keys.addrs.v4addrs.dst; hash_keys.ports.src = keys.ports.src; hash_keys.ports.dst = keys.ports.dst; hash_keys.basic.ip_proto = keys.basic.ip_proto; } else { memset(&hash_keys, 0, sizeof(hash_keys)); hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; hash_keys.addrs.v4addrs.src = fl4->saddr; hash_keys.addrs.v4addrs.dst = fl4->daddr; hash_keys.ports.src = fl4->fl4_sport; hash_keys.ports.dst = fl4->fl4_dport; hash_keys.basic.ip_proto = fl4->flowi4_proto; } break; } mhash = flow_hash_from_keys(&hash_keys); return mhash >> 1; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: image_pixel_add_alpha(image_pixel *this, PNG_CONST standard_display *display) { if (this->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(this); if ((this->colour_type & PNG_COLOR_MASK_ALPHA) == 0) { if (this->colour_type == PNG_COLOR_TYPE_GRAY) { if (this->bit_depth < 8) this->bit_depth = 8; if (this->have_tRNS) { this->have_tRNS = 0; /* Check the input, original, channel value here against the * original tRNS gray chunk valie. */ if (this->red == display->transparent.red) this->alphaf = 0; else this->alphaf = 1; } else this->alphaf = 1; this->colour_type = PNG_COLOR_TYPE_GRAY_ALPHA; } else if (this->colour_type == PNG_COLOR_TYPE_RGB) { if (this->have_tRNS) { this->have_tRNS = 0; /* Again, check the exact input values, not the current transformed * value! */ if (this->red == display->transparent.red && this->green == display->transparent.green && this->blue == display->transparent.blue) this->alphaf = 0; else this->alphaf = 1; this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; } } /* The error in the alpha is zero and the sBIT value comes from the * original sBIT data (actually it will always be the original bit depth). */ this->alphae = 0; this->alpha_sBIT = display->alpha_sBIT; } } CWE ID: Target: 1 Example 2: Code: static void netlink_ring_set_copied(struct sock *sk, struct sk_buff *skb) { struct netlink_sock *nlk = nlk_sk(sk); struct netlink_ring *ring = &nlk->rx_ring; struct nl_mmap_hdr *hdr; spin_lock_bh(&sk->sk_receive_queue.lock); hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED); if (hdr == NULL) { spin_unlock_bh(&sk->sk_receive_queue.lock); kfree_skb(skb); netlink_overrun(sk); return; } netlink_increment_head(ring); __skb_queue_tail(&sk->sk_receive_queue, skb); spin_unlock_bh(&sk->sk_receive_queue.lock); hdr->nm_len = skb->len; hdr->nm_group = NETLINK_CB(skb).dst_group; hdr->nm_pid = NETLINK_CB(skb).creds.pid; hdr->nm_uid = from_kuid(sk_user_ns(sk), NETLINK_CB(skb).creds.uid); hdr->nm_gid = from_kgid(sk_user_ns(sk), NETLINK_CB(skb).creds.gid); netlink_set_status(hdr, NL_MMAP_STATUS_COPY); } 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 update_db_bp_intercept(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); clr_exception_intercept(svm, DB_VECTOR); clr_exception_intercept(svm, BP_VECTOR); if (svm->nmi_singlestep) set_exception_intercept(svm, DB_VECTOR); if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) { if (vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) set_exception_intercept(svm, DB_VECTOR); if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) set_exception_intercept(svm, BP_VECTOR); } else vcpu->guest_debug = 0; } 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 CuePoint::Load(IMkvReader* pReader) { if (m_timecode >= 0) //already loaded return; assert(m_track_positions == NULL); assert(m_track_positions_count == 0); long long pos_ = -m_timecode; const long long element_start = pos_; long long stop; { long len; const long long id = ReadUInt(pReader, pos_, len); assert(id == 0x3B); //CuePoint ID if (id != 0x3B) return; pos_ += len; //consume ID const long long size = ReadUInt(pReader, pos_, len); assert(size >= 0); pos_ += len; //consume Size field stop = pos_ + size; } const long long element_size = stop - element_start; long long pos = pos_; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; //consume Size field assert((pos + size) <= stop); if (id == 0x33) //CueTime ID m_timecode = UnserializeUInt(pReader, pos, size); else if (id == 0x37) //CueTrackPosition(s) ID ++m_track_positions_count; pos += size; //consume payload assert(pos <= stop); } assert(m_timecode >= 0); assert(m_track_positions_count > 0); m_track_positions = new TrackPosition[m_track_positions_count]; TrackPosition* p = m_track_positions; pos = pos_; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; //consume Size field assert((pos + size) <= stop); if (id == 0x37) //CueTrackPosition(s) ID { TrackPosition& tp = *p++; tp.Parse(pReader, pos, size); } pos += size; //consume payload assert(pos <= stop); } assert(size_t(p - m_track_positions) == m_track_positions_count); m_element_start = element_start; m_element_size = element_size; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool WebContentsImpl::IsHidden() { return !IsBeingCaptured() && !should_normally_be_visible_; } 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 RenderFrameImpl::DidAccessInitialDocument() { DCHECK(!frame_->Parent()); if (!has_accessed_initial_document_) { DocumentState* document_state = DocumentState::FromDocumentLoader(frame_->GetDocumentLoader()); NavigationStateImpl* navigation_state = static_cast<NavigationStateImpl*>(document_state->navigation_state()); if (!navigation_state->request_committed()) { Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_)); } } has_accessed_initial_document_ = true; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int do_fpu_inst(unsigned short inst, struct pt_regs *regs) { struct task_struct *tsk = current; struct sh_fpu_soft_struct *fpu = &(tsk->thread.xstate->softfpu); perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); if (!(task_thread_info(tsk)->status & TS_USEDFPU)) { /* initialize once. */ fpu_init(fpu); task_thread_info(tsk)->status |= TS_USEDFPU; } return fpu_emulate(inst, fpu, regs); } CWE ID: CWE-399 Target: 1 Example 2: Code: static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag, const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data; size_t i, textsize = strlen(textstring); ucvector_init(&data); for(i = 0; keyword[i] != 0; i++) ucvector_push_back(&data, (unsigned char)keyword[i]); if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ ucvector_push_back(&data, 0); /*null termination char*/ ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/ ucvector_push_back(&data, 0); /*compression method*/ for(i = 0; langtag[i] != 0; i++) ucvector_push_back(&data, (unsigned char)langtag[i]); ucvector_push_back(&data, 0); /*null termination char*/ for(i = 0; transkey[i] != 0; i++) ucvector_push_back(&data, (unsigned char)transkey[i]); ucvector_push_back(&data, 0); /*null termination char*/ if(compressed) { ucvector compressed_data; ucvector_init(&compressed_data); error = zlib_compress(&compressed_data.data, &compressed_data.size, (unsigned char*)textstring, textsize, zlibsettings); if(!error) { for(i = 0; i < compressed_data.size; i++) ucvector_push_back(&data, compressed_data.data[i]); } ucvector_cleanup(&compressed_data); } else /*not compressed*/ { for(i = 0; textstring[i] != 0; i++) ucvector_push_back(&data, (unsigned char)textstring[i]); } if(!error) error = addChunk(out, "iTXt", data.data, data.size); ucvector_cleanup(&data); return error; } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void APIENTRY PassthroughGLDebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const GLvoid* user_param) { DCHECK(user_param != nullptr); GLES2DecoderPassthroughImpl* command_decoder = static_cast<GLES2DecoderPassthroughImpl*>(const_cast<void*>(user_param)); command_decoder->OnDebugMessage(source, type, id, severity, length, message); LogGLDebugMessage(source, type, id, severity, length, message, command_decoder->GetLogger()); } 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: xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int c, l; xmlChar stop; xmlChar *ret = NULL; const xmlChar *cur = NULL; xmlParserInputPtr input; if (RAW == '"') stop = '"'; else if (RAW == '\'') stop = '\''; else { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } /* * The content of the entity definition is copied in a buffer. */ ctxt->instate = XML_PARSER_ENTITY_VALUE; input = ctxt->input; GROW; NEXT; c = CUR_CHAR(l); /* * NOTE: 4.4.5 Included in Literal * When a parameter entity reference appears in a literal entity * value, ... a single or double quote character in the replacement * text is always treated as a normal data character and will not * terminate the literal. * In practice it means we stop the loop only when back at parsing * the initial entity and the quote is found */ while ((IS_CHAR(c)) && ((c != stop) || /* checked */ (ctxt->input != input))) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); return(NULL); } buf = tmp; } COPY_BUF(l,buf,len,c); NEXTL(l); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */ xmlPopInput(ctxt); GROW; c = CUR_CHAR(l); if (c == 0) { GROW; c = CUR_CHAR(l); } } buf[len] = 0; /* * Raise problem w.r.t. '&' and '%' being used in non-entities * reference constructs. Note Charref will be handled in * xmlStringDecodeEntities() */ cur = buf; while (*cur != 0) { /* non input consuming */ if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) { xmlChar *name; xmlChar tmp = *cur; cur++; name = xmlParseStringName(ctxt, &cur); if ((name == NULL) || (*cur != ';')) { xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR, "EntityValue: '%c' forbidden except for entities references\n", tmp); } if ((tmp == '%') && (ctxt->inSubset == 1) && (ctxt->inputNr == 1)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL); } if (name != NULL) xmlFree(name); if (*cur == 0) break; } cur++; } /* * Then PEReference entities are substituted. */ if (c != stop) { xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL); xmlFree(buf); } else { NEXT; /* * NOTE: 4.4.7 Bypassed * When a general entity reference appears in the EntityValue in * an entity declaration, it is bypassed and left as is. * so XML_SUBSTITUTE_REF is not set here. */ ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, 0, 0, 0); if (orig != NULL) *orig = buf; else xmlFree(buf); } return(ret); } CWE ID: CWE-119 Target: 1 Example 2: Code: void kvm_flush_remote_tlbs(struct kvm *kvm) { /* * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in * kvm_make_all_cpus_request. */ long dirty_count = smp_load_acquire(&kvm->tlbs_dirty); /* * We want to publish modifications to the page tables before reading * mode. Pairs with a memory barrier in arch-specific code. * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest * and smp_mb in walk_shadow_page_lockless_begin/end. * - powerpc: smp_mb in kvmppc_prepare_to_enter. * * There is already an smp_mb__after_atomic() before * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that * barrier here. */ if (kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH)) ++kvm->stat.remote_tlb_flush; cmpxchg(&kvm->tlbs_dirty, dirty_count, 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: size_t mptsas_config_sas_io_unit_1(MPTSASState *s, uint8_t **data, int address) { size_t size = MPTSAS_CONFIG_PACK_EXT(1, MPI_CONFIG_EXTPAGETYPE_SAS_IO_UNIT, 0x07, "*w*w*w*wb*b*b*b" repl(MPTSAS_NUM_PORTS, "*s12"), MPTSAS_NUM_PORTS); if (data) { size_t ofs = size - MPTSAS_NUM_PORTS * MPTSAS_CONFIG_SAS_IO_UNIT_1_SIZE; int i; for (i = 0; i < MPTSAS_NUM_PORTS; i++) { SCSIDevice *dev = mptsas_phy_get_device(s, i, NULL, NULL); fill(*data + ofs, MPTSAS_CONFIG_SAS_IO_UNIT_1_SIZE, "bbbblww", i, 0, 0, (MPI_SAS_IOUNIT0_RATE_3_0 << 4) | MPI_SAS_IOUNIT0_RATE_1_5, (dev ? MPI_SAS_DEVICE_INFO_END_DEVICE | MPI_SAS_DEVICE_INFO_SSP_TARGET : MPI_SAS_DEVICE_INFO_NO_DEVICE), 0, 0); ofs += MPTSAS_CONFIG_SAS_IO_UNIT_1_SIZE; } assert(ofs == size); } return size; } 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 *nlmsg_reserve(struct nl_msg *n, size_t len, int pad) { void *buf = n->nm_nlh; size_t nlmsg_len = n->nm_nlh->nlmsg_len; size_t tlen; tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len; if ((tlen + nlmsg_len) > n->nm_size) n->nm_nlh->nlmsg_len += tlen; if (tlen > len) memset(buf + len, 0, tlen - len); NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n", n, tlen, len, pad, n->nm_nlh->nlmsg_len); return buf; } CWE ID: CWE-190 Target: 1 Example 2: Code: static void pdf_run_B(fz_context *ctx, pdf_processor *proc) { pdf_run_processor *pr = (pdf_run_processor *)proc; pdf_show_path(ctx, pr, 0, 1, 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: static void skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.zshrc", &s) == 0) { copy_file("/etc/skel/.zshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.zshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.cshrc", &s) == 0) { copy_file("/etc/skel/.cshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.cshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.bashrc", &s) == 0) { copy_file("/etc/skel/.bashrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.bashrc"); } free(fname); } } CWE ID: CWE-269 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; size_t fname_len; int zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\""); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname); } return; } zname = (char*)zend_get_executed_filename(); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar); unlink(fname); efree(fname); RETURN_TRUE; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int qib_compatible_subctxts(int user_swmajor, int user_swminor) { /* this code is written long-hand for clarity */ if (QIB_USER_SWMAJOR != user_swmajor) { /* no promise of compatibility if major mismatch */ return 0; } if (QIB_USER_SWMAJOR == 1) { switch (QIB_USER_SWMINOR) { case 0: case 1: case 2: /* no subctxt implementation so cannot be compatible */ return 0; case 3: /* 3 is only compatible with itself */ return user_swminor == 3; default: /* >= 4 are compatible (or are expected to be) */ return user_swminor <= QIB_USER_SWMINOR; } } /* make no promises yet for future major versions */ return 0; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int read_part_of_packet(AVFormatContext *s, int64_t *pts, int *len, int *strid, int read_packet) { AVIOContext *pb = s->pb; PVAContext *pvactx = s->priv_data; int syncword, streamid, reserved, flags, length, pts_flag; int64_t pva_pts = AV_NOPTS_VALUE, startpos; int ret; recover: startpos = avio_tell(pb); syncword = avio_rb16(pb); streamid = avio_r8(pb); avio_r8(pb); /* counter not used */ reserved = avio_r8(pb); flags = avio_r8(pb); length = avio_rb16(pb); pts_flag = flags & 0x10; if (syncword != PVA_MAGIC) { pva_log(s, AV_LOG_ERROR, "invalid syncword\n"); return AVERROR(EIO); } if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) { pva_log(s, AV_LOG_ERROR, "invalid streamid\n"); return AVERROR(EIO); } if (reserved != 0x55) { pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n"); } if (length > PVA_MAX_PAYLOAD_LENGTH) { pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length); return AVERROR(EIO); } if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) { pva_pts = avio_rb32(pb); length -= 4; } else if (streamid == PVA_AUDIO_PAYLOAD) { /* PVA Audio Packets either start with a signaled PES packet or * are a continuation of the previous PES packet. New PES packets * always start at the beginning of a PVA Packet, never somewhere in * the middle. */ if (!pvactx->continue_pes) { int pes_signal, pes_header_data_length, pes_packet_length, pes_flags; unsigned char pes_header_data[256]; pes_signal = avio_rb24(pb); avio_r8(pb); pes_packet_length = avio_rb16(pb); pes_flags = avio_rb16(pb); pes_header_data_length = avio_r8(pb); if (pes_signal != 1 || pes_header_data_length == 0) { pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, " "trying to recover\n"); avio_skip(pb, length - 9); if (!read_packet) return AVERROR(EIO); goto recover; } ret = avio_read(pb, pes_header_data, pes_header_data_length); if (ret != pes_header_data_length) return ret < 0 ? ret : AVERROR_INVALIDDATA; length -= 9 + pes_header_data_length; pes_packet_length -= 3 + pes_header_data_length; pvactx->continue_pes = pes_packet_length; if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) { if (pes_header_data_length < 5) { pva_log(s, AV_LOG_ERROR, "header too short\n"); avio_skip(pb, length); return AVERROR_INVALIDDATA; } pva_pts = ff_parse_pes_pts(pes_header_data); } } pvactx->continue_pes -= length; if (pvactx->continue_pes < 0) { pva_log(s, AV_LOG_WARNING, "audio data corruption\n"); pvactx->continue_pes = 0; } } if (pva_pts != AV_NOPTS_VALUE) av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME); *pts = pva_pts; *len = length; *strid = streamid; return 0; } CWE ID: CWE-835 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 ContentEncoding::ParseEncryptionEntry( long long start, long long size, IMkvReader* pReader, ContentEncryption* encryption) { assert(pReader); assert(encryption); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x7E1) { encryption->algo = UnserializeUInt(pReader, pos, size); if (encryption->algo != 5) return E_FILE_FORMAT_INVALID; } else if (id == 0x7E2) { delete[] encryption->key_id; encryption->key_id = NULL; encryption->key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, buflen, buf); if (read_status) { delete [] buf; return status; } encryption->key_id = buf; encryption->key_id_len = buflen; } else if (id == 0x7E3) { delete[] encryption->signature; encryption->signature = NULL; encryption->signature_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, buflen, buf); if (read_status) { delete [] buf; return status; } encryption->signature = buf; encryption->signature_len = buflen; } else if (id == 0x7E4) { delete[] encryption->sig_key_id; encryption->sig_key_id = NULL; encryption->sig_key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, buflen, buf); if (read_status) { delete [] buf; return status; } encryption->sig_key_id = buf; encryption->sig_key_id_len = buflen; } else if (id == 0x7E5) { encryption->sig_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E6) { encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E7) { const long status = ParseContentEncAESSettingsEntry( pos, size, pReader, &encryption->aes_settings); if (status) return status; } pos += size; //consume payload assert(pos <= stop); } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: search_text (WebKitWebView *page, GArray *argv, const gboolean forward) { if (argv_idx(argv, 0) && (*argv_idx(argv, 0) != '\0')) { if (g_strcmp0 (uzbl.state.searchtx, argv_idx(argv, 0)) != 0) { webkit_web_view_unmark_text_matches (page); webkit_web_view_mark_text_matches (page, argv_idx(argv, 0), FALSE, 0); uzbl.state.searchtx = g_strdup(argv_idx(argv, 0)); } } if (uzbl.state.searchtx) { if (uzbl.state.verbose) printf ("Searching: %s\n", uzbl.state.searchtx); webkit_web_view_set_highlight_text_matches (page, TRUE); webkit_web_view_search_text (page, uzbl.state.searchtx, FALSE, forward, TRUE); } } 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 pfunc check_literal(struct jv_parser* p) { if (p->tokenpos == 0) return 0; const char* pattern = 0; int plen; jv v; switch (p->tokenbuf[0]) { case 't': pattern = "true"; plen = 4; v = jv_true(); break; case 'f': pattern = "false"; plen = 5; v = jv_false(); break; case 'n': pattern = "null"; plen = 4; v = jv_null(); break; } if (pattern) { if (p->tokenpos != plen) return "Invalid literal"; for (int i=0; i<plen; i++) if (p->tokenbuf[i] != pattern[i]) return "Invalid literal"; TRY(value(p, v)); } else { p->tokenbuf[p->tokenpos] = 0; // FIXME: invalid char* end = 0; double d = jvp_strtod(&p->dtoa, p->tokenbuf, &end); if (end == 0 || *end != 0) return "Invalid numeric literal"; TRY(value(p, jv_number(d))); } p->tokenpos = 0; return 0; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Resource::~Resource() { } CWE ID: CWE-399 Target: 1 Example 2: Code: void OxideQQuickWebView::prepareToClose() { Q_D(OxideQQuickWebView); if (!d->proxy_) { QCoreApplication::postEvent(this, new QEvent(GetPrepareToCloseBypassEventType())); return; } d->proxy_->prepareToClose(); } 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: long Chapters::ParseEdition( long long pos, long long size) { if (!ExpandEditionsArray()) return -1; Edition& e = m_editions[m_editions_count++]; e.Init(); return e.Parse(m_pSegment->m_pReader, pos, size); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *buf_in=NULL; int ret= -1,i,inl; EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (!EVP_VerifyInit_ex(&ctx,type, NULL)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } CWE ID: CWE-310 Target: 1 Example 2: Code: static int sctp_getsockopt_connectx3(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_getaddrs_old param; sctp_assoc_t assoc_id = 0; int err = 0; #ifdef CONFIG_COMPAT if (in_compat_syscall()) { struct compat_sctp_getaddrs_old param32; if (len < sizeof(param32)) return -EINVAL; if (copy_from_user(&param32, optval, sizeof(param32))) return -EFAULT; param.assoc_id = param32.assoc_id; param.addr_num = param32.addr_num; param.addrs = compat_ptr(param32.addrs); } else #endif { if (len < sizeof(param)) return -EINVAL; if (copy_from_user(&param, optval, sizeof(param))) return -EFAULT; } err = __sctp_setsockopt_connectx(sk, (struct sockaddr __user *) param.addrs, param.addr_num, &assoc_id); if (err == 0 || err == -EINPROGRESS) { if (copy_to_user(optval, &assoc_id, sizeof(assoc_id))) return -EFAULT; if (put_user(sizeof(assoc_id), optlen)) return -EFAULT; } return err; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void scsi_check_condition(SCSIDiskReq *r, SCSISense sense) { DPRINTF("Command complete tag=0x%x sense=%d/%d/%d\n", r->req.tag, sense.key, sense.asc, sense.ascq); scsi_req_build_sense(&r->req, sense); scsi_req_complete(&r->req, CHECK_CONDITION); } 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 GpuCommandBufferStub::OnGetTransferBuffer( int32 id, IPC::Message* reply_message) { if (!channel_->renderer_process()) return; if (command_buffer_.get()) { base::SharedMemoryHandle transfer_buffer = base::SharedMemoryHandle(); uint32 size = 0; gpu::Buffer buffer = command_buffer_->GetTransferBuffer(id); if (buffer.shared_memory) { buffer.shared_memory->ShareToProcess(channel_->renderer_process(), &transfer_buffer); size = buffer.size; } GpuCommandBufferMsg_GetTransferBuffer::WriteReplyParams(reply_message, transfer_buffer, size); } else { reply_message->set_reply_error(); } Send(reply_message); } CWE ID: Target: 1 Example 2: Code: int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) { ProgressivePaint progressive; progressive.rect = dirty; progressive.page_index = page_index; progressive.bitmap = nullptr; progressive.painted_ = false; progressive_paints_.push_back(progressive); return progressive_paints_.size() - 1; } 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 hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len, int reassembly) { hm_fragment *frag = NULL; unsigned char *buf = NULL; unsigned char *bitmask = NULL; frag = OPENSSL_malloc(sizeof(*frag)); if (frag == NULL) return NULL; if (frag_len) { buf = OPENSSL_malloc(frag_len); if (buf == NULL) { OPENSSL_free(frag); return NULL; } } /* zero length fragment gets zero frag->fragment */ frag->fragment = buf; /* Initialize reassembly bitmask if necessary */ if (reassembly) { bitmask = OPENSSL_zalloc(RSMBLY_BITMASK_SIZE(frag_len)); if (bitmask == NULL) { OPENSSL_free(buf); OPENSSL_free(frag); return NULL; } } frag->reassembly = bitmask; return frag; } 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 PrintRenderFrameHelper::PrintHeaderAndFooter( blink::WebCanvas* canvas, int page_number, int total_pages, const blink::WebLocalFrame& source_frame, float webkit_scale_factor, const PageSizeMargins& page_layout, const PrintMsg_Print_Params& params) { cc::PaintCanvasAutoRestore auto_restore(canvas, true); canvas->scale(1 / webkit_scale_factor, 1 / webkit_scale_factor); blink::WebSize page_size(page_layout.margin_left + page_layout.margin_right + page_layout.content_width, page_layout.margin_top + page_layout.margin_bottom + page_layout.content_height); blink::WebView* web_view = blink::WebView::Create( nullptr, blink::mojom::PageVisibilityState::kVisible); web_view->GetSettings()->SetJavaScriptEnabled(true); class HeaderAndFooterClient final : public blink::WebFrameClient { public: void BindToFrame(blink::WebLocalFrame* frame) override { frame_ = frame; } void FrameDetached(DetachType detach_type) override { frame_->FrameWidget()->Close(); frame_->Close(); frame_ = nullptr; } private: blink::WebLocalFrame* frame_; }; HeaderAndFooterClient frame_client; blink::WebLocalFrame* frame = blink::WebLocalFrame::CreateMainFrame( web_view, &frame_client, nullptr, nullptr); blink::WebWidgetClient web_widget_client; blink::WebFrameWidget::Create(&web_widget_client, frame); base::Value html(base::UTF8ToUTF16( ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_PRINT_PREVIEW_PAGE))); ExecuteScript(frame, kPageLoadScriptFormat, html); auto options = base::MakeUnique<base::DictionaryValue>(); options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime()); options->SetDouble("width", page_size.width); options->SetDouble("height", page_size.height); options->SetDouble("topMargin", page_layout.margin_top); options->SetDouble("bottomMargin", page_layout.margin_bottom); options->SetInteger("pageNumber", page_number); options->SetInteger("totalPages", total_pages); options->SetString("url", params.url); base::string16 title = source_frame.GetDocument().Title().Utf16(); options->SetString("title", title.empty() ? params.title : title); ExecuteScript(frame, kPageSetupScriptFormat, *options); blink::WebPrintParams webkit_params(page_size); webkit_params.printer_dpi = GetDPI(&params); frame->PrintBegin(webkit_params); frame->PrintPage(0, canvas); frame->PrintEnd(); web_view->Close(); } CWE ID: CWE-20 Target: 1 Example 2: Code: std::string GoogleChromeDistribution::GetSafeBrowsingName() { return "googlechrome"; } 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: smp_fetch_hdr(const struct arg *args, struct sample *smp, const char *kw, void *private) { struct hdr_idx *idx; struct hdr_ctx *ctx = smp->ctx.a[0]; const struct http_msg *msg; int occ = 0; const char *name_str = NULL; int name_len = 0; if (!ctx) { /* first call */ ctx = &static_hdr_ctx; ctx->idx = 0; smp->ctx.a[0] = ctx; } if (args) { if (args[0].type != ARGT_STR) return 0; name_str = args[0].data.str.str; name_len = args[0].data.str.len; if (args[1].type == ARGT_SINT) occ = args[1].data.sint; } CHECK_HTTP_MESSAGE_FIRST(); idx = &smp->strm->txn->hdr_idx; msg = ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &smp->strm->txn->req : &smp->strm->txn->rsp; if (ctx && !(smp->flags & SMP_F_NOT_LAST)) /* search for header from the beginning */ ctx->idx = 0; if (!occ && !(smp->opt & SMP_OPT_ITERATE)) /* no explicit occurrence and single fetch => last header by default */ occ = -1; if (!occ) /* prepare to report multiple occurrences for ACL fetches */ smp->flags |= SMP_F_NOT_LAST; smp->data.type = SMP_T_STR; smp->flags |= SMP_F_VOL_HDR | SMP_F_CONST; if (http_get_hdr(msg, name_str, name_len, idx, occ, ctx, &smp->data.u.str.str, &smp->data.u.str.len)) return 1; smp->flags &= ~SMP_F_NOT_LAST; return 0; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: rx_cache_find(const struct rx_header *rxh, const struct ip *ip, int sport, int32_t *opcode) { int i; struct rx_cache_entry *rxent; uint32_t clip; uint32_t sip; UNALIGNED_MEMCPY(&clip, &ip->ip_dst, sizeof(uint32_t)); UNALIGNED_MEMCPY(&sip, &ip->ip_src, sizeof(uint32_t)); /* Start the search where we last left off */ i = rx_cache_hint; do { rxent = &rx_cache[i]; if (rxent->callnum == EXTRACT_32BITS(&rxh->callNumber) && rxent->client.s_addr == clip && rxent->server.s_addr == sip && rxent->serviceId == EXTRACT_32BITS(&rxh->serviceId) && rxent->dport == sport) { /* We got a match! */ rx_cache_hint = i; *opcode = rxent->opcode; return(1); } if (++i >= RX_CACHE_SIZE) i = 0; } while (i != rx_cache_hint); /* Our search failed */ return(0); } CWE ID: CWE-125 Target: 1 Example 2: Code: static void json_delete_string(json_string_t *string) { jsonp_free(string->value); jsonp_free(string); } 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: bool PrintWebViewHelper::UpdatePrintSettings( WebKit::WebFrame* frame, const WebKit::WebNode& node, const DictionaryValue& passed_job_settings) { DCHECK(is_preview_enabled_); const DictionaryValue* job_settings = &passed_job_settings; DictionaryValue modified_job_settings; if (job_settings->empty()) { if (!print_for_preview_) print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } bool source_is_html = true; if (print_for_preview_) { if (!job_settings->GetBoolean(printing::kSettingPreviewModifiable, &source_is_html)) { NOTREACHED(); } } else { source_is_html = !PrintingNodeOrPdfFrame(frame, node); } if (print_for_preview_ || !source_is_html) { modified_job_settings.MergeDictionary(job_settings); modified_job_settings.SetBoolean(printing::kSettingHeaderFooterEnabled, false); modified_job_settings.SetInteger(printing::kSettingMarginsType, printing::NO_MARGINS); job_settings = &modified_job_settings; } int cookie = print_pages_params_.get() ? print_pages_params_->params.document_cookie : 0; PrintMsg_PrintPages_Params settings; Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie, *job_settings, &settings)); print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); if (!PrintMsg_Print_Params_IsValid(settings.params)) { if (!print_for_preview_) { print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS); } else { WebKit::WebFrame* print_frame = NULL; GetPrintFrame(&print_frame); if (print_frame) { render_view()->RunModalAlertDialog( print_frame, l10n_util::GetStringUTF16( IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS)); } } return false; } if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) { print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS); return false; } if (!print_for_preview_) { if (!job_settings->GetString(printing::kPreviewUIAddr, &(settings.params.preview_ui_addr)) || !job_settings->GetInteger(printing::kPreviewRequestID, &(settings.params.preview_request_id)) || !job_settings->GetBoolean(printing::kIsFirstRequest, &(settings.params.is_first_request))) { NOTREACHED(); print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings); UpdateFrameMarginsCssInfo(*job_settings); settings.params.print_scaling_option = GetPrintScalingOption( source_is_html, *job_settings, settings.params); if (settings.params.display_header_footer) { header_footer_info_.reset(new DictionaryValue()); header_footer_info_->SetString(printing::kSettingHeaderFooterDate, settings.params.date); header_footer_info_->SetString(printing::kSettingHeaderFooterURL, settings.params.url); header_footer_info_->SetString(printing::kSettingHeaderFooterTitle, settings.params.title); } } print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(), settings.params.document_cookie)); return true; } 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: aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword) { const AIFF_CAF_CHANNEL_MAP * map_info ; unsigned channel_bitmap, channel_decriptions, bytesread ; int layout_tag ; bytesread = psf_binheader_readf (psf, "444", &layout_tag, &channel_bitmap, &channel_decriptions) ; if ((map_info = aiff_caf_of_channel_layout_tag (layout_tag)) == NULL) return 0 ; psf_log_printf (psf, " Tag : %x\n", layout_tag) ; if (map_info) psf_log_printf (psf, " Layout : %s\n", map_info->name) ; if (bytesread < dword) psf_binheader_readf (psf, "j", dword - bytesread) ; if (map_info->channel_map != NULL) { size_t chanmap_size = psf->sf.channels * sizeof (psf->channel_map [0]) ; free (psf->channel_map) ; if ((psf->channel_map = malloc (chanmap_size)) == NULL) return SFE_MALLOC_FAILED ; memcpy (psf->channel_map, map_info->channel_map, chanmap_size) ; } ; return 0 ; } /* aiff_read_chanmap */ CWE ID: CWE-119 Target: 1 Example 2: Code: static int mmap_rcvegrbufs(struct vm_area_struct *vma, struct qib_ctxtdata *rcd) { struct qib_devdata *dd = rcd->dd; unsigned long start, size; size_t total_size, i; unsigned long pfn; int ret; size = rcd->rcvegrbuf_size; total_size = rcd->rcvegrbuf_chunks * size; if ((vma->vm_end - vma->vm_start) > total_size) { qib_devinfo(dd->pcidev, "FAIL on egr bufs: reqlen %lx > actual %lx\n", vma->vm_end - vma->vm_start, (unsigned long) total_size); ret = -EINVAL; goto bail; } if (vma->vm_flags & VM_WRITE) { qib_devinfo(dd->pcidev, "Can't map eager buffers as writable (flags=%lx)\n", vma->vm_flags); ret = -EPERM; goto bail; } /* don't allow them to later change to writeable with mprotect */ vma->vm_flags &= ~VM_MAYWRITE; start = vma->vm_start; for (i = 0; i < rcd->rcvegrbuf_chunks; i++, start += size) { pfn = virt_to_phys(rcd->rcvegrbuf[i]) >> PAGE_SHIFT; ret = remap_pfn_range(vma, start, pfn, size, vma->vm_page_prot); if (ret < 0) goto bail; } ret = 0; bail: return ret; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SocketStreamDispatcherHost::CancelSSLRequest( const content::GlobalRequestID& id, int error, const net::SSLInfo* ssl_info) { int socket_id = id.request_id; DVLOG(1) << "SocketStreamDispatcherHost::CancelSSLRequest socket_id=" << socket_id; DCHECK_NE(content::kNoSocketId, socket_id); SocketStreamHost* socket_stream_host = hosts_.Lookup(socket_id); DCHECK(socket_stream_host); if (ssl_info) socket_stream_host->CancelWithSSLError(*ssl_info); else socket_stream_host->CancelWithError(error); } 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: nfs3svc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_writeargs *args) { unsigned int len, v, hdr, dlen; u32 max_blocksize = svc_max_payload(rqstp); struct kvec *head = rqstp->rq_arg.head; struct kvec *tail = rqstp->rq_arg.tail; p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); args->stable = ntohl(*p++); len = args->len = ntohl(*p++); /* * The count must equal the amount of data passed. */ if (args->count != args->len) return 0; /* * Check to make sure that we got the right number of * bytes. */ hdr = (void*)p - head->iov_base; dlen = head->iov_len + rqstp->rq_arg.page_len + tail->iov_len - hdr; /* * Round the length of the data which was specified up to * the next multiple of XDR units and then compare that * against the length which was actually received. * Note that when RPCSEC/GSS (for example) is used, the * data buffer can be padded so dlen might be larger * than required. It must never be smaller. */ if (dlen < XDR_QUADLEN(len)*4) return 0; if (args->count > max_blocksize) { args->count = max_blocksize; len = args->len = max_blocksize; } rqstp->rq_vec[0].iov_base = (void*)p; rqstp->rq_vec[0].iov_len = head->iov_len - hdr; v = 0; while (len > rqstp->rq_vec[v].iov_len) { len -= rqstp->rq_vec[v].iov_len; v++; rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]); rqstp->rq_vec[v].iov_len = PAGE_SIZE; } rqstp->rq_vec[v].iov_len = len; args->vlen = v + 1; return 1; } CWE ID: CWE-119 Target: 1 Example 2: Code: n_tty_receive_buf_common(struct tty_struct *tty, const unsigned char *cp, char *fp, int count, int flow) { struct n_tty_data *ldata = tty->disc_data; int room, n, rcvd = 0, overflow; down_read(&tty->termios_rwsem); while (1) { /* * When PARMRK is set, each input char may take up to 3 chars * in the read buf; reduce the buffer space avail by 3x * * If we are doing input canonicalization, and there are no * pending newlines, let characters through without limit, so * that erase characters will be handled. Other excess * characters will be beeped. * * paired with store in *_copy_from_read_buf() -- guarantees * the consumer has loaded the data in read_buf up to the new * read_tail (so this producer will not overwrite unread data) */ size_t tail = smp_load_acquire(&ldata->read_tail); room = N_TTY_BUF_SIZE - (ldata->read_head - tail); if (I_PARMRK(tty)) room = (room + 2) / 3; room--; if (room <= 0) { overflow = ldata->icanon && ldata->canon_head == tail; if (overflow && room < 0) ldata->read_head--; room = overflow; ldata->no_room = flow && !room; } else overflow = 0; n = min(count, room); if (!n) break; /* ignore parity errors if handling overflow */ if (!overflow || !fp || *fp != TTY_PARITY) __receive_buf(tty, cp, fp, n); cp += n; if (fp) fp += n; count -= n; rcvd += n; } tty->receive_room = room; /* Unthrottle if handling overflow on pty */ if (tty->driver->type == TTY_DRIVER_TYPE_PTY) { if (overflow) { tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE); tty_unthrottle_safe(tty); __tty_set_flow_change(tty, 0); } } else n_tty_check_throttle(tty); up_read(&tty->termios_rwsem); return rcvd; } 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: static int dv_extract_video_info(DVDemuxContext *c, uint8_t* frame) { const uint8_t* vsc_pack; AVCodecContext* avctx; int apt, is16_9; int size = 0; if (c->sys) { avctx = c->vst->codec; avpriv_set_pts_info(c->vst, 64, c->sys->time_base.num, c->sys->time_base.den); avctx->time_base= c->sys->time_base; if (!avctx->width){ avctx->width = c->sys->width; avctx->height = c->sys->height; } avctx->pix_fmt = c->sys->pix_fmt; /* finding out SAR is a little bit messy */ vsc_pack = dv_extract_pack(frame, dv_video_control); apt = frame[4] & 0x07; is16_9 = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 || (!apt && (vsc_pack[2] & 0x07) == 0x07))); c->vst->sample_aspect_ratio = c->sys->sar[is16_9]; avctx->bit_rate = av_rescale_q(c->sys->frame_size, (AVRational){8,1}, c->sys->time_base); size = c->sys->frame_size; } return size; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int http_open(URLContext *h, const char *uri, int flags, AVDictionary **options) { HTTPContext *s = h->priv_data; int ret; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; s->filesize = -1; s->location = av_strdup(uri); if (!s->location) return AVERROR(ENOMEM); if (options) av_dict_copy(&s->chained_options, *options, 0); if (s->headers) { int len = strlen(s->headers); if (len < 2 || strcmp("\r\n", s->headers + len - 2)) { av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n"); ret = av_reallocp(&s->headers, len + 3); if (ret < 0) return ret; s->headers[len] = '\r'; s->headers[len + 1] = '\n'; s->headers[len + 2] = '\0'; } } if (s->listen) { return http_listen(h, uri, flags, options); } ret = http_open_cnx(h, options); if (ret < 0) av_dict_free(&s->chained_options); return ret; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool RenderWidgetHostViewAura::LockMouse() { aura::RootWindow* root_window = window_->GetRootWindow(); if (!root_window) return false; if (mouse_locked_) return true; mouse_locked_ = true; window_->SetCapture(); aura::client::CursorClient* cursor_client = aura::client::GetCursorClient(root_window); if (cursor_client) cursor_client->ShowCursor(false); synthetic_move_sent_ = true; window_->MoveCursorTo(gfx::Rect(window_->bounds().size()).CenterPoint()); if (aura::client::GetTooltipClient(root_window)) aura::client::GetTooltipClient(root_window)->SetTooltipsEnabled(false); return true; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ImageBitmap::ImageBitmap(ImageData* data, Optional<IntRect> cropRect, const ImageBitmapOptions& options) { IntRect dataSrcRect = IntRect(IntPoint(), data->size()); ParsedOptions parsedOptions = parseOptions(options, cropRect, data->bitmapSourceSize()); if (dstBufferSizeHasOverflow(parsedOptions)) return; IntRect srcRect = cropRect ? intersection(parsedOptions.cropRect, dataSrcRect) : dataSrcRect; if (!parsedOptions.premultiplyAlpha) { unsigned char* srcAddr = data->data()->data(); SkImageInfo info = SkImageInfo::Make( parsedOptions.cropRect.width(), parsedOptions.cropRect.height(), kN32_SkColorType, kUnpremul_SkAlphaType); size_t bytesPerPixel = static_cast<size_t>(info.bytesPerPixel()); size_t srcPixelBytesPerRow = bytesPerPixel * data->size().width(); size_t dstPixelBytesPerRow = bytesPerPixel * parsedOptions.cropRect.width(); sk_sp<SkImage> skImage; if (parsedOptions.cropRect == IntRect(IntPoint(), data->size())) { swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow, parsedOptions.flipY); skImage = SkImage::MakeRasterCopy(SkPixmap(info, srcAddr, dstPixelBytesPerRow)); swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow, parsedOptions.flipY); } else { RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull( static_cast<size_t>(parsedOptions.cropRect.height()) * parsedOptions.cropRect.width(), bytesPerPixel); if (!dstBuffer) return; RefPtr<Uint8Array> copiedDataBuffer = Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); if (!srcRect.isEmpty()) { IntPoint srcPoint = IntPoint( (parsedOptions.cropRect.x() > 0) ? parsedOptions.cropRect.x() : 0, (parsedOptions.cropRect.y() > 0) ? parsedOptions.cropRect.y() : 0); IntPoint dstPoint = IntPoint( (parsedOptions.cropRect.x() >= 0) ? 0 : -parsedOptions.cropRect.x(), (parsedOptions.cropRect.y() >= 0) ? 0 : -parsedOptions.cropRect.y()); int copyHeight = data->size().height() - srcPoint.y(); if (parsedOptions.cropRect.height() < copyHeight) copyHeight = parsedOptions.cropRect.height(); int copyWidth = data->size().width() - srcPoint.x(); if (parsedOptions.cropRect.width() < copyWidth) copyWidth = parsedOptions.cropRect.width(); for (int i = 0; i < copyHeight; i++) { size_t srcStartCopyPosition = (i + srcPoint.y()) * srcPixelBytesPerRow + srcPoint.x() * bytesPerPixel; size_t srcEndCopyPosition = srcStartCopyPosition + copyWidth * bytesPerPixel; size_t dstStartCopyPosition; if (parsedOptions.flipY) dstStartCopyPosition = (parsedOptions.cropRect.height() - 1 - dstPoint.y() - i) * dstPixelBytesPerRow + dstPoint.x() * bytesPerPixel; else dstStartCopyPosition = (dstPoint.y() + i) * dstPixelBytesPerRow + dstPoint.x() * bytesPerPixel; for (size_t j = 0; j < srcEndCopyPosition - srcStartCopyPosition; j++) { if (kN32_SkColorType == kBGRA_8888_SkColorType) { if (j % 4 == 0) copiedDataBuffer->data()[dstStartCopyPosition + j] = srcAddr[srcStartCopyPosition + j + 2]; else if (j % 4 == 2) copiedDataBuffer->data()[dstStartCopyPosition + j] = srcAddr[srcStartCopyPosition + j - 2]; else copiedDataBuffer->data()[dstStartCopyPosition + j] = srcAddr[srcStartCopyPosition + j]; } else { copiedDataBuffer->data()[dstStartCopyPosition + j] = srcAddr[srcStartCopyPosition + j]; } } } } skImage = newSkImageFromRaster(info, std::move(copiedDataBuffer), dstPixelBytesPerRow); } if (!skImage) return; if (parsedOptions.shouldScaleInput) m_image = StaticBitmapImage::create(scaleSkImage( skImage, parsedOptions.resizeWidth, parsedOptions.resizeHeight, parsedOptions.resizeQuality)); else m_image = StaticBitmapImage::create(skImage); if (!m_image) return; m_image->setPremultiplied(parsedOptions.premultiplyAlpha); return; } std::unique_ptr<ImageBuffer> buffer = ImageBuffer::create( parsedOptions.cropRect.size(), NonOpaque, DoNotInitializeImagePixels); if (!buffer) return; if (srcRect.isEmpty()) { m_image = StaticBitmapImage::create(buffer->newSkImageSnapshot( PreferNoAcceleration, SnapshotReasonUnknown)); return; } IntPoint dstPoint = IntPoint(std::min(0, -parsedOptions.cropRect.x()), std::min(0, -parsedOptions.cropRect.y())); if (parsedOptions.cropRect.x() < 0) dstPoint.setX(-parsedOptions.cropRect.x()); if (parsedOptions.cropRect.y() < 0) dstPoint.setY(-parsedOptions.cropRect.y()); buffer->putByteArray(Unmultiplied, data->data()->data(), data->size(), srcRect, dstPoint); sk_sp<SkImage> skImage = buffer->newSkImageSnapshot(PreferNoAcceleration, SnapshotReasonUnknown); if (parsedOptions.flipY) skImage = flipSkImageVertically(skImage.get(), PremultiplyAlpha); if (!skImage) return; if (parsedOptions.shouldScaleInput) { sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul( parsedOptions.resizeWidth, parsedOptions.resizeHeight); if (!surface) return; SkPaint paint; paint.setFilterQuality(parsedOptions.resizeQuality); SkRect dstDrawRect = SkRect::MakeWH(parsedOptions.resizeWidth, parsedOptions.resizeHeight); surface->getCanvas()->drawImageRect(skImage, dstDrawRect, &paint); skImage = surface->makeImageSnapshot(); } m_image = StaticBitmapImage::create(std::move(skImage)); } 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 inline struct futex_hash_bucket *queue_lock(struct futex_q *q) { struct futex_hash_bucket *hb; get_futex_key_refs(&q->key); hb = hash_futex(&q->key); q->lock_ptr = &hb->lock; spin_lock(&hb->lock); return hb; } CWE ID: CWE-119 Target: 1 Example 2: Code: void DevToolsWindow::SetLoadCompletedCallback(const base::Closure& closure) { if (life_stage_ == kLoadCompleted || life_stage_ == kClosing) { if (!closure.is_null()) closure.Run(); return; } load_completed_callback_ = closure; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void mark_all_clean(struct vmcb *vmcb) { vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1) & ~VMCB_ALWAYS_DIRTY_MASK; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } CWE ID: CWE-200 Target: 1 Example 2: Code: void WebContext::setCachePath(const QUrl& url) { DCHECK(!IsInitialized()); DCHECK(url.isLocalFile() || url.isEmpty()); construct_props_->cache_path = base::FilePath(url.toLocalFile().toStdString()); } 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 nfs4_xdr_enc_getacl(struct rpc_rqst *req, struct xdr_stream *xdr, struct nfs_getaclargs *args) { struct compound_hdr hdr = { .minorversion = nfs4_xdr_minorversion(&args->seq_args), }; uint32_t replen; encode_compound_hdr(xdr, req, &hdr); encode_sequence(xdr, &args->seq_args, &hdr); encode_putfh(xdr, args->fh, &hdr); replen = hdr.replen + op_decode_hdr_maxsz + nfs4_fattr_bitmap_maxsz + 1; encode_getattr_two(xdr, FATTR4_WORD0_ACL, 0, &hdr); xdr_inline_pages(&req->rq_rcv_buf, replen << 2, args->acl_pages, args->acl_pgbase, args->acl_len); encode_nops(&hdr); } 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: safecat_current_encoding(char *buffer, size_t bufsize, size_t pos, PNG_CONST png_modifier *pm) { pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding, pm->current_gamma); if (pm->encoding_ignored) pos = safecat(buffer, bufsize, pos, "[overridden]"); return pos; } CWE ID: Target: 1 Example 2: Code: int nfs4_open_delegation_recall(struct nfs_open_context *ctx, struct nfs4_state *state, const nfs4_stateid *stateid) { struct nfs4_exception exception = { }; struct nfs_server *server = NFS_SERVER(state->inode); int err; do { err = _nfs4_open_delegation_recall(ctx, state, stateid); switch (err) { case 0: case -ENOENT: case -ESTALE: goto out; case -NFS4ERR_BADSESSION: case -NFS4ERR_BADSLOT: case -NFS4ERR_BAD_HIGH_SLOT: case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION: case -NFS4ERR_DEADSESSION: nfs4_schedule_session_recovery(server->nfs_client->cl_session); goto out; case -NFS4ERR_STALE_CLIENTID: case -NFS4ERR_STALE_STATEID: case -NFS4ERR_EXPIRED: /* Don't recall a delegation if it was lost */ nfs4_schedule_lease_recovery(server->nfs_client); goto out; case -ERESTARTSYS: /* * The show must go on: exit, but mark the * stateid as needing recovery. */ case -NFS4ERR_ADMIN_REVOKED: case -NFS4ERR_BAD_STATEID: nfs4_schedule_stateid_recovery(server, state); case -EKEYEXPIRED: /* * User RPCSEC_GSS context has expired. * We cannot recover this stateid now, so * skip it and allow recovery thread to * proceed. */ case -ENOMEM: err = 0; goto out; } err = nfs4_handle_exception(server, err, &exception); } while (exception.retry); out: return err; } 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 AudioFlinger::EffectHandle::setEnabled(bool enabled) { if (mEffectClient != 0) { mEffectClient->enableStatusChanged(enabled); } } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended) { zval *IM, *EXT = NULL; gdImagePtr im=NULL; long col = -1, x = -1, y = -1; int str_len, fontname_len, i, brect[8]; double ptsize, angle; char *str = NULL, *fontname = NULL; char *error = NULL; int argc = ZEND_NUM_ARGS(); gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { if (argc < 4 || argc > ((extended) ? 5 : 4)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } } else { if (argc < 8 || argc > ((extended) ? 9 : 8)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && EXT) { /* parse extended info */ HashPosition pos; /* walk the assoc array */ zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos); do { zval ** item; char * key; ulong num_key; if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) { continue; } if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) { continue; } if (strcmp("linespacing", key) == 0) { convert_to_double_ex(item); strex.flags |= gdFTEX_LINESPACE; strex.linespacing = Z_DVAL_PP(item); } } while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS); } #ifdef VIRTUAL_DIR { char tmp_font_path[MAXPATHLEN]; if (!VCWD_REALPATH(fontname, tmp_font_path)) { fontname = NULL; } } #endif /* VIRTUAL_DIR */ PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename"); #ifdef HAVE_GD_FREETYPE if (extended) { error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex); } else error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str); #endif /* HAVE_GD_FREETYPE */ if (error) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error); RETURN_FALSE; } array_init(return_value); /* return array with the text's bounding box */ for (i = 0; i < 8; i++) { add_next_index_long(return_value, brect[i]); } } CWE ID: CWE-787 Target: 1 Example 2: Code: void BluetoothSocketSendFunction::OnError( BluetoothApiSocket::ErrorReason reason, const std::string& message) { DCHECK_CURRENTLY_ON(work_thread_id()); Respond(Error(message)); } 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: JSTestSerializedScriptValueInterface::~JSTestSerializedScriptValueInterface() { releaseImplIfNotNull(); } 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 RenderWidgetHostViewAura::OnLostResources() { image_transport_clients_.clear(); current_surface_ = 0; protection_state_id_ = 0; current_surface_is_protected_ = true; current_surface_in_use_by_compositor_ = true; surface_route_id_ = 0; UpdateExternalTexture(); locks_pending_commit_.clear(); DCHECK(!shared_surface_handle_.is_null()); ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); factory->DestroySharedSurfaceHandle(shared_surface_handle_); shared_surface_handle_ = factory->CreateSharedSurfaceHandle(); host_->CompositingSurfaceUpdated(); host_->ScheduleComposite(); } CWE ID: Target: 1 Example 2: Code: ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AppCacheDatabase::FindEntriesForCache(int64_t cache_id, std::vector<EntryRecord>* records) { DCHECK(records && records->empty()); if (!LazyOpen(kDontCreate)) return false; static const char kSql[] = "SELECT cache_id, url, flags, response_id, response_size FROM Entries" " WHERE cache_id = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, cache_id); while (statement.Step()) { records->push_back(EntryRecord()); ReadEntryRecord(statement, &records->back()); DCHECK(records->back().cache_id == cache_id); } return statement.Succeeded(); } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS) { const char* loc_name = NULL; int loc_name_len = 0; char* tag_value = NULL; char* empty_result = ""; int result = 0; char* msg = NULL; UErrorCode status = U_ZERO_ERROR; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name ,&loc_name_len ) == FAILURE) { spprintf(&msg , 0, "locale_get_%s : unable to parse input params", tag_name ); intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC ); efree(msg); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Call ICU get */ tag_value = get_icu_value_internal( loc_name , tag_name , &result ,0); /* No value found */ if( result == -1 ) { if( tag_value){ efree( tag_value); } RETURN_STRING( empty_result , TRUE); } /* value found */ if( tag_value){ RETURN_STRING( tag_value , FALSE); } /* Error encountered while fetching the value */ if( result ==0) { spprintf(&msg , 0, "locale_get_%s : unable to get locale %s", tag_name , tag_name ); intl_error_set( NULL, status, msg , 1 TSRMLS_CC ); efree(msg); RETURN_NULL(); } } CWE ID: CWE-125 Target: 1 Example 2: Code: static CURLcode smtp_parse_custom_request(struct connectdata *conn) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; struct SMTP *smtp = data->req.protop; const char *custom = data->set.str[STRING_CUSTOMREQUEST]; /* URL decode the custom request */ if(custom) result = Curl_urldecode(data, custom, 0, &smtp->custom, NULL, TRUE); return result; } 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: GC_API void * GC_CALL GC_generic_malloc(size_t lb, int k) { void * result; DCL_LOCK_STATE; if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); if (SMALL_OBJ(lb)) { LOCK(); result = GC_generic_malloc_inner((word)lb, k); UNLOCK(); } else { size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; LOCK(); result = (ptr_t)GC_alloc_large(lb_rounded, k, 0); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; UNLOCK(); if (init && !GC_debugging_started && 0 != result) { BZERO(result, n_blocks * HBLKSIZE); } } if (0 == result) { return((*GC_get_oom_fn())(lb)); } else { return(result); } } 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 caif_stream_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int copied = 0; int target; int err = 0; long timeo; err = -EOPNOTSUPP; if (flags&MSG_OOB) goto out; msg->msg_namelen = 0; /* * Lock the socket to prevent queue disordering * while sleeps in memcpy_tomsg */ err = -EAGAIN; if (sk->sk_state == CAIF_CONNECTING) goto out; caif_read_lock(sk); target = sock_rcvlowat(sk, flags&MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT); do { int chunk; struct sk_buff *skb; lock_sock(sk); skb = skb_dequeue(&sk->sk_receive_queue); caif_check_flow_release(sk); if (skb == NULL) { if (copied >= target) goto unlock; /* * POSIX 1003.1g mandates this order. */ err = sock_error(sk); if (err) goto unlock; err = -ECONNRESET; if (sk->sk_shutdown & RCV_SHUTDOWN) goto unlock; err = -EPIPE; if (sk->sk_state != CAIF_CONNECTED) goto unlock; if (sock_flag(sk, SOCK_DEAD)) goto unlock; release_sock(sk); err = -EAGAIN; if (!timeo) break; caif_read_unlock(sk); timeo = caif_stream_data_wait(sk, timeo); if (signal_pending(current)) { err = sock_intr_errno(timeo); goto out; } caif_read_lock(sk); continue; unlock: release_sock(sk); break; } release_sock(sk); chunk = min_t(unsigned int, skb->len, size); if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (copied == 0) copied = -EFAULT; break; } copied += chunk; size -= chunk; /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { skb_pull(skb, chunk); /* put the skb back if we didn't use it up. */ if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { /* * It is questionable, see note in unix_dgram_recvmsg. */ /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); caif_read_unlock(sk); out: return copied ? : err; } CWE ID: CWE-20 Target: 1 Example 2: Code: nfsd_readlink(struct svc_rqst *rqstp, struct svc_fh *fhp, char *buf, int *lenp) { mm_segment_t oldfs; __be32 err; int host_err; struct path path; err = fh_verify(rqstp, fhp, S_IFLNK, NFSD_MAY_NOP); if (err) goto out; path.mnt = fhp->fh_export->ex_path.mnt; path.dentry = fhp->fh_dentry; err = nfserr_inval; if (!d_is_symlink(path.dentry)) goto out; touch_atime(&path); /* N.B. Why does this call need a get_fs()?? * Remove the set_fs and watch the fireworks:-) --okir */ oldfs = get_fs(); set_fs(KERNEL_DS); host_err = vfs_readlink(path.dentry, (char __user *)buf, *lenp); set_fs(oldfs); if (host_err < 0) goto out_nfserr; *lenp = host_err; err = 0; out: return err; out_nfserr: err = nfserrno(host_err); goto out; } CWE ID: CWE-404 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ping_hash(struct sock *sk) { pr_debug("ping_hash(sk->port=%u)\n", inet_sk(sk)->inet_num); BUG(); /* "Please do not press this button again." */ return 0; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: perform_transform_test(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; while (next_format(&colour_type, &bit_depth, &palette_number, 0)) { png_uint_32 counter = 0; size_t base_pos; char name[64]; base_pos = safecat(name, sizeof name, 0, "transform:"); for (;;) { size_t pos = base_pos; PNG_CONST image_transform *list = 0; /* 'max' is currently hardwired to '1'; this should be settable on the * command line. */ counter = image_transform_add(&list, 1/*max*/, counter, name, sizeof name, &pos, colour_type, bit_depth); if (counter == 0) break; /* The command line can change this to checking interlaced images. */ do { pm->repeat = 0; transform_test(pm, FILEID(colour_type, bit_depth, palette_number, pm->interlace_type, 0, 0, 0), list, name); if (fail(pm)) return; } while (pm->repeat); } } } CWE ID: Target: 1 Example 2: Code: void doMergeNameDict(PDFDoc *doc, XRef *srcXRef, XRef *countRef, int oldRefNum, int newRefNum, Dict *srcNameDict, Dict *mergeNameDict, int numOffset) { for (int i = 0; i < mergeNameDict->getLength(); i++) { const char *key = mergeNameDict->getKey(i); Object mergeNameTree; Object srcNameTree; mergeNameDict->lookup(key, &mergeNameTree); srcNameDict->lookup(key, &srcNameTree); if (srcNameTree.isDict() && mergeNameTree.isDict()) { doMergeNameTree(doc, srcXRef, countRef, oldRefNum, newRefNum, srcNameTree.getDict(), mergeNameTree.getDict(), numOffset); } else if (srcNameTree.isNull() && mergeNameTree.isDict()) { Object *newNameTree = new Object(); newNameTree->initDict(srcXRef); doMergeNameTree(doc, srcXRef, countRef, oldRefNum, newRefNum, newNameTree->getDict(), mergeNameTree.getDict(), numOffset); srcNameDict->add(copyString(key), newNameTree); } srcNameTree.free(); mergeNameTree.free(); } } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void addToBlockedList(sqlite3 *db){ sqlite3 **pp; assertMutexHeld(); for( pp=&sqlite3BlockedList; *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; pp=&(*pp)->pNextBlocked ); db->pNextBlocked = *pp; *pp = db; } 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: GDataFile* AddFile(GDataDirectory* parent, GDataDirectoryService* directory_service, int sequence_id) { GDataFile* file = new GDataFile(NULL, directory_service); const std::string title = "file" + base::IntToString(sequence_id); const std::string resource_id = std::string("file_resource_id:") + title; file->set_title(title); file->set_resource_id(resource_id); file->set_file_md5(std::string("file_md5:") + title); GDataFileError error = GDATA_FILE_ERROR_FAILED; FilePath moved_file_path; directory_service->MoveEntryToDirectory( parent->GetFilePath(), file, base::Bind(&test_util::CopyResultsFromFileMoveCallback, &error, &moved_file_path)); test_util::RunBlockingPoolTask(); EXPECT_EQ(GDATA_FILE_OK, error); EXPECT_EQ(parent->GetFilePath().AppendASCII(title), moved_file_path); return file; } CWE ID: CWE-399 Target: 1 Example 2: Code: static int __init wanxl_init_module(void) { #ifdef MODULE pr_info("%s\n", version); #endif return pci_register_driver(&wanxl_pci_driver); } 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: do_translation_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { return 0; } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_MODERATELY_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\\u30fc]"), status); kana_letters_exceptions_.freeze(); DCHECK(U_SUCCESS(status)); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void reflectBooleanAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValueBool(info, imp->fastHasAttribute(HTMLNames::reflectbooleanattributeAttr)); } 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: nsPluginInstance::DestroyStream(NPStream* /*stream*/, NPError /*reason*/) { if (_streamfd != -1) { if (close(_streamfd) == -1) { perror("closing _streamfd"); } else { _streamfd = -1; } } return NPERR_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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithCallbackArg(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) { setDOMException(exec, TYPE_MISMATCH_ERR); return JSValue::encode(jsUndefined()); } RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject()); impl->methodWithCallbackArg(callback); return JSValue::encode(jsUndefined()); } CWE ID: CWE-20 Target: 1 Example 2: Code: static int hci_uart_open(struct hci_dev *hdev) { BT_DBG("%s %p", hdev->name, hdev); /* Undo clearing this from hci_uart_close() */ hdev->flush = hci_uart_flush; return 0; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static const char *parse_number( cJSON *item, const char *num ) { int64_t i = 0; double f = 0; int isint = 1; int sign = 1, scale = 0, subscale = 0, signsubscale = 1; /* Could use sscanf for this? */ if ( *num == '-' ) { /* Has sign. */ sign = -1; ++num; } if ( *num == '0' ) /* Is zero. */ ++num; if ( *num >= '1' && *num<='9' ) { /* Number. */ do { i = ( i * 10 ) + ( *num - '0' ); f = ( f * 10.0 ) + ( *num - '0' ); ++num; } while ( *num >= '0' && *num <= '9' ); } if ( *num == '.' && num[1] >= '0' && num[1] <= '9' ) { /* Fractional part. */ isint = 0; ++num; do { f = ( f * 10.0 ) + ( *num++ - '0' ); scale--; } while ( *num >= '0' && *num <= '9' ); } if ( *num == 'e' || *num == 'E' ) { /* Exponent. */ isint = 0; ++num; if ( *num == '+' ) ++num; else if ( *num == '-' ) { /* With sign. */ signsubscale = -1; ++num; } while ( *num >= '0' && *num <= '9' ) subscale = ( subscale * 10 ) + ( *num++ - '0' ); } /* Put it together. */ if ( isint ) { /* Int: number = +/- number */ i = sign * i; item->valueint = i; item->valuefloat = i; } else { /* Float: number = +/- number.fraction * 10^+/- exponent */ f = sign * f * ipow( 10.0, scale + subscale * signsubscale ); item->valueint = f; item->valuefloat = f; } item->type = cJSON_Number; return num; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(mcrypt_ofb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } CWE ID: CWE-190 Target: 1 Example 2: Code: static void truncate_hugepages(struct inode *inode, loff_t lstart) { struct hstate *h = hstate_inode(inode); struct address_space *mapping = &inode->i_data; const pgoff_t start = lstart >> huge_page_shift(h); struct pagevec pvec; pgoff_t next; int i, freed = 0; pagevec_init(&pvec, 0); next = start; while (1) { if (!pagevec_lookup(&pvec, mapping, next, PAGEVEC_SIZE)) { if (next == start) break; next = start; continue; } for (i = 0; i < pagevec_count(&pvec); ++i) { struct page *page = pvec.pages[i]; lock_page(page); if (page->index > next) next = page->index; ++next; truncate_huge_page(page); unlock_page(page); freed++; } huge_pagevec_release(&pvec); } BUG_ON(!lstart && mapping->nrpages); hugetlb_unreserve_pages(inode, start, freed); } 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 sb_wait_write(struct super_block *sb, int level) { s64 writers; /* * We just cycle-through lockdep here so that it does not complain * about returning with lock to userspace */ rwsem_acquire(&sb->s_writers.lock_map[level-1], 0, 0, _THIS_IP_); rwsem_release(&sb->s_writers.lock_map[level-1], 1, _THIS_IP_); do { DEFINE_WAIT(wait); /* * We use a barrier in prepare_to_wait() to separate setting * of frozen and checking of the counter */ prepare_to_wait(&sb->s_writers.wait, &wait, TASK_UNINTERRUPTIBLE); writers = percpu_counter_sum(&sb->s_writers.counter[level-1]); if (writers) schedule(); finish_wait(&sb->s_writers.wait, &wait); } while (writers); } CWE ID: CWE-17 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t SampleTable::setCompositionTimeToSampleParams( off64_t data_offset, size_t data_size) { ALOGI("There are reordered frames present."); if (mCompositionTimeDeltaEntries != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } size_t numEntries = U32_AT(&header[4]); if (data_size != (numEntries + 1) * 8) { return ERROR_MALFORMED; } mNumCompositionTimeDeltaEntries = numEntries; mCompositionTimeDeltaEntries = new uint32_t[2 * numEntries]; if (mDataSource->readAt( data_offset + 8, mCompositionTimeDeltaEntries, numEntries * 8) < (ssize_t)numEntries * 8) { delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; return ERROR_IO; } for (size_t i = 0; i < 2 * numEntries; ++i) { mCompositionTimeDeltaEntries[i] = ntohl(mCompositionTimeDeltaEntries[i]); } mCompositionDeltaLookup->setEntries( mCompositionTimeDeltaEntries, mNumCompositionTimeDeltaEntries); return OK; } CWE ID: CWE-189 Target: 1 Example 2: Code: void AddLibrary(int resource_id) { include_libraries_.push_back(resource_id); } CWE ID: CWE-284 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GF_Err tpyl_dump(GF_Box *a, FILE * trace) { GF_NTYLBox *p; p = (GF_NTYLBox *)a; gf_isom_box_dump_start(a, "LargeTotalMediaBytesBox", trace); fprintf(trace, "BytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes); gf_isom_box_dump_done("LargeTotalMediaBytesBox", a, trace); return GF_OK; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; int newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (mode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(path, state, wait); } CWE ID: Target: 1 Example 2: Code: xmlParseInternalSubset(xmlParserCtxtPtr ctxt) { /* * Is there any DTD definition ? */ if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; NEXT; /* * Parse the succession of Markup declarations and * PEReferences. * Subsequence (markupdecl | PEReference | S)* */ while (((RAW != ']') || (ctxt->inputNr > 1)) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; SKIP_BLANKS; xmlParseMarkupDecl(ctxt); xmlParsePEReference(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseInternalSubset: error detected in Markup declaration\n"); if (ctxt->inputNr > 1) xmlPopInput(ctxt); else break; } } if (RAW == ']') { NEXT; SKIP_BLANKS; } } /* * We should be at the end of the DOCTYPE declaration. */ if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL); return; } NEXT; } CWE ID: CWE-835 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SYSCALL_DEFINE1(uname, struct old_utsname __user *, name) { int error = 0; if (!name) return -EFAULT; down_read(&uts_sem); if (copy_to_user(name, utsname(), sizeof(*name))) error = -EFAULT; up_read(&uts_sem); if (!error && override_release(name->release, sizeof(name->release))) error = -EFAULT; if (!error && override_architecture(name)) error = -EFAULT; return 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: void UserSelectionScreen::FillUserMojoStruct( const user_manager::User* user, bool is_owner, bool is_signin_to_add, proximity_auth::mojom::AuthType auth_type, const std::vector<std::string>* public_session_recommended_locales, ash::mojom::LoginUserInfo* user_info) { user_info->basic_user_info = ash::mojom::UserInfo::New(); user_info->basic_user_info->type = user->GetType(); user_info->basic_user_info->account_id = user->GetAccountId(); user_info->basic_user_info->display_name = base::UTF16ToUTF8(user->GetDisplayName()); user_info->basic_user_info->display_email = user->display_email(); user_info->basic_user_info->avatar = BuildMojoUserAvatarForUser(user); user_info->auth_type = auth_type; user_info->is_signed_in = user->is_logged_in(); user_info->is_device_owner = is_owner; user_info->can_remove = CanRemoveUser(user); user_info->allow_fingerprint_unlock = AllowFingerprintForUser(user); if (!is_signin_to_add) { user_info->is_multiprofile_allowed = true; } else { GetMultiProfilePolicy(user, &user_info->is_multiprofile_allowed, &user_info->multiprofile_policy); } if (user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) { user_info->public_account_info = ash::mojom::PublicAccountInfo::New(); std::string domain; if (GetEnterpriseDomain(&domain)) user_info->public_account_info->enterprise_domain = domain; std::string selected_locale; bool has_multiple_locales; std::unique_ptr<base::ListValue> available_locales = GetPublicSessionLocales(public_session_recommended_locales, &selected_locale, &has_multiple_locales); DCHECK(available_locales); user_info->public_account_info->available_locales = lock_screen_utils::FromListValueToLocaleItem( std::move(available_locales)); user_info->public_account_info->default_locale = selected_locale; user_info->public_account_info->show_advanced_view = has_multiple_locales; } } CWE ID: Target: 1 Example 2: Code: static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gaddr, unsigned level, int direct, unsigned access, u64 *parent_pte) { union kvm_mmu_page_role role; unsigned quadrant; struct kvm_mmu_page *sp; bool need_sync = false; role = vcpu->arch.mmu.base_role; role.level = level; role.direct = direct; if (role.direct) role.cr4_pae = 0; role.access = access; if (!vcpu->arch.mmu.direct_map && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) { quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level)); quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1; role.quadrant = quadrant; } for_each_gfn_sp(vcpu->kvm, sp, gfn) { if (is_obsolete_sp(vcpu->kvm, sp)) continue; if (!need_sync && sp->unsync) need_sync = true; if (sp->role.word != role.word) continue; if (sp->unsync && kvm_sync_page_transient(vcpu, sp)) break; mmu_page_add_parent_pte(vcpu, sp, parent_pte); if (sp->unsync_children) { kvm_make_request(KVM_REQ_MMU_SYNC, vcpu); kvm_mmu_mark_parents_unsync(sp); } else if (sp->unsync) kvm_mmu_mark_parents_unsync(sp); __clear_sp_write_flooding_count(sp); trace_kvm_mmu_get_page(sp, false); return sp; } ++vcpu->kvm->stat.mmu_cache_miss; sp = kvm_mmu_alloc_page(vcpu, parent_pte, direct); if (!sp) return sp; sp->gfn = gfn; sp->role = role; hlist_add_head(&sp->hash_link, &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]); if (!direct) { if (rmap_write_protect(vcpu->kvm, gfn)) kvm_flush_remote_tlbs(vcpu->kvm); if (level > PT_PAGE_TABLE_LEVEL && need_sync) kvm_sync_pages(vcpu, gfn); account_shadowed(vcpu->kvm, gfn); } sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen; init_shadow_page_table(sp); trace_kvm_mmu_get_page(sp, true); return sp; } 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: ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append) { unsigned nSyms = darray_size(expr->keysym_list.syms); unsigned numEntries = darray_size(append->keysym_list.syms); darray_append(expr->keysym_list.symsMapIndex, nSyms); darray_append(expr->keysym_list.symsNumEntries, numEntries); darray_concat(expr->keysym_list.syms, append->keysym_list.syms); FreeStmt((ParseCommon *) &append); return expr; } 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: make_errors(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, int bdlo, int PNG_CONST bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { unsigned int test; char name[FILE_NAME_SIZE]; standard_name(name, sizeof name, 0, colour_type, 1<<bdlo, 0, interlace_type, 0, 0, 0); for (test=0; test<(sizeof error_test)/(sizeof error_test[0]); ++test) { make_error(&pm->this, colour_type, DEPTH(bdlo), interlace_type, test, name); if (fail(pm)) return 0; } } } return 1; /* keep going */ } CWE ID: Target: 1 Example 2: Code: GF_Err trgr_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_TrackGroupBox *ptr = (GF_TrackGroupBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; return gf_isom_box_array_write(s, ptr->groups, bs); } 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 expand_stack(struct vm_area_struct *vma, unsigned long address) { return expand_upwards(vma, address); } 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: DOMWindow* CreateWindow(const String& url_string, const AtomicString& frame_name, const String& window_features_string, LocalDOMWindow& calling_window, LocalFrame& first_frame, LocalFrame& opener_frame, ExceptionState& exception_state) { LocalFrame* active_frame = calling_window.GetFrame(); DCHECK(active_frame); KURL completed_url = url_string.IsEmpty() ? KURL(kParsedURLString, g_empty_string) : first_frame.GetDocument()->CompleteURL(url_string); if (!completed_url.IsEmpty() && !completed_url.IsValid()) { UseCounter::Count(active_frame, WebFeature::kWindowOpenWithInvalidURL); exception_state.ThrowDOMException( kSyntaxError, "Unable to open a window with invalid URL '" + completed_url.GetString() + "'.\n"); return nullptr; } WebWindowFeatures window_features = GetWindowFeaturesFromString(window_features_string); FrameLoadRequest frame_request(calling_window.document(), ResourceRequest(completed_url), frame_name); frame_request.SetShouldSetOpener(window_features.noopener ? kNeverSetOpener : kMaybeSetOpener); frame_request.GetResourceRequest().SetFrameType( WebURLRequest::kFrameTypeAuxiliary); frame_request.GetResourceRequest().SetRequestorOrigin( SecurityOrigin::Create(active_frame->GetDocument()->Url())); frame_request.GetResourceRequest().SetHTTPReferrer( SecurityPolicy::GenerateReferrer( active_frame->GetDocument()->GetReferrerPolicy(), completed_url, active_frame->GetDocument()->OutgoingReferrer())); bool has_user_gesture = UserGestureIndicator::ProcessingUserGesture(); bool created; Frame* new_frame = CreateWindowHelper( opener_frame, *active_frame, opener_frame, frame_request, window_features, kNavigationPolicyIgnore, created); if (!new_frame) return nullptr; if (new_frame->DomWindow()->IsInsecureScriptAccess(calling_window, completed_url)) return window_features.noopener ? nullptr : new_frame->DomWindow(); if (created) { FrameLoadRequest request(calling_window.document(), ResourceRequest(completed_url)); request.GetResourceRequest().SetHasUserGesture(has_user_gesture); new_frame->Navigate(request); } else if (!url_string.IsEmpty()) { new_frame->Navigate(*calling_window.document(), completed_url, false, has_user_gesture ? UserGestureStatus::kActive : UserGestureStatus::kNone); } return window_features.noopener ? nullptr : new_frame->DomWindow(); } CWE ID: Target: 1 Example 2: Code: void FrameSelection::PageActivationChanged() { FocusedOrActiveStateChanged(); } 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 xt_compat_add_offset(u_int8_t af, unsigned int offset, int delta) { struct xt_af *xp = &xt[af]; if (!xp->compat_tab) { if (!xp->number) return -EINVAL; xp->compat_tab = vmalloc(sizeof(struct compat_delta) * xp->number); if (!xp->compat_tab) return -ENOMEM; xp->cur = 0; } if (xp->cur >= xp->number) return -EINVAL; if (xp->cur) delta += xp->compat_tab[xp->cur - 1].delta; xp->compat_tab[xp->cur].offset = offset; xp->compat_tab[xp->cur].delta = delta; xp->cur++; return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SelectionEditor::NodeChildrenWillBeRemoved(ContainerNode& container) { if (selection_.IsNone()) return; const Position old_base = selection_.base_; const Position old_extent = selection_.extent_; const Position& new_base = ComputePositionForChildrenRemoval(old_base, container); const Position& new_extent = ComputePositionForChildrenRemoval(old_extent, container); if (new_base == old_base && new_extent == old_extent) return; selection_ = SelectionInDOMTree::Builder() .SetBaseAndExtent(new_base, new_extent) .SetIsHandleVisible(selection_.IsHandleVisible()) .Build(); MarkCacheDirty(); } CWE ID: CWE-119 Target: 1 Example 2: Code: ShowTranslateBubbleResult TestBrowserWindow::ShowTranslateBubble( content::WebContents* contents, translate::TranslateStep step, translate::TranslateErrors::Type error_type, bool is_user_gesture) { return ShowTranslateBubbleResult::SUCCESS; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GpuProcessHost::EstablishChannelError( const EstablishChannelCallback& callback, const IPC::ChannelHandle& channel_handle, base::ProcessHandle renderer_process_for_gpu, const content::GPUInfo& gpu_info) { callback.Run(channel_handle, renderer_process_for_gpu, gpu_info); } 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 QQuickWebViewFlickablePrivate::onComponentComplete() { Q_Q(QQuickWebView); m_viewportHandler.reset(new QtViewportHandler(webPageProxy.get(), q, pageView.data())); pageView->eventHandler()->setViewportHandler(m_viewportHandler.data()); _q_onVisibleChanged(); } CWE ID: Target: 1 Example 2: Code: void ProfilingProcessHost::ConfigureBackgroundProfilingTriggers() { background_triggers_.StartTimer(); } 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: Ins_IUP( INS_ARG ) { IUP_WorkerRec V; FT_Byte mask; FT_UInt first_point; /* first point of contour */ FT_UInt end_point; /* end point (last+1) of contour */ FT_UInt first_touched; /* first touched point in contour */ FT_UInt cur_touched; /* current touched point in contour */ FT_UInt point; /* current point */ FT_Short contour; /* current contour */ FT_UNUSED_ARG; /* ignore empty outlines */ if ( CUR.pts.n_contours == 0 ) return; if ( CUR.opcode & 1 ) { mask = FT_CURVE_TAG_TOUCH_X; V.orgs = CUR.pts.org; V.curs = CUR.pts.cur; V.orus = CUR.pts.orus; } else { mask = FT_CURVE_TAG_TOUCH_Y; V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 ); V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 ); V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 ); } V.max_points = CUR.pts.n_points; contour = 0; point = 0; do { end_point = CUR.pts.contours[contour] - CUR.pts.first_point; first_point = point; if ( CUR.pts.n_points <= end_point ) end_point = CUR.pts.n_points; while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 ) point++; if ( point <= end_point ) { first_touched = point; cur_touched = point; point++; while ( point <= end_point ) { if ( ( CUR.pts.tags[point] & mask ) != 0 ) { if ( point > 0 ) _iup_worker_interpolate( &V, cur_touched + 1, point - 1, cur_touched, point ); cur_touched = point; } point++; } if ( cur_touched == first_touched ) _iup_worker_shift( &V, first_point, end_point, cur_touched ); else { _iup_worker_interpolate( &V, (FT_UShort)( cur_touched + 1 ), end_point, cur_touched, first_touched ); if ( first_touched > 0 ) _iup_worker_interpolate( &V, first_point, first_touched - 1, cur_touched, first_touched ); } } contour++; } while ( contour < CUR.pts.n_contours ); } 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 ClipboardMessageFilter::OnReadImageReply( SkBitmap bitmap, IPC::Message* reply_msg) { base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle(); uint32 image_size = 0; std::string reply_data; if (!bitmap.isNull()) { std::vector<unsigned char> png_data; SkAutoLockPixels lock(bitmap); if (gfx::PNGCodec::EncodeWithCompressionLevel( static_cast<const unsigned char*>(bitmap.getPixels()), gfx::PNGCodec::FORMAT_BGRA, gfx::Size(bitmap.width(), bitmap.height()), bitmap.rowBytes(), false, std::vector<gfx::PNGCodec::Comment>(), Z_BEST_SPEED, &png_data)) { base::SharedMemory buffer; if (buffer.CreateAndMapAnonymous(png_data.size())) { memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size()); if (buffer.GiveToProcess(peer_handle(), &image_handle)) { image_size = png_data.size(); } } } } ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle, image_size); Send(reply_msg); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void gen_setcc1(DisasContext *s, int b, TCGv reg) { CCPrepare cc = gen_prepare_cc(s, b, reg); if (cc.no_setcond) { if (cc.cond == TCG_COND_EQ) { tcg_gen_xori_tl(reg, cc.reg, 1); } else { tcg_gen_mov_tl(reg, cc.reg); } return; } if (cc.cond == TCG_COND_NE && !cc.use_reg2 && cc.imm == 0 && cc.mask != 0 && (cc.mask & (cc.mask - 1)) == 0) { tcg_gen_shri_tl(reg, cc.reg, ctztl(cc.mask)); tcg_gen_andi_tl(reg, reg, 1); return; } if (cc.mask != -1) { tcg_gen_andi_tl(reg, cc.reg, cc.mask); cc.reg = reg; } if (cc.use_reg2) { tcg_gen_setcond_tl(cc.cond, reg, cc.reg, cc.reg2); } else { tcg_gen_setcondi_tl(cc.cond, reg, cc.reg, cc.imm); } } CWE ID: CWE-94 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 nodeHasRole(Node* node, const String& role) { if (!node || !node->isElementNode()) return false; return equalIgnoringCase(toElement(node)->getAttribute(roleAttr), role); } 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: transform_enable(PNG_CONST char *name) { /* Everything starts out enabled, so if we see an 'enable' disabled * everything else the first time round. */ static int all_disabled = 0; int found_it = 0; image_transform *list = image_transform_first; while (list != &image_transform_end) { if (strcmp(list->name, name) == 0) { list->enable = 1; found_it = 1; } else if (!all_disabled) list->enable = 0; list = list->list; } all_disabled = 1; if (!found_it) { fprintf(stderr, "pngvalid: --transform-enable=%s: unknown transform\n", name); exit(99); } } CWE ID: Target: 1 Example 2: Code: ~FileBrowserPrivateGetDownloadUrlFunction() { } 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 LocalFrameClientImpl::DispatchDidFailProvisionalLoad( const ResourceError& error, WebHistoryCommitType commit_type) { web_frame_->DidFail(error, true, commit_type); virtual_time_pauser_.UnpauseVirtualTime(); } 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: PHP_FUNCTION(openssl_seal) { zval *pubkeys, *pubkey, *sealdata, *ekeys, *iv = NULL; HashTable *pubkeysht; EVP_PKEY **pkeys; zend_resource ** key_resources; /* so we know what to cleanup */ int i, len1, len2, *eksl, nkeys, iv_len; unsigned char iv_buf[EVP_MAX_IV_LENGTH + 1], *buf = NULL, **eks; char * data; size_t data_len; char *method =NULL; size_t method_len = 0; const EVP_CIPHER *cipher; EVP_CIPHER_CTX *ctx; if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/a/|sz/", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len, &iv) == FAILURE) { return; } pubkeysht = Z_ARRVAL_P(pubkeys); nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0; if (!nkeys) { php_error_docref(NULL, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array"); RETURN_FALSE; } PHP_OPENSSL_CHECK_SIZE_T_TO_INT(data_len, data); if (method) { cipher = EVP_get_cipherbyname(method); if (!cipher) { php_error_docref(NULL, E_WARNING, "Unknown signature algorithm."); RETURN_FALSE; } } else { cipher = EVP_rc4(); } iv_len = EVP_CIPHER_iv_length(cipher); if (!iv && iv_len > 0) { php_error_docref(NULL, E_WARNING, "Cipher algorithm requires an IV to be supplied as a sixth parameter"); RETURN_FALSE; } pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0); eksl = safe_emalloc(nkeys, sizeof(*eksl), 0); eks = safe_emalloc(nkeys, sizeof(*eks), 0); memset(eks, 0, sizeof(*eks) * nkeys); key_resources = safe_emalloc(nkeys, sizeof(zend_resource*), 0); memset(key_resources, 0, sizeof(zend_resource*) * nkeys); memset(pkeys, 0, sizeof(*pkeys) * nkeys); /* get the public keys we are using to seal this data */ i = 0; ZEND_HASH_FOREACH_VAL(pubkeysht, pubkey) { pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, 0, &key_resources[i]); if (pkeys[i] == NULL) { php_error_docref(NULL, E_WARNING, "not a public key (%dth member of pubkeys)", i+1); RETVAL_FALSE; goto clean_exit; } eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1); i++; } ZEND_HASH_FOREACH_END(); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL || !EVP_EncryptInit(ctx,cipher,NULL,NULL)) { EVP_CIPHER_CTX_free(ctx); RETVAL_FALSE; goto clean_exit; } /* allocate one byte extra to make room for \0 */ buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx)); EVP_CIPHER_CTX_cleanup(ctx); if (!EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) || !EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) || !EVP_SealFinal(ctx, buf + len1, &len2)) { RETVAL_FALSE; efree(buf); EVP_CIPHER_CTX_free(ctx); goto clean_exit; } if (len1 + len2 > 0) { zval_dtor(sealdata); ZVAL_NEW_STR(sealdata, zend_string_init((char*)buf, len1 + len2, 0)); efree(buf); zval_dtor(ekeys); array_init(ekeys); for (i=0; i<nkeys; i++) { eks[i][eksl[i]] = '\0'; add_next_index_stringl(ekeys, (const char*)eks[i], eksl[i]); efree(eks[i]); eks[i] = NULL; } if (iv) { zval_dtor(iv); iv_buf[iv_len] = '\0'; ZVAL_NEW_STR(iv, zend_string_init((char*)iv_buf, iv_len, 0)); } } else { efree(buf); } RETVAL_LONG(len1 + len2); EVP_CIPHER_CTX_free(ctx); clean_exit: for (i=0; i<nkeys; i++) { if (key_resources[i] == NULL && pkeys[i] != NULL) { EVP_PKEY_free(pkeys[i]); } if (eks[i]) { efree(eks[i]); } } efree(eks); efree(eksl); efree(pkeys); efree(key_resources); } CWE ID: CWE-754 Target: 1 Example 2: Code: static int snd_seq_ioctl_set_client_pool(struct snd_seq_client *client, void __user *arg) { struct snd_seq_client_pool info; int rc; if (copy_from_user(&info, arg, sizeof(info))) return -EFAULT; if (client->number != info.client) return -EINVAL; /* can't change other clients */ if (info.output_pool >= 1 && info.output_pool <= SNDRV_SEQ_MAX_EVENTS && (! snd_seq_write_pool_allocated(client) || info.output_pool != client->pool->size)) { if (snd_seq_write_pool_allocated(client)) { /* remove all existing cells */ snd_seq_queue_client_leave_cells(client->number); snd_seq_pool_done(client->pool); } client->pool->size = info.output_pool; rc = snd_seq_pool_init(client->pool); if (rc < 0) return rc; } if (client->type == USER_CLIENT && client->data.user.fifo != NULL && info.input_pool >= 1 && info.input_pool <= SNDRV_SEQ_MAX_CLIENT_EVENTS && info.input_pool != client->data.user.fifo_pool_size) { /* change pool size */ rc = snd_seq_fifo_resize(client->data.user.fifo, info.input_pool); if (rc < 0) return rc; client->data.user.fifo_pool_size = info.input_pool; } if (info.output_room >= 1 && info.output_room <= client->pool->size) { client->pool->room = info.output_room; } return snd_seq_ioctl_get_client_pool(client, arg); } 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 __init files_init(unsigned long mempages) { unsigned long n; filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL); /* * One file with associated inode and dcache is very roughly 1K. * Per default don't use more than 10% of our memory for files. */ n = (mempages * (PAGE_SIZE / 1024)) / 10; files_stat.max_files = max_t(unsigned long, n, NR_FILE); files_defer_init(); lg_lock_init(&files_lglock, "files_lglock"); percpu_counter_init(&nr_files, 0); } 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: random_32(void) { for(;;) { png_byte mark[4]; png_uint_32 result; store_pool_mark(mark); result = png_get_uint_32(mark); if (result != 0) return result; } } CWE ID: Target: 1 Example 2: Code: bool PhotoDataUtils::IsValueDifferent ( const TIFF_Manager::TagInfo & exifInfo, const std::string & xmpValue, std::string * exifValue ) { if ( exifInfo.dataLen == 0 ) return false; // Ignore empty Exif values. if ( ReconcileUtils::IsUTF8 ( exifInfo.dataPtr, exifInfo.dataLen ) ) { // ! Note that ASCII is UTF-8. exifValue->assign ( (char*)exifInfo.dataPtr, exifInfo.dataLen ); } else { if ( ignoreLocalText ) return false; ReconcileUtils::LocalToUTF8 ( exifInfo.dataPtr, exifInfo.dataLen, exifValue ); } return (*exifValue != xmpValue); } // PhotoDataUtils::IsValueDifferent 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: LayoutRect RenderBlock::logicalRightSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock, RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo) { LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop; LayoutUnit rootBlockLogicalLeft = max(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + floorToInt(logicalRight), max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight))); LayoutUnit rootBlockLogicalRight = min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)); LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft; if (rootBlockLogicalWidth <= 0) return LayoutRect(); LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight)); if (paintInfo) paintInfo->context->fillRect(pixelSnappedIntRect(gapRect), selObj->selectionBackgroundColor()); return gapRect; } 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(cc::mojom::CompositorFrameMetadataDataView data, cc::CompositorFrameMetadata* out) { out->device_scale_factor = data.device_scale_factor(); if (!data.ReadRootScrollOffset(&out->root_scroll_offset)) return false; out->page_scale_factor = data.page_scale_factor(); if (!data.ReadScrollableViewportSize(&out->scrollable_viewport_size) || !data.ReadRootLayerSize(&out->root_layer_size)) { return false; } out->min_page_scale_factor = data.min_page_scale_factor(); out->max_page_scale_factor = data.max_page_scale_factor(); out->root_overflow_x_hidden = data.root_overflow_x_hidden(); out->root_overflow_y_hidden = data.root_overflow_y_hidden(); out->may_contain_video = data.may_contain_video(); out->is_resourceless_software_draw_with_scroll_or_animation = data.is_resourceless_software_draw_with_scroll_or_animation(); out->top_controls_height = data.top_controls_height(); out->top_controls_shown_ratio = data.top_controls_shown_ratio(); out->bottom_controls_height = data.bottom_controls_height(); out->bottom_controls_shown_ratio = data.bottom_controls_shown_ratio(); out->root_background_color = data.root_background_color(); out->can_activate_before_dependencies = data.can_activate_before_dependencies(); return data.ReadSelection(&out->selection) && data.ReadLatencyInfo(&out->latency_info) && data.ReadReferencedSurfaces(&out->referenced_surfaces); } CWE ID: CWE-362 Target: 1 Example 2: Code: static void fsl_emb_pmu_del(struct perf_event *event, int flags) { struct cpu_hw_events *cpuhw; int i = event->hw.idx; perf_pmu_disable(event->pmu); if (i < 0) goto out; fsl_emb_pmu_read(event); cpuhw = &get_cpu_var(cpu_hw_events); WARN_ON(event != cpuhw->event[event->hw.idx]); write_pmlca(i, 0); write_pmlcb(i, 0); write_pmc(i, 0); cpuhw->event[i] = NULL; event->hw.idx = -1; /* * TODO: if at least one restricted event exists, and we * just freed up a non-restricted-capable counter, and * there is a restricted-capable counter occupied by * a non-restricted event, migrate that event to the * vacated counter. */ cpuhw->n_events--; out: perf_pmu_enable(event->pmu); put_cpu_var(cpu_hw_events); } 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: xsltNumberFormatGetAnyLevel(xsltTransformContextPtr context, xmlNodePtr node, xsltCompMatchPtr countPat, xsltCompMatchPtr fromPat, double *array, xmlDocPtr doc, xmlNodePtr elem) { int amount = 0; int cnt = 0; xmlNodePtr cur; /* select the starting node */ switch (node->type) { case XML_ELEMENT_NODE: cur = node; break; case XML_ATTRIBUTE_NODE: cur = ((xmlAttrPtr) node)->parent; break; case XML_TEXT_NODE: case XML_PI_NODE: case XML_COMMENT_NODE: cur = node->parent; break; default: cur = NULL; break; } while (cur != NULL) { /* process current node */ if (countPat == NULL) { if ((node->type == cur->type) && /* FIXME: must use expanded-name instead of local name */ xmlStrEqual(node->name, cur->name)) { if ((node->ns == cur->ns) || ((node->ns != NULL) && (cur->ns != NULL) && (xmlStrEqual(node->ns->href, cur->ns->href) ))) cnt++; } } else { if (xsltTestCompMatchList(context, cur, countPat)) cnt++; } if ((fromPat != NULL) && xsltTestCompMatchList(context, cur, fromPat)) { break; /* while */ } /* Skip to next preceding or ancestor */ if ((cur->type == XML_DOCUMENT_NODE) || #ifdef LIBXML_DOCB_ENABLED (cur->type == XML_DOCB_DOCUMENT_NODE) || #endif (cur->type == XML_HTML_DOCUMENT_NODE)) break; /* while */ while ((cur->prev != NULL) && ((cur->prev->type == XML_DTD_NODE) || (cur->prev->type == XML_XINCLUDE_START) || (cur->prev->type == XML_XINCLUDE_END))) cur = cur->prev; if (cur->prev != NULL) { for (cur = cur->prev; cur->last != NULL; cur = cur->last); } else { cur = cur->parent; } } array[amount++] = (double) cnt; return(amount); } 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: long AudioTrack::Parse(Segment* pSegment, const Info& info, long long element_start, long long element_size, AudioTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kAudio) return -1; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; double rate = 8000.0; // MKV default long long channels = 1; long long bit_depth = 0; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x35) { // Sample Rate status = UnserializeFloat(pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x1F) { // Channel Count channels = UnserializeUInt(pReader, pos, size); if (channels <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x2264) { // Bit Depth bit_depth = UnserializeUInt(pReader, pos, size); if (bit_depth <= 0) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); AudioTrack* const pTrack = new (std::nothrow) AudioTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; // generic error const int status = info.Copy(pTrack->m_info); if (status) { delete pTrack; return status; } pTrack->m_rate = rate; pTrack->m_channels = channels; pTrack->m_bitDepth = bit_depth; pResult = pTrack; return 0; // success } CWE ID: CWE-20 Target: 1 Example 2: Code: void NormalPageArena::AllocatePage() { GetThreadState()->Heap().address_cache()->MarkDirty(); PageMemory* page_memory = GetThreadState()->Heap().GetFreePagePool()->Take(ArenaIndex()); if (!page_memory) { PageMemoryRegion* region = PageMemoryRegion::AllocateNormalPages( GetThreadState()->Heap().GetRegionTree()); for (size_t i = 0; i < kBlinkPagesPerRegion; ++i) { PageMemory* memory = PageMemory::SetupPageMemoryInRegion( region, i * kBlinkPageSize, BlinkPagePayloadSize()); if (!page_memory) { bool result = memory->Commit(); CHECK(result); page_memory = memory; } else { GetThreadState()->Heap().GetFreePagePool()->Add(ArenaIndex(), memory); } } } NormalPage* page = new (page_memory->WritableStart()) NormalPage(page_memory, this); page->Link(&first_page_); GetThreadState()->Heap().HeapStats().IncreaseAllocatedSpace(page->size()); #if DCHECK_IS_ON() || defined(LEAK_SANITIZER) || defined(ADDRESS_SANITIZER) ASAN_UNPOISON_MEMORY_REGION(page->Payload(), page->PayloadSize()); Address address = page->Payload(); for (size_t i = 0; i < page->PayloadSize(); i++) address[i] = kReuseAllowedZapValue; ASAN_POISON_MEMORY_REGION(page->Payload(), page->PayloadSize()); #endif AddToFreeList(page->Payload(), page->PayloadSize()); } 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 FrameView::addScrollableArea(ScrollableArea* scrollableArea) { ASSERT(scrollableArea); if (!m_scrollableAreas) m_scrollableAreas = adoptPtr(new ScrollableAreaSet); m_scrollableAreas->add(scrollableArea); } 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 linear_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct linear_c *lc = (struct linear_c *) ti->private; return __blkdev_driver_ioctl(lc->dev->bdev, lc->dev->mode, cmd, arg); } CWE ID: CWE-264 Target: 1 Example 2: Code: create_var_to_name_hash() { const struct var_name_to_ptr_t *n2v_p = var_name_to_ptr; uzbl.comm.proto_var = g_hash_table_new(g_str_hash, g_str_equal); while(n2v_p->name) { g_hash_table_insert(uzbl.comm.proto_var, (gpointer) n2v_p->name, (gpointer) &n2v_p->cp); n2v_p++; } } 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 clear_refs_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task; char buffer[PROC_NUMBUF]; struct mm_struct *mm; struct vm_area_struct *vma; enum clear_refs_types type; struct mmu_gather tlb; int itype; int rv; memset(buffer, 0, sizeof(buffer)); if (count > sizeof(buffer) - 1) count = sizeof(buffer) - 1; if (copy_from_user(buffer, buf, count)) return -EFAULT; rv = kstrtoint(strstrip(buffer), 10, &itype); if (rv < 0) return rv; type = (enum clear_refs_types)itype; if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST) return -EINVAL; task = get_proc_task(file_inode(file)); if (!task) return -ESRCH; mm = get_task_mm(task); if (mm) { struct mmu_notifier_range range; struct clear_refs_private cp = { .type = type, }; struct mm_walk clear_refs_walk = { .pmd_entry = clear_refs_pte_range, .test_walk = clear_refs_test_walk, .mm = mm, .private = &cp, }; if (type == CLEAR_REFS_MM_HIWATER_RSS) { if (down_write_killable(&mm->mmap_sem)) { count = -EINTR; goto out_mm; } /* * Writing 5 to /proc/pid/clear_refs resets the peak * resident set size to this mm's current rss value. */ reset_mm_hiwater_rss(mm); up_write(&mm->mmap_sem); goto out_mm; } down_read(&mm->mmap_sem); tlb_gather_mmu(&tlb, mm, 0, -1); if (type == CLEAR_REFS_SOFT_DIRTY) { for (vma = mm->mmap; vma; vma = vma->vm_next) { if (!(vma->vm_flags & VM_SOFTDIRTY)) continue; up_read(&mm->mmap_sem); if (down_write_killable(&mm->mmap_sem)) { count = -EINTR; goto out_mm; } for (vma = mm->mmap; vma; vma = vma->vm_next) { vma->vm_flags &= ~VM_SOFTDIRTY; vma_set_page_prot(vma); } downgrade_write(&mm->mmap_sem); break; } mmu_notifier_range_init(&range, mm, 0, -1UL); mmu_notifier_invalidate_range_start(&range); } walk_page_range(0, mm->highest_vm_end, &clear_refs_walk); if (type == CLEAR_REFS_SOFT_DIRTY) mmu_notifier_invalidate_range_end(&range); tlb_finish_mmu(&tlb, 0, -1); up_read(&mm->mmap_sem); out_mm: mmput(mm); } put_task_struct(task); return count; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int perf_swevent_init(struct perf_event *event) { int event_id = event->attr.config; if (event->attr.type != PERF_TYPE_SOFTWARE) return -ENOENT; /* * no branch sampling for software events */ if (has_branch_stack(event)) return -EOPNOTSUPP; switch (event_id) { case PERF_COUNT_SW_CPU_CLOCK: case PERF_COUNT_SW_TASK_CLOCK: return -ENOENT; default: break; } if (event_id >= PERF_COUNT_SW_MAX) return -ENOENT; if (!event->parent) { int err; err = swevent_hlist_get(event); if (err) return err; static_key_slow_inc(&perf_swevent_enabled[event_id]); event->destroy = sw_perf_event_destroy; } return 0; } CWE ID: CWE-189 Target: 1 Example 2: Code: DevToolsWindow* DevToolsWindow::CreateDevToolsWindowForWorker( Profile* profile) { base::RecordAction(base::UserMetricsAction("DevTools_InspectWorker")); return Create(profile, nullptr, kFrontendWorker, std::string(), false, "", ""); } CWE ID: CWE-668 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 WebMediaPlayerImpl::OnError(PipelineStatus status) { DVLOG(1) << __func__; DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK_NE(status, PIPELINE_OK); if (suppress_destruction_errors_) return; #if defined(OS_ANDROID) if (status == PipelineStatus::DEMUXER_ERROR_DETECTED_HLS) { renderer_factory_selector_->SetUseMediaPlayer(true); pipeline_controller_.Stop(); SetMemoryReportingState(false); main_task_runner_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerImpl::StartPipeline, AsWeakPtr())); return; } #endif ReportPipelineError(load_type_, status, media_log_.get()); media_log_->AddEvent(media_log_->CreatePipelineErrorEvent(status)); media_metrics_provider_->OnError(status); if (watch_time_reporter_) watch_time_reporter_->OnError(status); if (ready_state_ == WebMediaPlayer::kReadyStateHaveNothing) { SetNetworkState(WebMediaPlayer::kNetworkStateFormatError); } else { SetNetworkState(PipelineErrorToNetworkState(status)); } pipeline_controller_.Stop(); UpdatePlayState(); } CWE ID: CWE-346 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 JSValueRef touchEndCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { for (unsigned i = 0; i < touches.size(); ++i) if (touches[i].m_state != BlackBerry::Platform::TouchPoint::TouchReleased) { sendTouchEvent(BlackBerry::Platform::TouchEvent::TouchMove); return JSValueMakeUndefined(context); } sendTouchEvent(BlackBerry::Platform::TouchEvent::TouchEnd); touchActive = false; return JSValueMakeUndefined(context); } CWE ID: Target: 1 Example 2: Code: MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double result; register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; if ((traits & UpdatePixelTrait) == 0) continue; result=ApplyEvaluateOperator(random_info[id],q[i],op,value); if (op == MeanEvaluateOperator) result/=2.0; q[i]=ClampToQuantum(result); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EvaluateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } 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 OutOfProcessInstance::OnClientTimerFired(int32_t id) { engine_->OnCallback(id); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ssize_t v9fs_list_xattr(FsContext *ctx, const char *path, void *value, size_t vsize) { ssize_t size = 0; void *ovalue = value; XattrOperations *xops; char *orig_value, *orig_value_start; ssize_t xattr_len, parsed_len = 0, attr_len; char *dirpath, *name; int dirfd; /* Get the actual len */ dirpath = g_path_get_dirname(path); dirfd = local_opendir_nofollow(ctx, dirpath); g_free(dirpath); if (dirfd == -1) { return -1; } name = g_path_get_basename(path); xattr_len = flistxattrat_nofollow(dirfd, name, value, 0); if (xattr_len <= 0) { g_free(name); close_preserve_errno(dirfd); return xattr_len; } /* Now fetch the xattr and find the actual size */ orig_value = g_malloc(xattr_len); xattr_len = flistxattrat_nofollow(dirfd, name, orig_value, xattr_len); g_free(name); close_preserve_errno(dirfd); if (xattr_len < 0) { return -1; } orig_value_start = orig_value; while (xattr_len > parsed_len) { xops = get_xattr_operations(ctx->xops, orig_value); if (!xops) { goto next_entry; } if (!value) { size += xops->listxattr(ctx, path, orig_value, value, vsize); } else { size = xops->listxattr(ctx, path, orig_value, value, vsize); if (size < 0) { goto err_out; } value += size; vsize -= size; } next_entry: /* Got the next entry */ attr_len = strlen(orig_value) + 1; parsed_len += attr_len; orig_value += attr_len; } if (value) { size = value - ovalue; } err_out: g_free(orig_value_start); return size; } CWE ID: CWE-772 Target: 1 Example 2: Code: UIModelWorker* SyncBackendHost::ui_worker() { ModelSafeWorker* w = registrar_.workers[GROUP_UI]; if (w == NULL) return NULL; if (w->GetModelSafeGroup() != GROUP_UI) NOTREACHED(); return static_cast<UIModelWorker*>(w); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ip_setup_cork(struct sock *sk, struct inet_cork *cork, struct ipcm_cookie *ipc, struct rtable **rtp) { struct inet_sock *inet = inet_sk(sk); struct ip_options *opt; struct rtable *rt; /* * setup for corking. */ opt = ipc->opt; if (opt) { if (cork->opt == NULL) { cork->opt = kmalloc(sizeof(struct ip_options) + 40, sk->sk_allocation); if (unlikely(cork->opt == NULL)) return -ENOBUFS; } memcpy(cork->opt, opt, sizeof(struct ip_options) + opt->optlen); cork->flags |= IPCORK_OPT; cork->addr = ipc->addr; } rt = *rtp; if (unlikely(!rt)) return -EFAULT; /* * We steal reference to this route, caller should not release it */ *rtp = NULL; cork->fragsize = inet->pmtudisc == IP_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(rt->dst.path); cork->dst = &rt->dst; cork->length = 0; cork->tx_flags = ipc->tx_flags; cork->page = NULL; cork->off = 0; return 0; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __init balloon_init(void) { if (!xen_domain()) return -ENODEV; pr_info("Initialising balloon driver\n"); #ifdef CONFIG_XEN_PV balloon_stats.current_pages = xen_pv_domain() ? min(xen_start_info->nr_pages - xen_released_pages, max_pfn) : get_num_physpages(); #else balloon_stats.current_pages = get_num_physpages(); #endif balloon_stats.target_pages = balloon_stats.current_pages; balloon_stats.balloon_low = 0; balloon_stats.balloon_high = 0; balloon_stats.total_pages = balloon_stats.current_pages; balloon_stats.schedule_delay = 1; balloon_stats.max_schedule_delay = 32; balloon_stats.retry_count = 1; balloon_stats.max_retry_count = RETRY_UNLIMITED; #ifdef CONFIG_XEN_BALLOON_MEMORY_HOTPLUG set_online_page_callback(&xen_online_page); register_memory_notifier(&xen_memory_nb); register_sysctl_table(xen_root); #endif #ifdef CONFIG_XEN_PV { int i; /* * Initialize the balloon with pages from the extra memory * regions (see arch/x86/xen/setup.c). */ for (i = 0; i < XEN_EXTRA_MEM_MAX_REGIONS; i++) if (xen_extra_mem[i].n_pfns) balloon_add_region(xen_extra_mem[i].start_pfn, xen_extra_mem[i].n_pfns); } #endif /* Init the xen-balloon driver. */ xen_balloon_init(); return 0; } CWE ID: CWE-400 Target: 1 Example 2: Code: void V8TestObject::LongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_longAttribute_Getter"); test_object_v8_internal::LongAttributeAttributeGetter(info); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue){ int status = 0; int16_t level; int16_t ratio; uint32_t time; t_reverb_settings *pProperties; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; if (pContext->preset) { if (param != REVERB_PARAM_PRESET) { return -EINVAL; } uint16_t preset = *(uint16_t *)pValue; ALOGV("set REVERB_PARAM_PRESET, preset %d", preset); if (preset > REVERB_PRESET_LAST) { return -EINVAL; } pContext->nextPreset = preset; return 0; } switch (param){ case REVERB_PARAM_PROPERTIES: ALOGV("\tReverb_setParameter() REVERB_PARAM_PROPERTIES"); pProperties = (t_reverb_settings *) pValue; ReverbSetRoomLevel(pContext, pProperties->roomLevel); ReverbSetRoomHfLevel(pContext, pProperties->roomHFLevel); ReverbSetDecayTime(pContext, pProperties->decayTime); ReverbSetDecayHfRatio(pContext, pProperties->decayHFRatio); ReverbSetReverbLevel(pContext, pProperties->reverbLevel); ReverbSetDiffusion(pContext, pProperties->diffusion); ReverbSetDensity(pContext, pProperties->density); break; case REVERB_PARAM_ROOM_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomLevel(pContext, level); break; case REVERB_PARAM_ROOM_HF_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomHfLevel(pContext, level); break; case REVERB_PARAM_DECAY_TIME: time = *(uint32_t *)pValue; ReverbSetDecayTime(pContext, time); break; case REVERB_PARAM_DECAY_HF_RATIO: ratio = *(int16_t *)pValue; ReverbSetDecayHfRatio(pContext, ratio); break; case REVERB_PARAM_REVERB_LEVEL: level = *(int16_t *)pValue; ReverbSetReverbLevel(pContext, level); break; case REVERB_PARAM_DIFFUSION: ratio = *(int16_t *)pValue; ReverbSetDiffusion(pContext, ratio); break; case REVERB_PARAM_DENSITY: ratio = *(int16_t *)pValue; ReverbSetDensity(pContext, ratio); break; break; case REVERB_PARAM_REFLECTIONS_LEVEL: case REVERB_PARAM_REFLECTIONS_DELAY: case REVERB_PARAM_REVERB_DELAY: break; default: ALOGV("\tLVM_ERROR : Reverb_setParameter() invalid param %d", param); break; } return status; } /* end Reverb_setParameter */ CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static noinline void key_gc_unused_keys(struct list_head *keys) { while (!list_empty(keys)) { struct key *key = list_entry(keys->next, struct key, graveyard_link); list_del(&key->graveyard_link); kdebug("- %u", key->serial); key_check(key); /* Throw away the key data */ if (key->type->destroy) key->type->destroy(key); security_key_free(key); /* deal with the user's key tracking and quota */ if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { spin_lock(&key->user->lock); key->user->qnkeys--; key->user->qnbytes -= key->quotalen; spin_unlock(&key->user->lock); } atomic_dec(&key->user->nkeys); if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) atomic_dec(&key->user->nikeys); key_user_put(key->user); kfree(key->description); #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC_X; #endif kmem_cache_free(key_jar, key); } } CWE ID: CWE-20 Target: 1 Example 2: Code: static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } 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 FindBarController::UpdateFindBarForCurrentResult() { FindManager* find_manager = tab_contents_->GetFindManager(); const FindNotificationDetails& find_result = find_manager->find_result(); if (find_result.number_of_matches() > -1) { if (last_reported_matchcount_ > 0 && find_result.number_of_matches() == 1 && !find_result.final_update()) return; // Don't let interim result override match count. last_reported_matchcount_ = find_result.number_of_matches(); } find_bar_->UpdateUIForFindResult(find_result, find_manager->find_text()); } 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: char* dexOptGenerateCacheFileName(const char* fileName, const char* subFileName) { char nameBuf[512]; char absoluteFile[sizeof(nameBuf)]; const size_t kBufLen = sizeof(nameBuf) - 1; const char* dataRoot; char* cp; /* * Get the absolute path of the Jar or DEX file. */ absoluteFile[0] = '\0'; if (fileName[0] != '/') { /* * Generate the absolute path. This doesn't do everything it * should, e.g. if filename is "./out/whatever" it doesn't crunch * the leading "./" out, but it'll do. */ if (getcwd(absoluteFile, kBufLen) == NULL) { ALOGE("Can't get CWD while opening jar file"); return NULL; } strncat(absoluteFile, "/", kBufLen); } strncat(absoluteFile, fileName, kBufLen); /* * Append the name of the Jar file entry, if any. This is not currently * required, but will be if we start putting more than one DEX file * in a Jar. */ if (subFileName != NULL) { strncat(absoluteFile, "/", kBufLen); strncat(absoluteFile, subFileName, kBufLen); } /* Turn the path into a flat filename by replacing * any slashes after the first one with '@' characters. */ cp = absoluteFile + 1; while (*cp != '\0') { if (*cp == '/') { *cp = '@'; } cp++; } /* Build the name of the cache directory. */ dataRoot = getenv("ANDROID_DATA"); if (dataRoot == NULL) dataRoot = "/data"; snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCacheDirectoryName); if (strcmp(dataRoot, "/data") != 0) { int result = dexOptMkdir(nameBuf, 0700); if (result != 0 && errno != EEXIST) { ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno)); return NULL; } } snprintf(nameBuf, kBufLen, "%s/%s/%s", dataRoot, kCacheDirectoryName, kInstructionSet); if (strcmp(dataRoot, "/data") != 0) { int result = dexOptMkdir(nameBuf, 0700); if (result != 0 && errno != EEXIST) { ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno)); return NULL; } } /* Tack on the file name for the actual cache file path. */ strncat(nameBuf, absoluteFile, kBufLen); ALOGV("Cache file for '%s' '%s' is '%s'", fileName, subFileName, nameBuf); return strdup(nameBuf); } CWE ID: CWE-119 Target: 1 Example 2: Code: int skb_copy_and_csum_datagram_iovec(struct sk_buff *skb, int hlen, struct iovec *iov) { __wsum csum; int chunk = skb->len - hlen; if (!chunk) return 0; /* Skip filled elements. * Pretty silly, look at memcpy_toiovec, though 8) */ while (!iov->iov_len) iov++; if (iov->iov_len < chunk) { if (__skb_checksum_complete(skb)) goto csum_error; if (skb_copy_datagram_iovec(skb, hlen, iov, chunk)) goto fault; } else { csum = csum_partial(skb->data, hlen, skb->csum); if (skb_copy_and_csum_datagram(skb, hlen, iov->iov_base, chunk, &csum)) goto fault; if (csum_fold(csum)) goto csum_error; if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE)) netdev_rx_csum_fault(skb->dev); iov->iov_len -= chunk; iov->iov_base += chunk; } return 0; csum_error: return -EINVAL; fault: return -EFAULT; } 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 Browser::OpenURLFromTab(TabContents* source, const GURL& url, const GURL& referrer, WindowOpenDisposition disposition, PageTransition::Type transition) { browser::NavigateParams params(this, url, transition); params.source_contents = tabstrip_model()->GetTabContentsAt( tabstrip_model()->GetWrapperIndex(source)); params.referrer = referrer; params.disposition = disposition; params.tabstrip_add_types = TabStripModel::ADD_NONE; params.show_window = true; browser::Navigate(&params); } 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: PlatformSensorAmbientLightMac::PlatformSensorAmbientLightMac( mojo::ScopedSharedBufferMapping mapping, PlatformSensorProvider* provider) : PlatformSensor(SensorType::AMBIENT_LIGHT, std::move(mapping), provider), light_sensor_port_(nullptr), current_lux_(0.0) {} CWE ID: CWE-732 Target: 1 Example 2: Code: HTMLFormElement::HTMLFormElement(Document& document) : HTMLElement(formTag, document), listed_elements_are_dirty_(false), image_elements_are_dirty_(false), has_elements_associated_by_parser_(false), has_elements_associated_by_form_attribute_(false), did_finish_parsing_children_(false), is_in_reset_function_(false), was_demoted_(false) {} CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gst_asf_demux_process_bitrate_props_object (GstASFDemux * demux, guint8 * data, guint64 size) { guint16 num_streams, i; AsfStream *stream; if (size < 2) goto not_enough_data; num_streams = gst_asf_demux_get_uint16 (&data, &size); GST_INFO ("object is a bitrate properties object with %u streams", num_streams); if (size < (num_streams * (2 + 4))) goto not_enough_data; for (i = 0; i < num_streams; ++i) { guint32 bitrate; guint16 stream_id; stream_id = gst_asf_demux_get_uint16 (&data, &size); bitrate = gst_asf_demux_get_uint32 (&data, &size); if (stream_id < GST_ASF_DEMUX_NUM_STREAM_IDS) { GST_DEBUG_OBJECT (demux, "bitrate of stream %u = %u", stream_id, bitrate); stream = gst_asf_demux_get_stream (demux, stream_id); if (stream) { if (stream->pending_tags == NULL) stream->pending_tags = gst_tag_list_new_empty (); gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE, bitrate, NULL); } else { GST_WARNING_OBJECT (demux, "Stream id %u wasn't found", stream_id); } } else { GST_WARNING ("stream id %u is too large", stream_id); } } return GST_FLOW_OK; not_enough_data: { GST_WARNING_OBJECT (demux, "short read parsing bitrate props object!"); return GST_FLOW_OK; /* not really fatal */ } } CWE ID: CWE-125 Output:
0