prompt
stringlengths
799
20.4k
output
int64
0
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int cp2112_gpio_direction_output(struct gpio_chip *chip, unsigned offset, int value) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; unsigned long flags; int ret; spin_lock_irqsave(&dev->lock, flags); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto fail; } buf[1] |= 1 << offset; buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto fail; } spin_unlock_irqrestore(&dev->lock, flags); /* * Set gpio value when output direction is already set, * as specified in AN495, Rev. 0.2, cpt. 4.4 */ cp2112_gpio_set(chip, offset, value); return 0; fail: spin_unlock_irqrestore(&dev->lock, flags); return ret < 0 ? ret : -EIO; } CWE ID: CWE-404 Target: 1 Example 2: Code: int mlx5_ib_post_send(struct ib_qp *ibqp, const struct ib_send_wr *wr, const struct ib_send_wr **bad_wr) { return _mlx5_ib_post_send(ibqp, wr, bad_wr, false); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BrowserView::ShowAvatarBubbleFromAvatarButton() { AvatarMenuButton* button = frame_->GetAvatarMenuButton(); if (button) button->ShowAvatarBubble(); } 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 ihevcd_parse_sei_payload(codec_t *ps_codec, UWORD32 u4_payload_type, UWORD32 u4_payload_size, WORD8 i1_nal_type) { parse_ctxt_t *ps_parse = &ps_codec->s_parse; bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm; WORD32 payload_bits_remaining = 0; sps_t *ps_sps; UWORD32 i; for(i = 0; i < MAX_SPS_CNT; i++) { ps_sps = ps_codec->ps_sps_base + i; if(ps_sps->i1_sps_valid) { break; } } if(NULL == ps_sps) { return; } if(NAL_PREFIX_SEI == i1_nal_type) { switch(u4_payload_type) { case SEI_BUFFERING_PERIOD: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_buffering_period_sei(ps_codec, ps_sps); break; case SEI_PICTURE_TIMING: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_pic_timing_sei(ps_codec, ps_sps); break; case SEI_TIME_CODE: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_time_code_sei(ps_codec); break; case SEI_MASTERING_DISPLAY_COLOUR_VOLUME: ps_parse->s_sei_params.i4_sei_mastering_disp_colour_vol_params_present_flags = 1; ihevcd_parse_mastering_disp_params_sei(ps_codec); break; case SEI_USER_DATA_REGISTERED_ITU_T_T35: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_user_data_registered_itu_t_t35(ps_codec, u4_payload_size); break; default: for(i = 0; i < u4_payload_size; i++) { ihevcd_bits_flush(ps_bitstrm, 8); } break; } } else /* NAL_SUFFIX_SEI */ { switch(u4_payload_type) { case SEI_USER_DATA_REGISTERED_ITU_T_T35: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_user_data_registered_itu_t_t35(ps_codec, u4_payload_size); break; default: for(i = 0; i < u4_payload_size; i++) { ihevcd_bits_flush(ps_bitstrm, 8); } break; } } /** * By definition the underlying bitstream terminates in a byte-aligned manner. * 1. Extract all bar the last MIN(bitsremaining,nine) bits as reserved_payload_extension_data * 2. Examine the final 8 bits to determine the payload_bit_equal_to_one marker * 3. Extract the remainingreserved_payload_extension_data bits. * * If there are fewer than 9 bits available, extract them. */ payload_bits_remaining = ihevcd_bits_num_bits_remaining(ps_bitstrm); if(payload_bits_remaining) /* more_data_in_payload() */ { WORD32 final_bits; WORD32 final_payload_bits = 0; WORD32 mask = 0xFF; UWORD32 u4_dummy; UWORD32 u4_reserved_payload_extension_data; UNUSED(u4_dummy); UNUSED(u4_reserved_payload_extension_data); while(payload_bits_remaining > 9) { BITS_PARSE("reserved_payload_extension_data", u4_reserved_payload_extension_data, ps_bitstrm, 1); payload_bits_remaining--; } final_bits = ihevcd_bits_nxt(ps_bitstrm, payload_bits_remaining); while(final_bits & (mask >> final_payload_bits)) { final_payload_bits++; continue; } while(payload_bits_remaining > (9 - final_payload_bits)) { BITS_PARSE("reserved_payload_extension_data", u4_reserved_payload_extension_data, ps_bitstrm, 1); payload_bits_remaining--; } BITS_PARSE("payload_bit_equal_to_one", u4_dummy, ps_bitstrm, 1); payload_bits_remaining--; while(payload_bits_remaining) { BITS_PARSE("payload_bit_equal_to_zero", u4_dummy, ps_bitstrm, 1); payload_bits_remaining--; } } return; } CWE ID: CWE-190 Target: 1 Example 2: Code: struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev) { struct sk_buff *next, *head = NULL, *tail; for (; skb != NULL; skb = next) { next = skb->next; skb->next = NULL; /* in case skb wont be segmented, point to itself */ skb->prev = skb; skb = validate_xmit_skb(skb, dev); if (!skb) continue; if (!head) head = skb; else tail->next = skb; /* If skb was segmented, skb->prev points to * the last segment. If not, it still contains skb. */ tail = skb->prev; } return head; } CWE ID: CWE-400 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual status_t allocateBuffer( node_id node, OMX_U32 port_index, size_t size, buffer_id *buffer, void **buffer_data) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeInt32(port_index); data.writeInt64(size); remote()->transact(ALLOC_BUFFER, data, &reply); status_t err = reply.readInt32(); if (err != OK) { *buffer = 0; return err; } *buffer = (buffer_id)reply.readInt32(); *buffer_data = (void *)reply.readInt64(); return err; } 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: NotificationsNativeHandler::NotificationsNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetNotificationImageSizes", base::Bind(&NotificationsNativeHandler::GetNotificationImageSizes, base::Unretained(this))); } CWE ID: Target: 1 Example 2: Code: xmlAttrNormalizeSpace(const xmlChar *src, xmlChar *dst) { if ((src == NULL) || (dst == NULL)) return(NULL); while (*src == 0x20) src++; while (*src != 0) { if (*src == 0x20) { while (*src == 0x20) src++; if (*src != 0) *dst++ = 0x20; } else { *dst++ = *src++; } } *dst = 0; if (dst == src) return(NULL); return(dst); } CWE ID: CWE-611 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int dwc3_gadget_set_xfer_resource(struct dwc3 *dwc, struct dwc3_ep *dep) { struct dwc3_gadget_ep_cmd_params params; memset(&params, 0x00, sizeof(params)); params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1); return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE, &params); } 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: status_t NuPlayer::GenericSource::initFromDataSource() { sp<MediaExtractor> extractor; String8 mimeType; float confidence; sp<AMessage> dummy; bool isWidevineStreaming = false; CHECK(mDataSource != NULL); if (mIsWidevine) { isWidevineStreaming = SniffWVM( mDataSource, &mimeType, &confidence, &dummy); if (!isWidevineStreaming || strcasecmp( mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM)) { ALOGE("unsupported widevine mime: %s", mimeType.string()); return UNKNOWN_ERROR; } } else if (mIsStreaming) { if (!mDataSource->sniff(&mimeType, &confidence, &dummy)) { return UNKNOWN_ERROR; } isWidevineStreaming = !strcasecmp( mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM); } if (isWidevineStreaming) { mCachedSource.clear(); mDataSource = mHttpSource; mWVMExtractor = new WVMExtractor(mDataSource); mWVMExtractor->setAdaptiveStreamingMode(true); if (mUIDValid) { mWVMExtractor->setUID(mUID); } extractor = mWVMExtractor; } else { extractor = MediaExtractor::Create(mDataSource, mimeType.isEmpty() ? NULL : mimeType.string()); } if (extractor == NULL) { return UNKNOWN_ERROR; } if (extractor->getDrmFlag()) { checkDrmStatus(mDataSource); } mFileMeta = extractor->getMetaData(); if (mFileMeta != NULL) { int64_t duration; if (mFileMeta->findInt64(kKeyDuration, &duration)) { mDurationUs = duration; } if (!mIsWidevine) { const char *fileMime; if (mFileMeta->findCString(kKeyMIMEType, &fileMime) && !strncasecmp(fileMime, "video/wvm", 9)) { mIsWidevine = true; } } } int32_t totalBitrate = 0; size_t numtracks = extractor->countTracks(); if (numtracks == 0) { return UNKNOWN_ERROR; } for (size_t i = 0; i < numtracks; ++i) { sp<MediaSource> track = extractor->getTrack(i); sp<MetaData> meta = extractor->getTrackMetaData(i); const char *mime; CHECK(meta->findCString(kKeyMIMEType, &mime)); if (!strncasecmp(mime, "audio/", 6)) { if (mAudioTrack.mSource == NULL) { mAudioTrack.mIndex = i; mAudioTrack.mSource = track; mAudioTrack.mPackets = new AnotherPacketSource(mAudioTrack.mSource->getFormat()); if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) { mAudioIsVorbis = true; } else { mAudioIsVorbis = false; } } } else if (!strncasecmp(mime, "video/", 6)) { if (mVideoTrack.mSource == NULL) { mVideoTrack.mIndex = i; mVideoTrack.mSource = track; mVideoTrack.mPackets = new AnotherPacketSource(mVideoTrack.mSource->getFormat()); int32_t secure; if (meta->findInt32(kKeyRequiresSecureBuffers, &secure) && secure) { mIsSecure = true; if (mUIDValid) { extractor->setUID(mUID); } } } } if (track != NULL) { mSources.push(track); int64_t durationUs; if (meta->findInt64(kKeyDuration, &durationUs)) { if (durationUs > mDurationUs) { mDurationUs = durationUs; } } int32_t bitrate; if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) { totalBitrate += bitrate; } else { totalBitrate = -1; } } } mBitrate = totalBitrate; return OK; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int init_hyp_mode(void) { int cpu; int err = 0; /* * Allocate Hyp PGD and setup Hyp identity mapping */ err = kvm_mmu_init(); if (err) goto out_err; /* * It is probably enough to obtain the default on one * CPU. It's unlikely to be different on the others. */ hyp_default_vectors = __hyp_get_vectors(); /* * Allocate stack pages for Hypervisor-mode */ for_each_possible_cpu(cpu) { unsigned long stack_page; stack_page = __get_free_page(GFP_KERNEL); if (!stack_page) { err = -ENOMEM; goto out_free_stack_pages; } per_cpu(kvm_arm_hyp_stack_page, cpu) = stack_page; } /* * Map the Hyp-code called directly from the host */ err = create_hyp_mappings(__kvm_hyp_code_start, __kvm_hyp_code_end); if (err) { kvm_err("Cannot map world-switch code\n"); goto out_free_mappings; } /* * Map the Hyp stack pages */ for_each_possible_cpu(cpu) { char *stack_page = (char *)per_cpu(kvm_arm_hyp_stack_page, cpu); err = create_hyp_mappings(stack_page, stack_page + PAGE_SIZE); if (err) { kvm_err("Cannot map hyp stack\n"); goto out_free_mappings; } } /* * Map the host CPU structures */ kvm_host_cpu_state = alloc_percpu(kvm_cpu_context_t); if (!kvm_host_cpu_state) { err = -ENOMEM; kvm_err("Cannot allocate host CPU state\n"); goto out_free_mappings; } for_each_possible_cpu(cpu) { kvm_cpu_context_t *cpu_ctxt; cpu_ctxt = per_cpu_ptr(kvm_host_cpu_state, cpu); err = create_hyp_mappings(cpu_ctxt, cpu_ctxt + 1); if (err) { kvm_err("Cannot map host CPU state: %d\n", err); goto out_free_context; } } /* * Execute the init code on each CPU. */ on_each_cpu(cpu_init_hyp_mode, NULL, 1); /* * Init HYP view of VGIC */ err = kvm_vgic_hyp_init(); if (err) goto out_free_context; #ifdef CONFIG_KVM_ARM_VGIC vgic_present = true; #endif /* * Init HYP architected timer support */ err = kvm_timer_hyp_init(); if (err) goto out_free_mappings; #ifndef CONFIG_HOTPLUG_CPU free_boot_hyp_pgd(); #endif kvm_perf_init(); kvm_info("Hyp mode initialized successfully\n"); return 0; out_free_context: free_percpu(kvm_host_cpu_state); out_free_mappings: free_hyp_pgds(); out_free_stack_pages: for_each_possible_cpu(cpu) free_page(per_cpu(kvm_arm_hyp_stack_page, cpu)); out_err: kvm_err("error initializing Hyp mode: %d\n", err); return err; } 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 TransitionElementsKindImpl(Handle<JSObject> object, Handle<Map> to_map) { Handle<Map> from_map = handle(object->map()); ElementsKind from_kind = from_map->elements_kind(); ElementsKind to_kind = to_map->elements_kind(); if (IsFastHoleyElementsKind(from_kind)) { to_kind = GetHoleyElementsKind(to_kind); } if (from_kind != to_kind) { DCHECK(IsFastElementsKind(from_kind)); DCHECK(IsFastElementsKind(to_kind)); DCHECK_NE(TERMINAL_FAST_ELEMENTS_KIND, from_kind); Handle<FixedArrayBase> from_elements(object->elements()); if (object->elements() == object->GetHeap()->empty_fixed_array() || IsFastDoubleElementsKind(from_kind) == IsFastDoubleElementsKind(to_kind)) { JSObject::MigrateToMap(object, to_map); } else { DCHECK((IsFastSmiElementsKind(from_kind) && IsFastDoubleElementsKind(to_kind)) || (IsFastDoubleElementsKind(from_kind) && IsFastObjectElementsKind(to_kind))); uint32_t capacity = static_cast<uint32_t>(object->elements()->length()); Handle<FixedArrayBase> elements = ConvertElementsWithCapacity( object, from_elements, from_kind, capacity); JSObject::SetMapAndElements(object, to_map, elements); } if (FLAG_trace_elements_transitions) { JSObject::PrintElementsTransition(stdout, object, from_kind, from_elements, to_kind, handle(object->elements())); } } } CWE ID: CWE-704 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: json_t *json_object(void) { json_object_t *object = jsonp_malloc(sizeof(json_object_t)); if(!object) return NULL; json_init(&object->json, JSON_OBJECT); if(hashtable_init(&object->hashtable)) { jsonp_free(object); return NULL; } object->serial = 0; object->visited = 0; return &object->json; } CWE ID: CWE-310 Target: 1 Example 2: Code: gx_dc_binary_masked_get_dev_halftone(const gx_device_color * pdevc) { return pdevc->colors.binary.b_ht; } 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: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; zend_bool old_allow_url_fopen; /* xmlInitParser(); */ old_allow_url_fopen = PG(allow_url_fopen); PG(allow_url_fopen) = 1; ctxt = xmlCreateFileParserCtxt(filename); PG(allow_url_fopen) = old_allow_url_fopen; if (ctxt) { ctxt->keepBlanks = 0; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; /*ctxt->sax->fatalError = NULL;*/ xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ if (ret) { cleanup_xml_node((xmlNodePtr)ret); } return ret; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files, rpmpsm psm, int nodigest, int *setmeta, int * firsthardlink) { int rc = 0; int numHardlinks = rpmfiFNlink(fi); if (numHardlinks > 1) { /* Create first hardlinked file empty */ if (*firsthardlink < 0) { *firsthardlink = rpmfiFX(fi); rc = expandRegular(fi, dest, psm, nodigest, 1); } else { /* Create hard links for others */ char *fn = rpmfilesFN(files, *firsthardlink); rc = link(fn, dest); if (rc < 0) { rc = RPMERR_LINK_FAILED; } free(fn); } } /* Write normal files or fill the last hardlinked (already existing) file with content */ if (numHardlinks<=1) { if (!rc) rc = expandRegular(fi, dest, psm, nodigest, 0); } else if (rpmfiArchiveHasContent(fi)) { if (!rc) rc = expandRegular(fi, dest, psm, nodigest, 0); *firsthardlink = -1; } else { *setmeta = 0; } return rc; } CWE ID: CWE-59 Target: 1 Example 2: Code: void RenderFrameImpl::DownloadURL( const blink::WebURLRequest& request, CrossOriginRedirects cross_origin_redirect_behavior, mojo::ScopedMessagePipeHandle blob_url_token) { if (ShouldThrottleDownload()) return; FrameHostMsg_DownloadUrl_Params params; params.render_view_id = render_view_->GetRoutingID(); params.render_frame_id = GetRoutingID(); params.url = request.Url(); params.referrer = RenderViewImpl::GetReferrerFromRequest(frame_, request); params.initiator_origin = request.RequestorOrigin(); if (request.GetSuggestedFilename().has_value()) params.suggested_name = request.GetSuggestedFilename()->Utf16(); params.follow_cross_origin_redirects = (cross_origin_redirect_behavior == CrossOriginRedirects::kFollow); params.blob_url_token = blob_url_token.release(); Send(new FrameHostMsg_DownloadUrl(params)); } 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 perf_try_init_event(struct pmu *pmu, struct perf_event *event) { struct perf_event_context *ctx = NULL; int ret; if (!try_module_get(pmu->module)) return -ENODEV; if (event->group_leader != event) { /* * This ctx->mutex can nest when we're called through * inheritance. See the perf_event_ctx_lock_nested() comment. */ ctx = perf_event_ctx_lock_nested(event->group_leader, SINGLE_DEPTH_NESTING); BUG_ON(!ctx); } event->pmu = pmu; ret = pmu->event_init(event); if (ctx) perf_event_ctx_unlock(event->group_leader, ctx); if (ret) module_put(pmu->module); return ret; } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t i, maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, (const void *) ((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE2(si->si_count); *count = 0; maxcount = 0; *info = NULL; for (i = 0; i < CDF_TOLE4(si->si_count); i++) { if (i >= CDF_LOOP_LIMIT) { DPRINTF(("Unpack summary info loop limit")); errno = EFTYPE; return -1; } if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) { return -1; } } return 0; } CWE ID: CWE-399 Target: 1 Example 2: Code: static void fill_zero(struct inode *inode, pgoff_t index, loff_t start, loff_t len) { struct f2fs_sb_info *sbi = F2FS_SB(inode->i_sb); struct page *page; if (!len) return; f2fs_balance_fs(sbi); f2fs_lock_op(sbi); page = get_new_data_page(inode, NULL, index, false); f2fs_unlock_op(sbi); if (!IS_ERR(page)) { f2fs_wait_on_page_writeback(page, DATA); zero_user(page, start, len); set_page_dirty(page); f2fs_put_page(page, 1); } } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id, const struct match *match, int priority, ovs_version_t version, ovs_be64 cookie, ovs_be64 cookie_mask, ofp_port_t out_port, uint32_t out_group) { criteria->table_id = table_id; cls_rule_init(&criteria->cr, match, priority); criteria->version = version; criteria->cookie = cookie; criteria->cookie_mask = cookie_mask; criteria->out_port = out_port; criteria->out_group = out_group; /* We ordinarily want to skip hidden rules, but there has to be a way for * code internal to OVS to modify and delete them, so if the criteria * specify a priority that can only be for a hidden flow, then allow hidden * rules to be selected. (This doesn't allow OpenFlow clients to meddle * with hidden flows because OpenFlow uses only a 16-bit field to specify * priority.) */ criteria->include_hidden = priority > UINT16_MAX; /* We assume that the criteria are being used to collect flows for reading * but not modification. Thus, we should collect read-only flows. */ criteria->include_readonly = true; } CWE ID: CWE-617 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline int may_ptrace_stop(void) { if (!likely(current->ptrace)) return 0; /* * Are we in the middle of do_coredump? * If so and our tracer is also part of the coredump stopping * is a deadlock situation, and pointless because our tracer * is dead so don't allow us to stop. * If SIGKILL was already sent before the caller unlocked * ->siglock we must see ->core_state != NULL. Otherwise it * is safe to enter schedule(). */ if (unlikely(current->mm->core_state) && unlikely(current->mm == current->parent->mm)) return 0; return 1; } CWE ID: CWE-362 Target: 1 Example 2: Code: void Browser::FindNext() { UserMetrics::RecordAction(UserMetricsAction("FindNext")); FindInPage(true, true); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int br_parse_ip_options(struct sk_buff *skb) { struct ip_options *opt; struct iphdr *iph; struct net_device *dev = skb->dev; u32 len; iph = ip_hdr(skb); opt = &(IPCB(skb)->opt); /* Basic sanity checks */ if (iph->ihl < 5 || iph->version != 4) goto inhdr_error; if (!pskb_may_pull(skb, iph->ihl*4)) goto inhdr_error; iph = ip_hdr(skb); if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl))) goto inhdr_error; len = ntohs(iph->tot_len); if (skb->len < len) { IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INTRUNCATEDPKTS); goto drop; } else if (len < (iph->ihl*4)) goto inhdr_error; if (pskb_trim_rcsum(skb, len)) { IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INDISCARDS); goto drop; } /* Zero out the CB buffer if no options present */ if (iph->ihl == 5) { memset(IPCB(skb), 0, sizeof(struct inet_skb_parm)); return 0; } opt->optlen = iph->ihl*4 - sizeof(struct iphdr); if (ip_options_compile(dev_net(dev), opt, skb)) goto inhdr_error; /* Check correct handling of SRR option */ if (unlikely(opt->srr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); if (in_dev && !IN_DEV_SOURCE_ROUTE(in_dev)) goto drop; if (ip_options_rcv_srr(skb)) goto drop; } return 0; inhdr_error: IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INHDRERRORS); drop: return -1; } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int decompress_i(AVCodecContext *avctx, uint32_t *dst, int linesize) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; int cx = 0, cx1 = 0, k = 0, clr = 0; int run, r, g, b, off, y = 0, x = 0, z, ret; unsigned backstep = linesize - avctx->width; const int cxshift = s->cxshift; unsigned lx, ly, ptype; reinit_tables(s); bytestream2_skip(gb, 2); init_rangecoder(&s->rc, gb); while (k < avctx->width + 1) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = b >> cxshift; ret = decode_value(s, s->run_model[0], 256, 400, &run); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; k += run; while (run-- > 0) { dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } } off = -linesize - 1; ptype = 0; while (x < avctx->width && y < avctx->height) { ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype); if (ret < 0) return ret; if (ptype == 0) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; } if (ptype > 5) return AVERROR_INVALIDDATA; ret = decode_value(s, s->run_model[ptype], 256, 400, &run); if (ret < 0) return ret; switch (ptype) { case 0: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 1: while (run-- > 0) { if (y >= avctx->height) return AVERROR_INVALIDDATA; dst[y * linesize + x] = dst[ly * linesize + lx]; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } clr = dst[ly * linesize + lx]; break; case 2: while (run-- > 0) { if (y < 1 || y >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[y * linesize + x + off + 1]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 4: while (run-- > 0) { uint8_t *odst = (uint8_t *)dst; if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } r = odst[(ly * linesize + lx) * 4] + odst[((y * linesize + x) + off - z) * 4 + 4] - odst[((y * linesize + x) + off - z) * 4]; g = odst[(ly * linesize + lx) * 4 + 1] + odst[((y * linesize + x) + off - z) * 4 + 5] - odst[((y * linesize + x) + off - z) * 4 + 1]; b = odst[(ly * linesize + lx) * 4 + 2] + odst[((y * linesize + x) + off - z) * 4 + 6] - odst[((y * linesize + x) + off - z) * 4 + 2]; clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF); dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; case 5: while (run-- > 0) { if (y < 1 || y >= avctx->height || (y == 1 && x == 0)) return AVERROR_INVALIDDATA; if (x == 0) { z = backstep; } else { z = 0; } clr = dst[y * linesize + x + off - z]; dst[y * linesize + x] = clr; lx = x; ly = y; x++; if (x >= avctx->width) { x = 0; y++; } } break; } if (avctx->bits_per_coded_sample == 16) { cx1 = (clr & 0x3F00) >> 2; cx = (clr & 0xFFFFFF) >> 16; } else { cx1 = (clr & 0xFC00) >> 4; cx = (clr & 0xFFFFFF) >> 18; } } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void activityLoggingGetterPerWorldBindingsLongAttributeAttributeSetterCallbackForMainWorld(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); TestObjectPythonV8Internal::activityLoggingGetterPerWorldBindingsLongAttributeAttributeSetterForMainWorld(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int au1100fb_fb_setcolreg(unsigned regno, unsigned red, unsigned green, unsigned blue, unsigned transp, struct fb_info *fbi) { struct au1100fb_device *fbdev; u32 *palette; u32 value; fbdev = to_au1100fb_device(fbi); palette = fbdev->regs->lcd_pallettebase; if (regno > (AU1100_LCD_NBR_PALETTE_ENTRIES - 1)) return -EINVAL; if (fbi->var.grayscale) { /* Convert color to grayscale */ red = green = blue = (19595 * red + 38470 * green + 7471 * blue) >> 16; } if (fbi->fix.visual == FB_VISUAL_TRUECOLOR) { /* Place color in the pseudopalette */ if (regno > 16) return -EINVAL; palette = (u32*)fbi->pseudo_palette; red >>= (16 - fbi->var.red.length); green >>= (16 - fbi->var.green.length); blue >>= (16 - fbi->var.blue.length); value = (red << fbi->var.red.offset) | (green << fbi->var.green.offset)| (blue << fbi->var.blue.offset); value &= 0xFFFF; } else if (panel_is_active(fbdev->panel)) { /* COLOR TFT PALLETTIZED (use RGB 565) */ value = (red & 0xF800)|((green >> 5) & 0x07E0)|((blue >> 11) & 0x001F); value &= 0xFFFF; } else if (panel_is_color(fbdev->panel)) { /* COLOR STN MODE */ value = (((panel_swap_rgb(fbdev->panel) ? blue : red) >> 12) & 0x000F) | ((green >> 8) & 0x00F0) | (((panel_swap_rgb(fbdev->panel) ? red : blue) >> 4) & 0x0F00); value &= 0xFFF; } else { /* MONOCHROME MODE */ value = (green >> 12) & 0x000F; value &= 0xF; } palette[regno] = value; return 0; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t OMXNodeInstance::sendCommand( OMX_COMMANDTYPE cmd, OMX_S32 param) { const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && cmd == OMX_CommandStateSet) { if (param == OMX_StateIdle) { bufferSource->omxIdle(); } else if (param == OMX_StateLoaded) { bufferSource->omxLoaded(); setGraphicBufferSource(NULL); } } Mutex::Autolock autoLock(mLock); { Mutex::Autolock _l(mDebugLock); bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */); } const char *paramString = cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param); CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL); CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); return StatusFromOMXError(err); } CWE ID: CWE-200 Target: 1 Example 2: Code: DEFINE_TRACE(VRDisplay) { EventTargetWithInlineData::Trace(visitor); ContextLifecycleObserver::Trace(visitor); visitor->Trace(navigator_vr_); visitor->Trace(capabilities_); visitor->Trace(stage_parameters_); visitor->Trace(eye_parameters_left_); visitor->Trace(eye_parameters_right_); visitor->Trace(layer_); visitor->Trace(rendering_context_); visitor->Trace(scripted_animation_controller_); visitor->Trace(pending_present_resolvers_); } 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 do_monotonic_boot(s64 *t, cycle_t *cycle_now) { struct pvclock_gtod_data *gtod = &pvclock_gtod_data; unsigned long seq; int mode; u64 ns; do { seq = read_seqcount_begin(&gtod->seq); mode = gtod->clock.vclock_mode; ns = gtod->nsec_base; ns += vgettsc(cycle_now); ns >>= gtod->clock.shift; ns += gtod->boot_ns; } while (unlikely(read_seqcount_retry(&gtod->seq, seq))); *t = ns; return mode; } 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: OMX_ERRORTYPE omx_video::use_output_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes, OMX_IN OMX_U8* buffer) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header unsigned i= 0; // Temporary counter unsigned char *buf_addr = NULL; #ifdef _MSM8974_ int align_size; #endif DEBUG_PRINT_HIGH("Inside use_output_buffer()"); if (bytes != m_sOutPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: use_output_buffer: Size Mismatch!! " "bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sOutPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_out_mem_ptr) { output_use_buffer = true; int nBufHdrSize = 0; DEBUG_PRINT_LOW("Allocating First Output Buffer(%u)",(unsigned int)m_sOutPortDef.nBufferCountActual); nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE); /* * Memory for output side involves the following: * 1. Array of Buffer Headers * 2. Bitmask array to hold the buffer allocation details * In order to minimize the memory management entire allocation * is done in one step. */ m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1); if (m_out_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_out_mem_ptr"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sOutPortDef.nBufferCountActual); if (m_pOutput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual); if (m_pOutput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion"); return OMX_ErrorInsufficientResources; } #endif if (m_out_mem_ptr) { bufHdr = m_out_mem_ptr; DEBUG_PRINT_LOW("Memory Allocation Succeeded for OUT port%p",m_out_mem_ptr); for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) { bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE); bufHdr->nVersion.nVersion = OMX_SPEC_VERSION; bufHdr->nAllocLen = bytes; bufHdr->nFilledLen = 0; bufHdr->pAppPrivate = appData; bufHdr->nOutputPortIndex = PORT_INDEX_OUT; bufHdr->pBuffer = NULL; bufHdr++; m_pOutput_pmem[i].fd = -1; #ifdef USE_ION m_pOutput_ion[i].ion_device_fd =-1; m_pOutput_ion[i].fd_ion_data.fd=-1; m_pOutput_ion[i].ion_alloc_data.handle = 0; #endif } } else { DEBUG_PRINT_ERROR("ERROR: Output buf mem alloc failed[0x%p]",m_out_mem_ptr); eRet = OMX_ErrorInsufficientResources; } } for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_out_bm_count,i)) { break; } } if (eRet == OMX_ErrorNone) { if (i < m_sOutPortDef.nBufferCountActual) { *bufferHdr = (m_out_mem_ptr + i ); (*bufferHdr)->pBuffer = (OMX_U8 *)buffer; (*bufferHdr)->pAppPrivate = appData; BITMASK_SET(&m_out_bm_count,i); if (!m_use_output_pmem) { #ifdef USE_ION #ifdef _MSM8974_ align_size = (m_sOutPortDef.nBufferSize + (SZ_4K - 1)) & ~(SZ_4K - 1); m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,0); #else m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory( m_sOutPortDef.nBufferSize, &m_pOutput_ion[i].ion_alloc_data, &m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pOutput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd; #else m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pOutput_pmem[i].fd == 0) { m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pOutput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].offset = 0; m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { #ifdef _MSM8974_ m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, align_size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #else m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pOutput_pmem[i].fd,0); #endif if (m_pOutput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap() Failed"); close(m_pOutput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pOutput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } } else { OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO*>((*bufferHdr)->pAppPrivate); DEBUG_PRINT_LOW("Inside qcom_ext pParam: %p", pParam); if (pParam) { DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (int)pParam->offset); m_pOutput_pmem[i].fd = pParam->pmem_fd; m_pOutput_pmem[i].offset = pParam->offset; m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; m_pOutput_pmem[i].buffer = (unsigned char *)buffer; } else { DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM o/p UseBuffer case"); return OMX_ErrorBadParameter; } buf_addr = (unsigned char *)buffer; } DEBUG_PRINT_LOW("use_out:: bufhdr = %p, pBuffer = %p, m_pOutput_pmem[i].buffer = %p", (*bufferHdr), (*bufferHdr)->pBuffer, m_pOutput_pmem[i].buffer); if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf Failed for o/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All o/p Buffers have been Used, invalid use_buf call for " "index = %u", i); eRet = OMX_ErrorInsufficientResources; } } return eRet; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc, struct packet_sock *po) { struct tpacket_block_desc *pbd; smp_rmb(); /* 1. Get current block num */ pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc); /* 2. If this block is currently in_use then freeze the queue */ if (TP_STATUS_USER & BLOCK_STATUS(pbd)) { prb_freeze_queue(pkc, po); return NULL; } /* * 3. * open this block and return the offset where the first packet * needs to get stored. */ prb_open_block(pkc, pbd); return (void *)pkc->nxt_offset; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int nl80211_dump_wiphy(struct sk_buff *skb, struct netlink_callback *cb) { int idx = 0; int start = cb->args[0]; struct cfg80211_registered_device *dev; mutex_lock(&cfg80211_mutex); list_for_each_entry(dev, &cfg80211_rdev_list, list) { if (!net_eq(wiphy_net(&dev->wiphy), sock_net(skb->sk))) continue; if (++idx <= start) continue; if (nl80211_send_wiphy(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, NLM_F_MULTI, dev) < 0) { idx--; break; } } mutex_unlock(&cfg80211_mutex); cb->args[0] = idx; return skb->len; } 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 prepend_path(const struct path *path, const struct path *root, char **buffer, int *buflen) { struct dentry *dentry; struct vfsmount *vfsmnt; struct mount *mnt; int error = 0; unsigned seq, m_seq = 0; char *bptr; int blen; rcu_read_lock(); restart_mnt: read_seqbegin_or_lock(&mount_lock, &m_seq); seq = 0; rcu_read_lock(); restart: bptr = *buffer; blen = *buflen; error = 0; dentry = path->dentry; vfsmnt = path->mnt; mnt = real_mount(vfsmnt); read_seqbegin_or_lock(&rename_lock, &seq); while (dentry != root->dentry || vfsmnt != root->mnt) { struct dentry * parent; if (dentry == vfsmnt->mnt_root || IS_ROOT(dentry)) { struct mount *parent = ACCESS_ONCE(mnt->mnt_parent); /* Global root? */ if (mnt != parent) { dentry = ACCESS_ONCE(mnt->mnt_mountpoint); mnt = parent; vfsmnt = &mnt->mnt; continue; } if (!error) error = is_mounted(vfsmnt) ? 1 : 2; break; } parent = dentry->d_parent; prefetch(parent); error = prepend_name(&bptr, &blen, &dentry->d_name); if (error) break; dentry = parent; } if (!(seq & 1)) rcu_read_unlock(); if (need_seqretry(&rename_lock, seq)) { seq = 1; goto restart; } done_seqretry(&rename_lock, seq); if (!(m_seq & 1)) rcu_read_unlock(); if (need_seqretry(&mount_lock, m_seq)) { m_seq = 1; goto restart_mnt; } done_seqretry(&mount_lock, m_seq); if (error >= 0 && bptr == *buffer) { if (--blen < 0) error = -ENAMETOOLONG; else *--bptr = '/'; } *buffer = bptr; *buflen = blen; return error; } CWE ID: CWE-254 Target: 1 Example 2: Code: bool ContentSecurityPolicy::AllowFormAction( const KURL& url, RedirectStatus redirect_status, SecurityViolationReportingPolicy reporting_policy, CheckHeaderType check_header_type) const { if (ShouldBypassContentSecurityPolicy(url, execution_context_)) return true; bool is_allowed = true; for (const auto& policy : policies_) { if (!CheckHeaderTypeMatches(check_header_type, policy->HeaderType())) continue; is_allowed &= policy->AllowFormAction(url, redirect_status, reporting_policy); } return is_allowed; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: create_response(const char *nurl, const char *method, unsigned int *rp_code) { char *page, *fpath; struct MHD_Response *resp = NULL; if (!strncmp(nurl, URL_BASE_API_1_1, strlen(URL_BASE_API_1_1))) { resp = create_response_api(nurl, method, rp_code); } else { fpath = get_path(nurl, server_data.www_dir); resp = create_response_file(nurl, method, rp_code, fpath); free(fpath); } } CWE ID: CWE-22 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GrantActiveTab(const GURL& url) { APIPermissionSet tab_api_permissions; tab_api_permissions.insert(APIPermission::kTab); URLPatternSet tab_hosts; tab_hosts.AddOrigin(UserScript::ValidUserScriptSchemes(), url::Origin::Create(url).GetURL()); PermissionSet tab_permissions(std::move(tab_api_permissions), ManifestPermissionSet(), tab_hosts, tab_hosts); active_tab_->permissions_data()->UpdateTabSpecificPermissions( kTabId, tab_permissions); } CWE ID: CWE-20 Target: 1 Example 2: Code: void IncrementRefCount(const std::string& uuid) { context_->IncrementBlobRefCount(uuid); } 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 Maybe<bool> IncludesValueImpl(Isolate* isolate, Handle<JSObject> object, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *object)); Handle<Map> original_map = handle(object->map(), isolate); Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()), isolate); bool search_for_hole = value->IsUndefined(isolate); for (uint32_t k = start_from; k < length; ++k) { uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k, ALL_PROPERTIES); if (entry == kMaxUInt32) { if (search_for_hole) return Just(true); continue; } Handle<Object> element_k = Subclass::GetImpl(isolate, *parameter_map, entry); if (element_k->IsAccessorPair()) { LookupIterator it(isolate, object, k, LookupIterator::OWN); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k, Object::GetPropertyWithAccessor(&it), Nothing<bool>()); if (value->SameValueZero(*element_k)) return Just(true); if (object->map() != *original_map) { return IncludesValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->SameValueZero(*element_k)) { return Just(true); } } return Just(false); } CWE ID: CWE-704 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 VirtualAuthenticator::AddRegistration( blink::test::mojom::RegisteredKeyPtr registration, AddRegistrationCallback callback) { if (registration->application_parameter.size() != device::kRpIdHashLength) { std::move(callback).Run(false); return; } bool success = false; std::tie(std::ignore, success) = state_->registrations.emplace( std::move(registration->key_handle), ::device::VirtualFidoDevice::RegistrationData( crypto::ECPrivateKey::CreateFromPrivateKeyInfo( registration->private_key), registration->application_parameter, registration->counter)); std::move(callback).Run(success); } CWE ID: CWE-22 Target: 1 Example 2: Code: check_decryption_preparation (RIJNDAEL_context *ctx) { if ( !ctx->decryption_prepared ) { prepare_decryption ( ctx ); ctx->decryption_prepared = 1; } } CWE ID: CWE-310 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), Min(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } SkipDXTMipmaps(image, dds_info, 16); return MagickTrue; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ResourceDispatcherHostImpl::OnReadCompleted(net::URLRequest* request, int bytes_read) { DCHECK(request); VLOG(1) << "OnReadCompleted: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); if (bytes_read == -1) { DCHECK(!request->status().is_success()); ResponseCompleted(request); return; } info->set_has_started_reading(true); if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (request->status().is_success() && CompleteRead(request, &bytes_read)) { if (info->pause_count() == 0 && Read(request, &bytes_read) && request->status().is_success()) { if (bytes_read == 0) { CompleteRead(request, &bytes_read); } else { VLOG(1) << "OnReadCompleted postponing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; info->set_paused_read_bytes(bytes_read); info->set_is_paused(true); GlobalRequestID id(info->GetChildID(), info->GetRequestID()); MessageLoop::current()->PostTask( FROM_HERE, base::Bind( &ResourceDispatcherHostImpl::ResumeRequest, weak_factory_.GetWeakPtr(), id)); return; } } } if (PauseRequestIfNeeded(info)) { info->set_paused_read_bytes(bytes_read); VLOG(1) << "OnReadCompleted (CompleteRead) pausing: \"" << request->url().spec() << "\"" << " bytes_read = " << bytes_read; return; } if (!request->status().is_io_pending()) ResponseCompleted(request); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool ConvertRequestTypeFromApi(const RequestType& input, UsbDeviceHandle::TransferRequestType* output) { switch (input) { case usb::REQUEST_TYPE_STANDARD: *output = UsbDeviceHandle::STANDARD; return true; case usb::REQUEST_TYPE_CLASS: *output = UsbDeviceHandle::CLASS; return true; case usb::REQUEST_TYPE_VENDOR: *output = UsbDeviceHandle::VENDOR; return true; case usb::REQUEST_TYPE_RESERVED: *output = UsbDeviceHandle::RESERVED; return true; default: NOTREACHED(); return false; } } 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 RunNestedLoopTask(int* counter) { RunLoop nested_run_loop; ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&nested_run_loop), Unretained(counter))); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, BindOnce(&ShouldNotRunTask), TimeDelta::FromDays(1)); std::unique_ptr<MessageLoop::ScopedNestableTaskAllower> allower; if (MessageLoop::current()) { allower = base::MakeUnique<MessageLoop::ScopedNestableTaskAllower>( MessageLoop::current()); } nested_run_loop.Run(); ++(*counter); } 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 git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; line += PKT_LEN_SIZE; /* * TODO: How do we deal with empty lines? Try again? with the next * line? */ if (len == PKT_LEN_SIZE) { *head = NULL; *out = line; return 0; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool WebGraphicsContext3DCommandBufferImpl::SetParent( WebGraphicsContext3DCommandBufferImpl* new_parent) { if (parent_ == new_parent) return true; uint32 new_parent_texture_id = 0; if (command_buffer_) { if (new_parent) { int32 token = new_parent->gles2_helper_->InsertToken(); new_parent->gles2_helper_->WaitForToken(token); new_parent_texture_id = new_parent->gl_->MakeTextureId(); if (!command_buffer_->SetParent(new_parent->command_buffer_, new_parent_texture_id)) { new_parent->gl_->FreeTextureId(parent_texture_id_); return false; } } else { if (!command_buffer_->SetParent(NULL, 0)) return false; } } if (parent_ && parent_texture_id_ != 0) { gpu::gles2::GLES2Implementation* parent_gles2 = parent_->gl_; parent_gles2->helper()->CommandBufferHelper::Finish(); parent_gles2->FreeTextureId(parent_texture_id_); } if (new_parent) { parent_ = new_parent; parent_texture_id_ = new_parent_texture_id; } else { parent_ = NULL; parent_texture_id_ = 0; } 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: all_local_variables () { VARLIST *vlist; SHELL_VAR **ret; VAR_CONTEXT *vc; vc = shell_variables; for (vc = shell_variables; vc; vc = vc->down) if (vc_isfuncenv (vc) && vc->scope == variable_context) break; if (vc == 0) { internal_error (_("all_local_variables: no function context at current scope")); return (SHELL_VAR **)NULL; } if (vc->table == 0 || HASH_ENTRIES (vc->table) == 0 || vc_haslocals (vc) == 0) return (SHELL_VAR **)NULL; vlist = vlist_alloc (HASH_ENTRIES (vc->table)); flatten (vc->table, variable_in_context, vlist, 0); ret = vlist->list; free (vlist); if (ret) sort_variables (ret); return ret; } 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 float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; assert(0); return NULL; } CWE ID: CWE-20 Target: 1 Example 2: Code: int vb2_ioctl_create_bufs(struct file *file, void *priv, struct v4l2_create_buffers *p) { struct video_device *vdev = video_devdata(file); int res = vb2_verify_memory_type(vdev->queue, p->memory, p->format.type); p->index = vdev->queue->num_buffers; /* * If count == 0, then just check if memory and type are valid. * Any -EBUSY result from vb2_verify_memory_type can be mapped to 0. */ if (p->count == 0) return res != -EBUSY ? res : 0; if (res) return res; if (vb2_queue_is_busy(vdev, file)) return -EBUSY; res = vb2_create_bufs(vdev->queue, p); if (res == 0) vdev->queue->owner = file->private_data; return res; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Init() { if (CacheMemoryRegions()) { OpenSymbolFiles(); google::InstallSymbolizeOpenObjectFileCallback( &OpenObjectFileContainingPc); } } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0, ret = -1; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX *hctx = NULL; EVP_CIPHER_CTX *ctx; SSL_CTX *tctx = s->initial_ctx; /* Need at least keyname + iv + some encrypted data */ if (eticklen < 48) return 2; /* Initialize session ticket encryption and HMAC contexts */ hctx = HMAC_CTX_new(); if (hctx == NULL) hctx = HMAC_CTX_new(); if (hctx == NULL) return -2; ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ret = -2; goto err; } if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, ctx, hctx, 0); if (rv < 0) goto err; if (rv == 0) { ret = 2; goto err; } if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, sizeof(tctx->tlsext_tick_key_name)) != 0) { ret = 2; goto err; } if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, sizeof(tctx->tlsext_tick_hmac_key), EVP_sha256(), NULL) <= 0 || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + sizeof(tctx->tlsext_tick_key_name)) <= 0) { goto err; } } /* * Attempt to process session ticket, first conduct sanity and integrity * checks on ticket. if (mlen < 0) { goto err; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ if (HMAC_Update(hctx, etick, eticklen) <= 0 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) { EVP_CIPHER_CTX_free(ctx); return 2; } /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(ctx); eticklen -= 16 + EVP_CIPHER_CTX_iv_length(ctx); sdec = OPENSSL_malloc(eticklen); if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return -1; } if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_free(ctx); ctx = NULL; p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* * The session ID, if non-empty, is used by some clients to detect * that the ticket has been accepted. So we copy it to the session * structure. If it is empty set length to zero as required by * standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* * For session parse failure, indicate that we need to send a new ticket. */ return 2; err: EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return ret; } CWE ID: CWE-20 Target: 1 Example 2: Code: static char * uc_to_ascii( SQLWCHAR *uc ) { char *ascii = (char *)uc; int i; for ( i = 0; uc[ i ]; i ++ ) { ascii[ i ] = uc[ i ] & 0x00ff; } ascii[ i ] = 0; return ascii; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __key_instantiate_and_link(struct key *key, struct key_preparsed_payload *prep, struct key *keyring, struct key *authkey, struct assoc_array_edit **_edit) { int ret, awaken; key_check(key); key_check(keyring); awaken = 0; ret = -EBUSY; mutex_lock(&key_construction_mutex); /* can't instantiate twice */ if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { /* instantiate the key */ ret = key->type->instantiate(key, prep); if (ret == 0) { /* mark the key as being instantiated */ atomic_inc(&key->user->nikeys); set_bit(KEY_FLAG_INSTANTIATED, &key->flags); if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) awaken = 1; /* and link it into the destination keyring */ if (keyring) { if (test_bit(KEY_FLAG_KEEP, &keyring->flags)) set_bit(KEY_FLAG_KEEP, &key->flags); __key_link(key, _edit); } /* disable the authorisation key */ if (authkey) key_revoke(authkey); if (prep->expiry != TIME_T_MAX) { key->expiry = prep->expiry; key_schedule_gc(prep->expiry + key_gc_delay); } } } mutex_unlock(&key_construction_mutex); /* wake up anyone waiting for a key to be constructed */ if (awaken) wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT); return ret; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int get_default_root(pool *p, int allow_symlinks, char **root) { config_rec *c = NULL; char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir) { char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; struct stat st; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = dir; if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } pr_fs_clear_cache(); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks " "config)", path); errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } CWE ID: CWE-59 Target: 1 Example 2: Code: ChromeContentBrowserClient::~ChromeContentBrowserClient() { for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i) delete extra_parts_[i]; extra_parts_.clear(); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_METHOD(Phar, isCompressed) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } if (phar_obj->archive->flags & PHAR_FILE_COMPRESSED_GZ) { RETURN_LONG(PHAR_ENT_COMPRESSED_GZ); } if (phar_obj->archive->flags & PHAR_FILE_COMPRESSED_BZ2) { RETURN_LONG(PHAR_ENT_COMPRESSED_BZ2); } RETURN_FALSE; } 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: read_gif(Gif_Reader *grr, int read_flags, const char* landmark, Gif_ReadErrorHandler handler) { Gif_Stream *gfs; Gif_Image *gfi; Gif_Context gfc; int unknown_block_type = 0; if (gifgetc(grr) != 'G' || gifgetc(grr) != 'I' || gifgetc(grr) != 'F') return 0; (void)gifgetc(grr); (void)gifgetc(grr); (void)gifgetc(grr); gfs = Gif_NewStream(); gfi = Gif_NewImage(); gfc.stream = gfs; gfc.prefix = Gif_NewArray(Gif_Code, GIF_MAX_CODE); gfc.suffix = Gif_NewArray(uint8_t, GIF_MAX_CODE); gfc.length = Gif_NewArray(uint16_t, GIF_MAX_CODE); gfc.handler = handler; gfc.gfi = gfi; gfc.errors[0] = gfc.errors[1] = 0; if (!gfs || !gfi || !gfc.prefix || !gfc.suffix || !gfc.length) goto done; gfs->landmark = landmark; GIF_DEBUG(("\nGIF ")); if (!read_logical_screen_descriptor(gfs, grr)) goto done; GIF_DEBUG(("logscrdesc ")); while (!gifeof(grr)) { uint8_t block = gifgetbyte(grr); switch (block) { case ',': /* image block */ GIF_DEBUG(("imageread %d ", gfs->nimages)); gfi->identifier = last_name; last_name = 0; if (!Gif_AddImage(gfs, gfi)) goto done; else if (!read_image(grr, &gfc, gfi, read_flags)) { Gif_RemoveImage(gfs, gfs->nimages - 1); gfi = 0; goto done; } gfc.gfi = gfi = Gif_NewImage(); if (!gfi) goto done; break; case ';': /* terminator */ GIF_DEBUG(("term\n")); goto done; case '!': /* extension */ block = gifgetbyte(grr); GIF_DEBUG(("ext(0x%02X) ", block)); switch (block) { case 0xF9: read_graphic_control_extension(&gfc, gfi, grr); break; case 0xCE: last_name = suck_data(last_name, 0, grr); break; case 0xFE: if (!read_comment_extension(gfi, grr)) goto done; break; case 0xFF: read_application_extension(&gfc, grr); break; default: read_unknown_extension(&gfc, grr, block, 0, 0); break; } break; default: if (!unknown_block_type) { char buf[256]; sprintf(buf, "unknown block type %d at file offset %u", block, grr->pos - 1); gif_read_error(&gfc, 1, buf); unknown_block_type = 1; } break; } } done: /* Move comments and extensions after last image into stream. */ if (gfs && gfi) { Gif_Extension* gfex; gfs->end_comment = gfi->comment; gfi->comment = 0; gfs->end_extension_list = gfi->extension_list; gfi->extension_list = 0; for (gfex = gfs->end_extension_list; gfex; gfex = gfex->next) gfex->image = NULL; } Gif_DeleteImage(gfi); Gif_DeleteArray(last_name); Gif_DeleteArray(gfc.prefix); Gif_DeleteArray(gfc.suffix); Gif_DeleteArray(gfc.length); gfc.gfi = 0; if (gfs) gfs->errors = gfc.errors[1]; if (gfs && gfc.errors[1] == 0 && !(read_flags & GIF_READ_TRAILING_GARBAGE_OK) && !grr->eofer(grr)) gif_read_error(&gfc, 0, "trailing garbage after GIF ignored"); /* finally, export last message */ gif_read_error(&gfc, -1, 0); return gfs; } CWE ID: CWE-415 Target: 1 Example 2: Code: void WaitForIOThreadCompletion() { ChildProcess::current()->io_message_loop()->PostTask( FROM_HERE, base::Bind(&WaitCallback, base::Unretained(event_.get()))); EXPECT_TRUE(event_->TimedWait( base::TimeDelta::FromMilliseconds(TestTimeouts::action_timeout_ms()))); } 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 lookup_node(unsigned long addr) { struct page *p; int err; err = get_user_pages(addr & PAGE_MASK, 1, 0, &p, NULL); if (err >= 0) { err = page_to_nid(p); put_page(p); } return err; } CWE ID: CWE-388 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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 = NULL; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } 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: void HeadlessDevToolsManagerDelegate::BeginFrame( content::DevToolsAgentHost* agent_host, int session_id, int command_id, const base::DictionaryValue* params, const CommandCallback& callback) { DCHECK(callback); content::WebContents* web_contents = agent_host->GetWebContents(); if (!web_contents) { callback.Run(CreateErrorResponse(command_id, kErrorServerError, "Command not supported on this endpoint")); return; } HeadlessWebContentsImpl* headless_contents = HeadlessWebContentsImpl::From(browser_.get(), web_contents); if (!headless_contents->begin_frame_control_enabled()) { callback.Run(CreateErrorResponse( command_id, kErrorServerError, "Command is only supported if BeginFrameControl is enabled.")); return; } double frame_time_double = 0; double deadline_double = 0; double interval_double = 0; base::Time frame_time; base::TimeTicks frame_timeticks; base::TimeTicks deadline; base::TimeDelta interval; if (params->GetDouble("frameTime", &frame_time_double)) { frame_time = base::Time::FromDoubleT(frame_time_double); base::TimeDelta delta = frame_time - base::Time::UnixEpoch(); frame_timeticks = base::TimeTicks::UnixEpoch() + delta; } else { frame_timeticks = base::TimeTicks::Now(); } if (params->GetDouble("interval", &interval_double)) { if (interval_double <= 0) { callback.Run(CreateErrorResponse(command_id, kErrorInvalidParam, "interval has to be greater than 0")); return; } interval = base::TimeDelta::FromMillisecondsD(interval_double); } else { interval = viz::BeginFrameArgs::DefaultInterval(); } if (params->GetDouble("deadline", &deadline_double)) { base::TimeDelta delta = base::Time::FromDoubleT(deadline_double) - frame_time; if (delta <= base::TimeDelta()) { callback.Run(CreateErrorResponse(command_id, kErrorInvalidParam, "deadline has to be after frameTime")); return; } deadline = frame_timeticks + delta; } else { deadline = frame_timeticks + interval; } bool capture_screenshot = false; ImageEncoding encoding = ImageEncoding::kPng; int quality = kDefaultScreenshotQuality; const base::Value* value = nullptr; const base::DictionaryValue* screenshot_dict = nullptr; if (params->Get("screenshot", &value)) { if (!value->GetAsDictionary(&screenshot_dict)) { callback.Run(CreateInvalidParamResponse(command_id, "screenshot")); return; } capture_screenshot = true; std::string format; if (screenshot_dict->GetString("format", &format)) { if (format == kPng) { encoding = ImageEncoding::kPng; } else if (format == kJpeg) { encoding = ImageEncoding::kJpeg; } else { callback.Run( CreateInvalidParamResponse(command_id, "screenshot.format")); return; } } if (screenshot_dict->GetInteger("quality", &quality) && (quality < 0 || quality > 100)) { callback.Run( CreateErrorResponse(command_id, kErrorInvalidParam, "screenshot.quality has to be in range 0..100")); return; } } if (base::CommandLine::ForCurrentProcess()->HasSwitch( cc::switches::kRunAllCompositorStagesBeforeDraw) && headless_contents->HasPendingFrame()) { LOG(WARNING) << "A BeginFrame is already in flight. In " "--run-all-compositor-stages-before-draw mode, only a " "single BeginFrame should be active at the same time."; } headless_contents->BeginFrame(frame_timeticks, deadline, interval, capture_screenshot, base::Bind(&OnBeginFrameFinished, command_id, callback, encoding, quality)); } 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 RList *r_bin_wasm_get_data_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmDataEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; size_t n = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmDataEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(n = consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } ptr->offset.len = n; if (!(consume_u32 (buf + i, buf + len, &ptr->size, &i))) { free (ptr); return ret; } ptr->data = sec->payload_data + i; r_list_append (ret, ptr); r += 1; } return ret; } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bgp_attr_unknown (struct bgp_attr_parser_args *args) { bgp_size_t total; struct transit *transit; struct attr_extra *attre; struct peer *const peer = args->peer; struct attr *const attr = args->attr; u_char *const startp = args->startp; const u_char type = args->type; const u_char flag = args->flags; const bgp_size_t length = args->length; if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s Unknown attribute is received (type %d, length %d)", peer->host, type, length); if (BGP_DEBUG (events, EVENTS)) zlog (peer->log, LOG_DEBUG, "Unknown attribute type %d length %d is received", type, length); /* Forward read pointer of input stream. */ stream_forward_getp (peer->ibuf, length); /* If any of the mandatory well-known attributes are not recognized, then the Error Subcode is set to Unrecognized Well-known Attribute. The Data field contains the unrecognized attribute (type, length and value). */ if (!CHECK_FLAG (flag, BGP_ATTR_FLAG_OPTIONAL)) { return bgp_attr_malformed (args, BGP_NOTIFY_UPDATE_UNREC_ATTR, args->total); } /* Unrecognized non-transitive optional attributes must be quietly ignored and not passed along to other BGP peers. */ if (! CHECK_FLAG (flag, BGP_ATTR_FLAG_TRANS)) return BGP_ATTR_PARSE_PROCEED; /* If a path with recognized transitive optional attribute is accepted and passed along to other BGP peers and the Partial bit in the Attribute Flags octet is set to 1 by some previous AS, it is not set back to 0 by the current AS. */ SET_FLAG (*startp, BGP_ATTR_FLAG_PARTIAL); /* Store transitive attribute to the end of attr->transit. */ if (! ((attre = bgp_attr_extra_get(attr))->transit) ) attre->transit = XCALLOC (MTYPE_TRANSIT, sizeof (struct transit)); transit = attre->transit; if (transit->val) transit->val = XREALLOC (MTYPE_TRANSIT_VAL, transit->val, transit->length + total); else transit->val = XMALLOC (MTYPE_TRANSIT_VAL, total); memcpy (transit->val + transit->length, startp, total); transit->length += total; return BGP_ATTR_PARSE_PROCEED; } CWE ID: Target: 1 Example 2: Code: void OutOfProcessInstance::GetDocumentPassword( pp::CompletionCallbackWithOutput<pp::Var> callback) { if (password_callback_) { NOTREACHED(); return; } password_callback_.reset( new pp::CompletionCallbackWithOutput<pp::Var>(callback)); pp::VarDictionary message; message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType)); PostMessage(message); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Tracks::Tracks( Segment* pSegment, long long start, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_trackEntries(NULL), m_trackEntriesEnd(NULL) { } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_hash rhash; snprintf(rhash.type, CRYPTO_MAX_ALG_NAME, "%s", "ahash"); rhash.blocksize = alg->cra_blocksize; rhash.digestsize = __crypto_hash_alg_common(alg)->digestsize; if (nla_put(skb, CRYPTOCFGA_REPORT_HASH, sizeof(struct crypto_report_hash), &rhash)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } CWE ID: CWE-310 Target: 1 Example 2: Code: static String ValueEmpty(const EditorInternalCommand&, LocalFrame&, Event*) { return g_empty_string; } 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: BluetoothAdapterChromeOS::~BluetoothAdapterChromeOS() { DBusThreadManager::Get()->GetBluetoothAdapterClient()->RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->RemoveObserver(this); } 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 ieee80211_sta_ps_deliver_wakeup(struct sta_info *sta) { struct ieee80211_sub_if_data *sdata = sta->sdata; struct ieee80211_local *local = sdata->local; struct sk_buff_head pending; int filtered = 0, buffered = 0, ac; unsigned long flags; clear_sta_flag(sta, WLAN_STA_SP); BUILD_BUG_ON(BITS_TO_LONGS(IEEE80211_NUM_TIDS) > 1); sta->driver_buffered_tids = 0; if (!(local->hw.flags & IEEE80211_HW_AP_LINK_PS)) drv_sta_notify(local, sdata, STA_NOTIFY_AWAKE, &sta->sta); skb_queue_head_init(&pending); /* Send all buffered frames to the station */ for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) { int count = skb_queue_len(&pending), tmp; spin_lock_irqsave(&sta->tx_filtered[ac].lock, flags); skb_queue_splice_tail_init(&sta->tx_filtered[ac], &pending); spin_unlock_irqrestore(&sta->tx_filtered[ac].lock, flags); tmp = skb_queue_len(&pending); filtered += tmp - count; count = tmp; spin_lock_irqsave(&sta->ps_tx_buf[ac].lock, flags); skb_queue_splice_tail_init(&sta->ps_tx_buf[ac], &pending); spin_unlock_irqrestore(&sta->ps_tx_buf[ac].lock, flags); tmp = skb_queue_len(&pending); buffered += tmp - count; } ieee80211_add_pending_skbs_fn(local, &pending, clear_sta_ps_flags, sta); /* This station just woke up and isn't aware of our SMPS state */ if (!ieee80211_smps_is_restrictive(sta->known_smps_mode, sdata->smps_mode) && sta->known_smps_mode != sdata->bss->req_smps && sta_info_tx_streams(sta) != 1) { ht_dbg(sdata, "%pM just woke up and MIMO capable - update SMPS\n", sta->sta.addr); ieee80211_send_smps_action(sdata, sdata->bss->req_smps, sta->sta.addr, sdata->vif.bss_conf.bssid); } local->total_ps_buffered -= buffered; sta_info_recalc_tim(sta); ps_dbg(sdata, "STA %pM aid %d sending %d filtered/%d PS frames since STA not sleeping anymore\n", sta->sta.addr, sta->sta.aid, filtered, buffered); } CWE ID: CWE-362 Target: 1 Example 2: Code: int etm_perf_symlink(struct coresight_device *csdev, bool link) { char entry[sizeof("cpu9999999")]; int ret = 0, cpu = source_ops(csdev)->cpu_id(csdev); struct device *pmu_dev = etm_pmu.dev; struct device *cs_dev = &csdev->dev; sprintf(entry, "cpu%d", cpu); if (!etm_perf_up) return -EPROBE_DEFER; if (link) { ret = sysfs_create_link(&pmu_dev->kobj, &cs_dev->kobj, entry); if (ret) return ret; per_cpu(csdev_src, cpu) = csdev; } else { sysfs_remove_link(&pmu_dev->kobj, entry); per_cpu(csdev_src, cpu) = NULL; } return 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: COMPAT_SYSCALL_DEFINE5(waitid, int, which, compat_pid_t, pid, struct compat_siginfo __user *, infop, int, options, struct compat_rusage __user *, uru) { struct rusage ru; struct waitid_info info = {.status = 0}; long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL); int signo = 0; if (err > 0) { signo = SIGCHLD; err = 0; } if (!err && uru) { /* kernel_waitid() overwrites everything in ru */ if (COMPAT_USE_64BIT_TIME) err = copy_to_user(uru, &ru, sizeof(ru)); else err = put_compat_rusage(&ru, uru); if (err) return -EFAULT; } if (!infop) return err; user_access_begin(); unsafe_put_user(signo, &infop->si_signo, Efault); unsafe_put_user(0, &infop->si_errno, Efault); unsafe_put_user(info.cause, &infop->si_code, Efault); unsafe_put_user(info.pid, &infop->si_pid, Efault); unsafe_put_user(info.uid, &infop->si_uid, Efault); unsafe_put_user(info.status, &infop->si_status, Efault); user_access_end(); return err; Efault: user_access_end(); return -EFAULT; } 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 copy_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); if (rv) fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); unlink(src); } CWE ID: CWE-269 Target: 1 Example 2: Code: bool Textfield::HasCompositionText() const { return model_->HasCompositionText(); } 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: cifs_retry_async_readv(struct cifs_readdata *rdata) { int rc; struct TCP_Server_Info *server; server = tlink_tcon(rdata->cfile->tlink)->ses->server; do { if (rdata->cfile->invalidHandle) { rc = cifs_reopen_file(rdata->cfile, true); if (rc != 0) continue; } rc = server->ops->async_readv(rdata); } while (rc == -EAGAIN); return rc; } 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 fput(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; file_sb_list_del(file); if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) { init_task_work(&file->f_u.fu_rcuhead, ____fput); if (!task_work_add(task, &file->f_u.fu_rcuhead, true)) return; /* * After this task has run exit_task_work(), * task_work_add() will fail. Fall through to delayed * fput to avoid leaking *file. */ } if (llist_add(&file->f_u.fu_llist, &delayed_fput_list)) schedule_work(&delayed_fput_work); } } CWE ID: CWE-17 Target: 1 Example 2: Code: bool PDFiumEngine::New(const char* url, const char* headers) { url_ = url; if (headers) headers_ = headers; else headers_.clear(); return true; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct sock *llc_lookup_listener(struct llc_sap *sap, struct llc_addr *laddr) { static struct llc_addr null_addr; struct sock *rc = __llc_lookup_listener(sap, laddr); if (!rc) rc = __llc_lookup_listener(sap, &null_addr); return rc; } 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 cJSON_AddItemToArray( cJSON *array, cJSON *item ) { cJSON *c = array->child; if ( ! item ) return; if ( ! c ) { array->child = item; } else { while ( c && c->next ) c = c->next; suffix_object( c, item ); } } CWE ID: CWE-119 Target: 1 Example 2: Code: void Document::updateStyle(StyleRecalcChange change) { TRACE_EVENT_BEGIN0("blink,blink_style", "Document::updateStyle"); unsigned initialResolverAccessCount = styleEngine().resolverAccessCount(); HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates; m_lifecycle.advanceTo(DocumentLifecycle::InStyleRecalc); NthIndexCache nthIndexCache(*this); if (styleChangeType() >= SubtreeStyleChange) change = Force; if (change == Force) { m_hasNodesWithPlaceholderStyle = false; RefPtr<ComputedStyle> documentStyle = StyleResolver::styleForDocument(*this); StyleRecalcChange localChange = ComputedStyle::stylePropagationDiff(documentStyle.get(), layoutView()->style()); if (localChange != NoChange) layoutView()->setStyle(documentStyle.release()); } clearNeedsStyleRecalc(); StyleResolver& resolver = ensureStyleResolver(); bool shouldRecordStats; TRACE_EVENT_CATEGORY_GROUP_ENABLED("blink,blink_style", &shouldRecordStats); resolver.setStatsEnabled(shouldRecordStats); if (Element* documentElement = this->documentElement()) { inheritHtmlAndBodyElementStyles(change); dirtyElementsForLayerUpdate(); if (documentElement->shouldCallRecalcStyle(change)) documentElement->recalcStyle(change); while (dirtyElementsForLayerUpdate()) documentElement->recalcStyle(NoChange); } view()->recalcOverflowAfterStyleChange(); view()->setFrameTimingRequestsDirty(true); clearChildNeedsStyleRecalc(); styleEngine().resetCSSFeatureFlags(resolver.ensureUpdatedRuleFeatureSet()); resolver.clearStyleSharingList(); ASSERT(!needsStyleRecalc()); ASSERT(!childNeedsStyleRecalc()); ASSERT(inStyleRecalc()); ASSERT(styleResolver() == &resolver); m_lifecycle.advanceTo(DocumentLifecycle::StyleClean); if (shouldRecordStats) { TRACE_EVENT_END2("blink,blink_style", "Document::updateStyle", "resolverAccessCount", styleEngine().resolverAccessCount() - initialResolverAccessCount, "counters", resolver.stats()->toTracedValue()); } else { TRACE_EVENT_END1("blink,blink_style", "Document::updateStyle", "resolverAccessCount", styleEngine().resolverAccessCount() - initialResolverAccessCount); } } 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: PHP_FUNCTION(locale_get_display_script) { get_icu_disp_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if (g->sect <= 0 || g->head <= 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = "user format"; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; } CWE ID: CWE-369 Target: 1 Example 2: Code: bool JSTestNamedConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { JSTestNamedConstructor* thisObject = jsCast<JSTestNamedConstructor*>(cell); ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info); return getStaticValueSlot<JSTestNamedConstructor, Base>(exec, &JSTestNamedConstructorTable, thisObject, propertyName, slot); } 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: allocate(struct file *file, int allocate_idat) { struct control *control = png_voidcast(struct control*, file->alloc_ptr); if (allocate_idat) { assert(file->idat == NULL); IDAT_init(&control->idat, file); } else /* chunk */ { assert(file->chunk == NULL); chunk_init(&control->chunk, file); } } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p, struct user_namespace *user_ns) { mm->mmap = NULL; mm->mm_rb = RB_ROOT; mm->vmacache_seqnum = 0; atomic_set(&mm->mm_users, 1); atomic_set(&mm->mm_count, 1); init_rwsem(&mm->mmap_sem); INIT_LIST_HEAD(&mm->mmlist); mm->core_state = NULL; atomic_long_set(&mm->nr_ptes, 0); mm_nr_pmds_init(mm); mm->map_count = 0; mm->locked_vm = 0; mm->pinned_vm = 0; memset(&mm->rss_stat, 0, sizeof(mm->rss_stat)); spin_lock_init(&mm->page_table_lock); mm_init_cpumask(mm); mm_init_aio(mm); mm_init_owner(mm, p); mmu_notifier_mm_init(mm); init_tlb_flush_pending(mm); #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS mm->pmd_huge_pte = NULL; #endif if (current->mm) { mm->flags = current->mm->flags & MMF_INIT_MASK; mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK; } else { mm->flags = default_dump_filter; mm->def_flags = 0; } if (mm_alloc_pgd(mm)) goto fail_nopgd; if (init_new_context(p, mm)) goto fail_nocontext; mm->user_ns = get_user_ns(user_ns); return mm; fail_nocontext: mm_free_pgd(mm); fail_nopgd: free_mm(mm); return NULL; } CWE ID: CWE-416 Target: 1 Example 2: Code: ProcessManager* process_manager() { return ProcessManager::Get(profile()); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int hwsim_new_radio_nl(struct sk_buff *msg, struct genl_info *info) { struct hwsim_new_radio_params param = { 0 }; const char *hwname = NULL; int ret; param.reg_strict = info->attrs[HWSIM_ATTR_REG_STRICT_REG]; param.p2p_device = info->attrs[HWSIM_ATTR_SUPPORT_P2P_DEVICE]; param.channels = channels; param.destroy_on_close = info->attrs[HWSIM_ATTR_DESTROY_RADIO_ON_CLOSE]; if (info->attrs[HWSIM_ATTR_CHANNELS]) param.channels = nla_get_u32(info->attrs[HWSIM_ATTR_CHANNELS]); if (info->attrs[HWSIM_ATTR_NO_VIF]) param.no_vif = true; if (info->attrs[HWSIM_ATTR_RADIO_NAME]) { hwname = kasprintf(GFP_KERNEL, "%.*s", nla_len(info->attrs[HWSIM_ATTR_RADIO_NAME]), (char *)nla_data(info->attrs[HWSIM_ATTR_RADIO_NAME])); if (!hwname) return -ENOMEM; param.hwname = hwname; } if (info->attrs[HWSIM_ATTR_USE_CHANCTX]) param.use_chanctx = true; else param.use_chanctx = (param.channels > 1); if (info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]) param.reg_alpha2 = nla_data(info->attrs[HWSIM_ATTR_REG_HINT_ALPHA2]); if (info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]) { u32 idx = nla_get_u32(info->attrs[HWSIM_ATTR_REG_CUSTOM_REG]); if (idx >= ARRAY_SIZE(hwsim_world_regdom_custom)) return -EINVAL; param.regd = hwsim_world_regdom_custom[idx]; } ret = mac80211_hwsim_new_radio(info, &param); kfree(hwname); return ret; } CWE ID: CWE-772 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 ConversionContext::Convert(const PaintChunkSubset& paint_chunks, const DisplayItemList& display_items) { for (const auto& chunk : paint_chunks) { const auto& chunk_state = chunk.properties; bool switched_to_chunk_state = false; for (const auto& item : display_items.ItemsInPaintChunk(chunk)) { DCHECK(item.IsDrawing()); auto record = static_cast<const DrawingDisplayItem&>(item).GetPaintRecord(); if ((!record || record->size() == 0) && chunk_state.Effect() == EffectPaintPropertyNode::Root()) { continue; } TranslateForLayerOffsetOnce(); if (!switched_to_chunk_state) { SwitchToChunkState(chunk); switched_to_chunk_state = true; } cc_list_.StartPaint(); if (record && record->size() != 0) cc_list_.push<cc::DrawRecordOp>(std::move(record)); cc_list_.EndPaintOfUnpaired( chunk_to_layer_mapper_.MapVisualRect(item.VisualRect())); } UpdateEffectBounds(chunk.bounds, chunk_state.Transform()); } } CWE ID: Target: 1 Example 2: Code: lvs_timeouts(vector_t *strvec) { unsigned val; size_t i; if (vector_size(strvec) < 3) { report_config_error(CONFIG_GENERAL_ERROR, "lvs_timeouts requires at least one option"); return; } for (i = 1; i < vector_size(strvec); i++) { if (!strcmp(strvec_slot(strvec, i), "tcp")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout tcp - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout tcp (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_tcp_timeout = val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "tcpfin")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout tcpfin - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout tcpfin (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_tcpfin_timeout = val; i++; /* skip over value */ continue; } if (!strcmp(strvec_slot(strvec, i), "udp")) { if (i == vector_size(strvec) - 1) { report_config_error(CONFIG_GENERAL_ERROR, "No value specified for lvs_timeout udp - ignoring"); continue; } if (!read_unsigned_strvec(strvec, i + 1, &val, 0, LVS_MAX_TIMEOUT, false)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid lvs_timeout udp (%s) - ignoring", FMT_STR_VSLOT(strvec, i+1)); else global_data->lvs_udp_timeout = val; i++; /* skip over value */ continue; } report_config_error(CONFIG_GENERAL_ERROR, "Unknown option %s specified for lvs_timeouts", FMT_STR_VSLOT(strvec, i)); } } 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 EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod7(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")); DOMStringList* arrayArg(toDOMStringList(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(arrayArg); return JSValue::encode(jsUndefined()); } 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 *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; int strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, "%%%02X", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; } CWE ID: CWE-89 Target: 1 Example 2: Code: static void acm_port_dtr_rts(struct tty_port *port, int raise) { struct acm *acm = container_of(port, struct acm, port); int val; int res; if (raise) val = ACM_CTRL_DTR | ACM_CTRL_RTS; else val = 0; /* FIXME: add missing ctrlout locking throughout driver */ acm->ctrlout = val; res = acm_set_control(acm, val); if (res && (acm->ctrl_caps & USB_CDC_CAP_LINE)) dev_err(&acm->control->dev, "failed to set dtr/rts\n"); } 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 Browser::OpenSystemOptionsDialog() { UserMetrics::RecordAction(UserMetricsAction("OpenSystemOptionsDialog"), profile_); if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableTabbedOptions)) { ShowOptionsTab(chrome::kSystemOptionsSubPage); } else { ShowOptionsWindow(OPTIONS_PAGE_SYSTEM, OPTIONS_GROUP_NONE, profile_); } } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; k<localpalsize; k++) { i->palette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, "interlaced "); fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le "buffer" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); casspecial = (u8)act_code; old_code = act_code; WritePixel(i, &context, casspecial); npix--; } else { read_byt = act_code; if(act_code >= free) { /* code pas encore dans alphabet */ /* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf("actcode=%d\n", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoTraceEndCHROMIUM() { debug_marker_manager_.PopGroup(); if (!gpu_tracer_->End(kTraceCHROMIUM)) { LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "glTraceEndCHROMIUM", "no trace begin found"); return; } } 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 BROTLI_INLINE int SafeReadBlockLength(BrotliState* s, uint32_t* result, const HuffmanCode* table, BrotliBitReader* br) { uint32_t index; if (s->substate_read_block_length == BROTLI_STATE_READ_BLOCK_LENGTH_NONE) { if (!SafeReadSymbol(table, br, &index)) { return 0; } } else { index = s->block_length_index; } { uint32_t bits; uint32_t nbits = kBlockLengthPrefixCode[index].nbits; /* nbits == 2..24 */ if (!BrotliSafeReadBits(br, nbits, &bits)) { s->block_length_index = index; s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX; return 0; } *result = kBlockLengthPrefixCode[index].offset + bits; s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE; return 1; } } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void OnGetDevicesOnServiceThread( const std::vector<UsbDeviceFilter>& filters, const base::Callback<void(mojo::Array<DeviceInfoPtr>)>& callback, scoped_refptr<base::TaskRunner> callback_task_runner, const std::vector<scoped_refptr<UsbDevice>>& devices) { mojo::Array<DeviceInfoPtr> mojo_devices(0); for (size_t i = 0; i < devices.size(); ++i) { if (UsbDeviceFilter::MatchesAny(devices[i], filters)) mojo_devices.push_back(DeviceInfo::From(*devices[i])); } callback_task_runner->PostTask( FROM_HERE, base::Bind(callback, base::Passed(&mojo_devices))); } CWE ID: CWE-399 Target: 1 Example 2: Code: void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=0;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } 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: std::vector<gfx::Size> ConvertToFaviconSizes( const blink::WebVector<blink::WebSize>& web_sizes) { std::vector<gfx::Size> result; result.reserve(web_sizes.size()); for (const blink::WebSize& web_size : web_sizes) result.push_back(gfx::Size(web_size)); return result; } 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: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) return; } CWE ID: CWE-254 Target: 1 Example 2: Code: static void amd_gpio_irq_handler(struct irq_desc *desc) { u32 i; u32 off; u32 reg; u32 pin_reg; u64 reg64; int handled = 0; unsigned int irq; unsigned long flags; struct irq_chip *chip = irq_desc_get_chip(desc); struct gpio_chip *gc = irq_desc_get_handler_data(desc); struct amd_gpio *gpio_dev = gpiochip_get_data(gc); chained_irq_enter(chip, desc); /*enable GPIO interrupt again*/ spin_lock_irqsave(&gpio_dev->lock, flags); reg = readl(gpio_dev->base + WAKE_INT_STATUS_REG1); reg64 = reg; reg64 = reg64 << 32; reg = readl(gpio_dev->base + WAKE_INT_STATUS_REG0); reg64 |= reg; spin_unlock_irqrestore(&gpio_dev->lock, flags); /* * first 46 bits indicates interrupt status. * one bit represents four interrupt sources. */ for (off = 0; off < 46 ; off++) { if (reg64 & BIT(off)) { for (i = 0; i < 4; i++) { pin_reg = readl(gpio_dev->base + (off * 4 + i) * 4); if ((pin_reg & BIT(INTERRUPT_STS_OFF)) || (pin_reg & BIT(WAKE_STS_OFF))) { irq = irq_find_mapping(gc->irqdomain, off * 4 + i); generic_handle_irq(irq); writel(pin_reg, gpio_dev->base + (off * 4 + i) * 4); handled++; } } } } if (handled == 0) handle_bad_irq(desc); spin_lock_irqsave(&gpio_dev->lock, flags); reg = readl(gpio_dev->base + WAKE_INT_MASTER_REG); reg |= EOI_MASK; writel(reg, gpio_dev->base + WAKE_INT_MASTER_REG); spin_unlock_irqrestore(&gpio_dev->lock, flags); chained_irq_exit(chip, desc); } 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: PHP_FUNCTION(imagesetstyle) { zval *IM, *styles; gdImagePtr im; int * stylearr; int index; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* copy the style values in the stylearr */ stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0); zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos); for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) { zval ** item; if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) { break; } convert_to_long_ex(item); stylearr[index++] = Z_LVAL_PP(item); } gdImageSetStyle(im, stylearr, index); efree(stylearr); RETURN_TRUE; } 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: status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } if (cmdCode == EFFECT_CMD_GET_PARAM && (*replySize < sizeof(effect_param_t) || ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) { android_errorWriteLog(0x534e4554, "29251553"); return -EINVAL; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; } CWE ID: CWE-200 Target: 1 Example 2: Code: static inline int compare(const char *s1, const char *s2, int l1, int l2) { register const unsigned char *p1 = (const unsigned char *) s1; register const unsigned char *p2 = (const unsigned char *) s2; register const unsigned char *e1 = p1 + l1, *e2 = p2 + l2; int c1, c2; while (p1 < e1 && p2 < e2) { GET_UTF8_CHAR(p1, e1, c1); GET_UTF8_CHAR(p2, e2, c2); if (c1 == c2) continue; c1 = TOLOWER(c1); c2 = TOLOWER(c2); if (c1 != c2) return c1 - c2; } return l1 - l2; } 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 DecodeTunnel(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint32_t len, PacketQueue *pq, enum DecodeTunnelProto proto) { switch (proto) { case DECODE_TUNNEL_PPP: return DecodePPP(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_IPV4: return DecodeIPV4(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_IPV6: return DecodeIPV6(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_VLAN: return DecodeVLAN(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_ETHERNET: return DecodeEthernet(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_ERSPAN: return DecodeERSPAN(tv, dtv, p, pkt, len, pq); default: SCLogInfo("FIXME: DecodeTunnel: protocol %" PRIu32 " not supported.", proto); break; } return TM_ECODE_OK; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void perf_event_task_output(struct perf_event *event, struct perf_task_event *task_event) { struct perf_output_handle handle; struct perf_sample_data sample; struct task_struct *task = task_event->task; int ret, size = task_event->event_id.header.size; perf_event_header__init_id(&task_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, task_event->event_id.header.size, 0, 0); if (ret) goto out; task_event->event_id.pid = perf_event_pid(event, task); task_event->event_id.ppid = perf_event_pid(event, current); task_event->event_id.tid = perf_event_tid(event, task); task_event->event_id.ptid = perf_event_tid(event, current); perf_output_put(&handle, task_event->event_id); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: task_event->event_id.header.size = size; } CWE ID: CWE-399 Target: 1 Example 2: Code: ssize_t btrfs_getxattr(struct dentry *dentry, const char *name, void *buffer, size_t size) { /* * If this is a request for a synthetic attribute in the system.* * namespace use the generic infrastructure to resolve a handler * for it via sb->s_xattr. */ if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN)) return generic_getxattr(dentry, name, buffer, size); if (!btrfs_is_valid_xattr(name)) return -EOPNOTSUPP; return __btrfs_getxattr(dentry->d_inode, name, buffer, size); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int airo_change_mtu(struct net_device *dev, int new_mtu) { if ((new_mtu < 68) || (new_mtu > 2400)) return -EINVAL; dev->mtu = new_mtu; 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: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; /* xmlInitParser(); */ */ ctxt = xmlCreateMemoryParserCtxt(buf, buf_size); if (ctxt) { ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; #if LIBXML_VERSION >= 20703 ctxt->options |= XML_PARSE_HUGE; #endif xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ /* if (ret) { cleanup_xml_node((xmlNodePtr)ret); } */ return ret; } CWE ID: CWE-200 Target: 1 Example 2: Code: static int ext4_find_unwritten_pgoff(struct inode *inode, int whence, struct ext4_map_blocks *map, loff_t *offset) { struct pagevec pvec; unsigned int blkbits; pgoff_t index; pgoff_t end; loff_t endoff; loff_t startoff; loff_t lastoff; int found = 0; blkbits = inode->i_sb->s_blocksize_bits; startoff = *offset; lastoff = startoff; endoff = (loff_t)(map->m_lblk + map->m_len) << blkbits; index = startoff >> PAGE_CACHE_SHIFT; end = endoff >> PAGE_CACHE_SHIFT; pagevec_init(&pvec, 0); do { int i, num; unsigned long nr_pages; num = min_t(pgoff_t, end - index, PAGEVEC_SIZE); nr_pages = pagevec_lookup(&pvec, inode->i_mapping, index, (pgoff_t)num); if (nr_pages == 0) { if (whence == SEEK_DATA) break; BUG_ON(whence != SEEK_HOLE); /* * If this is the first time to go into the loop and * offset is not beyond the end offset, it will be a * hole at this offset */ if (lastoff == startoff || lastoff < endoff) found = 1; break; } /* * If this is the first time to go into the loop and * offset is smaller than the first page offset, it will be a * hole at this offset. */ if (lastoff == startoff && whence == SEEK_HOLE && lastoff < page_offset(pvec.pages[0])) { found = 1; break; } for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; struct buffer_head *bh, *head; /* * If the current offset is not beyond the end of given * range, it will be a hole. */ if (lastoff < endoff && whence == SEEK_HOLE && page->index > end) { found = 1; *offset = lastoff; goto out; } lock_page(page); if (unlikely(page->mapping != inode->i_mapping)) { unlock_page(page); continue; } if (!page_has_buffers(page)) { unlock_page(page); continue; } if (page_has_buffers(page)) { lastoff = page_offset(page); bh = head = page_buffers(page); do { if (buffer_uptodate(bh) || buffer_unwritten(bh)) { if (whence == SEEK_DATA) found = 1; } else { if (whence == SEEK_HOLE) found = 1; } if (found) { *offset = max_t(loff_t, startoff, lastoff); unlock_page(page); goto out; } lastoff += bh->b_size; bh = bh->b_this_page; } while (bh != head); } lastoff = page_offset(page) + PAGE_SIZE; unlock_page(page); } /* * The no. of pages is less than our desired, that would be a * hole in there. */ if (nr_pages < num && whence == SEEK_HOLE) { found = 1; *offset = lastoff; break; } index = pvec.pages[i - 1]->index + 1; pagevec_release(&pvec); } while (index <= end); out: pagevec_release(&pvec); return found; } 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: HRESULT UrlmonUrlRequest::InitPending(const GURL& url, IMoniker* moniker, IBindCtx* bind_context, bool enable_frame_busting, bool privileged_mode, HWND notification_window, IStream* cache) { DVLOG(1) << __FUNCTION__ << me() << url.spec(); DCHECK(bind_context_ == NULL); DCHECK(moniker_ == NULL); DCHECK(cache_ == NULL); DCHECK(thread_ == 0 || thread_ == base::PlatformThread::CurrentId()); thread_ = base::PlatformThread::CurrentId(); bind_context_ = bind_context; moniker_ = moniker; enable_frame_busting_ = enable_frame_busting; privileged_mode_ = privileged_mode; parent_window_ = notification_window; cache_ = cache; set_url(url.spec()); set_pending(true); method_ = "get"; return S_OK; } 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: image_transform_mod_end(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { PNG_CONST unsigned int scale = (1U<<that->sample_depth)-1; UNUSED(this) UNUSED(pp) UNUSED(display) /* At the end recalculate the digitized red green and blue values according * to the current sample_depth of the pixel. * * The sample value is simply scaled to the maximum, checking for over * and underflow (which can both happen for some image transforms, * including simple size scaling, though libpng doesn't do that at present. */ that->red = sample_scale(that->redf, scale); /* The error value is increased, at the end, according to the lowest sBIT * value seen. Common sense tells us that the intermediate integer * representations are no more accurate than +/- 0.5 in the integral values, * the sBIT allows the implementation to be worse than this. In addition the * PNG specification actually permits any error within the range (-1..+1), * but that is ignored here. Instead the final digitized value is compared, * below to the digitized value of the error limits - this has the net effect * of allowing (almost) +/-1 in the output value. It's difficult to see how * any algorithm that digitizes intermediate results can be more accurate. */ that->rede += 1./(2*((1U<<that->red_sBIT)-1)); if (that->colour_type & PNG_COLOR_MASK_COLOR) { that->green = sample_scale(that->greenf, scale); that->blue = sample_scale(that->bluef, scale); that->greene += 1./(2*((1U<<that->green_sBIT)-1)); that->bluee += 1./(2*((1U<<that->blue_sBIT)-1)); } else { that->blue = that->green = that->red; that->bluef = that->greenf = that->redf; that->bluee = that->greene = that->rede; } if ((that->colour_type & PNG_COLOR_MASK_ALPHA) || that->colour_type == PNG_COLOR_TYPE_PALETTE) { that->alpha = sample_scale(that->alphaf, scale); that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1)); } else { that->alpha = scale; /* opaque */ that->alpha = 1; /* Override this. */ that->alphae = 0; /* It's exact ;-) */ } } CWE ID: Target: 1 Example 2: Code: static int parse_location(HTTPContext *s, const char *p) { char redirected_location[MAX_URL_SIZE], *new_loc; ff_make_absolute_url(redirected_location, sizeof(redirected_location), s->location, p); new_loc = av_strdup(redirected_location); if (!new_loc) return AVERROR(ENOMEM); av_free(s->location); s->location = new_loc; 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: _zip_cdir_new(int nentry, struct zip_error *error) { struct zip_cdir *cd; if ((cd=(struct zip_cdir *)malloc(sizeof(*cd))) == NULL) { _zip_error_set(error, ZIP_ER_MEMORY, 0); return NULL; } if ((cd->entry=(struct zip_dirent *)malloc(sizeof(*(cd->entry))*nentry)) == NULL) { _zip_error_set(error, ZIP_ER_MEMORY, 0); free(cd); return NULL; } /* entries must be initialized by caller */ cd->nentry = nentry; cd->size = cd->offset = 0; cd->comment = NULL; cd->comment_len = 0; return cd; } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { if (parser->level <= XML_MAXLEVEL) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } efree(tag_name); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void nfs4_xdr_enc_lockt(struct rpc_rqst *req, struct xdr_stream *xdr, struct nfs_lockt_args *args) { struct compound_hdr hdr = { .minorversion = nfs4_xdr_minorversion(&args->seq_args), }; encode_compound_hdr(xdr, req, &hdr); encode_sequence(xdr, &args->seq_args, &hdr); encode_putfh(xdr, args->fh, &hdr); encode_lockt(xdr, args, &hdr); encode_nops(&hdr); } 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 FeatureInfo::EnableOESTextureFloatLinear() { if (!oes_texture_float_linear_available_) return; AddExtensionString("GL_OES_texture_float_linear"); feature_flags_.enable_texture_float_linear = true; validators_.texture_sized_texture_filterable_internal_format.AddValue( GL_R32F); validators_.texture_sized_texture_filterable_internal_format.AddValue( GL_RG32F); validators_.texture_sized_texture_filterable_internal_format.AddValue( GL_RGB32F); validators_.texture_sized_texture_filterable_internal_format.AddValue( GL_RGBA32F); } 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 int do_devinfo_ioctl(struct comedi_device *dev, struct comedi_devinfo __user *arg, struct file *file) { struct comedi_devinfo devinfo; const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_subdevice *read_subdev = comedi_get_read_subdevice(dev_file_info); struct comedi_subdevice *write_subdev = comedi_get_write_subdevice(dev_file_info); memset(&devinfo, 0, sizeof(devinfo)); /* fill devinfo structure */ devinfo.version_code = COMEDI_VERSION_CODE; devinfo.n_subdevs = dev->n_subdevices; memcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN); memcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN); if (read_subdev) devinfo.read_subdevice = read_subdev - dev->subdevices; else devinfo.read_subdevice = -1; if (write_subdev) devinfo.write_subdevice = write_subdev - dev->subdevices; else devinfo.write_subdevice = -1; if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo))) return -EFAULT; return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: void CreateBufferInfo(GLuint client_id, GLuint service_id) { return buffer_manager()->CreateBufferInfo(client_id, service_id); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TabStripModel::InsertTabContentsAt(int index, TabContentsWrapper* contents, int add_types) { bool active = add_types & ADD_ACTIVE; bool pin = contents->extension_tab_helper()->is_app() || add_types & ADD_PINNED; index = ConstrainInsertionIndex(index, pin); closing_all_ = false; TabContentsWrapper* selected_contents = GetSelectedTabContents(); TabContentsData* data = new TabContentsData(contents); data->pinned = pin; if ((add_types & ADD_INHERIT_GROUP) && selected_contents) { if (active) { ForgetAllOpeners(); } data->SetGroup(&selected_contents->controller()); } else if ((add_types & ADD_INHERIT_OPENER) && selected_contents) { if (active) { ForgetAllOpeners(); } data->opener = &selected_contents->controller(); } contents_data_.insert(contents_data_.begin() + index, data); selection_model_.IncrementFrom(index); FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabInsertedAt(contents, index, active)); if (active) { selection_model_.SetSelectedIndex(index); NotifyTabSelectedIfChanged(selected_contents, index, false); } } 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: CompositedLayerRasterInvalidatorTest& Properties( const RefCountedPropertyTreeState& state) { data_.chunks.back().properties = state; return *this; } CWE ID: Target: 1 Example 2: Code: std::unique_ptr<TracedValue> FrameLoader::ToTracedValue() const { std::unique_ptr<TracedValue> traced_value = TracedValue::Create(); traced_value->BeginDictionary("frame"); traced_value->SetString("id_ref", IdentifiersFactory::FrameId(frame_.Get())); traced_value->EndDictionary(); traced_value->SetBoolean("isLoadingMainFrame", IsLoadingMainFrame()); traced_value->SetString("stateMachine", state_machine_.ToString()); traced_value->SetString("provisionalDocumentLoaderURL", provisional_document_loader_ ? provisional_document_loader_->Url().GetString() : String()); traced_value->SetString( "documentLoaderURL", document_loader_ ? document_loader_->Url().GetString() : String()); return traced_value; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void a2dp_stream_common_init(struct a2dp_stream_common *common) { pthread_mutexattr_t lock_attr; FNLOG(); pthread_mutexattr_init(&lock_attr); pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&common->lock, &lock_attr); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; common->audio_fd = AUDIO_SKT_DISCONNECTED; common->state = AUDIO_A2DP_STATE_STOPPED; /* manages max capacity of socket pipe */ common->buffer_sz = AUDIO_STREAM_OUTPUT_BUFFER_SZ; } 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: ScriptPromise Bluetooth::requestLEScan(ScriptState* script_state, const BluetoothLEScanOptions* options, ExceptionState& exception_state) { ExecutionContext* context = ExecutionContext::From(script_state); DCHECK(context); context->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kInfo, "Web Bluetooth Scanning is experimental on this platform. See " "https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/" "implementation-status.md")); CHECK(context->IsSecureContext()); auto& doc = *To<Document>(context); auto* frame = doc.GetFrame(); if (!frame) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Document not active")); } if (!LocalFrame::HasTransientUserActivation(frame)) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Must be handling a user gesture to show a permission request.")); } if (!service_) { frame->GetInterfaceProvider().GetInterface(mojo::MakeRequest( &service_, context->GetTaskRunner(TaskType::kMiscPlatformAPI))); } auto scan_options = mojom::blink::WebBluetoothRequestLEScanOptions::New(); ConvertRequestLEScanOptions(options, scan_options, exception_state); if (exception_state.HadException()) return ScriptPromise(); Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); mojom::blink::WebBluetoothScanClientAssociatedPtrInfo client; mojo::BindingId id = client_bindings_.AddBinding( this, mojo::MakeRequest(&client), context->GetTaskRunner(TaskType::kMiscPlatformAPI)); service_->RequestScanningStart( std::move(client), std::move(scan_options), WTF::Bind(&Bluetooth::RequestScanningCallback, WrapPersistent(this), WrapPersistent(resolver), id)); return promise; } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int ohci_read_td(OHCIState *ohci, dma_addr_t addr, struct ohci_td *td) { return get_dwords(ohci, addr, (uint32_t *)td, sizeof(*td) >> 2); } 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: char *xmlrpc_array(int argc, ...) { va_list va; char *a; int idx = 0; char *s = NULL; int len; char buf[XMLRPC_BUFSIZE]; va_start(va, argc); for (idx = 0; idx < argc; idx++) { a = va_arg(va, char *); if (!s) { snprintf(buf, XMLRPC_BUFSIZE, " <value>%s</value>", a); s = sstrdup(buf); } else { snprintf(buf, XMLRPC_BUFSIZE, "%s\r\n <value>%s</value>", s, a); free(s); s = sstrdup(buf); } } va_end(va); snprintf(buf, XMLRPC_BUFSIZE, "<array>\r\n <data>\r\n %s\r\n </data>\r\n </array>", s); len = strlen(buf); free(s); return sstrdup(buf); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: nfsd4_layout_verify(struct svc_export *exp, unsigned int layout_type) { if (!exp->ex_layout_types) { dprintk("%s: export does not support pNFS\n", __func__); return NULL; } if (!(exp->ex_layout_types & (1 << layout_type))) { dprintk("%s: layout type %d not supported\n", __func__, layout_type); return NULL; } return nfsd4_layout_ops[layout_type]; } CWE ID: CWE-404 Target: 1 Example 2: Code: got_buffer_from_side (ProxySide *side, Buffer *buffer) { FlatpakProxyClient *client = side->client; if (side == &client->client_side) got_buffer_from_client (client, side, buffer); else got_buffer_from_bus (client, side, buffer); } CWE ID: CWE-436 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 megasas_handle_abort(MegasasState *s, MegasasCmd *cmd) { uint64_t abort_ctx = le64_to_cpu(cmd->frame->abort.abort_context); hwaddr abort_addr, addr_hi, addr_lo; MegasasCmd *abort_cmd; addr_hi = le32_to_cpu(cmd->frame->abort.abort_mfi_addr_hi); addr_lo = le32_to_cpu(cmd->frame->abort.abort_mfi_addr_lo); abort_addr = ((uint64_t)addr_hi << 32) | addr_lo; abort_cmd = megasas_lookup_frame(s, abort_addr); if (!abort_cmd) { trace_megasas_abort_no_cmd(cmd->index, abort_ctx); s->event_count++; return MFI_STAT_OK; } if (!megasas_use_queue64(s)) { abort_ctx &= (uint64_t)0xFFFFFFFF; } if (abort_cmd->context != abort_ctx) { trace_megasas_abort_invalid_context(cmd->index, abort_cmd->index, abort_cmd->context); s->event_count++; return MFI_STAT_ABORT_NOT_POSSIBLE; } trace_megasas_abort_frame(cmd->index, abort_cmd->index); megasas_abort_command(abort_cmd); if (!s->event_cmd || abort_cmd != s->event_cmd) { s->event_cmd = NULL; } s->event_count++; return MFI_STAT_OK; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void exit_sem(struct task_struct *tsk) { struct sem_undo_list *ulp; ulp = tsk->sysvsem.undo_list; if (!ulp) return; tsk->sysvsem.undo_list = NULL; if (!atomic_dec_and_test(&ulp->refcnt)) return; for (;;) { struct sem_array *sma; struct sem_undo *un; struct list_head tasks; int semid; int i; rcu_read_lock(); un = list_entry_rcu(ulp->list_proc.next, struct sem_undo, list_proc); if (&un->list_proc == &ulp->list_proc) semid = -1; else semid = un->semid; rcu_read_unlock(); if (semid == -1) break; sma = sem_lock_check(tsk->nsproxy->ipc_ns, un->semid); /* exit_sem raced with IPC_RMID, nothing to do */ if (IS_ERR(sma)) continue; un = __lookup_undo(ulp, semid); if (un == NULL) { /* exit_sem raced with IPC_RMID+semget() that created * exactly the same semid. Nothing to do. */ sem_unlock(sma); continue; } /* remove un from the linked lists */ assert_spin_locked(&sma->sem_perm.lock); list_del(&un->list_id); spin_lock(&ulp->lock); list_del_rcu(&un->list_proc); spin_unlock(&ulp->lock); /* perform adjustments registered in un */ for (i = 0; i < sma->sem_nsems; i++) { struct sem * semaphore = &sma->sem_base[i]; if (un->semadj[i]) { semaphore->semval += un->semadj[i]; /* * Range checks of the new semaphore value, * not defined by sus: * - Some unices ignore the undo entirely * (e.g. HP UX 11i 11.22, Tru64 V5.1) * - some cap the value (e.g. FreeBSD caps * at 0, but doesn't enforce SEMVMX) * * Linux caps the semaphore value, both at 0 * and at SEMVMX. * * Manfred <[email protected]> */ if (semaphore->semval < 0) semaphore->semval = 0; if (semaphore->semval > SEMVMX) semaphore->semval = SEMVMX; semaphore->sempid = task_tgid_vnr(current); } } /* maybe some queued-up processes were waiting for this */ INIT_LIST_HEAD(&tasks); do_smart_update(sma, NULL, 0, 1, &tasks); sem_unlock(sma); wake_up_sem_queue_do(&tasks); kfree_rcu(un, rcu); } kfree(ulp); } CWE ID: CWE-189 Target: 1 Example 2: Code: irc_ctcp_display_reply_from_nick (struct t_irc_server *server, time_t date, const char *command, const char *nick, const char *address, char *arguments) { char *pos_end, *pos_space, *pos_args, *pos_usec; struct timeval tv; long sec1, usec1, sec2, usec2, difftime; while (arguments && arguments[0]) { pos_end = strrchr (arguments + 1, '\01'); if (pos_end) pos_end[0] = '\0'; pos_space = strchr (arguments + 1, ' '); if (pos_space) { pos_space[0] = '\0'; pos_args = pos_space + 1; while (pos_args[0] == ' ') { pos_args++; } if (strcmp (arguments + 1, "PING") == 0) { pos_usec = strchr (pos_args, ' '); if (pos_usec) { pos_usec[0] = '\0'; gettimeofday (&tv, NULL); sec1 = atol (pos_args); usec1 = atol (pos_usec + 1); sec2 = tv.tv_sec; usec2 = tv.tv_usec; difftime = ((sec2 * 1000000) + usec2) - ((sec1 * 1000000) + usec1); weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, nick, NULL, "ctcp", NULL), date, irc_protocol_tags (command, "irc_ctcp", NULL, NULL), /* TRANSLATORS: %.3fs is a float number + "s" ("seconds") */ _("%sCTCP reply from %s%s%s: %s%s%s %.3fs"), weechat_prefix ("network"), irc_nick_color_for_msg (server, 0, NULL, nick), nick, IRC_COLOR_RESET, IRC_COLOR_CHAT_CHANNEL, arguments + 1, IRC_COLOR_RESET, (float)difftime / 1000000.0); pos_usec[0] = ' '; } } else { weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, nick, NULL, "ctcp", NULL), date, irc_protocol_tags (command, "irc_ctcp", NULL, address), _("%sCTCP reply from %s%s%s: %s%s%s%s%s"), weechat_prefix ("network"), irc_nick_color_for_msg (server, 0, NULL, nick), nick, IRC_COLOR_RESET, IRC_COLOR_CHAT_CHANNEL, arguments + 1, IRC_COLOR_RESET, " ", pos_args); } pos_space[0] = ' '; } else { weechat_printf_date_tags ( irc_msgbuffer_get_target_buffer ( server, nick, NULL, "ctcp", NULL), date, irc_protocol_tags (command, NULL, NULL, address), _("%sCTCP reply from %s%s%s: %s%s%s%s%s"), weechat_prefix ("network"), irc_nick_color_for_msg (server, 0, NULL, nick), nick, IRC_COLOR_RESET, IRC_COLOR_CHAT_CHANNEL, arguments + 1, "", "", ""); } if (pos_end) pos_end[0] = '\01'; arguments = (pos_end) ? pos_end + 1 : NULL; } } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: jbig2_image_new(Jbig2Ctx *ctx, int width, int height) { Jbig2Image *image; int stride; int64_t check; image = jbig2_new(ctx, Jbig2Image, 1); if (image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image structure in jbig2_image_new"); return NULL; } stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */ /* check for integer multiplication overflow */ check = ((int64_t) stride) * ((int64_t) height); if (check != (int)check) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow from stride(%d)*height(%d)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } /* Add 1 to accept runs that exceed image width and clamped to width+1 */ image->data = jbig2_new(ctx, uint8_t, (int)check + 1); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image data buffer! [stride(%d)*height(%d) bytes]", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->width = width; image->height = height; image->stride = stride; image->refcount = 1; return 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: static int ps_files_valid_key(const char *key) { size_t len; const char *p; char c; int ret = 1; for (p = key; (c = *p); p++) { /* valid characters are a..z,A..Z,0..9 */ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ',' || c == '-')) { ret = 0; break; } } len = p - key; /* Somewhat arbitrary length limit here, but should be way more than anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */ if (len == 0 || len > 128) { ret = 0; } return ret; } CWE ID: CWE-264 Target: 1 Example 2: Code: void usb_ehci_init(EHCIState *s, DeviceState *dev) { /* 2.2 host controller interface version */ s->caps[0x00] = (uint8_t)(s->opregbase - s->capsbase); s->caps[0x01] = 0x00; s->caps[0x02] = 0x00; s->caps[0x03] = 0x01; /* HC version */ s->caps[0x04] = s->portnr; /* Number of downstream ports */ s->caps[0x05] = 0x00; /* No companion ports at present */ s->caps[0x06] = 0x00; s->caps[0x07] = 0x00; s->caps[0x08] = 0x80; /* We can cache whole frame, no 64-bit */ s->caps[0x0a] = 0x00; s->caps[0x0b] = 0x00; QTAILQ_INIT(&s->aqueues); QTAILQ_INIT(&s->pqueues); usb_packet_init(&s->ipacket); memory_region_init(&s->mem, OBJECT(dev), "ehci", MMIO_SIZE); memory_region_init_io(&s->mem_caps, OBJECT(dev), &ehci_mmio_caps_ops, s, "capabilities", CAPA_SIZE); memory_region_init_io(&s->mem_opreg, OBJECT(dev), &ehci_mmio_opreg_ops, s, "operational", s->portscbase); memory_region_init_io(&s->mem_ports, OBJECT(dev), &ehci_mmio_port_ops, s, "ports", 4 * s->portnr); memory_region_add_subregion(&s->mem, s->capsbase, &s->mem_caps); memory_region_add_subregion(&s->mem, s->opregbase, &s->mem_opreg); memory_region_add_subregion(&s->mem, s->opregbase + s->portscbase, &s->mem_ports); } 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 u32 FFDemux_Run(void *par) { AVPacket pkt; s64 seek_to; GF_NetworkCommand com; GF_NetworkCommand map; GF_SLHeader slh; FFDemux *ffd = (FFDemux *) par; memset(&map, 0, sizeof(GF_NetworkCommand)); map.command_type = GF_NET_CHAN_MAP_TIME; memset(&com, 0, sizeof(GF_NetworkCommand)); com.command_type = GF_NET_BUFFER_QUERY; memset(&slh, 0, sizeof(GF_SLHeader)); slh.compositionTimeStampFlag = slh.decodingTimeStampFlag = 1; while (ffd->is_running) { if (!ffd->video_ch && !ffd->audio_ch) { gf_sleep(100); continue; } if ((ffd->seek_time>=0) && ffd->seekable) { seek_to = (s64) (AV_TIME_BASE*ffd->seek_time); av_seek_frame(ffd->ctx, -1, seek_to, AVSEEK_FLAG_BACKWARD); ffd->seek_time = -1; } pkt.stream_index = -1; /*EOF*/ if (av_read_frame(ffd->ctx, &pkt) <0) break; if (pkt.pts == AV_NOPTS_VALUE) pkt.pts = pkt.dts; if (!pkt.dts) pkt.dts = pkt.pts; slh.compositionTimeStamp = pkt.pts; slh.decodingTimeStamp = pkt.dts; gf_mx_p(ffd->mx); /*blindly send audio as soon as video is init*/ if (ffd->audio_ch && (pkt.stream_index == ffd->audio_st) ) { slh.compositionTimeStamp *= ffd->audio_tscale.num; slh.decodingTimeStamp *= ffd->audio_tscale.num; gf_service_send_packet(ffd->service, ffd->audio_ch, (char *) pkt.data, pkt.size, &slh, GF_OK); } else if (ffd->video_ch && (pkt.stream_index == ffd->video_st)) { slh.compositionTimeStamp *= ffd->video_tscale.num; slh.decodingTimeStamp *= ffd->video_tscale.num; slh.randomAccessPointFlag = pkt.flags&AV_PKT_FLAG_KEY ? 1 : 0; gf_service_send_packet(ffd->service, ffd->video_ch, (char *) pkt.data, pkt.size, &slh, GF_OK); } gf_mx_v(ffd->mx); av_free_packet(&pkt); /*sleep untill the buffer occupancy is too low - note that this work because all streams in this demuxer are synchronized*/ while (ffd->audio_run || ffd->video_run) { gf_service_command(ffd->service, &com, GF_OK); if (com.buffer.occupancy < com.buffer.max) break; gf_sleep(1); } if (!ffd->audio_run && !ffd->video_run) break; } /*signal EOS*/ if (ffd->audio_ch) gf_service_send_packet(ffd->service, ffd->audio_ch, NULL, 0, NULL, GF_EOS); if (ffd->video_ch) gf_service_send_packet(ffd->service, ffd->video_ch, NULL, 0, NULL, GF_EOS); ffd->is_running = 2; return 0; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void registerRewriteURL(const char* fromURL, const char* toURL) { m_rewriteURLs.add(fromURL, toURL); } CWE ID: CWE-119 Target: 1 Example 2: Code: const Result& result() const { return *result_.get(); } 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 IsNewTrace() { bool is_new_trace; TRACE_EVENT_IS_NEW_TRACE(&is_new_trace); return is_new_trace; } 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: PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } CWE ID: CWE-787 Target: 1 Example 2: Code: static void mpeg4_encode_visual_object_header(MpegEncContext *s) { int profile_and_level_indication; int vo_ver_id; if (s->avctx->profile != FF_PROFILE_UNKNOWN) { profile_and_level_indication = s->avctx->profile << 4; } else if (s->max_b_frames || s->quarter_sample) { profile_and_level_indication = 0xF0; // adv simple } else { profile_and_level_indication = 0x00; // simple } if (s->avctx->level != FF_LEVEL_UNKNOWN) profile_and_level_indication |= s->avctx->level; else profile_and_level_indication |= 1; // level 1 if (profile_and_level_indication >> 4 == 0xF) vo_ver_id = 5; else vo_ver_id = 1; put_bits(&s->pb, 16, 0); put_bits(&s->pb, 16, VOS_STARTCODE); put_bits(&s->pb, 8, profile_and_level_indication); put_bits(&s->pb, 16, 0); put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE); put_bits(&s->pb, 1, 1); put_bits(&s->pb, 4, vo_ver_id); put_bits(&s->pb, 3, 1); // priority put_bits(&s->pb, 4, 1); // visual obj type== video obj put_bits(&s->pb, 1, 0); // video signal type == no clue // FIXME ff_mpeg4_stuffing(&s->pb); } 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 WebBluetoothServiceImpl::RemoteCharacteristicGetDescriptors( const std::string& characteristic_instance_id, blink::mojom::WebBluetoothGATTQueryQuantity quantity, const base::Optional<BluetoothUUID>& descriptors_uuid, RemoteCharacteristicGetDescriptorsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RecordGetDescriptorsDescriptor(quantity, descriptors_uuid); if (descriptors_uuid && BluetoothBlocklist::Get().IsExcluded(descriptors_uuid.value())) { RecordGetDescriptorsOutcome(quantity, UMAGetDescriptorOutcome::BLOCKLISTED); std::move(callback).Run( blink::mojom::WebBluetoothResult::BLOCKLISTED_DESCRIPTOR_UUID, base::nullopt /* descriptor */); return; } const CacheQueryResult query_result = QueryCacheForCharacteristic(characteristic_instance_id); if (query_result.outcome == CacheQueryOutcome::BAD_RENDERER) { return; } if (query_result.outcome != CacheQueryOutcome::SUCCESS) { RecordGetDescriptorsOutcome(quantity, query_result.outcome); std::move(callback).Run(query_result.GetWebResult(), base::nullopt /* descriptor */); return; } auto descriptors = descriptors_uuid ? query_result.characteristic->GetDescriptorsByUUID( descriptors_uuid.value()) : query_result.characteristic->GetDescriptors(); std::vector<blink::mojom::WebBluetoothRemoteGATTDescriptorPtr> response_descriptors; for (device::BluetoothRemoteGattDescriptor* descriptor : descriptors) { if (BluetoothBlocklist::Get().IsExcluded(descriptor->GetUUID())) { continue; } std::string descriptor_instance_id = descriptor->GetIdentifier(); auto insert_result = descriptor_id_to_characteristic_id_.insert( {descriptor_instance_id, characteristic_instance_id}); if (!insert_result.second) DCHECK(insert_result.first->second == characteristic_instance_id); auto descriptor_ptr(blink::mojom::WebBluetoothRemoteGATTDescriptor::New()); descriptor_ptr->instance_id = descriptor_instance_id; descriptor_ptr->uuid = descriptor->GetUUID(); response_descriptors.push_back(std::move(descriptor_ptr)); if (quantity == blink::mojom::WebBluetoothGATTQueryQuantity::SINGLE) { break; } } if (!response_descriptors.empty()) { RecordGetDescriptorsOutcome(quantity, UMAGetDescriptorOutcome::SUCCESS); std::move(callback).Run(blink::mojom::WebBluetoothResult::SUCCESS, std::move(response_descriptors)); return; } RecordGetDescriptorsOutcome( quantity, descriptors_uuid ? UMAGetDescriptorOutcome::NOT_FOUND : UMAGetDescriptorOutcome::NO_DESCRIPTORS); std::move(callback).Run( descriptors_uuid ? blink::mojom::WebBluetoothResult::DESCRIPTOR_NOT_FOUND : blink::mojom::WebBluetoothResult::NO_DESCRIPTORS_FOUND, base::nullopt /* descriptors */); } 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 crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "blkcipher"); snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s", alg->cra_blkcipher.geniv ?: "<default>"); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_blkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_blkcipher.max_keysize; rblkcipher.ivsize = alg->cra_blkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } CWE ID: CWE-310 Target: 1 Example 2: Code: crm_client_name(crm_client_t * c) { if (c == NULL) { return "null"; } else if (c->name == NULL && c->id == NULL) { return "unknown"; } else if (c->name == NULL) { return c->id; } else { return c->name; } } CWE ID: CWE-285 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 WriteFile(const base::FilePath::StringType& filename, base::StringPiece contents) { base::ScopedAllowBlockingForTesting allow_blocking; EXPECT_EQ(base::checked_cast<int>(contents.size()), base::WriteFile(service_worker_dir_.GetPath().Append(filename), contents.data(), contents.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 qrio_cpuwd_flag(bool flag) { u8 reason1; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; reason1 = in_8(qrio_base + REASON1_OFF); if (flag) reason1 |= REASON1_CPUWD; else reason1 &= ~REASON1_CPUWD; out_8(qrio_base + REASON1_OFF, reason1); } CWE ID: CWE-787 Target: 1 Example 2: Code: QTNSort(QTNode *in) { int i; /* since this function recurses, it could be driven to stack overflow. */ check_stack_depth(); if (in->valnode->type != QI_OPR) return; for (i = 0; i < in->nchild; i++) QTNSort(in->child[i]); if (in->nchild > 1) qsort((void *) in->child, in->nchild, sizeof(QTNode *), cmpQTN); } 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: Document* LocalDOMWindow::CreateDocument(const String& mime_type, const DocumentInit& init, bool force_xhtml) { Document* document = nullptr; if (force_xhtml) { document = Document::Create(init); } else { document = DOMImplementation::createDocument( mime_type, init, init.GetFrame() ? init.GetFrame()->InViewSourceMode() : false); if (document->IsPluginDocument() && document->IsSandboxed(kSandboxPlugins)) document = SinkDocument::Create(init); } return document; } 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: xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) { const xmlChar *ptr; xmlChar cur; xmlChar *name; xmlEntityPtr entity = NULL; if ((str == NULL) || (*str == NULL)) return(NULL); ptr = *str; cur = *ptr; if (cur != '%') return(NULL); ptr++; name = xmlParseStringName(ctxt, &ptr); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStringPEReference: no name\n"); *str = ptr; return(NULL); } cur = *ptr; if (cur != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); xmlFree(name); *str = ptr; return(NULL); } ptr++; /* * 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 (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... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 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, "%%%s; is not a parameter entity\n", name, NULL); } } ctxt->hasPErefs = 1; xmlFree(name); *str = ptr; return(entity); } CWE ID: CWE-119 Target: 1 Example 2: Code: static sctp_disposition_t sctp_sf_do_dupcook_a(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, struct sctp_chunk *chunk, sctp_cmd_seq_t *commands, struct sctp_association *new_asoc) { sctp_init_chunk_t *peer_init; struct sctp_ulpevent *ev; struct sctp_chunk *repl; struct sctp_chunk *err; sctp_disposition_t disposition; /* new_asoc is a brand-new association, so these are not yet * side effects--it is safe to run them here. */ peer_init = &chunk->subh.cookie_hdr->c.peer_init[0]; if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init, GFP_ATOMIC)) goto nomem; /* Make sure no new addresses are being added during the * restart. Though this is a pretty complicated attack * since you'd have to get inside the cookie. */ if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) { return SCTP_DISPOSITION_CONSUME; } /* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes * the peer has restarted (Action A), it MUST NOT setup a new * association but instead resend the SHUTDOWN ACK and send an ERROR * chunk with a "Cookie Received while Shutting Down" error cause to * its peer. */ if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) { disposition = sctp_sf_do_9_2_reshutack(net, ep, asoc, SCTP_ST_CHUNK(chunk->chunk_hdr->type), chunk, commands); if (SCTP_DISPOSITION_NOMEM == disposition) goto nomem; err = sctp_make_op_error(asoc, chunk, SCTP_ERROR_COOKIE_IN_SHUTDOWN, NULL, 0, 0); if (err) sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(err)); return SCTP_DISPOSITION_CONSUME; } /* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked * data. Consider the optional choice of resending of this data. */ sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_SACK)); sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_OUTQUEUE, SCTP_NULL()); /* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue * and ASCONF-ACK cache. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_ASCONF_QUEUE, SCTP_NULL()); repl = sctp_make_cookie_ack(new_asoc, chunk); if (!repl) goto nomem; /* Report association restart to upper layer. */ ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_RESTART, 0, new_asoc->c.sinit_num_ostreams, new_asoc->c.sinit_max_instreams, NULL, GFP_ATOMIC); if (!ev) goto nomem_ev; /* Update the content of current association. */ sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); if (sctp_state(asoc, SHUTDOWN_PENDING) && (sctp_sstate(asoc->base.sk, CLOSING) || sock_flag(asoc->base.sk, SOCK_DEAD))) { /* if were currently in SHUTDOWN_PENDING, but the socket * has been closed by user, don't transition to ESTABLISHED. * Instead trigger SHUTDOWN bundled with COOKIE_ACK. */ sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); return sctp_sf_do_9_2_start_shutdown(net, ep, asoc, SCTP_ST_CHUNK(0), NULL, commands); } else { sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_ESTABLISHED)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); } return SCTP_DISPOSITION_CONSUME; nomem_ev: sctp_chunk_free(repl); nomem: return SCTP_DISPOSITION_NOMEM; } 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 ass_blur1246_vert_c(int16_t *dst, const int16_t *src, uintptr_t src_width, uintptr_t src_height, const int16_t *param) { uintptr_t dst_height = src_height + 12; uintptr_t step = STRIPE_WIDTH * src_height; for (uintptr_t x = 0; x < src_width; x += STRIPE_WIDTH) { uintptr_t offs = 0; for (uintptr_t y = 0; y < dst_height; ++y) { const int16_t *p4 = get_line(src, offs - 12 * STRIPE_WIDTH, step); const int16_t *p3 = get_line(src, offs - 10 * STRIPE_WIDTH, step); const int16_t *p2 = get_line(src, offs - 8 * STRIPE_WIDTH, step); const int16_t *p1 = get_line(src, offs - 7 * STRIPE_WIDTH, step); const int16_t *z0 = get_line(src, offs - 6 * STRIPE_WIDTH, step); const int16_t *n1 = get_line(src, offs - 5 * STRIPE_WIDTH, step); const int16_t *n2 = get_line(src, offs - 4 * STRIPE_WIDTH, step); const int16_t *n3 = get_line(src, offs - 2 * STRIPE_WIDTH, step); const int16_t *n4 = get_line(src, offs - 0 * STRIPE_WIDTH, step); for (int k = 0; k < STRIPE_WIDTH; ++k) dst[k] = blur_func(p4[k], p3[k], p2[k], p1[k], z0[k], n1[k], n2[k], n3[k], n4[k], param); dst += STRIPE_WIDTH; offs += STRIPE_WIDTH; } src += step; } } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int jas_stream_read(jas_stream_t *stream, void *buf, int cnt) { int n; int c; char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if ((c = jas_stream_getc(stream)) == EOF) { return n; } *bufptr++ = c; ++n; } return n; } CWE ID: CWE-190 Target: 1 Example 2: Code: static bool IsUnknownMimeType(const std::string& mime_type) { static const char* const kUnknownMimeTypes[] = { "", "unknown/unknown", "application/unknown", "*/*", }; for (size_t i = 0; i < arraysize(kUnknownMimeTypes); ++i) { if (mime_type == kUnknownMimeTypes[i]) return true; } if (mime_type.find('/') == std::string::npos) { return true; } return false; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: _exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type) { if (dt == NULL) return 1; if ((type & XS_TIME) != XS_TIME) { dt->value.date.hour = 0; dt->value.date.min = 0; dt->value.date.sec = 0.0; } if ((type & XS_GDAY) != XS_GDAY) dt->value.date.day = 0; if ((type & XS_GMONTH) != XS_GMONTH) dt->value.date.mon = 0; if ((type & XS_GYEAR) != XS_GYEAR) dt->value.date.year = 0; dt->type = type; 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: static int ax25_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int err = 0; lock_sock(sk); /* * This works for seqpacket too. The receiver has ordered the * queue for us! We do one quick check first though */ if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } /* Now we can treat all alike */ skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; if (!ax25_sk(sk)->pidincl) skb_pull(skb, 1); /* Remove PID */ skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (msg->msg_namelen != 0) { struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; ax25_digi digi; ax25_address src; const unsigned char *mac = skb_mac_header(skb); memset(sax, 0, sizeof(struct full_sockaddr_ax25)); ax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL, &digi, NULL, NULL); sax->sax25_family = AF_AX25; /* We set this correctly, even though we may not let the application know the digi calls further down (because it did NOT ask to know them). This could get political... **/ sax->sax25_ndigis = digi.ndigi; sax->sax25_call = src; if (sax->sax25_ndigis != 0) { int ct; struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax; for (ct = 0; ct < digi.ndigi; ct++) fsa->fsa_digipeater[ct] = digi.calls[ct]; } msg->msg_namelen = sizeof(struct full_sockaddr_ax25); } skb_free_datagram(sk, skb); err = copied; out: release_sock(sk); return err; } CWE ID: CWE-20 Target: 1 Example 2: Code: WORD32 ihevcd_set_flush_mode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { codec_t *ps_codec; ivd_ctl_flush_op_t *ps_ctl_op = (ivd_ctl_flush_op_t *)pv_api_op; UNUSED(pv_api_ip); ps_codec = (codec_t *)(ps_codec_obj->pv_codec_handle); /* Signal flush frame control call */ ps_codec->i4_flush_mode = 1; ps_ctl_op->u4_error_code = 0; /* Set pic count to zero, so that decoder starts buffering again */ /* once it comes out of flush mode */ ps_codec->u4_pic_cnt = 0; ps_codec->u4_disp_cnt = 0; return IV_SUCCESS; } CWE ID: CWE-770 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gplotMakeOutput(GPLOT *gplot) { char buf[L_BUF_SIZE]; char *cmdname; l_int32 ignore; PROCNAME("gplotMakeOutput"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); gplotGenCommandFile(gplot); gplotGenDataFiles(gplot); cmdname = genPathname(gplot->cmdname, NULL); #ifndef _WIN32 snprintf(buf, L_BUF_SIZE, "gnuplot %s", cmdname); #else snprintf(buf, L_BUF_SIZE, "wgnuplot %s", cmdname); #endif /* _WIN32 */ #ifndef OS_IOS /* iOS 11 does not support system() */ ignore = system(buf); /* gnuplot || wgnuplot */ #endif /* !OS_IOS */ LEPT_FREE(cmdname); 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: void EnterpriseEnrollmentScreen::RegisterForDevicePolicy( const std::string& token, policy::BrowserPolicyConnector::TokenType token_type) { policy::BrowserPolicyConnector* connector = g_browser_process->browser_policy_connector(); if (!connector->device_cloud_policy_subsystem()) { NOTREACHED() << "Cloud policy subsystem not initialized."; UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentOtherFailed, policy::kMetricEnrollmentSize); if (is_showing_) actor_->ShowFatalEnrollmentError(); return; } connector->ScheduleServiceInitialization(0); registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar( connector->device_cloud_policy_subsystem(), this)); connector->SetDeviceCredentials(user_, token, token_type); } CWE ID: CWE-399 Target: 1 Example 2: Code: IGraphicBufferConsumer::BufferItem::BufferItem() : mTransform(0), mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), mTimestamp(0), mIsAutoTimestamp(false), mFrameNumber(0), mBuf(INVALID_BUFFER_SLOT), mIsDroppable(false), mAcquireCalled(false), mTransformToDisplayInverse(false) { mCrop.makeInvalid(); } 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: static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos, struct page *page) { } 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: PHP_FUNCTION(unserialize) { char *buf = NULL; size_t buf_len; const unsigned char *p; php_unserialize_data_t var_hash; zval *options = NULL, *classes = NULL; HashTable *class_hash = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|a", &buf, &buf_len, &options) == FAILURE) { RETURN_FALSE; } if (buf_len == 0) { RETURN_FALSE; } p = (const unsigned char*) buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if(options != NULL) { classes = zend_hash_str_find(Z_ARRVAL_P(options), "allowed_classes", sizeof("allowed_classes")-1); if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) { ALLOC_HASHTABLE(class_hash); zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0); } if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) { zval *entry; zend_string *lcname; ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) { convert_to_string_ex(entry); lcname = zend_string_tolower(Z_STR_P(entry)); zend_hash_add_empty_element(class_hash, lcname); zend_string_release(lcname); } ZEND_HASH_FOREACH_END(); } } if (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } zval_ptr_dtor(return_value); if (!EG(exception)) { php_error_docref(NULL, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %zd bytes", (zend_long)((char*)p - buf), buf_len); } RETURN_FALSE; } /* We should keep an reference to return_value to prevent it from being dtor in case nesting calls to unserialize */ var_push_dtor(&var_hash, return_value); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (class_hash) { zend_hash_destroy(class_hash); FREE_HASHTABLE(class_hash); } } CWE ID: CWE-416 Target: 1 Example 2: Code: struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int length, gfp_t gfp_mask) { struct sk_buff *skb = NULL; unsigned int fragsz = SKB_DATA_ALIGN(length + NET_SKB_PAD) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); if (fragsz <= PAGE_SIZE && !(gfp_mask & (__GFP_WAIT | GFP_DMA))) { void *data; if (sk_memalloc_socks()) gfp_mask |= __GFP_MEMALLOC; data = __netdev_alloc_frag(fragsz, gfp_mask); if (likely(data)) { skb = build_skb(data, fragsz); if (unlikely(!skb)) put_page(virt_to_head_page(data)); } } else { skb = __alloc_skb(length + NET_SKB_PAD, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE); } if (likely(skb)) { skb_reserve(skb, NET_SKB_PAD); skb->dev = dev; } return skb; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool MockContentSettingsClient::allowImage(bool enabled_per_settings, const blink::WebURL& image_url) { bool allowed = enabled_per_settings && flags_->images_allowed(); if (flags_->dump_web_content_settings_client_callbacks() && delegate_) { delegate_->PrintMessage( std::string("MockContentSettingsClient: allowImage(") + NormalizeLayoutTestURL(image_url.string().utf8()) + "): " + (allowed ? "true" : "false") + "\n"); } return allowed; } 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 ahci_uninit(AHCIState *s) { g_free(s->dev); } CWE ID: CWE-772 Target: 1 Example 2: Code: getContext(XML_Parser parser) { DTD * const dtd = parser->m_dtd; /* save one level of indirection */ HASH_TABLE_ITER iter; XML_Bool needSep = XML_FALSE; if (dtd->defaultPrefix.binding) { int i; int len; if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS))) return NULL; len = dtd->defaultPrefix.binding->uriLen; if (parser->m_namespaceSeparator) len--; for (i = 0; i < len; i++) { if (!poolAppendChar(&parser->m_tempPool, dtd->defaultPrefix.binding->uri[i])) { /* Because of memory caching, I don't believe this line can be * executed. * * This is part of a loop copying the default prefix binding * URI into the parser's temporary string pool. Previously, * that URI was copied into the same string pool, with a * terminating NUL character, as part of setContext(). When * the pool was cleared, that leaves a block definitely big * enough to hold the URI on the free block list of the pool. * The URI copy in getContext() therefore cannot run out of * memory. * * If the pool is used between the setContext() and * getContext() calls, the worst it can do is leave a bigger * block on the front of the free list. Given that this is * all somewhat inobvious and program logic can be changed, we * don't delete the line but we do exclude it from the test * coverage statistics. */ return NULL; /* LCOV_EXCL_LINE */ } } needSep = XML_TRUE; } hashTableIterInit(&iter, &(dtd->prefixes)); for (;;) { int i; int len; const XML_Char *s; PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter); if (!prefix) break; if (!prefix->binding) { /* This test appears to be (justifiable) paranoia. There does * not seem to be a way of injecting a prefix without a binding * that doesn't get errored long before this function is called. * The test should remain for safety's sake, so we instead * exclude the following line from the coverage statistics. */ continue; /* LCOV_EXCL_LINE */ } if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP)) return NULL; for (s = prefix->name; *s; s++) if (!poolAppendChar(&parser->m_tempPool, *s)) return NULL; if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS))) return NULL; len = prefix->binding->uriLen; if (parser->m_namespaceSeparator) len--; for (i = 0; i < len; i++) if (!poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i])) return NULL; needSep = XML_TRUE; } hashTableIterInit(&iter, &(dtd->generalEntities)); for (;;) { const XML_Char *s; ENTITY *e = (ENTITY *)hashTableIterNext(&iter); if (!e) break; if (!e->open) continue; if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP)) return NULL; for (s = e->name; *s; s++) if (!poolAppendChar(&parser->m_tempPool, *s)) return 0; needSep = XML_TRUE; } if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) return NULL; return parser->m_tempPool.start; } CWE ID: CWE-611 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static u32 tg3_calc_dma_bndry(struct tg3 *tp, u32 val) { int cacheline_size; u8 byte; int goal; pci_read_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE, &byte); if (byte == 0) cacheline_size = 1024; else cacheline_size = (int) byte * 4; /* On 5703 and later chips, the boundary bits have no * effect. */ if (tg3_asic_rev(tp) != ASIC_REV_5700 && tg3_asic_rev(tp) != ASIC_REV_5701 && !tg3_flag(tp, PCI_EXPRESS)) goto out; #if defined(CONFIG_PPC64) || defined(CONFIG_IA64) || defined(CONFIG_PARISC) goal = BOUNDARY_MULTI_CACHELINE; #else #if defined(CONFIG_SPARC64) || defined(CONFIG_ALPHA) goal = BOUNDARY_SINGLE_CACHELINE; #else goal = 0; #endif #endif if (tg3_flag(tp, 57765_PLUS)) { val = goal ? 0 : DMA_RWCTRL_DIS_CACHE_ALIGNMENT; goto out; } if (!goal) goto out; /* PCI controllers on most RISC systems tend to disconnect * when a device tries to burst across a cache-line boundary. * Therefore, letting tg3 do so just wastes PCI bandwidth. * * Unfortunately, for PCI-E there are only limited * write-side controls for this, and thus for reads * we will still get the disconnects. We'll also waste * these PCI cycles for both read and write for chips * other than 5700 and 5701 which do not implement the * boundary bits. */ if (tg3_flag(tp, PCIX_MODE) && !tg3_flag(tp, PCI_EXPRESS)) { switch (cacheline_size) { case 16: case 32: case 64: case 128: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_128_PCIX | DMA_RWCTRL_WRITE_BNDRY_128_PCIX); } else { val |= (DMA_RWCTRL_READ_BNDRY_384_PCIX | DMA_RWCTRL_WRITE_BNDRY_384_PCIX); } break; case 256: val |= (DMA_RWCTRL_READ_BNDRY_256_PCIX | DMA_RWCTRL_WRITE_BNDRY_256_PCIX); break; default: val |= (DMA_RWCTRL_READ_BNDRY_384_PCIX | DMA_RWCTRL_WRITE_BNDRY_384_PCIX); break; } } else if (tg3_flag(tp, PCI_EXPRESS)) { switch (cacheline_size) { case 16: case 32: case 64: if (goal == BOUNDARY_SINGLE_CACHELINE) { val &= ~DMA_RWCTRL_WRITE_BNDRY_DISAB_PCIE; val |= DMA_RWCTRL_WRITE_BNDRY_64_PCIE; break; } /* fallthrough */ case 128: default: val &= ~DMA_RWCTRL_WRITE_BNDRY_DISAB_PCIE; val |= DMA_RWCTRL_WRITE_BNDRY_128_PCIE; break; } } else { switch (cacheline_size) { case 16: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_16 | DMA_RWCTRL_WRITE_BNDRY_16); break; } /* fallthrough */ case 32: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_32 | DMA_RWCTRL_WRITE_BNDRY_32); break; } /* fallthrough */ case 64: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_64 | DMA_RWCTRL_WRITE_BNDRY_64); break; } /* fallthrough */ case 128: if (goal == BOUNDARY_SINGLE_CACHELINE) { val |= (DMA_RWCTRL_READ_BNDRY_128 | DMA_RWCTRL_WRITE_BNDRY_128); break; } /* fallthrough */ case 256: val |= (DMA_RWCTRL_READ_BNDRY_256 | DMA_RWCTRL_WRITE_BNDRY_256); break; case 512: val |= (DMA_RWCTRL_READ_BNDRY_512 | DMA_RWCTRL_WRITE_BNDRY_512); break; case 1024: default: val |= (DMA_RWCTRL_READ_BNDRY_1024 | DMA_RWCTRL_WRITE_BNDRY_1024); break; } } out: return val; } 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 ceph_x_decrypt(struct ceph_crypto_key *secret, void **p, void *end, void *obuf, size_t olen) { struct ceph_x_encrypt_header head; size_t head_len = sizeof(head); int len, ret; len = ceph_decode_32(p); if (*p + len > end) return -EINVAL; dout("ceph_x_decrypt len %d\n", len); ret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen, *p, len); if (ret) return ret; if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC) return -EPERM; *p += len; return olen; } CWE ID: CWE-399 Target: 1 Example 2: Code: bool TypingCommand::insertParagraphSeparatorInQuotedContent( Document& document) { if (TypingCommand* lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document.frame())) { EditingState editingState; EventQueueScope eventQueueScope; lastTypingCommand->insertParagraphSeparatorInQuotedContent(&editingState); return !editingState.isAborted(); } return TypingCommand::create(document, InsertParagraphSeparatorInQuotedContent) ->apply(); } 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: xsltParseStylesheetAttributeSet(xsltStylesheetPtr style, xmlNodePtr cur) { const xmlChar *ncname; const xmlChar *prefix; xmlChar *value; xmlNodePtr child; xsltAttrElemPtr attrItems; if ((cur == NULL) || (style == NULL) || (cur->type != XML_ELEMENT_NODE)) return; value = xmlGetNsProp(cur, (const xmlChar *)"name", NULL); if (value == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : name is missing\n"); return; } ncname = xsltSplitQName(style->dict, value, &prefix); xmlFree(value); value = NULL; if (style->attributeSets == NULL) { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "creating attribute set table\n"); #endif style->attributeSets = xmlHashCreate(10); } if (style->attributeSets == NULL) return; attrItems = xmlHashLookup2(style->attributeSets, ncname, prefix); /* * Parse the content. Only xsl:attribute elements are allowed. */ child = cur->children; while (child != NULL) { /* * Report invalid nodes. */ if ((child->type != XML_ELEMENT_NODE) || (child->ns == NULL) || (! IS_XSLT_ELEM(child))) { if (child->type == XML_ELEMENT_NODE) xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child %s\n", child->name); else xsltTransformError(NULL, style, child, "xsl:attribute-set : child of unexpected type\n"); } else if (!IS_XSLT_NAME(child, "attribute")) { xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child xsl:%s\n", child->name); } else { #ifdef XSLT_REFACTORED xsltAttrElemPtr nextAttr, curAttr; /* * Process xsl:attribute * --------------------- */ #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * The following was taken over from * xsltAddAttrElemList(). */ if (attrItems == NULL) { attrItems = xsltNewAttrElem(child); } else { curAttr = attrItems; while (curAttr != NULL) { nextAttr = curAttr->next; if (curAttr->attr == child) { /* * URGENT TODO: Can somebody explain * why attrItems is set to curAttr * here? Is this somehow related to * avoidance of recursions? */ attrItems = curAttr; goto next_child; } if (curAttr->next == NULL) curAttr->next = xsltNewAttrElem(child); curAttr = nextAttr; } } /* * Parse the xsl:attribute and its content. */ xsltParseAnyXSLTElem(XSLT_CCTXT(style), child); #else #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * OLD behaviour: */ attrItems = xsltAddAttrElemList(attrItems, child); #endif } #ifdef XSLT_REFACTORED next_child: #endif child = child->next; } /* * Process attribue "use-attribute-sets". */ /* TODO check recursion */ value = xmlGetNsProp(cur, (const xmlChar *)"use-attribute-sets", NULL); if (value != NULL) { const xmlChar *curval, *endval; curval = value; while (*curval != 0) { while (IS_BLANK(*curval)) curval++; if (*curval == 0) break; endval = curval; while ((*endval != 0) && (!IS_BLANK(*endval))) endval++; curval = xmlDictLookup(style->dict, curval, endval - curval); if (curval) { const xmlChar *ncname2 = NULL; const xmlChar *prefix2 = NULL; xsltAttrElemPtr refAttrItems; #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "xsl:attribute-set : %s adds use %s\n", ncname, curval); #endif ncname2 = xsltSplitQName(style->dict, curval, &prefix2); refAttrItems = xsltNewAttrElem(NULL); if (refAttrItems != NULL) { refAttrItems->set = ncname2; refAttrItems->ns = prefix2; attrItems = xsltMergeAttrElemList(style, attrItems, refAttrItems); xsltFreeAttrElem(refAttrItems); } } curval = endval; } xmlFree(value); value = NULL; } /* * Update the value */ /* * TODO: Why is this dummy entry needed.? */ if (attrItems == NULL) attrItems = xsltNewAttrElem(NULL); xmlHashUpdateEntry2(style->attributeSets, ncname, prefix, attrItems, NULL); #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "updated attribute list %s\n", ncname); #endif } 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: init_ctx_new(OM_uint32 *minor_status, spnego_gss_cred_id_t spcred, gss_ctx_id_t *ctx, send_token_flag *tokflag) { OM_uint32 ret; spnego_gss_ctx_id_t sc = NULL; sc = create_spnego_ctx(); if (sc == NULL) return GSS_S_FAILURE; /* determine negotiation mech set */ ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE, &sc->mech_set); if (ret != GSS_S_COMPLETE) goto cleanup; /* Set an initial internal mech to make the first context token. */ sc->internal_mech = &sc->mech_set->elements[0]; if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) { ret = GSS_S_FAILURE; goto cleanup; } /* * The actual context is not yet determined, set the output * context handle to refer to the spnego context itself. */ sc->ctx_handle = GSS_C_NO_CONTEXT; *ctx = (gss_ctx_id_t)sc; sc = NULL; *tokflag = INIT_TOKEN_SEND; ret = GSS_S_CONTINUE_NEEDED; cleanup: release_spnego_ctx(&sc); return ret; } CWE ID: CWE-18 Target: 1 Example 2: Code: FLAC__StreamDecoderSeekStatus FLACParser::seek_callback( const FLAC__StreamDecoder * /* decoder */, FLAC__uint64 absolute_byte_offset, void *client_data) { return ((FLACParser *) client_data)->seekCallback(absolute_byte_offset); } 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 kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type) { u32 reg = kvm_apic_get_reg(apic, lvt_type); int vector, mode, trig_mode; if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) { vector = reg & APIC_VECTOR_MASK; mode = reg & APIC_MODE_MASK; trig_mode = reg & APIC_LVT_LEVEL_TRIGGER; return __apic_accept_irq(apic, mode, vector, 1, trig_mode, NULL); } return 0; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CompositingLayerPropertyUpdater::Update(const LayoutObject& object) { if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled() || RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) return; if (object.GetDocument().Printing() && !RuntimeEnabledFeatures::PrintBrowserEnabled()) return; if (!object.HasLayer()) return; const auto* paint_layer = ToLayoutBoxModelObject(object).Layer(); const auto* mapping = paint_layer->GetCompositedLayerMapping(); if (!mapping) return; const FragmentData& fragment_data = object.FirstFragment(); DCHECK(fragment_data.HasLocalBorderBoxProperties()); DCHECK(!fragment_data.NextFragment()); LayoutPoint layout_snapped_paint_offset = fragment_data.PaintOffset() - mapping->SubpixelAccumulation(); IntPoint snapped_paint_offset = RoundedIntPoint(layout_snapped_paint_offset); #if 0 bool subpixel_accumulation_may_be_bogus = paint_layer->SubtreeIsInvisible(); DCHECK(layout_snapped_paint_offset == snapped_paint_offset || subpixel_accumulation_may_be_bogus); #endif base::Optional<PropertyTreeState> container_layer_state; auto SetContainerLayerState = [&fragment_data, &snapped_paint_offset, &container_layer_state](GraphicsLayer* graphics_layer) { if (graphics_layer) { if (!container_layer_state) { container_layer_state = fragment_data.LocalBorderBoxProperties(); if (const auto* properties = fragment_data.PaintProperties()) { if (const auto* css_clip = properties->CssClip()) container_layer_state->SetClip(css_clip->Parent()); } } graphics_layer->SetLayerState( *container_layer_state, snapped_paint_offset + graphics_layer->OffsetFromLayoutObject()); } }; SetContainerLayerState(mapping->MainGraphicsLayer()); SetContainerLayerState(mapping->DecorationOutlineLayer()); SetContainerLayerState(mapping->ChildClippingMaskLayer()); base::Optional<PropertyTreeState> scrollbar_layer_state; auto SetContainerLayerStateForScrollbars = [&fragment_data, &snapped_paint_offset, &container_layer_state, &scrollbar_layer_state](GraphicsLayer* graphics_layer) { if (graphics_layer) { if (!scrollbar_layer_state) { if (container_layer_state) { scrollbar_layer_state = container_layer_state; } else { scrollbar_layer_state = fragment_data.LocalBorderBoxProperties(); } if (const auto* properties = fragment_data.PaintProperties()) { if (const auto* clip = properties->OverflowControlsClip()) { scrollbar_layer_state->SetClip(clip); } else if (const auto* css_clip = properties->CssClip()) { scrollbar_layer_state->SetClip(css_clip->Parent()); } } } graphics_layer->SetLayerState( *scrollbar_layer_state, snapped_paint_offset + graphics_layer->OffsetFromLayoutObject()); } }; SetContainerLayerStateForScrollbars(mapping->LayerForHorizontalScrollbar()); SetContainerLayerStateForScrollbars(mapping->LayerForVerticalScrollbar()); SetContainerLayerStateForScrollbars(mapping->LayerForScrollCorner()); if (mapping->ScrollingContentsLayer()) { auto paint_offset = snapped_paint_offset; if (object.IsBox() && object.HasFlippedBlocksWritingMode()) paint_offset.Move(ToLayoutBox(object).VerticalScrollbarWidth(), 0); auto SetContentsLayerState = [&fragment_data, &paint_offset](GraphicsLayer* graphics_layer) { if (graphics_layer) { graphics_layer->SetLayerState( fragment_data.ContentsProperties(), paint_offset + graphics_layer->OffsetFromLayoutObject()); } }; SetContentsLayerState(mapping->ScrollingContentsLayer()); SetContentsLayerState(mapping->ForegroundLayer()); } else { SetContainerLayerState(mapping->ForegroundLayer()); } if (auto* squashing_layer = mapping->SquashingLayer()) { auto state = fragment_data.PreEffectProperties(); const auto* clipping_container = paint_layer->ClippingContainer(); state.SetClip( clipping_container ? clipping_container->FirstFragment().ContentsProperties().Clip() : ClipPaintPropertyNode::Root()); squashing_layer->SetLayerState( state, snapped_paint_offset + mapping->SquashingLayerOffsetFromLayoutObject()); } if (auto* mask_layer = mapping->MaskLayer()) { auto state = fragment_data.LocalBorderBoxProperties(); const auto* properties = fragment_data.PaintProperties(); DCHECK(properties && properties->Mask()); state.SetEffect(properties->Mask()); state.SetClip(properties->MaskClip()); mask_layer->SetLayerState( state, snapped_paint_offset + mask_layer->OffsetFromLayoutObject()); } if (auto* ancestor_clipping_mask_layer = mapping->AncestorClippingMaskLayer()) { PropertyTreeState state( fragment_data.PreTransform(), mapping->ClipInheritanceAncestor() ->GetLayoutObject() .FirstFragment() .PostOverflowClip(), fragment_data.PreFilter()); ancestor_clipping_mask_layer->SetLayerState( state, snapped_paint_offset + ancestor_clipping_mask_layer->OffsetFromLayoutObject()); } if (auto* child_clipping_mask_layer = mapping->ChildClippingMaskLayer()) { PropertyTreeState state = fragment_data.LocalBorderBoxProperties(); state.SetEffect(fragment_data.PreFilter()); child_clipping_mask_layer->SetLayerState( state, snapped_paint_offset + child_clipping_mask_layer->OffsetFromLayoutObject()); } } CWE ID: Target: 1 Example 2: Code: int luaopen_libssh2 (lua_State *L) { lua_settop(L, 0); /* clear the stack */ luaL_newlibtable(L, libssh2); lua_newtable(L); /* ssh2 session metatable */ lua_pushvalue(L, -1); lua_pushcclosure(L, gc, 1); lua_setfield(L, -2, "__gc"); lua_pushvalue(L, -1); lua_pushcclosure(L, filter, 1); lua_setfield(L, -2, "filter"); luaL_setfuncs(L, libssh2, 1); static bool libssh2_initialized = false; if (!libssh2_initialized && (libssh2_init(0) != 0)) luaL_error(L, "unable to open libssh2"); libssh2_initialized = true; return 1; } 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: http_dissect_hdrs(struct worker *w, struct http *hp, int fd, char *p, const struct http_conn *htc) { char *q, *r; txt t = htc->rxbuf; if (*p == '\r') p++; hp->nhd = HTTP_HDR_FIRST; hp->conds = 0; r = NULL; /* For FlexeLint */ for (; p < t.e; p = r) { /* Find end of next header */ q = r = p; while (r < t.e) { if (!vct_iscrlf(*r)) { r++; continue; } q = r; assert(r < t.e); r += vct_skipcrlf(r); if (r >= t.e) break; /* If line does not continue: got it. */ if (!vct_issp(*r)) break; /* Clear line continuation LWS to spaces */ while (vct_islws(*q)) *q++ = ' '; } if (q - p > htc->maxhdr) { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } /* Empty header = end of headers */ if (p == q) break; if ((p[0] == 'i' || p[0] == 'I') && (p[1] == 'f' || p[1] == 'F') && p[2] == '-') hp->conds = 1; while (q > p && vct_issp(q[-1])) q--; *q = '\0'; if (hp->nhd < hp->shd) { hp->hdf[hp->nhd] = 0; hp->hd[hp->nhd].b = p; hp->hd[hp->nhd].e = q; WSLH(w, fd, hp, hp->nhd); hp->nhd++; } else { VSC_C_main->losthdr++; WSL(w, SLT_LostHeader, fd, "%.*s", q - p > 20 ? 20 : q - p, p); return (413); } } return (0); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int send_reply_chunks(struct svcxprt_rdma *xprt, struct rpcrdma_write_array *rp_ary, struct rpcrdma_msg *rdma_resp, struct svc_rqst *rqstp, struct svc_rdma_req_map *vec) { u32 xfer_len = rqstp->rq_res.len; int write_len; u32 xdr_off; int chunk_no; int chunk_off; int nchunks; struct rpcrdma_segment *ch; struct rpcrdma_write_array *res_ary; int ret; /* XXX: need to fix when reply lists occur with read-list and or * write-list */ res_ary = (struct rpcrdma_write_array *) &rdma_resp->rm_body.rm_chunks[2]; /* xdr offset starts at RPC message */ nchunks = be32_to_cpu(rp_ary->wc_nchunks); for (xdr_off = 0, chunk_no = 0; xfer_len && chunk_no < nchunks; chunk_no++) { u64 rs_offset; ch = &rp_ary->wc_array[chunk_no].wc_target; write_len = min(xfer_len, be32_to_cpu(ch->rs_length)); /* Prepare the reply chunk given the length actually * written */ xdr_decode_hyper((__be32 *)&ch->rs_offset, &rs_offset); svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no, ch->rs_handle, ch->rs_offset, write_len); chunk_off = 0; while (write_len) { ret = send_write(xprt, rqstp, be32_to_cpu(ch->rs_handle), rs_offset + chunk_off, xdr_off, write_len, vec); if (ret <= 0) goto out_err; chunk_off += ret; xdr_off += ret; xfer_len -= ret; write_len -= ret; } } /* Update the req with the number of chunks actually used */ svc_rdma_xdr_encode_reply_array(res_ary, chunk_no); return rqstp->rq_res.len; out_err: pr_err("svcrdma: failed to send reply chunks, rc=%d\n", ret); return -EIO; } CWE ID: CWE-404 Target: 1 Example 2: Code: virtual void HandleBadMessage() { } 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 PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) { Resource::LastPluginRefWasDeleted(instance_destroyed); if (instance_destroyed) { loader_.reset(); } } 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 spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; if (intern->file_name) { efree(intern->file_name); } intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } if (intern->_path) { efree(intern->_path); } intern->_path = estrndup(path, intern->_path_len); } /* }}} */ CWE ID: CWE-190 Target: 1 Example 2: Code: static void nfs_commit_clear_lock(struct nfs_inode *nfsi) { clear_bit(NFS_INO_COMMIT, &nfsi->flags); smp_mb__after_clear_bit(); wake_up_bit(&nfsi->flags, NFS_INO_COMMIT); } 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: TT_VecLen( FT_F26Dot6 X, FT_F26Dot6 Y ) { FT_Vector v; v.x = X; v.y = Y; return FT_Vector_Length( &v ); } 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 RenderWidgetHostImpl::SendFrontSurfaceIsProtected( bool is_protected, uint32 protection_state_id, int32 route_id, int gpu_host_id) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) { ui_shim->Send(new AcceleratedSurfaceMsg_SetFrontSurfaceIsProtected( route_id, is_protected, protection_state_id)); } } CWE ID: Target: 1 Example 2: Code: WebContents* WebContents::CreateWithSessionStorage( const WebContents::CreateParams& params, const SessionStorageNamespaceMap& session_storage_namespace_map) { WebContentsImpl* new_contents = new WebContentsImpl(params.browser_context); RenderFrameHostImpl* opener_rfh = FindOpenerRFH(params); FrameTreeNode* opener = nullptr; if (opener_rfh) opener = opener_rfh->frame_tree_node(); new_contents->SetOpenerForNewContents(opener, params.opener_suppressed); for (SessionStorageNamespaceMap::const_iterator it = session_storage_namespace_map.begin(); it != session_storage_namespace_map.end(); ++it) { new_contents->GetController() .SetSessionStorageNamespace(it->first, it->second.get()); } new_contents->Init(params); return new_contents; } 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: OTRBrowserContextImpl::OTRBrowserContextImpl( BrowserContextImpl* original, BrowserContextIODataImpl* original_io_data) : BrowserContext(new OTRBrowserContextIODataImpl(original_io_data)), original_context_(original), weak_ptr_factory_(this) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void impeg2d_dec_pnb_mb_params(dec_state_t *ps_dec) { stream_t *ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_mb_addr_incr; UWORD16 u2_total_len; UWORD16 u2_len; UWORD16 u2_mb_type; UWORD32 u4_next_word; const dec_mb_params_t *ps_dec_mb_params; if(impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,1); } else { u2_mb_addr_incr = impeg2d_get_mb_addr_incr(ps_stream); if(ps_dec->u2_first_mb) { /****************************************************************/ /* Section 6.3.17 */ /* The first MB of a slice cannot be skipped */ /* But the mb_addr_incr can be > 1, because at the beginning of */ /* a slice, it indicates the offset from the last MB in the */ /* previous row. Hence for the first slice in a row, the */ /* mb_addr_incr needs to be 1. */ /****************************************************************/ /* MB_x is set to zero whenever MB_y changes. */ ps_dec->u2_mb_x = u2_mb_addr_incr - 1; /* For error resilience */ ps_dec->u2_mb_x = MIN(ps_dec->u2_mb_x, (ps_dec->u2_num_horiz_mb - 1)); /****************************************************************/ /* mb_addr_incr is forced to 1 because in this decoder it is used */ /* more as an indicator of the number of MBs skipped than the */ /* as defined by the standard (Section 6.3.17) */ /****************************************************************/ u2_mb_addr_incr = 1; ps_dec->u2_first_mb = 0; } else { /****************************************************************/ /* In MPEG-2, the last MB of the row cannot be skipped and the */ /* mb_addr_incr cannot be such that it will take the current MB */ /* beyond the current row */ /* In MPEG-1, the slice could start and end anywhere and is not */ /* restricted to a row like in MPEG-2. Hence this check should */ /* not be done for MPEG-1 streams. */ /****************************************************************/ if(ps_dec->u2_is_mpeg2 && ((ps_dec->u2_mb_x + u2_mb_addr_incr) > ps_dec->u2_num_horiz_mb)) { u2_mb_addr_incr = ps_dec->u2_num_horiz_mb - ps_dec->u2_mb_x; } impeg2d_dec_skip_mbs(ps_dec, (UWORD16)(u2_mb_addr_incr - 1)); } } u4_next_word = (UWORD16)impeg2d_bit_stream_nxt(ps_stream,16); /*-----------------------------------------------------------------------*/ /* MB type */ /*-----------------------------------------------------------------------*/ { u2_mb_type = ps_dec->pu2_mb_type[BITS((UWORD16)u4_next_word,15,10)]; u2_len = BITS(u2_mb_type,15,8); u2_total_len = u2_len; u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << u2_len); } /*-----------------------------------------------------------------------*/ /* motion type */ /*-----------------------------------------------------------------------*/ { WORD32 i4_motion_type = ps_dec->u2_motion_type; if((u2_mb_type & MB_FORW_OR_BACK) && ps_dec->u2_read_motion_type) { ps_dec->u2_motion_type = BITS((UWORD16)u4_next_word,15,14); u2_total_len += MB_MOTION_TYPE_LEN; u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << MB_MOTION_TYPE_LEN); i4_motion_type = ps_dec->u2_motion_type; } if ((u2_mb_type & MB_FORW_OR_BACK) && ((i4_motion_type == 0) || (i4_motion_type == 3) || (i4_motion_type == 4) || (i4_motion_type >= 7))) { i4_motion_type = 1; } } /*-----------------------------------------------------------------------*/ /* dct type */ /*-----------------------------------------------------------------------*/ { if((u2_mb_type & MB_CODED) && ps_dec->u2_read_dct_type) { ps_dec->u2_field_dct = BIT((UWORD16)u4_next_word,15); u2_total_len += MB_DCT_TYPE_LEN; u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << MB_DCT_TYPE_LEN); } } /*-----------------------------------------------------------------------*/ /* Quant scale code */ /*-----------------------------------------------------------------------*/ if(u2_mb_type & MB_QUANT) { UWORD16 u2_quant_scale_code; u2_quant_scale_code = BITS((UWORD16)u4_next_word,15,11); ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); u2_total_len += MB_QUANT_SCALE_CODE_LEN; } impeg2d_bit_stream_flush(ps_stream,u2_total_len); /*-----------------------------------------------------------------------*/ /* Set the function pointers */ /*-----------------------------------------------------------------------*/ ps_dec->u2_coded_mb = (UWORD16)(u2_mb_type & MB_CODED); if(u2_mb_type & MB_BIDRECT) { UWORD16 u2_index = (ps_dec->u2_motion_type); ps_dec->u2_prev_intra_mb = 0; ps_dec->e_mb_pred = BIDIRECT; ps_dec_mb_params = &ps_dec->ps_func_bi_direct[u2_index]; ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; ps_dec_mb_params->pf_func_mb_params(ps_dec); } else if(u2_mb_type & MB_FORW_OR_BACK) { UWORD16 u2_refPic = !(u2_mb_type & MB_MV_FORW); UWORD16 u2_index = (ps_dec->u2_motion_type); ps_dec->u2_prev_intra_mb = 0; ps_dec->e_mb_pred = (e_pred_direction_t)u2_refPic; ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[u2_index]; ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; ps_dec_mb_params->pf_func_mb_params(ps_dec); } else if(u2_mb_type & MB_TYPE_INTRA) { ps_dec->u2_prev_intra_mb = 1; impeg2d_dec_intra_mb(ps_dec); } else { ps_dec->u2_prev_intra_mb =0; ps_dec->e_mb_pred = FORW; ps_dec->u2_motion_type = 0; impeg2d_dec_0mv_coded_mb(ps_dec); } /*-----------------------------------------------------------------------*/ /* decode cbp */ /*-----------------------------------------------------------------------*/ if((u2_mb_type & MB_TYPE_INTRA)) { ps_dec->u2_cbp = 0x3f; ps_dec->u2_prev_intra_mb = 1; } else { ps_dec->u2_prev_intra_mb = 0; ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; if((ps_dec->u2_coded_mb)) { UWORD16 cbpValue; cbpValue = gau2_impeg2d_cbp_code[impeg2d_bit_stream_nxt(ps_stream,MB_CBP_LEN)]; ps_dec->u2_cbp = cbpValue & 0xFF; impeg2d_bit_stream_flush(ps_stream,(cbpValue >> 8) & 0x0FF); } else { ps_dec->u2_cbp = 0; } } } CWE ID: CWE-119 Target: 1 Example 2: Code: juniper_es_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ipsec_header { uint8_t sa_index[2]; uint8_t ttl; uint8_t type; uint8_t spi[4]; uint8_t src_ip[4]; uint8_t dst_ip[4]; }; u_int rewrite_len,es_type_bundle; const struct juniper_ipsec_header *ih; l2info.pictype = DLT_JUNIPER_ES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ih = (const struct juniper_ipsec_header *)p; switch (ih->type) { case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE: rewrite_len = 0; es_type_bundle = 1; break; case JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE: rewrite_len = 16; es_type_bundle = 0; break; default: ND_PRINT((ndo, "ES Invalid type %u, length %u", ih->type, l2info.length)); return l2info.header_len; } l2info.length-=rewrite_len; p+=rewrite_len; if (ndo->ndo_eflag) { if (!es_type_bundle) { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), spi %u, Tunnel %s > %s, length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, EXTRACT_32BITS(&ih->spi), ipaddr_string(ndo, &ih->src_ip), ipaddr_string(ndo, &ih->dst_ip), l2info.length)); } else { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, l2info.length)); } } ip_print(ndo, p, l2info.length); return l2info.header_len; } 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: horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { ip += n - 1; /* point to last one */ wp += n - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) } } } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int kvm_ioctl_create_device(struct kvm *kvm, struct kvm_create_device *cd) { struct kvm_device_ops *ops = NULL; struct kvm_device *dev; bool test = cd->flags & KVM_CREATE_DEVICE_TEST; int ret; if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) return -ENODEV; ops = kvm_device_ops_table[cd->type]; if (ops == NULL) return -ENODEV; if (test) return 0; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->ops = ops; dev->kvm = kvm; mutex_lock(&kvm->lock); ret = ops->create(dev, cd->type); if (ret < 0) { mutex_unlock(&kvm->lock); kfree(dev); return ret; } list_add(&dev->vm_node, &kvm->devices); mutex_unlock(&kvm->lock); if (ops->init) ops->init(dev); ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); if (ret < 0) { mutex_lock(&kvm->lock); list_del(&dev->vm_node); mutex_unlock(&kvm->lock); ops->destroy(dev); return ret; } kvm_get_kvm(kvm); cd->fd = ret; return 0; } CWE ID: CWE-362 Target: 1 Example 2: Code: DefragTracker *DefragLookupTrackerFromHash (Packet *p) { DefragTracker *dt = NULL; /* get the key to our bucket */ uint32_t key = DefragHashGetKey(p); /* get our hash bucket and lock it */ DefragTrackerHashRow *hb = &defragtracker_hash[key]; DRLOCK_LOCK(hb); /* see if the bucket already has a tracker */ if (hb->head == NULL) { DRLOCK_UNLOCK(hb); return dt; } /* ok, we have a tracker in the bucket. Let's find out if it is our tracker */ dt = hb->head; /* see if this is the tracker we are looking for */ if (DefragTrackerCompare(dt, p) == 0) { while (dt) { dt = dt->hnext; if (dt == NULL) { DRLOCK_UNLOCK(hb); return dt; } if (DefragTrackerCompare(dt, p) != 0) { /* we found our tracker, lets put it on top of the * hash list -- this rewards active tracker */ if (dt->hnext) { dt->hnext->hprev = dt->hprev; } if (dt->hprev) { dt->hprev->hnext = dt->hnext; } if (dt == hb->tail) { hb->tail = dt->hprev; } dt->hnext = hb->head; dt->hprev = NULL; hb->head->hprev = dt; hb->head = dt; /* found our tracker, lock & return */ SCMutexLock(&dt->lock); (void) DefragTrackerIncrUsecnt(dt); DRLOCK_UNLOCK(hb); return dt; } } } /* lock & return */ SCMutexLock(&dt->lock); (void) DefragTrackerIncrUsecnt(dt); DRLOCK_UNLOCK(hb); return dt; } CWE ID: CWE-358 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 JSTestEventTargetConstructor::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor<JSTestEventTargetConstructor, JSDOMWrapper>(exec, &JSTestEventTargetConstructorTable, jsCast<JSTestEventTargetConstructor*>(object), propertyName, descriptor); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DXVAVideoDecodeAccelerator::DXVAVideoDecodeAccelerator( media::VideoDecodeAccelerator::Client* client, base::ProcessHandle renderer_process) : client_(client), egl_config_(NULL), state_(kUninitialized), pictures_requested_(false), renderer_process_(renderer_process), last_input_buffer_id_(-1), inputs_before_decode_(0) { memset(&input_stream_info_, 0, sizeof(input_stream_info_)); memset(&output_stream_info_, 0, sizeof(output_stream_info_)); } CWE ID: Target: 1 Example 2: Code: int sock_no_getname(struct socket *sock, struct sockaddr *saddr, int *len, int peer) { return -EOPNOTSUPP; } 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: CastStreamingNativeHandler::CastStreamingNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context), last_transport_id_(1), weak_factory_(this) { RouteFunction("CreateSession", base::Bind(&CastStreamingNativeHandler::CreateCastSession, weak_factory_.GetWeakPtr())); RouteFunction("DestroyCastRtpStream", base::Bind(&CastStreamingNativeHandler::DestroyCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction( "GetSupportedParamsCastRtpStream", base::Bind(&CastStreamingNativeHandler::GetSupportedParamsCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("StartCastRtpStream", base::Bind(&CastStreamingNativeHandler::StartCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("StopCastRtpStream", base::Bind(&CastStreamingNativeHandler::StopCastRtpStream, weak_factory_.GetWeakPtr())); RouteFunction("DestroyCastUdpTransport", base::Bind(&CastStreamingNativeHandler::DestroyCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction( "SetDestinationCastUdpTransport", base::Bind(&CastStreamingNativeHandler::SetDestinationCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction( "SetOptionsCastUdpTransport", base::Bind(&CastStreamingNativeHandler::SetOptionsCastUdpTransport, weak_factory_.GetWeakPtr())); RouteFunction("ToggleLogging", base::Bind(&CastStreamingNativeHandler::ToggleLogging, weak_factory_.GetWeakPtr())); RouteFunction("GetRawEvents", base::Bind(&CastStreamingNativeHandler::GetRawEvents, weak_factory_.GetWeakPtr())); RouteFunction("GetStats", base::Bind(&CastStreamingNativeHandler::GetStats, weak_factory_.GetWeakPtr())); RouteFunction("StartCastRtpReceiver", base::Bind(&CastStreamingNativeHandler::StartCastRtpReceiver, weak_factory_.GetWeakPtr())); } 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 qeth_snmp_command(struct qeth_card *card, char __user *udata) { struct qeth_cmd_buffer *iob; struct qeth_ipa_cmd *cmd; struct qeth_snmp_ureq *ureq; int req_len; struct qeth_arp_query_info qinfo = {0, }; int rc = 0; QETH_CARD_TEXT(card, 3, "snmpcmd"); if (card->info.guestlan) return -EOPNOTSUPP; if ((!qeth_adp_supported(card, IPA_SETADP_SET_SNMP_CONTROL)) && (!card->options.layer2)) { return -EOPNOTSUPP; } /* skip 4 bytes (data_len struct member) to get req_len */ if (copy_from_user(&req_len, udata + sizeof(int), sizeof(int))) return -EFAULT; ureq = memdup_user(udata, req_len + sizeof(struct qeth_snmp_ureq_hdr)); if (IS_ERR(ureq)) { QETH_CARD_TEXT(card, 2, "snmpnome"); return PTR_ERR(ureq); } qinfo.udata_len = ureq->hdr.data_len; qinfo.udata = kzalloc(qinfo.udata_len, GFP_KERNEL); if (!qinfo.udata) { kfree(ureq); return -ENOMEM; } qinfo.udata_offset = sizeof(struct qeth_snmp_ureq_hdr); iob = qeth_get_adapter_cmd(card, IPA_SETADP_SET_SNMP_CONTROL, QETH_SNMP_SETADP_CMDLENGTH + req_len); cmd = (struct qeth_ipa_cmd *)(iob->data+IPA_PDU_HEADER_SIZE); memcpy(&cmd->data.setadapterparms.data.snmp, &ureq->cmd, req_len); rc = qeth_send_ipa_snmp_cmd(card, iob, QETH_SETADP_BASE_LEN + req_len, qeth_snmp_command_cb, (void *)&qinfo); if (rc) QETH_DBF_MESSAGE(2, "SNMP command failed on %s: (0x%x)\n", QETH_CARD_IFNAME(card), rc); else { if (copy_to_user(udata, qinfo.udata, qinfo.udata_len)) rc = -EFAULT; } kfree(ureq); kfree(qinfo.udata); return rc; } CWE ID: CWE-119 Target: 1 Example 2: Code: void PaintLayerScrollableArea::Resize(const IntPoint& pos, const LayoutSize& old_offset) { if (!InResizeMode() || !GetLayoutBox()->CanResize() || !GetLayoutBox()->GetNode()) return; DCHECK(GetLayoutBox()->GetNode()->IsElementNode()); Element* element = ToElement(GetLayoutBox()->GetNode()); Document& document = element->GetDocument(); float zoom_factor = GetLayoutBox()->StyleRef().EffectiveZoom(); IntSize new_offset = OffsetFromResizeCorner(document.View()->ConvertFromRootFrame(pos)); new_offset.SetWidth(new_offset.Width() / zoom_factor); new_offset.SetHeight(new_offset.Height() / zoom_factor); LayoutSize current_size = GetLayoutBox()->Size(); current_size.Scale(1 / zoom_factor); LayoutSize adjusted_old_offset = LayoutSize( old_offset.Width() / zoom_factor, old_offset.Height() / zoom_factor); if (GetLayoutBox()->ShouldPlaceBlockDirectionScrollbarOnLogicalLeft()) { new_offset.SetWidth(-new_offset.Width()); adjusted_old_offset.SetWidth(-adjusted_old_offset.Width()); } LayoutSize difference((current_size + new_offset - adjusted_old_offset) .ExpandedTo(MinimumSizeForResizing(zoom_factor)) - current_size); bool is_box_sizing_border = GetLayoutBox()->StyleRef().BoxSizing() == EBoxSizing::kBorderBox; EResize resize = ResolvedResize(GetLayoutBox()->StyleRef(), GetLayoutBox()->ContainingBlock()->StyleRef()); if (resize != EResize::kVertical && difference.Width()) { if (element->IsFormControlElement()) { element->SetInlineStyleProperty( CSSPropertyMarginLeft, GetLayoutBox()->MarginLeft() / zoom_factor, CSSPrimitiveValue::UnitType::kPixels); element->SetInlineStyleProperty( CSSPropertyMarginRight, GetLayoutBox()->MarginRight() / zoom_factor, CSSPrimitiveValue::UnitType::kPixels); } LayoutUnit base_width = GetLayoutBox()->Size().Width() - (is_box_sizing_border ? LayoutUnit() : GetLayoutBox()->BorderAndPaddingWidth()); base_width = LayoutUnit(base_width / zoom_factor); element->SetInlineStyleProperty(CSSPropertyWidth, RoundToInt(base_width + difference.Width()), CSSPrimitiveValue::UnitType::kPixels); } if (resize != EResize::kHorizontal && difference.Height()) { if (element->IsFormControlElement()) { element->SetInlineStyleProperty(CSSPropertyMarginTop, GetLayoutBox()->MarginTop() / zoom_factor, CSSPrimitiveValue::UnitType::kPixels); element->SetInlineStyleProperty( CSSPropertyMarginBottom, GetLayoutBox()->MarginBottom() / zoom_factor, CSSPrimitiveValue::UnitType::kPixels); } LayoutUnit base_height = GetLayoutBox()->Size().Height() - (is_box_sizing_border ? LayoutUnit() : GetLayoutBox()->BorderAndPaddingHeight()); base_height = LayoutUnit(base_height / zoom_factor); element->SetInlineStyleProperty( CSSPropertyHeight, RoundToInt(base_height + difference.Height()), CSSPrimitiveValue::UnitType::kPixels); } document.UpdateStyleAndLayout(); } CWE ID: CWE-79 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: compile_length_bag_node(BagNode* node, regex_t* reg) { int len; int tlen; if (node->type == BAG_OPTION) return compile_length_option_node(node, reg); if (NODE_BAG_BODY(node)) { tlen = compile_length_tree(NODE_BAG_BODY(node), reg); if (tlen < 0) return tlen; } else tlen = 0; switch (node->type) { case BAG_MEMORY: #ifdef USE_CALL if (node->m.regnum == 0 && NODE_IS_CALLED(node)) { len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; return len; } if (NODE_IS_CALLED(node)) { len = SIZE_OP_MEMORY_START_PUSH + tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH); else len += (NODE_IS_RECURSION(node) ? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END); } else if (NODE_IS_RECURSION(node)) { len = SIZE_OP_MEMORY_START_PUSH; len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC); } else #endif { if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum)) len = SIZE_OP_MEMORY_START_PUSH; else len = SIZE_OP_MEMORY_START; len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) ? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END); } break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { int v; QuantNode* qn; qn = QUANT_(NODE_BAG_BODY(node)); tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (tlen < 0) return tlen; v = onig_positive_int_multiply(qn->lower, tlen); if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP; } else { len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END; } break; case BAG_IF_ELSE: { Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; len = compile_length_tree(cond, reg); if (len < 0) return len; len += SIZE_OP_PUSH; len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END; if (IS_NOT_NULL(Then)) { tlen = compile_length_tree(Then, reg); if (tlen < 0) return tlen; len += tlen; } if (IS_NOT_NULL(Else)) { len += SIZE_OP_JUMP; tlen = compile_length_tree(Else, reg); if (tlen < 0) return tlen; len += tlen; } } break; case BAG_OPTION: /* never come here, but set for escape warning */ len = 0; break; } return len; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: fb_mmap(struct file *file, struct vm_area_struct * vma) { struct fb_info *info = file_fb_info(file); struct fb_ops *fb; unsigned long off; unsigned long start; u32 len; if (!info) return -ENODEV; if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) return -EINVAL; off = vma->vm_pgoff << PAGE_SHIFT; fb = info->fbops; if (!fb) return -ENODEV; mutex_lock(&info->mm_lock); if (fb->fb_mmap) { int res; res = fb->fb_mmap(info, vma); mutex_unlock(&info->mm_lock); return res; } /* frame buffer memory */ start = info->fix.smem_start; len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.smem_len); if (off >= len) { /* memory mapped io */ off -= len; if (info->var.accel_flags) { mutex_unlock(&info->mm_lock); return -EINVAL; } start = info->fix.mmio_start; len = PAGE_ALIGN((start & ~PAGE_MASK) + info->fix.mmio_len); } mutex_unlock(&info->mm_lock); start &= PAGE_MASK; if ((vma->vm_end - vma->vm_start + off) > len) return -EINVAL; off += start; vma->vm_pgoff = off >> PAGE_SHIFT; /* VM_IO | VM_DONTEXPAND | VM_DONTDUMP are set by io_remap_pfn_range()*/ vma->vm_page_prot = vm_get_page_prot(vma->vm_flags); fb_pgprotect(file, vma, off); if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot)) return -EAGAIN; return 0; } CWE ID: CWE-189 Target: 1 Example 2: Code: GF_Err subs_Size(GF_Box *s) { GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *) s; GF_SubSampleInfoEntry *pSamp; u32 entry_count, i; u16 subsample_count; ptr->size += 4; entry_count = gf_list_count(ptr->Samples); for (i=0; i<entry_count; i++) { pSamp = (GF_SubSampleInfoEntry*) gf_list_get(ptr->Samples, i); subsample_count = gf_list_count(pSamp->SubSamples); ptr->size += 4 + 2 + subsample_count * (6 + (ptr->version==1 ? 4 : 2)); } return GF_OK; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static char *cm_devnode(struct device *dev, umode_t *mode) { if (mode) *mode = 0666; return kasprintf(GFP_KERNEL, "infiniband/%s", dev_name(dev)); } 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 DataReductionProxyConfigServiceClient::RetrieveRemoteConfig() { DCHECK(thread_checker_.CalledOnValidThread()); CreateClientConfigRequest request; std::string serialized_request; #if defined(OS_ANDROID) request.set_telephony_network_operator( net::android::GetTelephonyNetworkOperator()); #endif data_reduction_proxy::ConfigDeviceInfo* device_info = request.mutable_device_info(); device_info->set_total_device_memory_kb( base::SysInfo::AmountOfPhysicalMemory() / 1024); const std::string& session_key = request_options_->GetSecureSession(); if (!session_key.empty()) request.set_session_key(request_options_->GetSecureSession()); request.set_dogfood_group( base::FeatureList::IsEnabled(features::kDogfood) ? CreateClientConfigRequest_DogfoodGroup_DOGFOOD : CreateClientConfigRequest_DogfoodGroup_NONDOGFOOD); data_reduction_proxy::VersionInfo* version_info = request.mutable_version_info(); uint32_t build; uint32_t patch; util::GetChromiumBuildAndPatchAsInts(util::ChromiumVersion(), &build, &patch); version_info->set_client(util::GetStringForClient(io_data_->client())); version_info->set_build(build); version_info->set_patch(patch); version_info->set_channel(io_data_->channel()); request.SerializeToString(&serialized_request); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("data_reduction_proxy_config", R"( semantics { sender: "Data Reduction Proxy" description: "Requests a configuration that specifies how to connect to the " "data reduction proxy." trigger: "Requested when Data Saver is enabled and the browser does not " "have a configuration that is not older than a threshold set by " "the server." data: "None." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via 'Data Saver' setting. " "Data Saver is not available on iOS, and on desktop it is enabled " "by insalling the Data Saver extension." policy_exception_justification: "Not implemented." })"); fetch_in_progress_ = true; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = config_service_url_; resource_request->method = "POST"; resource_request->load_flags = net::LOAD_BYPASS_PROXY; resource_request->allow_credentials = false; url_loader_ = variations::CreateSimpleURLLoaderWithVariationsHeader( std::move(resource_request), variations::InIncognito::kNo, variations::SignedIn::kNo, traffic_annotation); url_loader_->AttachStringForUpload(serialized_request, "application/x-protobuf"); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( url_loader_factory_.get(), base::BindOnce(&DataReductionProxyConfigServiceClient::OnURLLoadComplete, base::Unretained(this))); } CWE ID: CWE-416 Target: 1 Example 2: Code: void SetupTest() { GURL test_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(a)")); EXPECT_TRUE(NavigateToURL(shell(), test_url)); frame_observer_ = std::make_unique<RenderFrameSubmissionObserver>( shell()->web_contents()); FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree() ->root(); EXPECT_EQ( " Site A\n" " +--Site A\n" "Where A = http://a.com/", FrameTreeVisualizer().DepictFrameTree(root)); TestNavigationObserver observer(shell()->web_contents()); EXPECT_EQ(1u, root->child_count()); child_frame_tree_node_ = root->child_at(0); root_rwhv_ = static_cast<RenderWidgetHostViewAndroid*>( root->current_frame_host()->GetRenderWidgetHost()->GetView()); selection_controller_client_ = new TouchSelectionControllerClientTestWrapper( root_rwhv_->GetSelectionControllerClientManagerForTesting()); root_rwhv_->SetSelectionControllerClientForTesting( base::WrapUnique(selection_controller_client_)); GURL child_url( embedded_test_server()->GetURL("b.com", "/touch_selection.html")); NavigateFrameToURL(child_frame_tree_node_, child_url); EXPECT_EQ( " Site A ------------ proxies for B\n" " +--Site B ------- proxies for A\n" "Where A = http://a.com/\n" " B = http://b.com/", FrameTreeVisualizer().DepictFrameTree(root)); child_frame_tree_node_ = root->child_at(0); WaitForHitTestDataOrChildSurfaceReady( child_frame_tree_node_->current_frame_host()); child_rwhv_ = static_cast<RenderWidgetHostViewChildFrame*>( child_frame_tree_node_->current_frame_host() ->GetRenderWidgetHost() ->GetView()); EXPECT_EQ(child_url, observer.last_navigation_url()); EXPECT_TRUE(observer.last_navigation_succeeded()); FrameStableObserver child_frame_stable_observer( child_rwhv_, TestTimeouts::tiny_timeout()); child_frame_stable_observer.WaitUntilStable(); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BuildObjectForResourceRequest(const ResourceRequest& request) { std::unique_ptr<protocol::Network::Request> request_object = protocol::Network::Request::create() .setUrl(UrlWithoutFragment(request.Url()).GetString()) .setMethod(request.HttpMethod()) .setHeaders(BuildObjectForHeaders(request.HttpHeaderFields())) .setInitialPriority(ResourcePriorityJSON(request.Priority())) .setReferrerPolicy(GetReferrerPolicy(request.GetReferrerPolicy())) .build(); if (request.HttpBody() && !request.HttpBody()->IsEmpty()) { Vector<char> bytes; request.HttpBody()->Flatten(bytes); request_object->setPostData( String::FromUTF8WithLatin1Fallback(bytes.data(), bytes.size())); } return request_object; } 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 const char *lua_authz_parse(cmd_parms *cmd, const char *require_line, const void **parsed_require_line) { const char *provider_name; lua_authz_provider_spec *spec; apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE, cmd->temp_pool); ap_assert(provider_name != NULL); spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING); ap_assert(spec != NULL); if (require_line && *require_line) { const char *arg; spec->args = apr_array_make(cmd->pool, 2, sizeof(const char *)); while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) { APR_ARRAY_PUSH(spec->args, const char *) = arg; } } *parsed_require_line = spec; return NULL; } CWE ID: CWE-264 Target: 1 Example 2: Code: set_local_file (const char **file, const char *default_file) { if (opt.output_document) { if (output_stream_regular) *file = opt.output_document; } else *file = default_file; } 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: varbit_in(PG_FUNCTION_ARGS) { char *input_string = PG_GETARG_CSTRING(0); #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif int32 atttypmod = PG_GETARG_INT32(2); VarBit *result; /* The resulting bit string */ char *sp; /* pointer into the character string */ bits8 *r; /* pointer into the result */ int len, /* Length of the whole data structure */ bitlen, /* Number of bits in the bit string */ slen; /* Length of the input string */ bool bit_not_hex; /* false = hex string true = bit string */ int bc; bits8 x = 0; /* Check that the first character is a b or an x */ if (input_string[0] == 'b' || input_string[0] == 'B') { bit_not_hex = true; sp = input_string + 1; } else if (input_string[0] == 'x' || input_string[0] == 'X') { bit_not_hex = false; sp = input_string + 1; } else { bit_not_hex = true; sp = input_string; } slen = strlen(sp); /* Determine bitlength from input string */ if (bit_not_hex) bitlen = slen; else bitlen = slen * 4; /* * Sometimes atttypmod is not supplied. If it is supplied we need to make * sure that the bitstring fits. */ if (atttypmod <= 0) atttypmod = bitlen; else if (bitlen > atttypmod) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION), errmsg("bit string too long for type bit varying(%d)", atttypmod))); len = VARBITTOTALLEN(bitlen); /* set to 0 so that *r is always initialised and string is zero-padded */ result = (VarBit *) palloc0(len); SET_VARSIZE(result, len); VARBITLEN(result) = Min(bitlen, atttypmod); r = VARBITS(result); if (bit_not_hex) { /* Parse the bit representation of the string */ /* We know it fits, as bitlen was compared to atttypmod */ x = HIGHBIT; for (; *sp; sp++) { if (*sp == '1') *r |= x; else if (*sp != '0') ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("\"%c\" is not a valid binary digit", *sp))); x >>= 1; if (x == 0) { x = HIGHBIT; r++; } } } else { /* Parse the hex representation of the string */ for (bc = 0; *sp; sp++) { if (*sp >= '0' && *sp <= '9') x = (bits8) (*sp - '0'); else if (*sp >= 'A' && *sp <= 'F') x = (bits8) (*sp - 'A') + 10; else if (*sp >= 'a' && *sp <= 'f') x = (bits8) (*sp - 'a') + 10; else ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("\"%c\" is not a valid hexadecimal digit", *sp))); if (bc) { *r++ |= x; bc = 0; } else { *r = x << 4; bc = 1; } } } PG_RETURN_VARBIT_P(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: T42_Open_Face( T42_Face face ) { T42_LoaderRec loader; T42_Parser parser; T1_Font type1 = &face->type1; FT_Memory memory = face->root.memory; FT_Error error; PSAux_Service psaux = (PSAux_Service)face->psaux; t42_loader_init( &loader, face ); parser = &loader.parser; if ( FT_ALLOC( face->ttf_data, 12 ) ) goto Exit; error = t42_parser_init( parser, face->root.stream, memory, if ( error ) goto Exit; if ( type1->font_type != 42 ) { FT_ERROR(( "T42_Open_Face: cannot handle FontType %d\n", type1->font_type )); error = FT_THROW( Unknown_File_Format ); goto Exit; } /* now, propagate the charstrings and glyphnames tables */ /* to the Type1 data */ type1->num_glyphs = loader.num_glyphs; if ( !loader.charstrings.init ) { FT_ERROR(( "T42_Open_Face: no charstrings array in face\n" )); error = FT_THROW( Invalid_File_Format ); } loader.charstrings.init = 0; type1->charstrings_block = loader.charstrings.block; type1->charstrings = loader.charstrings.elements; type1->charstrings_len = loader.charstrings.lengths; /* we copy the glyph names `block' and `elements' fields; */ /* the `lengths' field must be released later */ type1->glyph_names_block = loader.glyph_names.block; type1->glyph_names = (FT_String**)loader.glyph_names.elements; loader.glyph_names.block = 0; loader.glyph_names.elements = 0; /* we must now build type1.encoding when we have a custom array */ if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY ) { FT_Int charcode, idx, min_char, max_char; FT_Byte* glyph_name; /* OK, we do the following: for each element in the encoding */ /* table, look up the index of the glyph having the same name */ /* as defined in the CharStrings array. */ /* The index is then stored in type1.encoding.char_index, and */ /* the name in type1.encoding.char_name */ min_char = 0; max_char = 0; charcode = 0; for ( ; charcode < loader.encoding_table.max_elems; charcode++ ) { FT_Byte* char_name; type1->encoding.char_index[charcode] = 0; type1->encoding.char_name [charcode] = (char *)".notdef"; char_name = loader.encoding_table.elements[charcode]; if ( char_name ) for ( idx = 0; idx < type1->num_glyphs; idx++ ) { glyph_name = (FT_Byte*)type1->glyph_names[idx]; if ( ft_strcmp( (const char*)char_name, (const char*)glyph_name ) == 0 ) { type1->encoding.char_index[charcode] = (FT_UShort)idx; type1->encoding.char_name [charcode] = (char*)glyph_name; /* Change min/max encoded char only if glyph name is */ /* not /.notdef */ if ( ft_strcmp( (const char*)".notdef", (const char*)glyph_name ) != 0 ) { if ( charcode < min_char ) min_char = charcode; if ( charcode >= max_char ) max_char = charcode + 1; } break; } } } type1->encoding.code_first = min_char; type1->encoding.code_last = max_char; type1->encoding.num_chars = loader.num_chars; } Exit: t42_loader_done( &loader ); return error; } CWE ID: Target: 1 Example 2: Code: scoped_refptr<extensions::Extension> MakeApp(const std::string& name, const std::string& version, const std::string& url, const std::string& id) { std::string err; base::DictionaryValue value; value.SetString("name", name); value.SetString("version", version); value.SetString("app.launch.web_url", url); scoped_refptr<extensions::Extension> app = extensions::Extension::Create( base::FilePath(), extensions::Manifest::INTERNAL, value, extensions::Extension::WAS_INSTALLED_BY_DEFAULT, id, &err); EXPECT_EQ(err, ""); return app; } 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: num_entries(char *bufstart, char *end_of_buf, char **lastentry, size_t size) { int len; unsigned int entrycount = 0; unsigned int next_offset = 0; FILE_DIRECTORY_INFO *entryptr; if (bufstart == NULL) return 0; entryptr = (FILE_DIRECTORY_INFO *)bufstart; while (1) { entryptr = (FILE_DIRECTORY_INFO *) ((char *)entryptr + next_offset); if ((char *)entryptr + size > end_of_buf) { cifs_dbg(VFS, "malformed search entry would overflow\n"); break; } len = le32_to_cpu(entryptr->FileNameLength); if ((char *)entryptr + len + size > end_of_buf) { cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n", end_of_buf); break; } *lastentry = (char *)entryptr; entrycount++; next_offset = le32_to_cpu(entryptr->NextEntryOffset); if (!next_offset) break; } return entrycount; } 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: setv4key_principal_2_svc(setv4key_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setv4key_principal((void *)handle, arg->princ, arg->keyblock); } else { log_unauth("kadm5_setv4key_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setv4key_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } CWE ID: CWE-119 Target: 1 Example 2: Code: IV_API_CALL_STATUS_T ihevcd_cxa_api_function(iv_obj_t *ps_handle, void *pv_api_ip, void *pv_api_op) { WORD32 command; UWORD32 *pu4_ptr_cmd; WORD32 ret = 0; IV_API_CALL_STATUS_T e_status; e_status = api_check_struct_sanity(ps_handle, pv_api_ip, pv_api_op); if(e_status != IV_SUCCESS) { DEBUG("error code = %d\n", *((UWORD32 *)pv_api_op + 1)); return IV_FAIL; } pu4_ptr_cmd = (UWORD32 *)pv_api_ip; pu4_ptr_cmd++; command = *pu4_ptr_cmd; switch(command) { case IVD_CMD_CREATE: ret = ihevcd_create(ps_handle, (void *)pv_api_ip, (void *)pv_api_op); break; case IVD_CMD_DELETE: ret = ihevcd_delete(ps_handle, (void *)pv_api_ip, (void *)pv_api_op); break; case IVD_CMD_VIDEO_DECODE: ret = ihevcd_decode(ps_handle, (void *)pv_api_ip, (void *)pv_api_op); break; case IVD_CMD_GET_DISPLAY_FRAME: break; case IVD_CMD_SET_DISPLAY_FRAME: ret = ihevcd_set_display_frame(ps_handle, (void *)pv_api_ip, (void *)pv_api_op); break; case IVD_CMD_REL_DISPLAY_FRAME: ret = ihevcd_rel_display_frame(ps_handle, (void *)pv_api_ip, (void *)pv_api_op); break; case IVD_CMD_VIDEO_CTL: ret = ihevcd_ctl(ps_handle, (void *)pv_api_ip, (void *)pv_api_op); break; default: ret = IV_FAIL; break; } return (IV_API_CALL_STATUS_T)ret; } CWE ID: CWE-770 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MenuCacheDir* menu_cache_item_get_parent( MenuCacheItem* item ) { MenuCacheDir* dir = menu_cache_item_dup_parent(item); /* NOTE: this is very ugly hack but parent may be changed by item freeing so we should keep it alive :( */ if(dir) g_timeout_add_seconds(10, (GSourceFunc)menu_cache_item_unref, dir); return dir; } 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: ModuleExport size_t RegisterPNGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char *PNGNote= { "See http://www.libpng.org/ for details about the PNG format." }, *JNGNote= { "See http://www.libpng.org/pub/mng/ for details about the JNG\n" "format." }, *MNGNote= { "See http://www.libpng.org/pub/mng/ for details about the MNG\n" "format." }; *version='\0'; #if defined(PNG_LIBPNG_VER_STRING) (void) ConcatenateMagickString(version,"libpng ",MaxTextExtent); (void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent); if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,png_get_libpng_ver(NULL), MaxTextExtent); } #endif entry=SetMagickInfo("MNG"); entry->seekable_stream=MagickTrue; /* To do: eliminate this. */ #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMNGImage; entry->encoder=(EncodeImageHandler *) WriteMNGImage; #endif entry->magick=(IsImageFormatHandler *) IsMNG; entry->description=ConstantString("Multiple-image Network Graphics"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("video/x-mng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(MNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->adjoin=MagickFalse; entry->description=ConstantString("Portable Network Graphics"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); if (*version != '\0') entry->version=ConstantString(version); entry->note=ConstantString(PNGNote); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG8"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->adjoin=MagickFalse; entry->description=ConstantString( "8-bit indexed with optional binary transparency"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG24"); *version='\0'; #if defined(ZLIB_VERSION) (void) ConcatenateMagickString(version,"zlib ",MaxTextExtent); (void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent); if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0) { (void) ConcatenateMagickString(version,",",MaxTextExtent); (void) ConcatenateMagickString(version,zlib_version,MaxTextExtent); } #endif if (*version != '\0') entry->version=ConstantString(version); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 24-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG32"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 32-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG48"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or binary transparent 48-bit RGB"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG64"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->adjoin=MagickFalse; entry->description=ConstantString("opaque or transparent 64-bit RGBA"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNG00"); #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadPNGImage; entry->encoder=(EncodeImageHandler *) WritePNGImage; #endif entry->magick=(IsImageFormatHandler *) IsPNG; entry->adjoin=MagickFalse; entry->description=ConstantString( "PNG inheriting bit-depth, color-type from original if possible"); entry->mime_type=ConstantString("image/png"); entry->module=ConstantString("PNG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JNG"); #if defined(JNG_SUPPORTED) #if defined(MAGICKCORE_PNG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJNGImage; entry->encoder=(EncodeImageHandler *) WriteJNGImage; #endif #endif entry->magick=(IsImageFormatHandler *) IsJNG; entry->adjoin=MagickFalse; entry->description=ConstantString("JPEG Network Graphics"); entry->mime_type=ConstantString("image/x-jng"); entry->module=ConstantString("PNG"); entry->note=ConstantString(JNGNote); (void) RegisterMagickInfo(entry); #ifdef IMPNG_SETJMP_NOT_THREAD_SAFE ping_semaphore=AllocateSemaphoreInfo(); #endif return(MagickImageCoderSignature); } CWE ID: CWE-754 Target: 1 Example 2: Code: static int sco_conn_del(struct hci_conn *hcon, int err) { struct sco_conn *conn = hcon->sco_data; struct sock *sk; if (!conn) return 0; BT_DBG("hcon %p conn %p, err %d", hcon, conn, err); /* Kill socket */ sk = sco_chan_get(conn); if (sk) { bh_lock_sock(sk); sco_sock_clear_timer(sk); sco_chan_del(sk, err); bh_unlock_sock(sk); sco_sock_kill(sk); } hcon->sco_data = NULL; kfree(conn); return 0; } 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: v8::Handle<v8::Value> V8WebSocket::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.WebSocket.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() == 0) return V8Proxy::throwNotEnoughArgumentsError(); v8::TryCatch tryCatch; v8::Handle<v8::String> urlstring = args[0]->ToString(); if (tryCatch.HasCaught()) return throwError(tryCatch.Exception(), args.GetIsolate()); if (urlstring.IsEmpty()) return V8Proxy::throwError(V8Proxy::SyntaxError, "Empty URL", args.GetIsolate()); ScriptExecutionContext* context = getScriptExecutionContext(); if (!context) return V8Proxy::throwError(V8Proxy::ReferenceError, "WebSocket constructor's associated frame is not available", args.GetIsolate()); const KURL& url = context->completeURL(toWebCoreString(urlstring)); RefPtr<WebSocket> webSocket = WebSocket::create(context); ExceptionCode ec = 0; if (args.Length() < 2) webSocket->connect(url, ec); else { v8::Local<v8::Value> protocolsValue = args[1]; if (protocolsValue->IsArray()) { Vector<String> protocols; v8::Local<v8::Array> protocolsArray = v8::Local<v8::Array>::Cast(protocolsValue); for (uint32_t i = 0; i < protocolsArray->Length(); ++i) { v8::TryCatch tryCatchProtocol; v8::Handle<v8::String> protocol = protocolsArray->Get(v8::Int32::New(i))->ToString(); if (tryCatchProtocol.HasCaught()) return throwError(tryCatchProtocol.Exception(), args.GetIsolate()); protocols.append(toWebCoreString(protocol)); } webSocket->connect(url, protocols, ec); } else { v8::TryCatch tryCatchProtocol; v8::Handle<v8::String> protocol = protocolsValue->ToString(); if (tryCatchProtocol.HasCaught()) return throwError(tryCatchProtocol.Exception(), args.GetIsolate()); webSocket->connect(url, toWebCoreString(protocol), ec); } } if (ec) return throwError(ec, args.GetIsolate()); V8DOMWrapper::setDOMWrapper(args.Holder(), &info, webSocket.get()); V8DOMWrapper::setJSWrapperForActiveDOMObject(webSocket.release(), v8::Persistent<v8::Object>::New(args.Holder())); 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: int yr_re_fast_exec( uint8_t* code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args, int* matches) { RE_REPEAT_ANY_ARGS* repeat_any_args; uint8_t* code_stack[MAX_FAST_RE_STACK]; uint8_t* input_stack[MAX_FAST_RE_STACK]; int matches_stack[MAX_FAST_RE_STACK]; uint8_t* ip = code; uint8_t* input = input_data; uint8_t* next_input; uint8_t* next_opcode; uint8_t mask; uint8_t value; int i; int stop; int input_incr; int sp = 0; int bytes_matched; int max_bytes_matched; max_bytes_matched = flags & RE_FLAGS_BACKWARDS ? (int) input_backwards_size : (int) input_forwards_size; input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1; if (flags & RE_FLAGS_BACKWARDS) input--; code_stack[sp] = code; input_stack[sp] = input; matches_stack[sp] = 0; sp++; while (sp > 0) { sp--; ip = code_stack[sp]; input = input_stack[sp]; bytes_matched = matches_stack[sp]; stop = FALSE; while(!stop) { if (*ip == RE_OPCODE_MATCH) { if (flags & RE_FLAGS_EXHAUSTIVE) { FAIL_ON_ERROR(callback( flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data, bytes_matched, flags, callback_args)); break; } else { if (matches != NULL) *matches = bytes_matched; return ERROR_SUCCESS; } } if (bytes_matched >= max_bytes_matched) break; switch(*ip) { case RE_OPCODE_LITERAL: if (*input == *(ip + 1)) { bytes_matched++; input += input_incr; ip += 2; } else { stop = TRUE; } break; case RE_OPCODE_MASKED_LITERAL: value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; if ((*input & mask) == value) { bytes_matched++; input += input_incr; ip += 3; } else { stop = TRUE; } break; case RE_OPCODE_ANY: bytes_matched++; input += input_incr; ip += 1; break; case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1); next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS); for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++) { next_input = input + i * input_incr; if (bytes_matched + i >= max_bytes_matched) break; if ( *(next_opcode) != RE_OPCODE_LITERAL || (*(next_opcode) == RE_OPCODE_LITERAL && *(next_opcode + 1) == *next_input)) { if (sp >= MAX_FAST_RE_STACK) return -4; code_stack[sp] = next_opcode; input_stack[sp] = next_input; matches_stack[sp] = bytes_matched + i; sp++; } } input += input_incr * repeat_any_args->min; bytes_matched += repeat_any_args->min; ip = next_opcode; break; default: assert(FALSE); } } } if (matches != NULL) *matches = -1; return ERROR_SUCCESS; } CWE ID: CWE-125 Target: 1 Example 2: Code: void AXTableCell::columnIndexRange(std::pair<unsigned, unsigned>& columnRange) { if (!m_layoutObject || !m_layoutObject->isTableCell()) return; LayoutTableCell* cell = toLayoutTableCell(m_layoutObject); columnRange.first = cell->table()->absoluteColumnToEffectiveColumn( cell->absoluteColumnIndex()); columnRange.second = cell->table()->absoluteColumnToEffectiveColumn( cell->absoluteColumnIndex() + cell->colSpan()) - columnRange.first; } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void QQuickWebViewPrivate::_q_onUrlChanged() { Q_Q(QQuickWebView); context->iconDatabase()->requestIconForPageURL(q->url()); } 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: std::string SanitizeRevision(const std::string& revision) { for (size_t i = 0; i < revision.length(); i++) { if (!(revision[i] == '@' && i == 0) && !(revision[i] >= '0' && revision[i] <= '9') && !(revision[i] >= 'a' && revision[i] <= 'z') && !(revision[i] >= 'A' && revision[i] <= 'Z')) { return std::string(); } } return revision; } CWE ID: CWE-200 Target: 1 Example 2: Code: static fileHandle_t FS_HandleForFile(void) { int i; for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) { if ( fsh[i].handleFiles.file.o == NULL ) { return i; } } Com_Error( ERR_DROP, "FS_HandleForFile: none free" ); return 0; } CWE ID: CWE-269 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderBlock::setBreakAtLineToAvoidWidow(int lineToBreak) { ASSERT(lineToBreak >= 0); if (!m_rareData) m_rareData = adoptPtr(new RenderBlockRareData()); ASSERT(!m_rareData->m_didBreakAtLineToAvoidWidow); m_rareData->m_lineBreakToAvoidWidow = lineToBreak; } 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: process_demand_active(STREAM s) { uint8 type; uint16 len_src_descriptor, len_combined_caps; /* at this point we need to ensure that we have ui created */ rd_create_ui(); in_uint32_le(s, g_rdp_shareid); in_uint16_le(s, len_src_descriptor); in_uint16_le(s, len_combined_caps); in_uint8s(s, len_src_descriptor); logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid); rdp_process_server_caps(s, len_combined_caps); rdp_send_confirm_active(); rdp_send_synchronise(); rdp_send_control(RDP_CTL_COOPERATE); rdp_send_control(RDP_CTL_REQUEST_CONTROL); rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */ rdp_recv(&type); /* RDP_CTL_COOPERATE */ rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */ rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0, g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0); if (g_rdp_version >= RDP_V5) { rdp_enum_bmpcache2(); rdp_send_fonts(3); } else { rdp_send_fonts(1); rdp_send_fonts(2); } rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */ reset_order_state(); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void reset_intr(void) { pr_info("weird, reset interrupt called\n"); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 )); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; return chr; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr; struct sock *sk = sock->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk); lsa->l2tp_family = AF_INET6; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (peer) { if (!lsk->peer_conn_id) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr = np->daddr; if (np->sndflow) lsa->l2tp_flowinfo = np->flow_label; } else { if (ipv6_addr_any(&np->rcv_saddr)) lsa->l2tp_addr = np->saddr; else lsa->l2tp_addr = np->rcv_saddr; lsa->l2tp_conn_id = lsk->conn_id; } if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = sk->sk_bound_dev_if; *uaddr_len = sizeof(*lsa); return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: static int __hwahc_op_set_ptk(struct wusbhc *wusbhc, u8 port_idx, u32 tkid, const void *key, size_t key_size) { int result = -ENOMEM; struct hwahc *hwahc = container_of(wusbhc, struct hwahc, wusbhc); struct wahc *wa = &hwahc->wa; u8 iface_no = wa->usb_iface->cur_altsetting->desc.bInterfaceNumber; u8 encryption_value; /* Tell the host which key to use to talk to the device */ if (key) { u8 key_idx = wusb_key_index(0, WUSB_KEY_INDEX_TYPE_PTK, WUSB_KEY_INDEX_ORIGINATOR_HOST); result = __hwahc_dev_set_key(wusbhc, port_idx, tkid, key, key_size, key_idx); if (result < 0) goto error_set_key; encryption_value = wusbhc->ccm1_etd->bEncryptionValue; } else { /* FIXME: this should come from wusbhc->etd[UNSECURE].value */ encryption_value = 0; } /* Set the encryption type for communicating with the device */ result = usb_control_msg(wa->usb_dev, usb_sndctrlpipe(wa->usb_dev, 0), USB_REQ_SET_ENCRYPTION, USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE, encryption_value, port_idx << 8 | iface_no, NULL, 0, USB_CTRL_SET_TIMEOUT); if (result < 0) dev_err(wusbhc->dev, "Can't set host's WUSB encryption for " "port index %u to %s (value %d): %d\n", port_idx, wusb_et_name(wusbhc->ccm1_etd->bEncryptionType), wusbhc->ccm1_etd->bEncryptionValue, result); error_set_key: return result; } CWE ID: CWE-400 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void HTMLInputElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const { HTMLTextFormControlElement::addSubresourceAttributeURLs(urls); addSubresourceURL(urls, src()); } 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: decrypt_response(struct sc_card *card, unsigned char *in, unsigned char *out, size_t * out_len) { size_t in_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { in_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { in_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { in_len = in[2] * 0x100; in_len += in[3]; i = 5; } else { return -1; } /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], in_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], in_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[in_len - 2] && (in_len - 2 > 0)) in_len--; if (2 == in_len) return -1; memcpy(out, plaintext, in_len - 2); *out_len = in_len - 2; return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: GahpClient::cream_job_register(const char *service, const char *delg_id, const char *jdl, const char *lease_id, char **job_id, char **upload_url, char **download_url) { static const char* command = "CREAM_JOB_REGISTER"; if (server->m_commands_supported->contains_anycase(command)==FALSE) { return GAHPCLIENT_COMMAND_NOT_SUPPORTED; } if (!service) service=NULLSTRING; if (!delg_id) delg_id=NULLSTRING; if (!jdl) jdl = NULLSTRING; if (!lease_id) lease_id = ""; std::string reqline; char *esc1 = strdup( escapeGahpString(service) ); char *esc2 = strdup( escapeGahpString(delg_id) ); char *esc3 = strdup( escapeGahpString(jdl) ); char *esc4 = strdup( escapeGahpString(lease_id) ); int x = sprintf( reqline, "%s %s %s %s", esc1, esc2, esc3, esc4 ); free( esc1 ); free( esc2 ); free( esc3 ); free( esc4 ); ASSERT( x > 0 ); const char *buf = reqline.c_str(); if ( !is_pending(command,buf) ) { if ( m_mode == results_only ) { return GAHPCLIENT_COMMAND_NOT_SUBMITTED; } now_pending(command,buf,deleg_proxy,low_prio); } Gahp_Args* result = get_pending_result(command,buf); if ( result ) { int rc = 0; if ( result->argc == 2 ) { if ( !strcmp( result->argv[1], NULLSTRING ) ) { EXCEPT( "Bad %s result", command ); } error_string = result->argv[1]; rc = 1; } else if ( result->argc == 5 ) { if ( strcmp( result->argv[1], NULLSTRING ) ) { EXCEPT( "Bad %s result", command ); } if ( strcasecmp(result->argv[2], NULLSTRING) ) { *job_id = strdup(result->argv[2]); } if ( strcasecmp(result->argv[3], NULLSTRING) ) { *upload_url = strdup(result->argv[3]); } if ( strcasecmp(result->argv[4], NULLSTRING) ) { *download_url = strdup(result->argv[4]); } rc = 0; } else { EXCEPT( "Bad %s result", command ); } delete result; return rc; } if ( check_pending_timeout(command,buf) ) { sprintf( error_string, "%s timed out", command ); return GAHPCLIENT_COMMAND_TIMED_OUT; } return GAHPCLIENT_COMMAND_PENDING; } 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: PHPAPI int php_raw_url_decode(char *str, int len) { char *dest = str; char *data = str; while (len--) { if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) { #ifndef CHARSET_EBCDIC *dest = (char) php_htoi(data + 1); #else *dest = os_toebcdic[(char) php_htoi(data + 1)]; #endif data += 2; len -= 2; } else { *dest = *data; } data++; dest++; } *dest = '\0'; return dest - str; } 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: status_t OMXNodeInstance::allocateSecureBuffer( OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer, void **buffer_data, sp<NativeHandle> *native_handle) { if (buffer == NULL || buffer_data == NULL || native_handle == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); BufferMeta *buffer_meta = new BufferMeta(size, portIndex); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, size); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); if (mSecureBufferType[portIndex] == kSecureBufferTypeNativeHandle) { *buffer_data = NULL; *native_handle = NativeHandle::create( (native_handle_t *)header->pBuffer, false /* ownsHandle */); } else { *buffer_data = header->pBuffer; *native_handle = NULL; } addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateSecureBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%zu@%p:%p", size, *buffer_data, *native_handle == NULL ? NULL : (*native_handle)->handle())); return OK; } CWE ID: CWE-264 Target: 1 Example 2: Code: status_t ACodec::setupH263EncoderParameters(const sp<AMessage> &msg) { int32_t bitrate, iFrameInterval; if (!msg->findInt32("bitrate", &bitrate) || !msg->findInt32("i-frame-interval", &iFrameInterval)) { return INVALID_OPERATION; } OMX_VIDEO_CONTROLRATETYPE bitrateMode = getBitrateMode(msg); float frameRate; if (!msg->findFloat("frame-rate", &frameRate)) { int32_t tmp; if (!msg->findInt32("frame-rate", &tmp)) { return INVALID_OPERATION; } frameRate = (float)tmp; } OMX_VIDEO_PARAM_H263TYPE h263type; InitOMXParams(&h263type); h263type.nPortIndex = kPortIndexOutput; status_t err = mOMX->getParameter( mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type)); if (err != OK) { return err; } h263type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP; h263type.nPFrames = setPFramesSpacing(iFrameInterval, frameRate); if (h263type.nPFrames == 0) { h263type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI; } h263type.nBFrames = 0; int32_t profile; if (msg->findInt32("profile", &profile)) { int32_t level; if (!msg->findInt32("level", &level)) { return INVALID_OPERATION; } err = verifySupportForProfileAndLevel(profile, level); if (err != OK) { return err; } h263type.eProfile = static_cast<OMX_VIDEO_H263PROFILETYPE>(profile); h263type.eLevel = static_cast<OMX_VIDEO_H263LEVELTYPE>(level); } h263type.bPLUSPTYPEAllowed = OMX_FALSE; h263type.bForceRoundingTypeToZero = OMX_FALSE; h263type.nPictureHeaderRepetition = 0; h263type.nGOBHeaderInterval = 0; err = mOMX->setParameter( mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type)); if (err != OK) { return err; } err = configureBitrate(bitrate, bitrateMode); if (err != OK) { return err; } return setupErrorCorrectionParameters(); } 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: MagickExport void SetQuantumPack(QuantumInfo *quantum_info, const MagickBooleanType pack) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->pack=pack; } 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: char *my_asctime(time_t t) { struct tm *tm; char *str; int len; tm = localtime(&t); str = g_strdup(asctime(tm)); len = strlen(str); if (len > 0) str[len-1] = '\0'; return str; } CWE ID: CWE-416 Target: 1 Example 2: Code: static void nfs_increment_seqid(int status, struct nfs_seqid *seqid) { BUG_ON(list_first_entry(&seqid->sequence->sequence->list, struct nfs_seqid, list) != seqid); switch (status) { case 0: break; case -NFS4ERR_BAD_SEQID: if (seqid->sequence->flags & NFS_SEQID_CONFIRMED) return; printk(KERN_WARNING "NFS: v4 server returned a bad" " sequence-id error on an" " unconfirmed sequence %p!\n", seqid->sequence); case -NFS4ERR_STALE_CLIENTID: case -NFS4ERR_STALE_STATEID: case -NFS4ERR_BAD_STATEID: case -NFS4ERR_BADXDR: case -NFS4ERR_RESOURCE: case -NFS4ERR_NOFILEHANDLE: /* Non-seqid mutating errors */ return; }; /* * Note: no locking needed as we are guaranteed to be first * on the sequence list */ seqid->sequence->counter++; } 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 xt_compat_calc_jump(u_int8_t af, unsigned int offset) { struct compat_delta *tmp = xt[af].compat_tab; int mid, left = 0, right = xt[af].cur - 1; while (left <= right) { mid = (left + right) >> 1; if (offset > tmp[mid].offset) left = mid + 1; else if (offset < tmp[mid].offset) right = mid - 1; else return mid ? tmp[mid - 1].delta : 0; } return left ? tmp[left - 1].delta : 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: PrintMsg_Print_Params::PrintMsg_Print_Params() : page_size(), content_size(), printable_area(), margin_top(0), margin_left(0), dpi(0), scale_factor(1.0f), rasterize_pdf(false), document_cookie(0), selection_only(false), supports_alpha_blend(false), preview_ui_id(-1), preview_request_id(0), is_first_request(false), print_scaling_option(blink::kWebPrintScalingOptionSourceSize), print_to_pdf(false), display_header_footer(false), title(), url(), should_print_backgrounds(false), printed_doc_type(printing::SkiaDocumentType::PDF) {} CWE ID: CWE-20 Target: 1 Example 2: Code: void Automation::MouseButtonUp(int tab_id, const gfx::Point& p, Error** error) { *error = CheckAdvancedInteractionsSupported(); if (*error) return; int windex = 0, tab_index = 0; *error = GetIndicesForTab(tab_id, &windex, &tab_index); if (*error) return; std::string error_msg; if (!SendMouseButtonUpJSONRequest( automation(), windex, tab_index, p.x(), p.y(), &error_msg)) { *error = new Error(kUnknownError, error_msg); } } 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 vb2_internal_qbuf(struct vb2_queue *q, struct v4l2_buffer *b) { int ret = vb2_queue_or_prepare_buf(q, b, "qbuf"); return ret ? ret : vb2_core_qbuf(q, b->index, b); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void TearDownTestCase() { vpx_free(input_ - 1); input_ = NULL; vpx_free(output_); output_ = NULL; } CWE ID: CWE-119 Target: 1 Example 2: Code: net::URLRequestContext* ContentBrowserClient::OverrideRequestContextForURL( const GURL& url, ResourceContext* context) { return NULL; } 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 inline void tg3_rd32_loop(struct tg3 *tp, u32 *dst, u32 off, u32 len) { int i; dst = (u32 *)((u8 *)dst + off); for (i = 0; i < len; i += sizeof(u32)) *dst++ = tr32(off + i); } 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 struct nfs4_state *nfs4_do_open(struct inode *dir, struct path *path, int flags, struct iattr *sattr, struct rpc_cred *cred) { struct nfs4_exception exception = { }; struct nfs4_state *res; int status; do { status = _nfs4_do_open(dir, path, flags, sattr, cred, &res); if (status == 0) break; /* NOTE: BAD_SEQID means the server and client disagree about the * book-keeping w.r.t. state-changing operations * (OPEN/CLOSE/LOCK/LOCKU...) * It is actually a sign of a bug on the client or on the server. * * If we receive a BAD_SEQID error in the particular case of * doing an OPEN, we assume that nfs_increment_open_seqid() will * have unhashed the old state_owner for us, and that we can * therefore safely retry using a new one. We should still warn * the user though... */ if (status == -NFS4ERR_BAD_SEQID) { printk(KERN_WARNING "NFS: v4 server %s " " returned a bad sequence-id error!\n", NFS_SERVER(dir)->nfs_client->cl_hostname); exception.retry = 1; continue; } /* * BAD_STATEID on OPEN means that the server cancelled our * state before it received the OPEN_CONFIRM. * Recover by retrying the request as per the discussion * on Page 181 of RFC3530. */ if (status == -NFS4ERR_BAD_STATEID) { exception.retry = 1; continue; } if (status == -EAGAIN) { /* We must have found a delegation */ exception.retry = 1; continue; } res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir), status, &exception)); } while (exception.retry); return res; } CWE ID: Target: 1 Example 2: Code: void Document::dispatchVisibilityStateChangeEvent() { dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false)); } 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 InfoBarCountObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(type == chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED || type == chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED); CheckCount(); } 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: jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t *p_header_size) { Jbig2Segment *result; uint8_t rtscarf; uint32_t rtscarf_long; uint32_t *referred_to_segments; int referred_to_segment_count; int referred_to_segment_size; int pa_size; int offset; /* minimum possible size of a jbig2 segment header */ if (buf_size < 11) return NULL; result = jbig2_new(ctx, Jbig2Segment, 1); if (result == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate segment in jbig2_parse_segment_header"); return result; } /* 7.2.2 */ result->number = jbig2_get_uint32(buf); /* 7.2.3 */ result->flags = buf[4]; /* 7.2.4 referred-to segments */ rtscarf = buf[5]; if ((rtscarf & 0xe0) == 0xe0) { rtscarf_long = jbig2_get_uint32(buf + 5); referred_to_segment_count = rtscarf_long & 0x1fffffff; offset = 5 + 4 + (referred_to_segment_count + 1) / 8; } else { referred_to_segment_count = (rtscarf >> 5); offset = 5 + 1; } result->referred_to_segment_count = referred_to_segment_count; /* we now have enough information to compute the full header length */ referred_to_segment_size = result->number <= 256 ? 1 : result->number <= 65536 ? 2 : 4; /* 7.2.5 */ pa_size = result->flags & 0x40 ? 4 : 1; /* 7.2.6 */ if (offset + referred_to_segment_count * referred_to_segment_size + pa_size + 4 > buf_size) { jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "jbig2_parse_segment_header() called with insufficient data", -1); jbig2_free(ctx->allocator, result); return NULL; } /* 7.2.5 */ if (referred_to_segment_count) { int i; referred_to_segments = jbig2_new(ctx, uint32_t, referred_to_segment_count * referred_to_segment_size); if (referred_to_segments == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate referred_to_segments " "in jbig2_parse_segment_header"); return NULL; } for (i = 0; i < referred_to_segment_count; i++) { referred_to_segments[i] = (referred_to_segment_size == 1) ? buf[offset] : (referred_to_segment_size == 2) ? jbig2_get_uint16(buf + offset) : jbig2_get_uint32(buf + offset); offset += referred_to_segment_size; jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d refers to segment %d", result->number, referred_to_segments[i]); } result->referred_to_segments = referred_to_segments; } else { /* no referred-to segments */ result->referred_to_segments = NULL; } /* 7.2.6 */ if (result->flags & 0x40) { result->page_association = jbig2_get_uint32(buf + offset); offset += 4; } else { result->page_association = buf[offset++]; } jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, "segment %d is associated with page %d", result->number, result->page_association); /* 7.2.7 */ result->data_length = jbig2_get_uint32(buf + offset); *p_header_size = offset + 4; /* no body parsing results yet */ result->result = NULL; return result; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int cluster_pages_for_defrag(struct inode *inode, struct page **pages, unsigned long start_index, int num_pages) { unsigned long file_end; u64 isize = i_size_read(inode); u64 page_start; u64 page_end; u64 page_cnt; int ret; int i; int i_done; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; struct extent_io_tree *tree; gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping); file_end = (isize - 1) >> PAGE_CACHE_SHIFT; if (!isize || start_index > file_end) return 0; page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1); ret = btrfs_delalloc_reserve_space(inode, page_cnt << PAGE_CACHE_SHIFT); if (ret) return ret; i_done = 0; tree = &BTRFS_I(inode)->io_tree; /* step one, lock all the pages */ for (i = 0; i < page_cnt; i++) { struct page *page; again: page = find_or_create_page(inode->i_mapping, start_index + i, mask); if (!page) break; page_start = page_offset(page); page_end = page_start + PAGE_CACHE_SIZE - 1; while (1) { lock_extent(tree, page_start, page_end); ordered = btrfs_lookup_ordered_extent(inode, page_start); unlock_extent(tree, page_start, page_end); if (!ordered) break; unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); lock_page(page); /* * we unlocked the page above, so we need check if * it was released or not. */ if (page->mapping != inode->i_mapping) { unlock_page(page); page_cache_release(page); goto again; } } if (!PageUptodate(page)) { btrfs_readpage(NULL, page); lock_page(page); if (!PageUptodate(page)) { unlock_page(page); page_cache_release(page); ret = -EIO; break; } } if (page->mapping != inode->i_mapping) { unlock_page(page); page_cache_release(page); goto again; } pages[i] = page; i_done++; } if (!i_done || ret) goto out; if (!(inode->i_sb->s_flags & MS_ACTIVE)) goto out; /* * so now we have a nice long stream of locked * and up to date pages, lets wait on them */ for (i = 0; i < i_done; i++) wait_on_page_writeback(pages[i]); page_start = page_offset(pages[0]); page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE; lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, 0, &cached_state); clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); if (i_done != page_cnt) { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); btrfs_delalloc_release_space(inode, (page_cnt - i_done) << PAGE_CACHE_SHIFT); } set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, &cached_state, GFP_NOFS); unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, &cached_state, GFP_NOFS); for (i = 0; i < i_done; i++) { clear_page_dirty_for_io(pages[i]); ClearPageChecked(pages[i]); set_page_extent_mapped(pages[i]); set_page_dirty(pages[i]); unlock_page(pages[i]); page_cache_release(pages[i]); } return i_done; out: for (i = 0; i < i_done; i++) { unlock_page(pages[i]); page_cache_release(pages[i]); } btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT); return ret; } 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: makepol(QPRS_STATE *state) { int32 val = 0, type; int32 lenval = 0; char *strval = NULL; int32 stack[STACKDEPTH]; int32 lenstack = 0; uint16 flag = 0; while ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END) { switch (type) { case VAL: pushval_asis(state, VAL, strval, lenval, flag); while (lenstack && (stack[lenstack - 1] == (int32) '&' || stack[lenstack - 1] == (int32) '!')) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); } break; case OPR: if (lenstack && val == (int32) '|') pushquery(state, OPR, val, 0, 0, 0); else { if (lenstack == STACKDEPTH) /* internal error */ elog(ERROR, "stack too short"); stack[lenstack] = val; lenstack++; } break; case OPEN: if (makepol(state) == ERR) return ERR; while (lenstack && (stack[lenstack - 1] == (int32) '&' || stack[lenstack - 1] == (int32) '!')) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); } break; case CLOSE: while (lenstack) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); }; return END; break; case ERR: default: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); return ERR; } } while (lenstack) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); }; return END; } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Resource::LastPluginRefWasDeleted(bool instance_destroyed) { DCHECK(resource_id_ != 0); instance()->module()->GetCallbackTracker()->PostAbortForResource( resource_id_); resource_id_ = 0; if (instance_destroyed) instance_ = NULL; } CWE ID: CWE-399 Target: 1 Example 2: Code: get_unknown(display *d, png_infop info_ptr, int after_IDAT) /* Otherwise this will return the cached values set by any user callback */ { UNUSED(info_ptr); if (after_IDAT) return d->after_IDAT; else return d->before_IDAT; } 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: GF_SceneManager *gf_sm_new(GF_SceneGraph *graph) { GF_SceneManager *tmp; if (!graph) return NULL; GF_SAFEALLOC(tmp, GF_SceneManager); if (!tmp) return NULL; tmp->streams = gf_list_new(); tmp->scene_graph = graph; return tmp; } 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 DataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } CWE ID: CWE-20 Target: 1 Example 2: Code: bool RenderBox::sizesToIntrinsicLogicalWidth(LogicalWidthType widthType) const { if (isFloating() || (isInlineBlockOrInlineTable() && !isHTMLMarquee())) return true; Length logicalWidth = (widthType == MaxLogicalWidth) ? style()->logicalMaxWidth() : style()->logicalWidth(); if (logicalWidth.type() == Intrinsic) return true; if (parent()->style()->overflowX() == OMARQUEE) { EMarqueeDirection dir = parent()->style()->marqueeDirection(); if (dir == MAUTO || dir == MFORWARD || dir == MBACKWARD || dir == MLEFT || dir == MRIGHT) return true; } if (parent()->isDeprecatedFlexibleBox() && (parent()->style()->boxOrient() == HORIZONTAL || parent()->style()->boxAlign() != BSTRETCH)) return true; if (logicalWidth.type() == Auto && !(parent()->isDeprecatedFlexibleBox() && parent()->style()->boxOrient() == VERTICAL && parent()->style()->boxAlign() == BSTRETCH) && node() && (node()->hasTagName(inputTag) || node()->hasTagName(selectTag) || node()->hasTagName(buttonTag) || node()->hasTagName(textareaTag) || node()->hasTagName(legendTag))) return true; return false; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int chksum_update(struct shash_desc *desc, const u8 *data, unsigned int length) { struct chksum_desc_ctx *ctx = shash_desc_ctx(desc); ctx->crc = __crc32c_le(ctx->crc, data, length); 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: ExtensionsGuestViewMessageFilter::~ExtensionsGuestViewMessageFilter() { DCHECK_CURRENTLY_ON(BrowserThread::IO); (*GetProcessIdToFilterMap())[render_process_id_] = nullptr; base::PostTaskWithTraits( FROM_HERE, BrowserThread::UI, base::BindOnce(RemoveProcessIdFromGlobalMap, render_process_id_)); } CWE ID: CWE-362 Target: 1 Example 2: Code: const struct ldb_val *ldb_dn_get_rdn_val(struct ldb_dn *dn) { if ( ! ldb_dn_validate(dn)) { return NULL; } if (dn->comp_num == 0) return NULL; return &dn->components[0].value; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int http_proxy_open(URLContext *h, const char *uri, int flags) { HTTPContext *s = h->priv_data; char hostname[1024], hoststr[1024]; char auth[1024], pathbuf[1024], *path; char lower_url[100]; int port, ret = 0, attempts = 0; HTTPAuthType cur_auth_type; char *authstr; int new_loc; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port, pathbuf, sizeof(pathbuf), uri); ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL); path = pathbuf; if (*path == '/') path++; ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port, NULL); redo: ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE, &h->interrupt_callback, NULL, h->protocol_whitelist, h->protocol_blacklist, h); if (ret < 0) return ret; authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth, path, "CONNECT"); snprintf(s->buffer, sizeof(s->buffer), "CONNECT %s HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n" "%s%s" "\r\n", path, hoststr, authstr ? "Proxy-" : "", authstr ? authstr : ""); av_freep(&authstr); if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) goto fail; s->buf_ptr = s->buffer; s->buf_end = s->buffer; s->line_count = 0; s->filesize = -1; cur_auth_type = s->proxy_auth_state.auth_type; /* Note: This uses buffering, potentially reading more than the * HTTP header. If tunneling a protocol where the server starts * the conversation, we might buffer part of that here, too. * Reading that requires using the proper ffurl_read() function * on this URLContext, not using the fd directly (as the tls * protocol does). This shouldn't be an issue for tls though, * since the client starts the conversation there, so there * is no extra data that we might buffer up here. */ ret = http_read_header(h, &new_loc); if (ret < 0) goto fail; attempts++; if (s->http_code == 407 && (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) && s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) { ffurl_closep(&s->hd); goto redo; } if (s->http_code < 400) return 0; ret = ff_http_averror(s->http_code, AVERROR(EIO)); fail: http_proxy_close(h); return ret; } 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 CallbackAndDie(bool succeeded) { v8::Isolate* isolate = context_->isolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Value> args[] = {v8::Boolean::New(isolate, succeeded)}; context_->CallFunction(v8::Local<v8::Function>::New(isolate, callback_), arraysize(args), args); delete this; } CWE ID: Target: 1 Example 2: Code: static int ext4_run_lazyinit_thread(void) { ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread, ext4_li_info, "ext4lazyinit"); if (IS_ERR(ext4_lazyinit_task)) { int err = PTR_ERR(ext4_lazyinit_task); ext4_clear_request_list(); kfree(ext4_li_info); ext4_li_info = NULL; printk(KERN_CRIT "EXT4: error %d creating inode table " "initialization thread\n", err); return err; } ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING; return 0; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int do_adjtimex(struct timex *txc) { long mtemp, save_adjust, rem; s64 freq_adj; int result; /* In order to modify anything, you gotta be super-user! */ if (txc->modes && !capable(CAP_SYS_TIME)) return -EPERM; /* Now we validate the data before disabling interrupts */ if ((txc->modes & ADJ_OFFSET_SINGLESHOT) == ADJ_OFFSET_SINGLESHOT) { /* singleshot must not be used with any other mode bits */ if (txc->modes != ADJ_OFFSET_SINGLESHOT && txc->modes != ADJ_OFFSET_SS_READ) return -EINVAL; } if (txc->modes != ADJ_OFFSET_SINGLESHOT && (txc->modes & ADJ_OFFSET)) /* adjustment Offset limited to +- .512 seconds */ if (txc->offset <= - MAXPHASE || txc->offset >= MAXPHASE ) return -EINVAL; /* if the quartz is off by more than 10% something is VERY wrong ! */ if (txc->modes & ADJ_TICK) if (txc->tick < 900000/USER_HZ || txc->tick > 1100000/USER_HZ) return -EINVAL; write_seqlock_irq(&xtime_lock); result = time_state; /* mostly `TIME_OK' */ /* Save for later - semantics of adjtime is to return old value */ save_adjust = time_adjust; #if 0 /* STA_CLOCKERR is never set yet */ time_status &= ~STA_CLOCKERR; /* reset STA_CLOCKERR */ #endif /* If there are input parameters, then process them */ if (txc->modes) { if (txc->modes & ADJ_STATUS) /* only set allowed bits */ time_status = (txc->status & ~STA_RONLY) | (time_status & STA_RONLY); if (txc->modes & ADJ_FREQUENCY) { /* p. 22 */ if (txc->freq > MAXFREQ || txc->freq < -MAXFREQ) { result = -EINVAL; goto leave; } time_freq = ((s64)txc->freq * NSEC_PER_USEC) >> (SHIFT_USEC - SHIFT_NSEC); } if (txc->modes & ADJ_MAXERROR) { if (txc->maxerror < 0 || txc->maxerror >= NTP_PHASE_LIMIT) { result = -EINVAL; goto leave; } time_maxerror = txc->maxerror; } if (txc->modes & ADJ_ESTERROR) { if (txc->esterror < 0 || txc->esterror >= NTP_PHASE_LIMIT) { result = -EINVAL; goto leave; } time_esterror = txc->esterror; } if (txc->modes & ADJ_TIMECONST) { /* p. 24 */ if (txc->constant < 0) { /* NTP v4 uses values > 6 */ result = -EINVAL; goto leave; } time_constant = min(txc->constant + 4, (long)MAXTC); } if (txc->modes & ADJ_OFFSET) { /* values checked earlier */ if (txc->modes == ADJ_OFFSET_SINGLESHOT) { /* adjtime() is independent from ntp_adjtime() */ time_adjust = txc->offset; } else if (time_status & STA_PLL) { time_offset = txc->offset * NSEC_PER_USEC; /* * Scale the phase adjustment and * clamp to the operating range. */ time_offset = min(time_offset, (s64)MAXPHASE * NSEC_PER_USEC); time_offset = max(time_offset, (s64)-MAXPHASE * NSEC_PER_USEC); /* * Select whether the frequency is to be controlled * and in which mode (PLL or FLL). Clamp to the operating * range. Ugly multiply/divide should be replaced someday. */ if (time_status & STA_FREQHOLD || time_reftime == 0) time_reftime = xtime.tv_sec; mtemp = xtime.tv_sec - time_reftime; time_reftime = xtime.tv_sec; freq_adj = time_offset * mtemp; freq_adj = shift_right(freq_adj, time_constant * 2 + (SHIFT_PLL + 2) * 2 - SHIFT_NSEC); if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp > MAXSEC)) freq_adj += div_s64(time_offset << (SHIFT_NSEC - SHIFT_FLL), mtemp); freq_adj += time_freq; freq_adj = min(freq_adj, (s64)MAXFREQ_NSEC); time_freq = max(freq_adj, (s64)-MAXFREQ_NSEC); time_offset = div_long_long_rem_signed(time_offset, NTP_INTERVAL_FREQ, &rem); time_offset <<= SHIFT_UPDATE; } /* STA_PLL */ } /* txc->modes & ADJ_OFFSET */ if (txc->modes & ADJ_TICK) tick_usec = txc->tick; if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET)) ntp_update_frequency(); } /* txc->modes */ leave: if ((time_status & (STA_UNSYNC|STA_CLOCKERR)) != 0) result = TIME_ERROR; if ((txc->modes == ADJ_OFFSET_SINGLESHOT) || (txc->modes == ADJ_OFFSET_SS_READ)) txc->offset = save_adjust; else txc->offset = ((long)shift_right(time_offset, SHIFT_UPDATE)) * NTP_INTERVAL_FREQ / 1000; txc->freq = (time_freq / NSEC_PER_USEC) << (SHIFT_USEC - SHIFT_NSEC); txc->maxerror = time_maxerror; txc->esterror = time_esterror; txc->status = time_status; txc->constant = time_constant; txc->precision = 1; txc->tolerance = MAXFREQ; txc->tick = tick_usec; /* PPS is not implemented, so these are zero */ txc->ppsfreq = 0; txc->jitter = 0; txc->shift = 0; txc->stabil = 0; txc->jitcnt = 0; txc->calcnt = 0; txc->errcnt = 0; txc->stbcnt = 0; write_sequnlock_irq(&xtime_lock); do_gettimeofday(&txc->time); notify_cmos_timer(); 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: int main(int argc, char **argv) { FILE *infile = NULL; vpx_codec_ctx_t codec = {0}; vpx_codec_enc_cfg_t cfg = {0}; int frame_count = 0; vpx_image_t raw; vpx_codec_err_t res; VpxVideoInfo info = {0}; VpxVideoWriter *writer = NULL; const VpxInterface *encoder = NULL; int update_frame_num = 0; const int fps = 30; // TODO(dkovalev) add command line argument const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument exec_name = argv[0]; if (argc != 6) die("Invalid number of arguments"); encoder = get_vpx_encoder_by_name("vp8"); if (!encoder) die("Unsupported codec."); update_frame_num = atoi(argv[5]); if (!update_frame_num) die("Couldn't parse frame number '%s'\n", argv[5]); info.codec_fourcc = encoder->fourcc; info.frame_width = strtol(argv[1], NULL, 0); info.frame_height = strtol(argv[2], NULL, 0); info.time_base.numerator = 1; info.time_base.denominator = fps; if (info.frame_width <= 0 || info.frame_height <= 0 || (info.frame_width % 2) != 0 || (info.frame_height % 2) != 0) { die("Invalid frame size: %dx%d", info.frame_width, info.frame_height); } if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width, info.frame_height, 1)) { die("Failed to allocate image."); } printf("Using %s\n", vpx_codec_iface_name(encoder->interface())); res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0); if (res) die_codec(&codec, "Failed to get default codec config."); cfg.g_w = info.frame_width; cfg.g_h = info.frame_height; cfg.g_timebase.num = info.time_base.numerator; cfg.g_timebase.den = info.time_base.denominator; cfg.rc_target_bitrate = bitrate; writer = vpx_video_writer_open(argv[4], kContainerIVF, &info); if (!writer) die("Failed to open %s for writing.", argv[4]); if (!(infile = fopen(argv[3], "rb"))) die("Failed to open %s for reading.", argv[3]); if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); while (vpx_img_read(&raw, infile)) { if (frame_count + 1 == update_frame_num) { vpx_ref_frame_t ref; ref.frame_type = VP8_LAST_FRAME; ref.img = raw; if (vpx_codec_control(&codec, VP8_SET_REFERENCE, &ref)) die_codec(&codec, "Failed to set reference frame"); } encode_frame(&codec, &raw, frame_count++, writer); } encode_frame(&codec, NULL, -1, writer); printf("\n"); fclose(infile); printf("Processed %d frames.\n", frame_count); vpx_img_free(&raw); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_writer_close(writer); return EXIT_SUCCESS; } CWE ID: CWE-119 Target: 1 Example 2: Code: void QueryManager::StartTracking(QueryManager::Query* /* query */) { ++query_count_; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: kex_send_ext_info(struct ssh *ssh) { int r; char *algs; if ((algs = sshkey_alg_list(0, 1, ',')) == NULL) return SSH_ERR_ALLOC_FAIL; if ((r = sshpkt_start(ssh, SSH2_MSG_EXT_INFO)) != 0 || (r = sshpkt_put_u32(ssh, 1)) != 0 || (r = sshpkt_put_cstring(ssh, "server-sig-algs")) != 0 || (r = sshpkt_put_cstring(ssh, algs)) != 0 || (r = sshpkt_send(ssh)) != 0) goto out; /* success */ r = 0; out: free(algs); 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: xfs_attr3_leaf_lookup_int( struct xfs_buf *bp, struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_entry *entries; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; xfs_dahash_t hashval; int probe; int span; trace_xfs_attr_leaf_lookup(args); leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); entries = xfs_attr3_leaf_entryp(leaf); ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8); /* * Binary search. (note: small blocks will skip this loop) */ hashval = args->hashval; probe = span = ichdr.count / 2; for (entry = &entries[probe]; span > 4; entry = &entries[probe]) { span /= 2; if (be32_to_cpu(entry->hashval) < hashval) probe += span; else if (be32_to_cpu(entry->hashval) > hashval) probe -= span; else break; } ASSERT(probe >= 0 && (!ichdr.count || probe < ichdr.count)); ASSERT(span <= 4 || be32_to_cpu(entry->hashval) == hashval); /* * Since we may have duplicate hashval's, find the first matching * hashval in the leaf. */ while (probe > 0 && be32_to_cpu(entry->hashval) >= hashval) { entry--; probe--; } while (probe < ichdr.count && be32_to_cpu(entry->hashval) < hashval) { entry++; probe++; } if (probe == ichdr.count || be32_to_cpu(entry->hashval) != hashval) { args->index = probe; return XFS_ERROR(ENOATTR); } /* * Duplicate keys may be present, so search all of them for a match. */ for (; probe < ichdr.count && (be32_to_cpu(entry->hashval) == hashval); entry++, probe++) { /* * GROT: Add code to remove incomplete entries. */ /* * If we are looking for INCOMPLETE entries, show only those. * If we are looking for complete entries, show only those. */ if ((args->flags & XFS_ATTR_INCOMPLETE) != (entry->flags & XFS_ATTR_INCOMPLETE)) { continue; } if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, probe); if (name_loc->namelen != args->namelen) continue; if (memcmp(args->name, name_loc->nameval, args->namelen) != 0) continue; if (!xfs_attr_namesp_match(args->flags, entry->flags)) continue; args->index = probe; return XFS_ERROR(EEXIST); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, probe); if (name_rmt->namelen != args->namelen) continue; if (memcmp(args->name, name_rmt->name, args->namelen) != 0) continue; if (!xfs_attr_namesp_match(args->flags, entry->flags)) continue; args->index = probe; args->valuelen = be32_to_cpu(name_rmt->valuelen); args->rmtblkno = be32_to_cpu(name_rmt->valueblk); args->rmtblkcnt = xfs_attr3_rmt_blocks( args->dp->i_mount, args->valuelen); return XFS_ERROR(EEXIST); } } args->index = probe; return XFS_ERROR(ENOATTR); } CWE ID: CWE-19 Target: 1 Example 2: Code: int vhost_net_set_ubuf_info(struct vhost_net *n) { bool zcopy; int i; for (i = 0; i < VHOST_NET_VQ_MAX; ++i) { zcopy = vhost_net_zcopy_mask & (0x1 << i); if (!zcopy) continue; n->vqs[i].ubuf_info = kmalloc(sizeof(*n->vqs[i].ubuf_info) * UIO_MAXIOV, GFP_KERNEL); if (!n->vqs[i].ubuf_info) goto err; } return 0; err: vhost_net_clear_ubuf_info(n); return -ENOMEM; } 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 PHP_INI_MH(OnUpdateSaveHandler) /* {{{ */ { ps_module *tmp; SESSION_CHECK_ACTIVE_STATE; tmp = _php_find_ps_module(new_value TSRMLS_CC); if (PG(modules_activated) && !tmp) { int err_type; if (stage == ZEND_INI_STAGE_RUNTIME) { err_type = E_WARNING; } else { err_type = E_ERROR; } /* Do not output error when restoring ini options. */ if (stage != ZEND_INI_STAGE_DEACTIVATE) { php_error_docref(NULL TSRMLS_CC, err_type, "Cannot find save handler '%s'", new_value); } return FAILURE; } PS(default_mod) = PS(mod); PS(mod) = tmp; return SUCCESS; } /* }}} */ 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 Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system, ScriptContext* context, Dispatcher* dispatcher, RequestSender* request_sender, V8SchemaRegistry* v8_schema_registry) { module_system->RegisterNativeHandler( "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context))); module_system->RegisterNativeHandler( "lazy_background_page", scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context))); module_system->RegisterNativeHandler( "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context))); module_system->RegisterNativeHandler("schema_registry", v8_schema_registry->AsNativeHandler()); module_system->RegisterNativeHandler( "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context))); module_system->RegisterNativeHandler( "test_features", scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context))); module_system->RegisterNativeHandler( "test_native_handler", scoped_ptr<NativeHandler>(new TestNativeHandler(context))); module_system->RegisterNativeHandler( "user_gestures", scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context))); module_system->RegisterNativeHandler( "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context))); module_system->RegisterNativeHandler( "v8_context", scoped_ptr<NativeHandler>(new V8ContextNativeHandler(context))); module_system->RegisterNativeHandler( "event_natives", scoped_ptr<NativeHandler>(new EventBindings(context))); module_system->RegisterNativeHandler( "messaging_natives", scoped_ptr<NativeHandler>(MessagingBindings::Get(dispatcher, context))); module_system->RegisterNativeHandler( "apiDefinitions", scoped_ptr<NativeHandler>( new ApiDefinitionsNatives(dispatcher, context))); module_system->RegisterNativeHandler( "sendRequest", scoped_ptr<NativeHandler>( new SendRequestNatives(request_sender, context))); module_system->RegisterNativeHandler( "setIcon", scoped_ptr<NativeHandler>(new SetIconNatives(context))); module_system->RegisterNativeHandler( "activityLogger", scoped_ptr<NativeHandler>(new APIActivityLogger(context))); module_system->RegisterNativeHandler( "renderFrameObserverNatives", scoped_ptr<NativeHandler>(new RenderFrameObserverNatives(context))); module_system->RegisterNativeHandler( "file_system_natives", scoped_ptr<NativeHandler>(new FileSystemNatives(context))); module_system->RegisterNativeHandler( "app_window_natives", scoped_ptr<NativeHandler>(new AppWindowCustomBindings(context))); module_system->RegisterNativeHandler( "blob_natives", scoped_ptr<NativeHandler>(new BlobNativeHandler(context))); module_system->RegisterNativeHandler( "context_menus", scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context))); module_system->RegisterNativeHandler( "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context))); module_system->RegisterNativeHandler( "document_natives", scoped_ptr<NativeHandler>(new DocumentCustomBindings(context))); module_system->RegisterNativeHandler( "guest_view_internal", scoped_ptr<NativeHandler>( new GuestViewInternalCustomBindings(context))); module_system->RegisterNativeHandler( "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context))); module_system->RegisterNativeHandler( "id_generator", scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context))); module_system->RegisterNativeHandler( "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context))); module_system->RegisterNativeHandler( "display_source", scoped_ptr<NativeHandler>(new DisplaySourceCustomBindings(context))); } CWE ID: CWE-284 Target: 1 Example 2: Code: WebviewInfo::~WebviewInfo() { } 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 inline unsigned short ReadPropertyUnsignedShort(const EndianType endian, const unsigned char *buffer) { unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); return((unsigned short) (value & 0xffff)); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); return((unsigned short) (value & 0xffff)); } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: String AXNodeObject::textFromDescendants(AXObjectSet& visited, bool recursive) const { if (!canHaveChildren() && recursive) return String(); StringBuilder accumulatedText; AXObject* previous = nullptr; AXObjectVector children; HeapVector<Member<AXObject>> ownedChildren; computeAriaOwnsChildren(ownedChildren); for (AXObject* obj = rawFirstChild(); obj; obj = obj->rawNextSibling()) { if (!axObjectCache().isAriaOwned(obj)) children.push_back(obj); } for (const auto& ownedChild : ownedChildren) children.push_back(ownedChild); for (AXObject* child : children) { if (equalIgnoringCase(child->getAttribute(aria_hiddenAttr), "true")) continue; if (previous && accumulatedText.length() && !isHTMLSpace(accumulatedText[accumulatedText.length() - 1])) { if (!isInSameNonInlineBlockFlow(child->getLayoutObject(), previous->getLayoutObject())) accumulatedText.append(' '); } String result; if (child->isPresentational()) result = child->textFromDescendants(visited, true); else result = recursiveTextAlternative(*child, false, visited); accumulatedText.append(result); previous = child; } return accumulatedText.toString(); } CWE ID: CWE-254 Target: 1 Example 2: Code: void DownloadManagerImpl::GetAllDownloads(DownloadVector* downloads) { for (const auto& it : downloads_) { downloads->push_back(it.second.get()); } } 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 WebGL2RenderingContextBase::texImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, GLintptr offset) { if (isContextLost()) return; if (!ValidateTexture3DBinding("texImage3D", target)) return; if (!bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texImage3D", "no bound PIXEL_UNPACK_BUFFER"); return; } if (!ValidateTexFunc("texImage3D", kTexImage, kSourceUnpackBuffer, target, level, internalformat, width, height, depth, border, format, type, 0, 0, 0)) return; if (!ValidateValueFitNonNegInt32("texImage3D", "offset", offset)) return; ContextGL()->TexImage3D(target, level, ConvertTexInternalFormat(internalformat, type), width, height, depth, border, format, type, reinterpret_cast<const void*>(offset)); } 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: ResourceRequestBlockedReason BaseFetchContext::CanRequest( Resource::Type type, const ResourceRequest& resource_request, const KURL& url, const ResourceLoaderOptions& options, SecurityViolationReportingPolicy reporting_policy, FetchParameters::OriginRestriction origin_restriction, ResourceRequest::RedirectStatus redirect_status) const { ResourceRequestBlockedReason blocked_reason = CanRequestInternal(type, resource_request, url, options, reporting_policy, origin_restriction, redirect_status); if (blocked_reason != ResourceRequestBlockedReason::kNone && reporting_policy == SecurityViolationReportingPolicy::kReport) { DispatchDidBlockRequest(resource_request, options.initiator_info, blocked_reason); } return blocked_reason; } CWE ID: CWE-119 Target: 1 Example 2: Code: bgp_attr_prefix_sid(int32_t tlength, struct bgp_attr_parser_args *args, struct bgp_nlri *mp_update) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; bgp_attr_parse_ret_t ret; attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID); while (tlength) { int32_t type, length; type = stream_getc(peer->curr); length = stream_getw(peer->curr); ret = bgp_attr_psid_sub(type, length, args, mp_update); if (ret != BGP_ATTR_PARSE_PROCEED) return ret; /* * Subtract length + the T and the L * since length is the Vector portion */ tlength -= length + 3; if (tlength < 0) { flog_err( EC_BGP_ATTR_LEN, "Prefix SID internal length %d causes us to read beyond the total Prefix SID length", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } } return BGP_ATTR_PARSE_PROCEED; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct crypto_instance *crypto_authenc_alloc(struct rtattr **tb) { struct crypto_attr_type *algt; struct crypto_instance *inst; struct hash_alg_common *auth; struct crypto_alg *auth_base; struct crypto_alg *enc; struct authenc_instance_ctx *ctx; const char *enc_name; int err; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return ERR_CAST(algt); if ((algt->type ^ CRYPTO_ALG_TYPE_AEAD) & algt->mask) return ERR_PTR(-EINVAL); auth = ahash_attr_alg(tb[1], CRYPTO_ALG_TYPE_HASH, CRYPTO_ALG_TYPE_AHASH_MASK); if (IS_ERR(auth)) return ERR_CAST(auth); auth_base = &auth->base; enc_name = crypto_attr_alg_name(tb[2]); err = PTR_ERR(enc_name); if (IS_ERR(enc_name)) goto out_put_auth; inst = kzalloc(sizeof(*inst) + sizeof(*ctx), GFP_KERNEL); err = -ENOMEM; if (!inst) goto out_put_auth; ctx = crypto_instance_ctx(inst); err = crypto_init_ahash_spawn(&ctx->auth, auth, inst); if (err) goto err_free_inst; crypto_set_skcipher_spawn(&ctx->enc, inst); err = crypto_grab_skcipher(&ctx->enc, enc_name, 0, crypto_requires_sync(algt->type, algt->mask)); if (err) goto err_drop_auth; enc = crypto_skcipher_spawn_alg(&ctx->enc); err = -ENAMETOOLONG; if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME, "authenc(%s,%s)", auth_base->cra_name, enc->cra_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_enc; if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME, "authenc(%s,%s)", auth_base->cra_driver_name, enc->cra_driver_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_enc; inst->alg.cra_flags = CRYPTO_ALG_TYPE_AEAD; inst->alg.cra_flags |= enc->cra_flags & CRYPTO_ALG_ASYNC; inst->alg.cra_priority = enc->cra_priority * 10 + auth_base->cra_priority; inst->alg.cra_blocksize = enc->cra_blocksize; inst->alg.cra_alignmask = auth_base->cra_alignmask | enc->cra_alignmask; inst->alg.cra_type = &crypto_aead_type; inst->alg.cra_aead.ivsize = enc->cra_ablkcipher.ivsize; inst->alg.cra_aead.maxauthsize = auth->digestsize; inst->alg.cra_ctxsize = sizeof(struct crypto_authenc_ctx); inst->alg.cra_init = crypto_authenc_init_tfm; inst->alg.cra_exit = crypto_authenc_exit_tfm; inst->alg.cra_aead.setkey = crypto_authenc_setkey; inst->alg.cra_aead.encrypt = crypto_authenc_encrypt; inst->alg.cra_aead.decrypt = crypto_authenc_decrypt; inst->alg.cra_aead.givencrypt = crypto_authenc_givencrypt; out: crypto_mod_put(auth_base); return inst; err_drop_enc: crypto_drop_skcipher(&ctx->enc); err_drop_auth: crypto_drop_ahash(&ctx->auth); err_free_inst: kfree(inst); out_put_auth: inst = ERR_PTR(err); goto out; } 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 dtls1_retrieve_buffered_fragment(SSL *s, int *ok) { /*- * (0) check whether the desired fragment is available * if so: * (1) copy over the fragment to s->init_buf->data[] * (2) update s->init_num */ pitem *item; hm_fragment *frag; int al; *ok = 0; item = pqueue_peek(s->d1->buffered_messages); if (item == NULL) return 0; frag = (hm_fragment *)item->data; /* Don't return if reassembly still in progress */ if (frag->reassembly != NULL) frag->msg_header.frag_len); } CWE ID: CWE-399 Target: 1 Example 2: Code: void PasswordAutofillAgent::PasswordValueGatekeeper::OnUserGesture() { if (was_user_gesture_seen_) return; was_user_gesture_seen_ = true; for (WebInputElement& element : elements_) ShowValue(&element); elements_.clear(); } 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 vp7_fade_frame(VP8Context *s, VP56RangeCoder *c) { int alpha = (int8_t) vp8_rac_get_uint(c, 8); int beta = (int8_t) vp8_rac_get_uint(c, 8); int ret; if (!s->keyframe && (alpha || beta)) { int width = s->mb_width * 16; int height = s->mb_height * 16; AVFrame *src, *dst; if (!s->framep[VP56_FRAME_PREVIOUS] || !s->framep[VP56_FRAME_GOLDEN]) { av_log(s->avctx, AV_LOG_WARNING, "Discarding interframe without a prior keyframe!\n"); return AVERROR_INVALIDDATA; } dst = src = s->framep[VP56_FRAME_PREVIOUS]->tf.f; /* preserve the golden frame, write a new previous frame */ if (s->framep[VP56_FRAME_GOLDEN] == s->framep[VP56_FRAME_PREVIOUS]) { s->framep[VP56_FRAME_PREVIOUS] = vp8_find_free_buffer(s); if ((ret = vp8_alloc_frame(s, s->framep[VP56_FRAME_PREVIOUS], 1)) < 0) return ret; dst = s->framep[VP56_FRAME_PREVIOUS]->tf.f; copy_chroma(dst, src, width, height); } fade(dst->data[0], dst->linesize[0], src->data[0], src->linesize[0], width, height, alpha, beta); } return 0; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int asf_read_marker(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int i, count, name_len, ret; char name[1024]; avio_rl64(pb); // reserved 16 bytes avio_rl64(pb); // ... count = avio_rl32(pb); // markers count avio_rl16(pb); // reserved 2 bytes name_len = avio_rl16(pb); // name length for (i = 0; i < name_len; i++) avio_r8(pb); // skip the name for (i = 0; i < count; i++) { int64_t pres_time; int name_len; avio_rl64(pb); // offset, 8 bytes pres_time = avio_rl64(pb); // presentation time pres_time -= asf->hdr.preroll * 10000; avio_rl16(pb); // entry length avio_rl32(pb); // send time avio_rl32(pb); // flags name_len = avio_rl32(pb); // name length if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len) avio_skip(pb, name_len - ret); avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pres_time, AV_NOPTS_VALUE, name); } return 0; } CWE ID: CWE-834 Target: 1 Example 2: Code: struct nfs4_state_owner *nfs4_get_state_owner(struct nfs_server *server, struct rpc_cred *cred) { struct nfs_client *clp = server->nfs_client; struct nfs4_state_owner *sp, *new; spin_lock(&clp->cl_lock); sp = nfs4_find_state_owner(server, cred); spin_unlock(&clp->cl_lock); if (sp != NULL) return sp; new = nfs4_alloc_state_owner(); if (new == NULL) return NULL; new->so_client = clp; new->so_server = server; new->so_cred = cred; spin_lock(&clp->cl_lock); sp = nfs4_insert_state_owner(clp, new); spin_unlock(&clp->cl_lock); if (sp == new) get_rpccred(cred); else { rpc_destroy_wait_queue(&new->so_sequence.wait); kfree(new); } return sp; } 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: serverStatus_t *CL_GetServerStatus( netadr_t from ) { int i, oldest, oldestTime; for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) { if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) { return &cl_serverStatusList[i]; } } for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) { if ( cl_serverStatusList[i].retrieved ) { return &cl_serverStatusList[i]; } } oldest = -1; oldestTime = 0; for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) { if ( oldest == -1 || cl_serverStatusList[i].startTime < oldestTime ) { oldest = i; oldestTime = cl_serverStatusList[i].startTime; } } return &cl_serverStatusList[oldest]; } CWE ID: CWE-269 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 semctl_down(struct ipc_namespace *ns, int semid, int cmd, int version, void __user *p) { struct sem_array *sma; int err; struct semid64_ds semid64; struct kern_ipc_perm *ipcp; if(cmd == IPC_SET) { if (copy_semid_from_user(&semid64, p, version)) return -EFAULT; } ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd, &semid64.sem_perm, 0); if (IS_ERR(ipcp)) return PTR_ERR(ipcp); sma = container_of(ipcp, struct sem_array, sem_perm); err = security_sem_semctl(sma, cmd); if (err) { rcu_read_unlock(); goto out_unlock; } switch(cmd){ case IPC_RMID: ipc_lock_object(&sma->sem_perm); freeary(ns, ipcp); goto out_up; case IPC_SET: ipc_lock_object(&sma->sem_perm); err = ipc_update_perm(&semid64.sem_perm, ipcp); if (err) goto out_unlock; sma->sem_ctime = get_seconds(); break; default: rcu_read_unlock(); err = -EINVAL; goto out_up; } out_unlock: sem_unlock(sma); out_up: up_write(&sem_ids(ns).rw_mutex); return err; } CWE ID: CWE-189 Target: 1 Example 2: Code: pdf14_push_parent_color(gx_device *dev, const gs_gstate *pgs) { pdf14_device *pdev = (pdf14_device *)dev; pdf14_parent_color_t *new_parent_color; cmm_profile_t *icc_profile; gsicc_rendering_param_t render_cond; cmm_dev_profile_t *dev_profile; dev_proc(dev, get_profile)(dev, &dev_profile); gsicc_extract_profile(GS_UNKNOWN_TAG, dev_profile, &icc_profile, &render_cond); if_debug0m('v', dev->memory, "[v]pdf14_push_parent_color\n"); /* Allocate a new one */ new_parent_color = gs_alloc_struct(dev->memory, pdf14_parent_color_t, &st_pdf14_clr,"pdf14_clr_new"); /* Link to old one */ new_parent_color->previous = pdev->trans_group_parent_cmap_procs; /* Reassign new one to dev */ pdev->trans_group_parent_cmap_procs = new_parent_color; /* Initialize with values */ new_parent_color->get_cmap_procs = pgs->get_cmap_procs; new_parent_color->parent_color_mapping_procs = pdev->procs.get_color_mapping_procs; new_parent_color->parent_color_comp_index = pdev->procs.get_color_comp_index; new_parent_color->parent_blending_procs = pdev->blend_procs; new_parent_color->polarity = pdev->color_info.polarity; new_parent_color->num_components = pdev->color_info.num_components; new_parent_color->unpack_procs = pdev->pdf14_procs; new_parent_color->depth = pdev->color_info.depth; new_parent_color->max_color = pdev->color_info.max_color; new_parent_color->max_gray = pdev->color_info.max_gray; new_parent_color->decode = pdev->procs.decode_color; new_parent_color->encode = pdev->procs.encode_color; memcpy(&(new_parent_color->comp_bits),&(pdev->color_info.comp_bits), GX_DEVICE_COLOR_MAX_COMPONENTS); memcpy(&(new_parent_color->comp_shift),&(pdev->color_info.comp_shift), GX_DEVICE_COLOR_MAX_COMPONENTS); /* The ICC manager has the ICC profile for the device */ new_parent_color->icc_profile = icc_profile; rc_increment(icc_profile); /* isadditive is only used in ctx */ if (pdev->ctx) { new_parent_color->isadditive = pdev->ctx->additive; } } 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: cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = (size_t)off + len; if ((off_t)(off + len) != (off_t)siz) { errno = EINVAL; return -1; } if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return (ssize_t)len; } if (info->i_fd == -1) return -1; if (pread(info->i_fd, buf, len, off) != (ssize_t)len) return -1; return (ssize_t)len; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void local_socket_close(asocket* s) { adb_mutex_lock(&socket_list_lock); local_socket_close_locked(s); adb_mutex_unlock(&socket_list_lock); } CWE ID: CWE-264 Target: 1 Example 2: Code: static void WriteAlphaData(void* pixels, uint32_t row_count, uint32_t channel_count, uint32_t alpha_channel_index, uint32_t unpadded_row_size, uint32_t padded_row_size, pixel_data_type alpha_value) { DCHECK_GT(channel_count, 0U); DCHECK_EQ(unpadded_row_size % sizeof(pixel_data_type), 0U); uint32_t unpadded_row_size_in_elements = unpadded_row_size / sizeof(pixel_data_type); DCHECK_EQ(padded_row_size % sizeof(pixel_data_type), 0U); uint32_t padded_row_size_in_elements = padded_row_size / sizeof(pixel_data_type); pixel_data_type* dst = static_cast<pixel_data_type*>(pixels) + alpha_channel_index; for (uint32_t yy = 0; yy < row_count; ++yy) { pixel_data_type* end = dst + unpadded_row_size_in_elements; for (pixel_data_type* d = dst; d < end; d += channel_count) { *d = alpha_value; } dst += padded_row_size_in_elements; } } 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: LocalFrameClient* LocalFrame::Client() const { return static_cast<LocalFrameClient*>(Frame::Client()); } CWE ID: CWE-285 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 get_scl(void) { return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SCL1); } CWE ID: CWE-787 Target: 1 Example 2: Code: static inline bool cast6_fpu_begin(bool fpu_enabled, unsigned int nbytes) { return glue_fpu_begin(CAST6_BLOCK_SIZE, CAST6_PARALLEL_BLOCKS, NULL, fpu_enabled, nbytes); } 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: key_ref_t key_create_or_update(key_ref_t keyring_ref, const char *type, const char *description, const void *payload, size_t plen, key_perm_t perm, unsigned long flags) { struct keyring_index_key index_key = { .description = description, }; struct key_preparsed_payload prep; struct assoc_array_edit *edit; const struct cred *cred = current_cred(); struct key *keyring, *key = NULL; key_ref_t key_ref; int ret; /* look up the key type to see if it's one of the registered kernel * types */ index_key.type = key_type_lookup(type); if (IS_ERR(index_key.type)) { key_ref = ERR_PTR(-ENODEV); goto error; } key_ref = ERR_PTR(-EINVAL); if (!index_key.type->match || !index_key.type->instantiate || (!index_key.description && !index_key.type->preparse)) goto error_put_type; keyring = key_ref_to_ptr(keyring_ref); key_check(keyring); key_ref = ERR_PTR(-ENOTDIR); if (keyring->type != &key_type_keyring) goto error_put_type; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = index_key.type->def_datalen; prep.trusted = flags & KEY_ALLOC_TRUSTED; prep.expiry = TIME_T_MAX; if (index_key.type->preparse) { ret = index_key.type->preparse(&prep); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_free_prep; } if (!index_key.description) index_key.description = prep.description; key_ref = ERR_PTR(-EINVAL); if (!index_key.description) goto error_free_prep; } index_key.desc_len = strlen(index_key.description); key_ref = ERR_PTR(-EPERM); if (!prep.trusted && test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags)) goto error_free_prep; flags |= prep.trusted ? KEY_ALLOC_TRUSTED : 0; ret = __key_link_begin(keyring, &index_key, &edit); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_free_prep; } /* if we're going to allocate a new key, we're going to have * to modify the keyring */ ret = key_permission(keyring_ref, KEY_NEED_WRITE); if (ret < 0) { key_ref = ERR_PTR(ret); goto error_link_end; } /* if it's possible to update this type of key, search for an existing * key of the same type and description in the destination keyring and * update that instead if possible */ if (index_key.type->update) { key_ref = find_key_to_update(keyring_ref, &index_key); if (key_ref) goto found_matching_key; } /* if the client doesn't provide, decide on the permissions we want */ if (perm == KEY_PERM_UNDEF) { perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (index_key.type->read) perm |= KEY_POS_READ; if (index_key.type == &key_type_keyring || index_key.type->update) perm |= KEY_POS_WRITE; } /* allocate a new key */ key = key_alloc(index_key.type, index_key.description, cred->fsuid, cred->fsgid, cred, perm, flags); if (IS_ERR(key)) { key_ref = ERR_CAST(key); goto error_link_end; } /* instantiate it and link it into the target keyring */ ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit); if (ret < 0) { key_put(key); key_ref = ERR_PTR(ret); goto error_link_end; } key_ref = make_key_ref(key, is_key_possessed(keyring_ref)); error_link_end: __key_link_end(keyring, &index_key, edit); error_free_prep: if (index_key.type->preparse) index_key.type->free_preparse(&prep); error_put_type: key_type_put(index_key.type); error: return key_ref; found_matching_key: /* we found a matching key, so we're going to try to update it * - we can drop the locks first as we have the key pinned */ __key_link_end(keyring, &index_key, edit); key_ref = __key_update(key_ref, &prep); goto error_free_prep; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: XRRGetProviderResources(Display *dpy, Window window) { XExtDisplayInfo *info = XRRFindDisplay(dpy); xRRGetProvidersReply rep; xRRGetProvidersReq *req; XRRProviderResources *xrpr; long nbytes, nbytesRead; int rbytes; RRCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq(RRGetProviders, req); req->reqType = info->codes->major_opcode; req->randrReqType = X_RRGetProviders; req->window = window; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; return NULL; } nbytes = (long) rep.length << 2; nbytesRead = (long) (rep.nProviders * 4); rbytes = (sizeof(XRRProviderResources) + rep.nProviders * sizeof(RRProvider)); xrpr = (XRRProviderResources *) Xmalloc(rbytes); if (xrpr == NULL) { _XEatDataWords (dpy, rep.length); _XRead32(dpy, (long *) xrpr->providers, rep.nProviders << 2); if (nbytes > nbytesRead) _XEatData (dpy, (unsigned long) (nbytes - nbytesRead)); UnlockDisplay (dpy); SyncHandle(); return (XRRProviderResources *) xrpr; } void XRRFreeProviderResources(XRRProviderResources *provider_resources) { free(provider_resources); } #define ProviderInfoExtra (SIZEOF(xRRGetProviderInfoReply) - 32) XRRProviderInfo * XRRGetProviderInfo(Display *dpy, XRRScreenResources *resources, RRProvider provider) { XExtDisplayInfo *info = XRRFindDisplay(dpy); xRRGetProviderInfoReply rep; xRRGetProviderInfoReq *req; int nbytes, nbytesRead, rbytes; XRRProviderInfo *xpi; RRCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (RRGetProviderInfo, req); req->reqType = info->codes->major_opcode; req->randrReqType = X_RRGetProviderInfo; req->provider = provider; req->configTimestamp = resources->configTimestamp; if (!_XReply (dpy, (xReply *) &rep, ProviderInfoExtra >> 2, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; } nbytes = ((long) rep.length << 2) - ProviderInfoExtra; nbytesRead = (long)(rep.nCrtcs * 4 + rep.nOutputs * 4 + rep.nAssociatedProviders * 8 + ((rep.nameLength + 3) & ~3)); return NULL; } nbytes = ((long) rep.length << 2) - ProviderInfoExtra; nbytesRead = (long)(rep.nCrtcs * 4 + xpi->noutputs = rep.nOutputs; xpi->nassociatedproviders = rep.nAssociatedProviders; xpi->crtcs = (RRCrtc *)(xpi + 1); xpi->outputs = (RROutput *)(xpi->crtcs + rep.nCrtcs); xpi->associated_providers = (RRProvider *)(xpi->outputs + rep.nOutputs); xpi->associated_capability = (unsigned int *)(xpi->associated_providers + rep.nAssociatedProviders); xpi->name = (char *)(xpi->associated_capability + rep.nAssociatedProviders); _XRead32(dpy, (long *) xpi->crtcs, rep.nCrtcs << 2); _XRead32(dpy, (long *) xpi->outputs, rep.nOutputs << 2); _XRead32(dpy, (long *) xpi->associated_providers, rep.nAssociatedProviders << 2); /* * _XRead32 reads a series of 32-bit values from the protocol and writes * them out as a series of "long int" values, but associated_capability * is defined as unsigned int *, so that won't work for this array. * Instead we assume for now that "unsigned int" is also 32-bits, so * the values can be read without any conversion. */ _XRead(dpy, (char *) xpi->associated_capability, rep.nAssociatedProviders << 2); _XReadPad(dpy, xpi->name, rep.nameLength); xpi->name[rep.nameLength] = '\0'; /* * Skip any extra data */ if (nbytes > nbytesRead) _XEatData (dpy, (unsigned long) (nbytes - nbytesRead)); UnlockDisplay (dpy); SyncHandle (); return (XRRProviderInfo *) xpi; } CWE ID: CWE-787 Target: 1 Example 2: Code: static void auth_gssapi_display_status_1( char *m, OM_uint32 code, int type, int rec) { OM_uint32 gssstat, minor_stat; gss_buffer_desc msg; OM_uint32 msg_ctx; msg_ctx = 0; while (1) { gssstat = gss_display_status(&minor_stat, code, type, GSS_C_NULL_OID, &msg_ctx, &msg); if (gssstat != GSS_S_COMPLETE) { if (!rec) { auth_gssapi_display_status_1(m,gssstat,GSS_C_GSS_CODE,1); auth_gssapi_display_status_1(m, minor_stat, GSS_C_MECH_CODE, 1); } else { fputs ("GSS-API authentication error ", stderr); fwrite (msg.value, msg.length, 1, stderr); fputs (": recursive failure!\n", stderr); } return; } fprintf (stderr, "GSS-API authentication error %s: ", m); fwrite (msg.value, msg.length, 1, stderr); putc ('\n', stderr); if (misc_debug_gssapi) gssrpcint_printf("GSS-API authentication error %s: %*s\n", m, (int)msg.length, (char *) msg.value); (void) gss_release_buffer(&minor_stat, &msg); if (!msg_ctx) break; } } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Document::PropagateStyleToViewport() { DCHECK(InStyleRecalc()); if (!documentElement()) return; HTMLElement* body = this->body(); const ComputedStyle* body_style = body ? body->EnsureComputedStyle() : nullptr; const ComputedStyle* document_element_style = documentElement()->EnsureComputedStyle(); TouchAction effective_touch_action = document_element_style->GetEffectiveTouchAction(); WritingMode root_writing_mode = document_element_style->GetWritingMode(); TextDirection root_direction = document_element_style->Direction(); if (body_style) { root_writing_mode = body_style->GetWritingMode(); root_direction = body_style->Direction(); } const ComputedStyle* background_style = document_element_style; if (IsHTMLHtmlElement(documentElement()) && document_element_style->Display() != EDisplay::kNone && IsHTMLBodyElement(body) && !background_style->HasBackground()) { background_style = body_style; } Color background_color = Color::kTransparent; FillLayer background_layers(EFillLayerType::kBackground, true); EImageRendering image_rendering = EImageRendering::kAuto; if (background_style->Display() != EDisplay::kNone) { background_color = background_style->VisitedDependentColor( GetCSSPropertyBackgroundColor()); background_layers = background_style->BackgroundLayers(); for (auto* current_layer = &background_layers; current_layer; current_layer = current_layer->Next()) { current_layer->SetClip(EFillBox::kBorder); if (current_layer->Attachment() == EFillAttachment::kScroll) current_layer->SetAttachment(EFillAttachment::kLocal); } image_rendering = background_style->ImageRendering(); } const ComputedStyle* overflow_style = nullptr; Element* viewport_element = ViewportDefiningElement(); DCHECK(viewport_element); if (viewport_element == body) { overflow_style = body_style; } else { DCHECK_EQ(viewport_element, documentElement()); overflow_style = document_element_style; if (body_style && !body_style->IsOverflowVisible()) UseCounter::Count(*this, WebFeature::kBodyScrollsInAdditionToViewport); } DCHECK(overflow_style); EOverflowAnchor overflow_anchor = overflow_style->OverflowAnchor(); EOverflow overflow_x = overflow_style->OverflowX(); EOverflow overflow_y = overflow_style->OverflowY(); if (overflow_x == EOverflow::kVisible) overflow_x = EOverflow::kAuto; if (overflow_y == EOverflow::kVisible) overflow_y = EOverflow::kAuto; if (overflow_anchor == EOverflowAnchor::kVisible) overflow_anchor = EOverflowAnchor::kAuto; GapLength column_gap = overflow_style->ColumnGap(); ScrollSnapType snap_type = overflow_style->GetScrollSnapType(); ScrollBehavior scroll_behavior = document_element_style->GetScrollBehavior(); EOverscrollBehavior overscroll_behavior_x = overflow_style->OverscrollBehaviorX(); EOverscrollBehavior overscroll_behavior_y = overflow_style->OverscrollBehaviorY(); using OverscrollBehaviorType = cc::OverscrollBehavior::OverscrollBehaviorType; if (IsInMainFrame()) { GetPage()->GetOverscrollController().SetOverscrollBehavior( cc::OverscrollBehavior( static_cast<OverscrollBehaviorType>(overscroll_behavior_x), static_cast<OverscrollBehaviorType>(overscroll_behavior_y))); } Length scroll_padding_top = overflow_style->ScrollPaddingTop(); Length scroll_padding_right = overflow_style->ScrollPaddingRight(); Length scroll_padding_bottom = overflow_style->ScrollPaddingBottom(); Length scroll_padding_left = overflow_style->ScrollPaddingLeft(); const ComputedStyle& viewport_style = GetLayoutView()->StyleRef(); if (viewport_style.GetWritingMode() != root_writing_mode || viewport_style.Direction() != root_direction || viewport_style.VisitedDependentColor(GetCSSPropertyBackgroundColor()) != background_color || viewport_style.BackgroundLayers() != background_layers || viewport_style.ImageRendering() != image_rendering || viewport_style.OverflowAnchor() != overflow_anchor || viewport_style.OverflowX() != overflow_x || viewport_style.OverflowY() != overflow_y || viewport_style.ColumnGap() != column_gap || viewport_style.GetScrollSnapType() != snap_type || viewport_style.GetScrollBehavior() != scroll_behavior || viewport_style.OverscrollBehaviorX() != overscroll_behavior_x || viewport_style.OverscrollBehaviorY() != overscroll_behavior_y || viewport_style.ScrollPaddingTop() != scroll_padding_top || viewport_style.ScrollPaddingRight() != scroll_padding_right || viewport_style.ScrollPaddingBottom() != scroll_padding_bottom || viewport_style.ScrollPaddingLeft() != scroll_padding_left || viewport_style.GetEffectiveTouchAction() != effective_touch_action) { scoped_refptr<ComputedStyle> new_style = ComputedStyle::Clone(viewport_style); new_style->SetWritingMode(root_writing_mode); new_style->UpdateFontOrientation(); new_style->SetDirection(root_direction); new_style->SetBackgroundColor(background_color); new_style->AccessBackgroundLayers() = background_layers; new_style->SetImageRendering(image_rendering); new_style->SetOverflowAnchor(overflow_anchor); new_style->SetOverflowX(overflow_x); new_style->SetOverflowY(overflow_y); new_style->SetColumnGap(column_gap); new_style->SetScrollSnapType(snap_type); new_style->SetScrollBehavior(scroll_behavior); new_style->SetOverscrollBehaviorX(overscroll_behavior_x); new_style->SetOverscrollBehaviorY(overscroll_behavior_y); new_style->SetScrollPaddingTop(scroll_padding_top); new_style->SetScrollPaddingRight(scroll_padding_right); new_style->SetScrollPaddingBottom(scroll_padding_bottom); new_style->SetScrollPaddingLeft(scroll_padding_left); new_style->SetEffectiveTouchAction(effective_touch_action); GetLayoutView()->SetStyle(new_style); SetupFontBuilder(*new_style); if (PaintLayerScrollableArea* scrollable_area = GetLayoutView()->GetScrollableArea()) { if (scrollable_area->HorizontalScrollbar() && scrollable_area->HorizontalScrollbar()->IsCustomScrollbar()) scrollable_area->HorizontalScrollbar()->StyleChanged(); if (scrollable_area->VerticalScrollbar() && scrollable_area->VerticalScrollbar()->IsCustomScrollbar()) scrollable_area->VerticalScrollbar()->StyleChanged(); } } } 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: SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } CWE ID: CWE-200 Target: 1 Example 2: Code: int trace_array_get(struct trace_array *this_tr) { struct trace_array *tr; int ret = -ENODEV; mutex_lock(&trace_types_lock); list_for_each_entry(tr, &ftrace_trace_arrays, list) { if (tr == this_tr) { tr->ref++; ret = 0; break; } } mutex_unlock(&trace_types_lock); return ret; } 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 inline void skcipher_map_src(struct skcipher_walk *walk) { walk->src.virt.addr = skcipher_map(&walk->in); } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()) { char *file; int file_len; long srcx, srcy, width, height; gdImagePtr im = NULL; php_stream *stream; FILE * fp = NULL; #ifdef HAVE_GD_JPG long ignore_warning; #endif if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) { return; } if (width < 1 || height < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed"); RETURN_FALSE; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &file, &file_len) == FAILURE) { return; } } stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL); if (stream == NULL) { RETURN_FALSE; } #ifndef USE_GD_IOCTX ioctx_func_p = NULL; /* don't allow sockets without IOCtx */ #endif if (image_type == PHP_GDIMG_TYPE_WEBP) { size_t buff_size; char *buff; /* needs to be malloc (persistent) - GD will free() it later */ buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1); if (!buff_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data"); goto out_err; } im = (*ioctx_func_p)(buff_size, buff); if (!im) { goto out_err; } goto register_im; } /* try and avoid allocating a FILE* if the stream is not naturally a FILE* */ if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) { if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { goto out_err; } } else if (ioctx_func_p) { #ifdef USE_GD_IOCTX /* we can create an io context */ gdIOCtx* io_ctx; size_t buff_size; char *buff; /* needs to be malloc (persistent) - GD will free() it later */ buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1); if (!buff_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data"); goto out_err; } io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0); if (!io_ctx) { pefree(buff, 1); php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context"); goto out_err; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height); } else { im = (*ioctx_func_p)(io_ctx); } #if HAVE_LIBGD204 io_ctx->gd_free(io_ctx); #else io_ctx->free(io_ctx); #endif pefree(buff, 1); #endif } else { /* try and force the stream to be FILE* */ if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) { goto out_err; } } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = (*func_p)(fp, srcx, srcy, width, height); break; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(file); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); #ifdef HAVE_GD_BUNDLED im = gdImageCreateFromJpeg(fp, ignore_warning); #else im = gdImageCreateFromJpeg(fp); #endif break; #endif default: im = (*func_p)(fp); break; } fflush(fp); } register_im: if (im) { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); php_stream_close(stream); return; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn); out_err: php_stream_close(stream); RETURN_FALSE; } CWE ID: CWE-254 Target: 1 Example 2: Code: EventTarget* Document::ErrorEventTarget() { return domWindow(); } 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: dbus_g_proxy_manager_unmonitor_name_owner (DBusGProxyManager *manager, const char *name) { DBusGProxyNameOwnerInfo *info; const char *owner; gboolean ret; ret = dbus_g_proxy_manager_lookup_name_owner (manager, name, &info, &owner); g_assert (ret); g_assert (info != NULL); g_assert (owner != NULL); info->refcount--; if (info->refcount == 0) { GSList *names; GSList *link; names = g_hash_table_lookup (manager->owner_names, owner); link = g_slist_find_custom (names, name, find_name_in_info); names = g_slist_delete_link (names, link); if (names != NULL) g_hash_table_insert (manager->owner_names, g_strdup (owner), names); else g_hash_table_remove (manager->owner_names, owner); g_free (info->name); g_free (info); } } 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 mm_release(struct task_struct *tsk, struct mm_struct *mm) { struct completion *vfork_done = tsk->vfork_done; /* Get rid of any cached register state */ deactivate_mm(tsk, mm); /* notify parent sleeping on vfork() */ if (vfork_done) { tsk->vfork_done = NULL; complete(vfork_done); } /* * If we're exiting normally, clear a user-space tid field if * requested. We leave this alone when dying by signal, to leave * the value intact in a core dump, and to save the unnecessary * trouble otherwise. Userland only wants this done for a sys_exit. */ if (tsk->clear_child_tid && !(tsk->flags & PF_SIGNALED) && atomic_read(&mm->mm_users) > 1) { u32 __user * tidptr = tsk->clear_child_tid; tsk->clear_child_tid = NULL; /* * We don't check the error code - if userspace has * not set up a proper pointer then tough luck. */ put_user(0, tidptr); sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0); } } CWE ID: CWE-264 Target: 1 Example 2: Code: int32_t WebContentsImpl::GetMaxPageID() { return GetMaxPageIDForSiteInstance(GetSiteInstance()); } 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 ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr, pmd_t *pmd, unsigned int flags) { int result; handle_t *handle = NULL; struct inode *inode = file_inode(vma->vm_file); struct super_block *sb = inode->i_sb; bool write = flags & FAULT_FLAG_WRITE; if (write) { sb_start_pagefault(sb); file_update_time(vma->vm_file); handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE, ext4_chunk_trans_blocks(inode, PMD_SIZE / PAGE_SIZE)); } if (IS_ERR(handle)) result = VM_FAULT_SIGBUS; else result = __dax_pmd_fault(vma, addr, pmd, flags, ext4_get_block_dax, ext4_end_io_unwritten); if (write) { if (!IS_ERR(handle)) ext4_journal_stop(handle); sb_end_pagefault(sb); } return result; } CWE ID: CWE-362 Output:
1