prompt
stringlengths
799
20.4k
output
int64
0
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ff_h264_free_tables(H264Context *h, int free_rbsp) { int i; H264Context *hx; av_freep(&h->intra4x4_pred_mode); av_freep(&h->chroma_pred_mode_table); av_freep(&h->cbp_table); av_freep(&h->mvd_table[0]); av_freep(&h->mvd_table[1]); av_freep(&h->direct_table); av_freep(&h->non_zero_count); av_freep(&h->slice_table_base); h->slice_table = NULL; av_freep(&h->list_counts); av_freep(&h->mb2b_xy); av_freep(&h->mb2br_xy); av_buffer_pool_uninit(&h->qscale_table_pool); av_buffer_pool_uninit(&h->mb_type_pool); av_buffer_pool_uninit(&h->motion_val_pool); av_buffer_pool_uninit(&h->ref_index_pool); if (free_rbsp && h->DPB) { for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) ff_h264_unref_picture(h, &h->DPB[i]); av_freep(&h->DPB); } else if (h->DPB) { for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) h->DPB[i].needs_realloc = 1; } h->cur_pic_ptr = NULL; for (i = 0; i < H264_MAX_THREADS; i++) { hx = h->thread_context[i]; if (!hx) continue; av_freep(&hx->top_borders[1]); av_freep(&hx->top_borders[0]); av_freep(&hx->bipred_scratchpad); av_freep(&hx->edge_emu_buffer); av_freep(&hx->dc_val_base); av_freep(&hx->er.mb_index2xy); av_freep(&hx->er.error_status_table); av_freep(&hx->er.er_temp_buffer); av_freep(&hx->er.mbintra_table); av_freep(&hx->er.mbskip_table); if (free_rbsp) { av_freep(&hx->rbsp_buffer[1]); av_freep(&hx->rbsp_buffer[0]); hx->rbsp_buffer_size[0] = 0; hx->rbsp_buffer_size[1] = 0; } if (i) av_freep(&h->thread_context[i]); } } CWE ID: Target: 1 Example 2: Code: static int vfat_find(struct inode *dir, struct qstr *qname, struct fat_slot_info *sinfo) { unsigned int len = vfat_striptail_len(qname); if (len == 0) return -ENOENT; return fat_search_long(dir, qname->name, len, sinfo); } 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 ColorChooserDialog::DidCloseDialog(bool chose_color, SkColor color, RunState run_state) { if (!listener_) return; EndRun(run_state); CopyCustomColors(custom_colors_, g_custom_colors); if (chose_color) listener_->OnColorChosen(color); listener_->OnColorChooserDialogClosed(); } 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 PluginInfoMessageFilter::PluginsLoaded( const GetPluginInfo_Params& params, IPC::Message* reply_msg, const std::vector<WebPluginInfo>& plugins) { ChromeViewHostMsg_GetPluginInfo_Output output; scoped_ptr<PluginMetadata> plugin_metadata; if (context_.FindEnabledPlugin(params.render_view_id, params.url, params.top_origin_url, params.mime_type, &output.status, &output.plugin, &output.actual_mime_type, &plugin_metadata)) { context_.DecidePluginStatus(params, output.plugin, plugin_metadata.get(), &output.status); } if (plugin_metadata) { output.group_identifier = plugin_metadata->identifier(); output.group_name = plugin_metadata->name(); } context_.GrantAccess(output.status, output.plugin.path); ChromeViewHostMsg_GetPluginInfo::WriteReplyParams(reply_msg, output); Send(reply_msg); } CWE ID: CWE-287 Target: 1 Example 2: Code: static void atl2_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo) { struct atl2_adapter *adapter = netdev_priv(netdev); strlcpy(drvinfo->driver, atl2_driver_name, sizeof(drvinfo->driver)); strlcpy(drvinfo->version, atl2_driver_version, sizeof(drvinfo->version)); strlcpy(drvinfo->fw_version, "L2", sizeof(drvinfo->fw_version)); strlcpy(drvinfo->bus_info, pci_name(adapter->pdev), sizeof(drvinfo->bus_info)); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline bool checkAddChild(ContainerNode* newParent, Node* newChild, ExceptionState& es) { return checkAcceptChild(newParent, newChild, 0, es); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DaemonProcess::OnChannelConnected() { DCHECK(caller_task_runner()->BelongsToCurrentThread()); DeleteAllDesktopSessions(); next_terminal_id_ = 0; SendToNetwork( new ChromotingDaemonNetworkMsg_Configuration(serialized_config_)); } CWE ID: CWE-399 Target: 1 Example 2: Code: bool DBusHelperProxy::hasToStopAction() { QEventLoop loop; loop.processEvents(QEventLoop::AllEvents); return m_stopRequest; } CWE ID: CWE-290 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PrintPreviewUI::GetCurrentPrintPreviewStatus( const std::string& preview_ui_addr, int request_id, bool* cancel) { int current_id = -1; if (!g_print_preview_request_id_map.Get().Get(preview_ui_addr, &current_id)) { *cancel = true; return; } *cancel = (request_id != current_id); } 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: bool ScreenLayoutObserver::GetDisplayMessageForNotification( const ScreenLayoutObserver::DisplayInfoMap& old_info, base::string16* out_message, base::string16* out_additional_message) { if (old_display_mode_ != current_display_mode_) { if (current_display_mode_ == DisplayMode::MIRRORING) { *out_message = GetEnterMirrorModeMessage(); return true; } if (old_display_mode_ == DisplayMode::MIRRORING && GetExitMirrorModeMessage(out_message, out_additional_message)) { return true; } if (current_display_mode_ == DisplayMode::UNIFIED) { *out_message = GetEnterUnifiedModeMessage(); return true; } if (old_display_mode_ == DisplayMode::UNIFIED) { *out_message = GetExitUnifiedModeMessage(); return true; } if (current_display_mode_ == DisplayMode::DOCKED || old_display_mode_ == DisplayMode::DOCKED) { return false; } } if (display_info_.size() < old_info.size()) { for (const auto& iter : old_info) { if (display_info_.count(iter.first)) continue; *out_message = GetDisplayRemovedMessage(iter.second, out_additional_message); return true; } } else if (display_info_.size() > old_info.size()) { for (const auto& iter : display_info_) { if (old_info.count(iter.first)) continue; *out_message = GetDisplayAddedMessage(iter.first, out_additional_message); return true; } } for (const auto& iter : display_info_) { DisplayInfoMap::const_iterator old_iter = old_info.find(iter.first); if (old_iter == old_info.end()) { NOTREACHED() << "A display mode transition that should have been handled" "earlier."; return false; } if (iter.second.configured_ui_scale() != old_iter->second.configured_ui_scale()) { *out_additional_message = l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_RESOLUTION_CHANGED, GetDisplayName(iter.first), GetDisplaySize(iter.first)); return true; } if (iter.second.GetActiveRotation() != old_iter->second.GetActiveRotation()) { int rotation_text_id = 0; switch (iter.second.GetActiveRotation()) { case display::Display::ROTATE_0: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_STANDARD_ORIENTATION; break; case display::Display::ROTATE_90: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_90; break; case display::Display::ROTATE_180: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_180; break; case display::Display::ROTATE_270: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_270; break; } *out_additional_message = l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_ROTATED, GetDisplayName(iter.first), l10n_util::GetStringUTF16(rotation_text_id)); return true; } } return false; } CWE ID: CWE-17 Target: 1 Example 2: Code: static void release_wddx_packet_rsrc(zend_resource *rsrc) { smart_str *str = (smart_str *)rsrc->ptr; smart_str_free(str); efree(str); } 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: Element* ContainerNode::lastElementChild() const { Node* n = lastChild(); while (n && !n->isElementNode()) n = n->previousSibling(); return toElement(n); } 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: header_put_le_3byte (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; } ; } /* header_put_le_3byte */ CWE ID: CWE-119 Target: 1 Example 2: Code: static int nfs_idmap_instantiate(struct key *key, struct key *authkey, char *data, size_t datalen) { return key_instantiate_and_link(key, data, datalen, id_resolver_cache->thread_keyring, authkey); } 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: ProcQueryTree(ClientPtr client) { xQueryTreeReply reply; int rc, numChildren = 0; WindowPtr pChild, pWin, pHead; Window *childIDs = (Window *) NULL; REQUEST(xResourceReq); REQUEST_SIZE_MATCH(xResourceReq); rc = dixLookupWindow(&pWin, stuff->id, client, DixListAccess); if (rc != Success) return rc; reply = (xQueryTreeReply) { .type = X_Reply, .sequenceNumber = client->sequence, .root = pWin->drawable.pScreen->root->drawable.id, .parent = (pWin->parent) ? pWin->parent->drawable.id : (Window) None }; pHead = RealChildHead(pWin); for (pChild = pWin->lastChild; pChild != pHead; pChild = pChild->prevSib) numChildren++; if (numChildren) { int curChild = 0; childIDs = malloc(numChildren * sizeof(Window)); if (!childIDs) return BadAlloc; for (pChild = pWin->lastChild; pChild != pHead; pChild = pChild->prevSib) childIDs[curChild++] = pChild->drawable.id; } reply.nChildren = numChildren; reply.length = bytes_to_int32(numChildren * sizeof(Window)); WriteReplyToClient(client, sizeof(xQueryTreeReply), &reply); if (numChildren) { client->pSwapReplyFunc = (ReplySwapPtr) Swap32Write; WriteSwappedDataToClient(client, numChildren * sizeof(Window), childIDs); free(childIDs); } return Success; } CWE ID: CWE-369 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RTCPeerConnection::createOffer(PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback, const Dictionary& mediaConstraints, ExceptionCode& ec) { if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) { ec = INVALID_STATE_ERR; return; } if (!successCallback) { ec = TYPE_MISMATCH_ERR; return; } RefPtr<MediaConstraints> constraints = MediaConstraintsImpl::create(mediaConstraints, ec); if (ec) return; RefPtr<RTCSessionDescriptionRequestImpl> request = RTCSessionDescriptionRequestImpl::create(scriptExecutionContext(), successCallback, errorCallback); m_peerHandler->createOffer(request.release(), constraints); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void i6300esb_reset(DeviceState *dev) { PCIDevice *pdev = PCI_DEVICE(dev); I6300State *d = WATCHDOG_I6300ESB_DEVICE(pdev); i6300esb_debug("I6300State = %p\n", d); i6300esb_disable_timer(d); /* NB: Don't change d->previous_reboot_flag in this function. */ d->reboot_enabled = 1; d->clock_scale = CLOCK_SCALE_1KHZ; d->int_type = INT_TYPE_IRQ; d->free_run = 0; d->locked = 0; d->enabled = 0; d->timer1_preload = 0xfffff; d->timer2_preload = 0xfffff; d->stage = 1; d->unlock_state = 0; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int f2fs_get_block(struct dnode_of_data *dn, pgoff_t index) { struct extent_info ei; struct inode *inode = dn->inode; if (f2fs_lookup_extent_cache(inode, index, &ei)) { dn->data_blkaddr = ei.blk + index - ei.fofs; return 0; } return f2fs_reserve_block(dn, index); } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { int id = ctxt->input->id; SKIP(3); SKIP_BLANKS; if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) { SKIP(7); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering INCLUDE Conditional Section\n"); } while ((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || (NXT(2) != '>'))) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving INCLUDE Conditional Section\n"); } } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) { int state; xmlParserInputState instate; int depth = 0; SKIP(6); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering IGNORE Conditional Section\n"); } /* * Parse up to the end of the conditional section * But disable SAX event generating DTD building in the meantime */ state = ctxt->disableSAX; instate = ctxt->instate; if (ctxt->recovery == 0) ctxt->disableSAX = 1; ctxt->instate = XML_PARSER_IGNORE; while ((depth >= 0) && (RAW != 0)) { if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { depth++; SKIP(3); continue; } if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (--depth >= 0) SKIP(3); continue; } NEXT; continue; } ctxt->disableSAX = state; ctxt->instate = instate; if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving IGNORE Conditional Section\n"); } } else { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL); } if (RAW == 0) SHRINK; if (RAW == 0) { xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } SKIP(3); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static struct async *reap_as(struct usb_dev_state *ps) { DECLARE_WAITQUEUE(wait, current); struct async *as = NULL; struct usb_device *dev = ps->dev; add_wait_queue(&ps->wait, &wait); for (;;) { __set_current_state(TASK_INTERRUPTIBLE); as = async_getcompleted(ps); if (as || !connected(ps)) break; if (signal_pending(current)) break; usb_unlock_device(dev); schedule(); usb_lock_device(dev); } remove_wait_queue(&ps->wait, &wait); set_current_state(TASK_RUNNING); return as; } 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: void BrowserEventRouter::DispatchSimpleBrowserEvent( Profile* profile, const int window_id, const char* event_name) { if (!profile_->IsSameProfile(profile)) return; scoped_ptr<ListValue> args(new ListValue()); args->Append(Value::CreateIntegerValue(window_id)); DispatchEvent(profile, event_name, args.Pass(), EventRouter::USER_GESTURE_UNKNOWN); } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType) { bool errorOccurred = false; double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0; ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred); pendingScript.stopWatchingForLoad(this); if (!isExecutingScript()) { Microtask::performCheckpoint(); if (pendingScriptType == PendingScript::ParsingBlocking) { m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady(); if (m_hasScriptsWaitingForResources) return; } } RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear(); double compilationFinishTime = 0; if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) { NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document); if (errorOccurred) scriptLoader->dispatchErrorEvent(); else { ASSERT(isExecutingScript()); if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) { scriptLoader->dispatchErrorEvent(); } else { element->dispatchEvent(createScriptLoadEvent()); } } } const double epsilon = 1; if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) { Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50); } ASSERT(!isExecutingScript()); } CWE ID: CWE-254 Target: 1 Example 2: Code: void drm_property_destroy(struct drm_device *dev, struct drm_property *property) { struct drm_property_enum *prop_enum, *pt; list_for_each_entry_safe(prop_enum, pt, &property->enum_blob_list, head) { list_del(&prop_enum->head); kfree(prop_enum); } if (property->num_values) kfree(property->values); drm_mode_object_put(dev, &property->base); list_del(&property->head); kfree(property); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool config_save(const config_t *config, const char *filename) { assert(config != NULL); assert(filename != NULL); assert(*filename != '\0'); char *temp_filename = osi_calloc(strlen(filename) + 5); if (!temp_filename) { LOG_ERROR("%s unable to allocate memory for filename.", __func__); return false; } strcpy(temp_filename, filename); strcat(temp_filename, ".new"); FILE *fp = fopen(temp_filename, "wt"); if (!fp) { LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno)); goto error; } for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) { const section_t *section = (const section_t *)list_node(node); fprintf(fp, "[%s]\n", section->name); for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) { const entry_t *entry = (const entry_t *)list_node(enode); fprintf(fp, "%s = %s\n", entry->key, entry->value); } if (list_next(node) != list_end(config->sections)) fputc('\n', fp); } fflush(fp); fclose(fp); if (chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) { LOG_ERROR("%s unable to change file permissions '%s': %s", __func__, filename, strerror(errno)); goto error; } if (rename(temp_filename, filename) == -1) { LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno)); goto error; } osi_free(temp_filename); return true; error:; unlink(temp_filename); osi_free(temp_filename); return false; } CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr) { int err = simple_setattr(dentry, iattr); if (!err && (iattr->ia_valid & ATTR_UID)) { struct socket *sock = SOCKET_I(d_inode(dentry)); sock->sk->sk_uid = iattr->ia_uid; } return err; } CWE ID: CWE-362 Target: 1 Example 2: Code: static __init int hardware_setup(void) { if (setup_vmcs_config(&vmcs_config) < 0) return -EIO; if (boot_cpu_has(X86_FEATURE_NX)) kvm_enable_efer_bits(EFER_NX); if (!cpu_has_vmx_vpid()) enable_vpid = 0; if (!cpu_has_vmx_shadow_vmcs()) enable_shadow_vmcs = 0; if (!cpu_has_vmx_ept() || !cpu_has_vmx_ept_4levels()) { enable_ept = 0; enable_unrestricted_guest = 0; enable_ept_ad_bits = 0; } if (!cpu_has_vmx_ept_ad_bits()) enable_ept_ad_bits = 0; if (!cpu_has_vmx_unrestricted_guest()) enable_unrestricted_guest = 0; if (!cpu_has_vmx_flexpriority()) flexpriority_enabled = 0; if (!cpu_has_vmx_tpr_shadow()) kvm_x86_ops->update_cr8_intercept = NULL; if (enable_ept && !cpu_has_vmx_ept_2m_page()) kvm_disable_largepages(); if (!cpu_has_vmx_ple()) ple_gap = 0; if (!cpu_has_vmx_apicv()) enable_apicv = 0; if (enable_apicv) kvm_x86_ops->update_cr8_intercept = NULL; else { kvm_x86_ops->hwapic_irr_update = NULL; kvm_x86_ops->deliver_posted_interrupt = NULL; kvm_x86_ops->sync_pir_to_irr = vmx_sync_pir_to_irr_dummy; } if (nested) nested_vmx_setup_ctls_msrs(); return alloc_kvm_area(); } 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 stop_tty(struct tty_struct *tty) { unsigned long flags; spin_lock_irqsave(&tty->ctrl_lock, flags); if (tty->stopped) { spin_unlock_irqrestore(&tty->ctrl_lock, flags); return; } tty->stopped = 1; if (tty->link && tty->link->packet) { tty->ctrl_status &= ~TIOCPKT_START; tty->ctrl_status |= TIOCPKT_STOP; wake_up_interruptible_poll(&tty->link->read_wait, POLLIN); } spin_unlock_irqrestore(&tty->ctrl_lock, flags); if (tty->ops->stop) (tty->ops->stop)(tty); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void VaapiVideoDecodeAccelerator::VaapiH264Accelerator::Reset() { vaapi_wrapper_->DestroyPendingBuffers(); } CWE ID: CWE-362 Target: 1 Example 2: Code: static void elementAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValueFast(info, WTF::getPtr(imp->elementAttribute()), imp); } 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: header_read (SF_PRIVATE *psf, void *ptr, int bytes) { int count = 0 ; if (psf->headindex >= SIGNED_SIZEOF (psf->header)) return psf_fread (ptr, 1, bytes, psf) ; if (psf->headindex + bytes > SIGNED_SIZEOF (psf->header)) { int most ; most = SIGNED_SIZEOF (psf->header) - psf->headend ; psf_fread (psf->header + psf->headend, 1, most, psf) ; memcpy (ptr, psf->header + psf->headend, most) ; psf->headend = psf->headindex += most ; psf_fread ((char *) ptr + most, bytes - most, 1, psf) ; return bytes ; } ; if (psf->headindex + bytes > psf->headend) { count = psf_fread (psf->header + psf->headend, 1, bytes - (psf->headend - psf->headindex), psf) ; if (count != bytes - (int) (psf->headend - psf->headindex)) { psf_log_printf (psf, "Error : psf_fread returned short count.\n") ; return count ; } ; psf->headend += count ; } ; memcpy (ptr, psf->header + psf->headindex, bytes) ; psf->headindex += bytes ; return bytes ; } /* header_read */ 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: _TIFFmalloc(tsize_t s) { return (malloc((size_t) s)); } CWE ID: CWE-369 Target: 1 Example 2: Code: bool IsSyncableApp(const Extension* extension) { return GetSyncType(extension) == SYNC_TYPE_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: static void voidMethodTestInterfaceEmptyArgVariadicTestInterfaceEmptyArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::voidMethodTestInterfaceEmptyArgVariadicTestInterfaceEmptyArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void sas_eh_handle_sas_errors(struct Scsi_Host *shost, struct list_head *work_q) { struct scsi_cmnd *cmd, *n; enum task_disposition res = TASK_IS_DONE; int tmf_resp, need_reset; struct sas_internal *i = to_sas_internal(shost->transportt); unsigned long flags; struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost); LIST_HEAD(done); /* clean out any commands that won the completion vs eh race */ list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_task *task; spin_lock_irqsave(&dev->done_lock, flags); /* by this point the lldd has either observed * SAS_HA_FROZEN and is leaving the task alone, or has * won the race with eh and decided to complete it */ task = TO_SAS_TASK(cmd); spin_unlock_irqrestore(&dev->done_lock, flags); if (!task) list_move_tail(&cmd->eh_entry, &done); } Again: list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct sas_task *task = TO_SAS_TASK(cmd); list_del_init(&cmd->eh_entry); spin_lock_irqsave(&task->task_state_lock, flags); need_reset = task->task_state_flags & SAS_TASK_NEED_DEV_RESET; spin_unlock_irqrestore(&task->task_state_lock, flags); if (need_reset) { SAS_DPRINTK("%s: task 0x%p requests reset\n", __func__, task); goto reset; } SAS_DPRINTK("trying to find task 0x%p\n", task); res = sas_scsi_find_task(task); switch (res) { case TASK_IS_DONE: SAS_DPRINTK("%s: task 0x%p is done\n", __func__, task); sas_eh_defer_cmd(cmd); continue; case TASK_IS_ABORTED: SAS_DPRINTK("%s: task 0x%p is aborted\n", __func__, task); sas_eh_defer_cmd(cmd); continue; case TASK_IS_AT_LU: SAS_DPRINTK("task 0x%p is at LU: lu recover\n", task); reset: tmf_resp = sas_recover_lu(task->dev, cmd); if (tmf_resp == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("dev %016llx LU %llx is " "recovered\n", SAS_ADDR(task->dev), cmd->device->lun); sas_eh_defer_cmd(cmd); sas_scsi_clear_queue_lu(work_q, cmd); goto Again; } /* fallthrough */ case TASK_IS_NOT_AT_LU: case TASK_ABORT_FAILED: SAS_DPRINTK("task 0x%p is not at LU: I_T recover\n", task); tmf_resp = sas_recover_I_T(task->dev); if (tmf_resp == TMF_RESP_FUNC_COMPLETE || tmf_resp == -ENODEV) { struct domain_device *dev = task->dev; SAS_DPRINTK("I_T %016llx recovered\n", SAS_ADDR(task->dev->sas_addr)); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_I_T(work_q, dev); goto Again; } /* Hammer time :-) */ try_to_reset_cmd_device(cmd); if (i->dft->lldd_clear_nexus_port) { struct asd_sas_port *port = task->dev->port; SAS_DPRINTK("clearing nexus for port:%d\n", port->id); res = i->dft->lldd_clear_nexus_port(port); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus port:%d " "succeeded\n", port->id); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_port(work_q, port); goto Again; } } if (i->dft->lldd_clear_nexus_ha) { SAS_DPRINTK("clear nexus ha\n"); res = i->dft->lldd_clear_nexus_ha(ha); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus ha " "succeeded\n"); sas_eh_finish_cmd(cmd); goto clear_q; } } /* If we are here -- this means that no amount * of effort could recover from errors. Quite * possibly the HA just disappeared. */ SAS_DPRINTK("error from device %llx, LUN %llx " "couldn't be recovered in any way\n", SAS_ADDR(task->dev->sas_addr), cmd->device->lun); sas_eh_finish_cmd(cmd); goto clear_q; } } out: list_splice_tail(&done, work_q); list_splice_tail_init(&ha->eh_ata_q, work_q); return; clear_q: SAS_DPRINTK("--- Exit %s -- clear_q\n", __func__); list_for_each_entry_safe(cmd, n, work_q, eh_entry) sas_eh_finish_cmd(cmd); goto out; } CWE ID: Target: 1 Example 2: Code: SYSCALL_DEFINE1(set_thread_area, struct user_desc __user *, u_info) { return do_set_thread_area(current, -1, u_info, 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: int ip_options_get_from_user(struct net *net, struct ip_options **optp, unsigned char __user *data, int optlen) { struct ip_options *opt = ip_options_get_alloc(optlen); if (!opt) return -ENOMEM; if (optlen && copy_from_user(opt->__data, data, optlen)) { kfree(opt); return -EFAULT; } return ip_options_get_finish(net, optp, opt, optlen); } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags) { CMS_SignerInfo *si; STACK_OF(CMS_SignerInfo) *sinfos; STACK_OF(X509) *cms_certs = NULL; STACK_OF(X509_CRL) *crls = NULL; X509 *signer; int i, scount = 0, ret = 0; BIO *cmsbio = NULL, *tmpin = NULL; if (!dcont && !check_content(cms)) return 0; /* Attempt to find all signer certificates */ sinfos = CMS_get0_SignerInfos(cms); if (sk_CMS_SignerInfo_num(sinfos) <= 0) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_NO_SIGNERS); goto err; } for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); CMS_SignerInfo_get0_algs(si, NULL, &signer, NULL, NULL); if (signer) scount++; } if (scount != sk_CMS_SignerInfo_num(sinfos)) scount += CMS_set1_signers_certs(cms, certs, flags); if (scount != sk_CMS_SignerInfo_num(sinfos)) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND); goto err; } /* Attempt to verify all signers certs */ if (!(flags & CMS_NO_SIGNER_CERT_VERIFY)) { cms_certs = CMS_get1_certs(cms); if (!(flags & CMS_NOCRL)) crls = CMS_get1_crls(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (!cms_signerinfo_verify_cert(si, store, cms_certs, crls, flags)) goto err; } } /* Attempt to verify all SignerInfo signed attribute signatures */ if (!(flags & CMS_NO_ATTR_VERIFY)) { for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (CMS_signed_get_attr_count(si) < 0) continue; if (CMS_SignerInfo_verify(si) <= 0) goto err; } } /* Performance optimization: if the content is a memory BIO then * store its contents in a temporary read only memory BIO. This * avoids potentially large numbers of slow copies of data which will * occur when reading from a read write memory BIO when signatures * are calculated. */ if (dcont && (BIO_method_type(dcont) == BIO_TYPE_MEM)) { char *ptr; long len; len = BIO_get_mem_data(dcont, &ptr); tmpin = BIO_new_mem_buf(ptr, len); if (tmpin == NULL) { CMSerr(CMS_F_CMS_VERIFY,ERR_R_MALLOC_FAILURE); return 0; } } else tmpin = dcont; cmsbio=CMS_dataInit(cms, tmpin); if (!cmsbio) goto err; if (!cms_copy_content(out, cmsbio, flags)) goto err; if (!(flags & CMS_NO_CONTENT_VERIFY)) { for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) { si = sk_CMS_SignerInfo_value(sinfos, i); if (CMS_SignerInfo_verify_content(si, cmsbio) <= 0) { CMSerr(CMS_F_CMS_VERIFY, CMS_R_CONTENT_VERIFY_ERROR); goto err; } } } ret = 1; err: if (dcont && (tmpin == dcont)) do_free_upto(cmsbio, dcont); else BIO_free_all(cmsbio); if (cms_certs) sk_X509_pop_free(cms_certs, X509_free); if (crls) sk_X509_CRL_pop_free(crls, X509_CRL_free); return ret; } CWE ID: CWE-399 Target: 1 Example 2: Code: void TabStripModel::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: { int index = GetIndexOfWebContents( content::Source<WebContents>(source).ptr()); if (index != TabStripModel::kNoTab) { DetachTabContentsAt(index); } break; } case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const extensions::Extension* extension = content::Details<extensions::UnloadedExtensionInfo>( details)->extension; for (int i = count() - 1; i >= 0; i--) { WebContents* contents = GetWebContentsAtImpl(i); if (extensions::TabHelper::FromWebContents(contents)-> extension_app() == extension) { InternalCloseTab(contents, i, false); } } break; } default: NOTREACHED(); } } 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: MagickExport int LocaleUppercase(const int c) { if (c < 0) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(toupper_l((int) ((unsigned char) c),c_locale)); #endif return(toupper((int) ((unsigned char) c))); } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChangeCurrentInputMethodFromId(const std::string& input_method_id) { const chromeos::InputMethodDescriptor* descriptor = chromeos::input_method::GetInputMethodDescriptorFromId( input_method_id); if (descriptor) { ChangeCurrentInputMethod(*descriptor); } else { LOG(ERROR) << "Descriptor is not found for: " << input_method_id; } } CWE ID: CWE-399 Target: 1 Example 2: Code: int dma_get_cache_alignment(void) { return ia64_max_cacheline_size; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Document::TasksNeedSuspension() { Page* page = GetPage(); return page && page->Paused(); } 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 check_request_for_cacheability(struct stream *s, struct channel *chn) { struct http_txn *txn = s->txn; char *p1, *p2; char *cur_ptr, *cur_end, *cur_next; int pragma_found; int cc_found; int cur_idx; if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE) return; /* nothing more to do here */ cur_idx = 0; pragma_found = cc_found = 0; cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx); while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) { struct hdr_idx_elem *cur_hdr; int val; cur_hdr = &txn->hdr_idx.v[cur_idx]; cur_ptr = cur_next; cur_end = cur_ptr + cur_hdr->len; cur_next = cur_end + cur_hdr->cr + 1; /* We have one full header between cur_ptr and cur_end, and the * next header starts at cur_next. */ val = http_header_match2(cur_ptr, cur_end, "Pragma", 6); if (val) { if ((cur_end - (cur_ptr + val) >= 8) && strncasecmp(cur_ptr + val, "no-cache", 8) == 0) { pragma_found = 1; continue; } } val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13); if (!val) continue; p2 = p1; while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2)) p2++; /* we have a complete value between p1 and p2. We don't check the * values after max-age, max-stale nor min-fresh, we simply don't * use the cache when they're specified. */ if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) || ((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) || ((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) || ((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) { txn->flags |= TX_CACHE_IGNORE; continue; } if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) { txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK; continue; } } /* RFC7234#5.4: * When the Cache-Control header field is also present and * understood in a request, Pragma is ignored. * When the Cache-Control header field is not present in a * request, caches MUST consider the no-cache request * pragma-directive as having the same effect as if * "Cache-Control: no-cache" were present. */ if (!cc_found && pragma_found) txn->flags |= TX_CACHE_IGNORE; } CWE ID: CWE-200 Target: 1 Example 2: Code: GLvoid StubGLBlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { glBlendColor(red, green, blue, alpha); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock_iocb *siocb = kiocb_to_siocb(kiocb); struct sock *sk = sock->sk; struct netlink_sock *nlk = nlk_sk(sk); struct sockaddr_nl *addr = msg->msg_name; u32 dst_pid; u32 dst_group; struct sk_buff *skb; int err; struct scm_cookie scm; if (msg->msg_flags&MSG_OOB) return -EOPNOTSUPP; if (NULL == siocb->scm) siocb->scm = &scm; err = scm_send(sock, msg, siocb->scm); if (err < 0) return err; if (msg->msg_namelen) { err = -EINVAL; if (addr->nl_family != AF_NETLINK) goto out; dst_pid = addr->nl_pid; dst_group = ffs(addr->nl_groups); err = -EPERM; if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND)) goto out; } else { dst_pid = nlk->dst_pid; dst_group = nlk->dst_group; } if (!nlk->pid) { err = netlink_autobind(sock); if (err) goto out; } err = -EMSGSIZE; if (len > sk->sk_sndbuf - 32) goto out; err = -ENOBUFS; skb = alloc_skb(len, GFP_KERNEL); if (skb == NULL) goto out; NETLINK_CB(skb).pid = nlk->pid; NETLINK_CB(skb).dst_group = dst_group; memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred)); err = -EFAULT; if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) { kfree_skb(skb); goto out; } err = security_netlink_send(sk, skb); if (err) { kfree_skb(skb); goto out; } if (dst_group) { atomic_inc(&skb->users); netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL); } err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT); out: scm_destroy(siocb->scm); return err; } CWE ID: CWE-287 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(mcrypt_module_is_block_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } CWE ID: CWE-190 Target: 1 Example 2: Code: static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) { long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib; /* * No need to update load_avg for root_task_group as it is not used. */ if (cfs_rq->tg == &root_task_group) return; if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) { atomic_long_add(delta, &cfs_rq->tg->load_avg); cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg; } } CWE ID: CWE-400 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void opl3_panning(int dev, int voice, int value) { devc->voc[voice].panning = value; } 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: XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return) { XIDeviceInfo *info = NULL; xXIQueryDeviceReq *req; xXIQueryDeviceReq *req; xXIQueryDeviceReply reply; char *ptr; int i; char *buf; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1) goto error_unlocked; GetReq(XIQueryDevice, req); req->reqType = extinfo->codes->major_opcode; req->ReqType = X_XIQueryDevice; req->deviceid = deviceid; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; *ndevices_return = reply.num_devices; info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo)); if (!info) goto error; buf = Xmalloc(reply.length * 4); _XRead(dpy, buf, reply.length * 4); ptr = buf; /* info is a null-terminated array */ info[reply.num_devices].name = NULL; nclasses = wire->num_classes; ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); XIDeviceInfo *lib = &info[i]; xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr; lib->deviceid = wire->deviceid; lib->use = wire->use; lib->attachment = wire->attachment; Xfree(buf); ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); strncpy(lib->name, ptr, wire->name_len); ptr += ((wire->name_len + 3)/4) * 4; sz = size_classes((xXIAnyInfo*)ptr, nclasses); lib->classes = Xmalloc(sz); ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses); /* We skip over unused classes */ lib->num_classes = nclasses; } CWE ID: CWE-284 Target: 1 Example 2: Code: SynchronousCompositorImpl* SynchronousCompositorImpl::FromRoutingID( int routing_id) { if (g_factory == nullptr) return nullptr; if (g_process_id == ChildProcessHost::kInvalidUniqueID) return nullptr; RenderViewHost* rvh = RenderViewHost::FromID(g_process_id, routing_id); if (!rvh) return nullptr; RenderWidgetHostViewAndroid* rwhva = static_cast<RenderWidgetHostViewAndroid*>(rvh->GetWidget()->GetView()); if (!rwhva) return nullptr; return rwhva->GetSynchronousCompositorImpl(); } 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 fuse_open_common(struct inode *inode, struct file *file, bool isdir) { struct fuse_conn *fc = get_fuse_conn(inode); int err; /* VFS checks this, but only _after_ ->open() */ if (file->f_flags & O_DIRECT) return -EINVAL; err = generic_file_open(inode, file); if (err) return err; err = fuse_do_open(fc, get_node_id(inode), file, isdir); if (err) return err; fuse_finish_open(inode, file); 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 struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(" = %d", ret); return ERR_PTR(ret); } CWE ID: CWE-862 Target: 1 Example 2: Code: static int apparmor_path_chmod(const struct path *path, umode_t mode) { return common_perm_path(OP_CHMOD, path, AA_MAY_CHMOD); } 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: long Cluster::Load(long long& pos, long& len) const { assert(m_pSegment); assert(m_pos >= m_element_start); if (m_timecode >= 0) //at least partially loaded return 0; assert(m_pos == m_element_start); assert(m_element_size < 0); IMkvReader* const pReader = m_pSegment->m_pReader; long long total, avail; const int status = pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); assert((total < 0) || (m_pos <= total)); //TODO: verify this pos = m_pos; long long cluster_size = -1; { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error or underflow return static_cast<long>(result); if (result > 0) //underflow (weird) return E_BUFFER_NOT_FULL; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id_ = ReadUInt(pReader, pos, len); if (id_ < 0) //error return static_cast<long>(id_); if (id_ != 0x0F43B675) //Cluster ID return E_FILE_FORMAT_INVALID; pos += len; //consume id if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(cluster_size); if (size == 0) return E_FILE_FORMAT_INVALID; //TODO: verify this pos += len; //consume length of size of element const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) cluster_size = size; } //// pos points to start of payload #if 0 len = static_cast<long>(size_); if (cluster_stop > avail) return E_BUFFER_NOT_FULL; #endif long long timecode = -1; long long new_pos = -1; bool bBlock = false; long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size; for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) break; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast<long>(id); if (id == 0) return E_FILE_FORMAT_INVALID; if (id == 0x0F43B675) //Cluster ID break; if (id == 0x0C53BB6B) //Cues ID break; pos += len; //consume ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(size); const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; pos += len; //consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) //weird continue; if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x67) //TimeCode ID { len = static_cast<long>(size); if ((pos + size) > avail) return E_BUFFER_NOT_FULL; timecode = UnserializeUInt(pReader, pos, size); if (timecode < 0) //error (or underflow) return static_cast<long>(timecode); new_pos = pos + size; if (bBlock) break; } else if (id == 0x20) //BlockGroup ID { bBlock = true; break; } else if (id == 0x23) //SimpleBlock ID { bBlock = true; break; } pos += size; //consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } assert((cluster_stop < 0) || (pos <= cluster_stop)); if (timecode < 0) //no timecode found return E_FILE_FORMAT_INVALID; if (!bBlock) return E_FILE_FORMAT_INVALID; m_pos = new_pos; //designates position just beyond timecode payload m_timecode = timecode; // m_timecode >= 0 means we're partially loaded if (cluster_size >= 0) m_element_size = cluster_stop - m_element_start; 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: PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */ { const char *p; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); for (p = val; p < endptr; ) { zval **tmp; namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF); if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) { return FAILURE; } name = estrndup(p + 1, namelen); p += namelen + 1; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { efree(name); continue; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } else { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } PS_ADD_VARL(name, namelen); efree(name); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */ CWE ID: CWE-416 Target: 1 Example 2: Code: virDomainGetSecurityLabel(virDomainPtr domain, virSecurityLabelPtr seclabel) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "seclabel=%p", seclabel); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(seclabel, error); if (conn->driver->domainGetSecurityLabel) { int ret; ret = conn->driver->domainGetSecurityLabel(domain, seclabel); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } 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: xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) { xmlChar *name; const xmlChar *ptr; xmlChar cur; xmlEntityPtr ent = 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, "xmlParseStringEntityRef: no name\n"); *str = ptr; return(NULL); } if (*ptr != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); xmlFree(name); *str = ptr; return(NULL); } ptr++; /* * Predefined entites override any extra definition */ if ((ctxt->options & XML_PARSE_OLDSAX) == 0) { ent = xmlGetPredefinedEntity(name); if (ent != NULL) { xmlFree(name); *str = ptr; return(ent); } } /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Ask first SAX for entity resolution, otherwise try the * entities which may have stored in the parser context. */ if (ctxt->sax != NULL) { if (ctxt->sax->getEntity != NULL) ent = ctxt->sax->getEntity(ctxt->userData, name); if ((ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX)) ent = xmlGetPredefinedEntity(name); if ((ent == NULL) && (ctxt->userData==ctxt)) { ent = xmlSAX2GetEntity(ctxt, name); } } /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", the * Name given in the entity reference must match that in an * entity declaration, except that well-formed documents * need not declare any of the following entities: amp, lt, * gt, apos, quot. * The declaration of a parameter entity must precede any * reference to it. * Similarly, the declaration of a general entity must * precede any reference to it which appears in a default * value in an attribute-list declaration. Note that if * entities are declared in the external subset or in * external parameter entities, a non-validating processor * is not obligated to read and process their declarations; * for such documents, the rule that an entity must be * declared is a well-formedness constraint only if * standalone='yes'. */ if (ent == NULL) { if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } else { xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY, "Entity '%s' not defined\n", name); } /* TODO ? check regressions ctxt->valid = 0; */ } /* * [ WFC: Parsed Entity ] * An entity reference must not contain the name of an * unparsed entity */ else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY, "Entity reference to unparsed entity %s\n", name); } /* * [ WFC: No External Entity References ] * Attribute values cannot contain direct or indirect * entity references to external entities. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) { xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL, "Attribute references external entity '%s'\n", name); } /* * [ WFC: No < in Attribute Values ] * The replacement text of any entity referred to directly or * indirectly in an attribute value (other than "&lt;") must * not contain a <. */ else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) && (ent != NULL) && (ent->content != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (xmlStrchr(ent->content, '<'))) { xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, "'<' in entity '%s' is not allowed in attributes values\n", name); } /* * Internal check, no parameter entities here ... */ else { switch (ent->etype) { case XML_INTERNAL_PARAMETER_ENTITY: case XML_EXTERNAL_PARAMETER_ENTITY: xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, "Attempt to reference the parameter entity '%s'\n", name); break; default: break; } } /* * [ WFC: No Recursion ] * A parsed entity must not contain a recursive reference * to itself, either directly or indirectly. * Done somewhere else */ xmlFree(name); *str = ptr; return(ent); } 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 FragmentPaintPropertyTreeBuilder::UpdateCssClip() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsCssClip(object_)) { DCHECK(object_.CanContainAbsolutePositionObjects()); OnUpdateClip(properties_->UpdateCssClip( context_.current.clip, ClipPaintPropertyNode::State{context_.current.transform, ToClipRect(ToLayoutBox(object_).ClipRect( context_.current.paint_offset))})); } else { OnClearClip(properties_->ClearCssClip()); } } if (properties_->CssClip()) context_.current.clip = properties_->CssClip(); } CWE ID: Target: 1 Example 2: Code: void SendAlternateCopy() { if (TestingNativeMac()) SendKeyEvent(ui::VKEY_C, false, true); else SendKeyEvent(ui::VKEY_INSERT, false, true); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RunCSSTest(const base::FilePath::CharType* file_path) { base::FilePath test_path = GetTestFilePath("accessibility", "css"); { base::ScopedAllowBlockingForTesting allow_blocking; ASSERT_TRUE(base::PathExists(test_path)) << test_path.LossyDisplayName(); } base::FilePath css_file = test_path.Append(base::FilePath(file_path)); RunTest(css_file, "accessibility/css"); } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual InputMethodDescriptor previous_input_method() const { return previous_input_method_; } CWE ID: CWE-399 Target: 1 Example 2: Code: int kvm_arch_hardware_enable(void *garbage) { struct kvm *kvm; struct kvm_vcpu *vcpu; int i; kvm_shared_msr_cpu_online(); list_for_each_entry(kvm, &vm_list, vm_list) kvm_for_each_vcpu(i, vcpu, kvm) if (vcpu->cpu == smp_processor_id()) kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); return kvm_x86_ops->hardware_enable(garbage); } 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: std::string SanitizeFrontendQueryParam( const std::string& key, const std::string& value) { if (key == "can_dock" || key == "debugFrontend" || key == "experiments" || key == "isSharedWorker" || key == "v8only" || key == "remoteFrontend" || key == "nodeFrontend" || key == "hasOtherClients") return "true"; if (key == "ws" || key == "service-backend") return SanitizeEndpoint(value); if (key == "dockSide" && value == "undocked") return value; if (key == "panel" && (value == "elements" || value == "console")) return value; if (key == "remoteBase") return SanitizeRemoteBase(value); if (key == "remoteFrontendUrl") return SanitizeRemoteFrontendURL(value); return std::string(); } 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: my_object_recursive1 (MyObject *obj, GArray *array, guint32 *len_ret, GError **error) { *len_ret = array->len; return TRUE; } CWE ID: CWE-264 Target: 1 Example 2: Code: int evm_inode_removexattr(struct dentry *dentry, const char *xattr_name) { return evm_protect_xattr(dentry, xattr_name, NULL, 0); } CWE ID: CWE-19 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: on_unregister_handler(TCMUService1HandlerManager1 *interface, GDBusMethodInvocation *invocation, gchar *subtype, gpointer user_data) { struct tcmur_handler *handler = find_handler_by_subtype(subtype); struct dbus_info *info = handler ? handler->opaque : NULL; if (!handler) { g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", FALSE, "unknown subtype")); return TRUE; } dbus_unexport_handler(handler); tcmur_unregister_handler(handler); g_bus_unwatch_name(info->watcher_id); g_free(info); g_free(handler); g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", TRUE, "succeeded")); return TRUE; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); } CWE ID: CWE-264 Target: 1 Example 2: Code: void MessageLoop::AddDestructionObserver( DestructionObserver* destruction_observer) { DCHECK_EQ(this, current()); destruction_observers_.AddObserver(destruction_observer); } 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: receive_carbon(void **state) { prof_input("/carbons on"); prof_connect(); assert_true(stbbr_received( "<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>" )); stbbr_send( "<presence to='stabber@localhost' from='buddy1@localhost/mobile'>" "<priority>10</priority>" "<status>On my mobile</status>" "</presence>" ); assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\"")); prof_input("/msg Buddy1"); assert_true(prof_output_exact("unencrypted")); stbbr_send( "<message type='chat' to='stabber@localhost/profanity' from='buddy1@localhost'>" "<received xmlns='urn:xmpp:carbons:2'>" "<forwarded xmlns='urn:xmpp:forward:0'>" "<message id='prof_msg_7' xmlns='jabber:client' type='chat' lang='en' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>" "<body>test carbon from recipient</body>" "</message>" "</forwarded>" "</received>" "</message>" ); assert_true(prof_output_regex("Buddy1/mobile: .+test carbon from recipient")); } CWE ID: CWE-346 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WebString WebPageSerializer::generateBaseTagDeclaration(const WebString& baseTarget) { if (baseTarget.isEmpty()) return String("<base href=\".\">"); String baseString = "<base href=\".\" target=\"" + static_cast<const String&>(baseTarget) + "\">"; return baseString; } CWE ID: CWE-20 Target: 1 Example 2: Code: void VerifyCollectedEvent(size_t i, unsigned phase, const std::string& category, const std::string& name) { EXPECT_EQ(phase, collected_events_phases_[i]); EXPECT_EQ(category, collected_events_categories_[i]); EXPECT_EQ(name, collected_events_names_[i]); } 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 DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq) { if (!g_teredo_enabled) return TM_ECODE_FAILED; uint8_t *start = pkt; /* Is this packet to short to contain an IPv6 packet ? */ if (len < IPV6_HEADER_LEN) return TM_ECODE_FAILED; /* Teredo encapsulate IPv6 in UDP and can add some custom message * part before the IPv6 packet. In our case, we just want to get * over an ORIGIN indication. So we just make one offset if needed. */ if (start[0] == 0x0) { switch (start[1]) { /* origin indication: compatible with tunnel */ case 0x0: /* offset is coherent with len and presence of an IPv6 header */ if (len >= TEREDO_ORIG_INDICATION_LENGTH + IPV6_HEADER_LEN) start += TEREDO_ORIG_INDICATION_LENGTH; else return TM_ECODE_FAILED; break; /* authentication: negotiation not real tunnel */ case 0x1: return TM_ECODE_FAILED; /* this case is not possible in Teredo: not that protocol */ default: return TM_ECODE_FAILED; } } /* There is no specific field that we can check to prove that the packet * is a Teredo packet. We've zapped here all the possible Teredo header * and we should have an IPv6 packet at the start pointer. * We then can only do two checks before sending the encapsulated packets * to decoding: * - The packet has a protocol version which is IPv6. * - The IPv6 length of the packet matches what remains in buffer. */ if (IP_GET_RAW_VER(start) == 6) { IPV6Hdr *thdr = (IPV6Hdr *)start; if (len == IPV6_HEADER_LEN + IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) { if (pq != NULL) { int blen = len - (start - pkt); /* spawn off tunnel packet */ Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen, DECODE_TUNNEL_IPV6, pq); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO); /* add the tp to the packet queue. */ PacketEnqueue(pq,tp); StatsIncr(tv, dtv->counter_teredo); return TM_ECODE_OK; } } } return TM_ECODE_FAILED; } return TM_ECODE_FAILED; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols) { int size; int i; size = numrows * numcols; if (size > matrix->datasize_ || numrows > matrix->maxrows_) { return -1; } matrix->numrows_ = numrows; matrix->numcols_ = numcols; for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[numcols * i]; } return 0; } CWE ID: CWE-190 Target: 1 Example 2: Code: static int qeth_query_ipassists_cb(struct qeth_card *card, struct qeth_reply *reply, unsigned long data) { struct qeth_ipa_cmd *cmd; QETH_DBF_TEXT(SETUP, 2, "qipasscb"); cmd = (struct qeth_ipa_cmd *) data; switch (cmd->hdr.return_code) { case IPA_RC_NOTSUPP: case IPA_RC_L2_UNSUPPORTED_CMD: QETH_DBF_TEXT(SETUP, 2, "ipaunsup"); card->options.ipa4.supported_funcs |= IPA_SETADAPTERPARMS; card->options.ipa6.supported_funcs |= IPA_SETADAPTERPARMS; return -0; default: if (cmd->hdr.return_code) { QETH_DBF_MESSAGE(1, "%s IPA_CMD_QIPASSIST: Unhandled " "rc=%d\n", dev_name(&card->gdev->dev), cmd->hdr.return_code); return 0; } } if (cmd->hdr.prot_version == QETH_PROT_IPV4) { card->options.ipa4.supported_funcs = cmd->hdr.ipa_supported; card->options.ipa4.enabled_funcs = cmd->hdr.ipa_enabled; } else if (cmd->hdr.prot_version == QETH_PROT_IPV6) { card->options.ipa6.supported_funcs = cmd->hdr.ipa_supported; card->options.ipa6.enabled_funcs = cmd->hdr.ipa_enabled; } else QETH_DBF_MESSAGE(1, "%s IPA_CMD_QIPASSIST: Flawed LIC detected" "\n", dev_name(&card->gdev->dev)); 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: void FillRandom(uint8_t *data, int stride) { for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { data[h * stride + w] = rnd_.Rand8(); } } } 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 decode_map(codebook *s, oggpack_buffer *b, ogg_int32_t *v, int point){ ogg_uint32_t entry = decode_packed_entry_number(s,b); int i; if(oggpack_eop(b))return(-1); /* 1 used by test file 0 */ /* according to decode type */ switch(s->dec_type){ case 1:{ /* packed vector of values */ int mask=(1<<s->q_bits)-1; for(i=0;i<s->dim;i++){ v[i]=entry&mask; entry>>=s->q_bits; } break; } case 2:{ /* packed vector of column offsets */ int mask=(1<<s->q_pack)-1; for(i=0;i<s->dim;i++){ if(s->q_bits<=8) v[i]=((unsigned char *)(s->q_val))[entry&mask]; else v[i]=((ogg_uint16_t *)(s->q_val))[entry&mask]; entry>>=s->q_pack; } break; } case 3:{ /* offset into array */ void *ptr=((char *)s->q_val)+entry*s->q_pack; if(s->q_bits<=8){ for(i=0;i<s->dim;i++) v[i]=((unsigned char *)ptr)[i]; }else{ for(i=0;i<s->dim;i++) v[i]=((ogg_uint16_t *)ptr)[i]; } break; } default: return -1; } /* we have the unpacked multiplicands; compute final vals */ { int shiftM = point-s->q_delp; ogg_int32_t add = point-s->q_minp; int mul = s->q_del; if(add>0) add= s->q_min >> add; else add= s->q_min << -add; if (shiftM<0) { mul <<= -shiftM; shiftM = 0; } add <<= shiftM; for(i=0;i<s->dim;i++) v[i]= ((add + v[i] * mul) >> shiftM); if(s->q_seq) for(i=1;i<s->dim;i++) v[i]+=v[i-1]; } return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: static void get_id3_tag(AVFormatContext *s, int len) { ID3v2ExtraMeta *id3v2_extra_meta = NULL; ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, len); if (id3v2_extra_meta) { ff_id3v2_parse_apic(s, &id3v2_extra_meta); ff_id3v2_parse_chapters(s, &id3v2_extra_meta); } ff_id3v2_free_extra_meta(&id3v2_extra_meta); } 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 __u8 *lg_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { struct lg_drv_data *drv_data = hid_get_drvdata(hdev); struct usb_device_descriptor *udesc; __u16 bcdDevice, rev_maj, rev_min; if ((drv_data->quirks & LG_RDESC) && *rsize >= 90 && rdesc[83] == 0x26 && rdesc[84] == 0x8c && rdesc[85] == 0x02) { hid_info(hdev, "fixing up Logitech keyboard report descriptor\n"); rdesc[84] = rdesc[89] = 0x4d; rdesc[85] = rdesc[90] = 0x10; } if ((drv_data->quirks & LG_RDESC_REL_ABS) && *rsize >= 50 && rdesc[32] == 0x81 && rdesc[33] == 0x06 && rdesc[49] == 0x81 && rdesc[50] == 0x06) { hid_info(hdev, "fixing up rel/abs in Logitech report descriptor\n"); rdesc[33] = rdesc[50] = 0x02; } switch (hdev->product) { /* Several wheels report as this id when operating in emulation mode. */ case USB_DEVICE_ID_LOGITECH_WHEEL: udesc = &(hid_to_usb_dev(hdev)->descriptor); if (!udesc) { hid_err(hdev, "NULL USB device descriptor\n"); break; } bcdDevice = le16_to_cpu(udesc->bcdDevice); rev_maj = bcdDevice >> 8; rev_min = bcdDevice & 0xff; /* Update the report descriptor for only the Driving Force wheel */ if (rev_maj == 1 && rev_min == 2 && *rsize == DF_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force report descriptor\n"); rdesc = df_rdesc_fixed; *rsize = sizeof(df_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL: if (*rsize == MOMO_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Force (Red) report descriptor\n"); rdesc = momo_rdesc_fixed; *rsize = sizeof(momo_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_MOMO_WHEEL2: if (*rsize == MOMO2_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Momo Racing Force (Black) report descriptor\n"); rdesc = momo2_rdesc_fixed; *rsize = sizeof(momo2_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_VIBRATION_WHEEL: if (*rsize == FV_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Formula Vibration report descriptor\n"); rdesc = fv_rdesc_fixed; *rsize = sizeof(fv_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_DFP_WHEEL: if (*rsize == DFP_RDESC_ORIG_SIZE) { hid_info(hdev, "fixing up Logitech Driving Force Pro report descriptor\n"); rdesc = dfp_rdesc_fixed; *rsize = sizeof(dfp_rdesc_fixed); } break; case USB_DEVICE_ID_LOGITECH_WII_WHEEL: if (*rsize >= 101 && rdesc[41] == 0x95 && rdesc[42] == 0x0B && rdesc[47] == 0x05 && rdesc[48] == 0x09) { hid_info(hdev, "fixing up Logitech Speed Force Wireless report descriptor\n"); rdesc[41] = 0x05; rdesc[42] = 0x09; rdesc[47] = 0x95; rdesc[48] = 0x0B; } break; } return rdesc; } 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: const std::string& AppControllerImpl::MaybeGetAndroidPackageName( const std::string& app_id) { const auto& package_name_it = android_package_map_.find(app_id); if (package_name_it != android_package_map_.end()) { return package_name_it->second; } ArcAppListPrefs* arc_prefs_ = ArcAppListPrefs::Get(profile_); if (!arc_prefs_) { return base::EmptyString(); } std::unique_ptr<ArcAppListPrefs::AppInfo> arc_info = arc_prefs_->GetApp(app_id); if (!arc_info) { return base::EmptyString(); } android_package_map_[app_id] = arc_info->package_name; return android_package_map_[app_id]; } CWE ID: CWE-416 Target: 1 Example 2: Code: bool Browser::IsMouseLocked() const { return exclusive_access_manager_->mouse_lock_controller()->IsMouseLocked(); } 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 PageRequestSummary::UpdateOrAddToOrigins( const content::mojom::ResourceLoadInfo& resource_load_info) { for (const auto& redirect_info : resource_load_info.redirect_info_chain) UpdateOrAddToOrigins(redirect_info->url, redirect_info->network_info); UpdateOrAddToOrigins(resource_load_info.url, resource_load_info.network_info); } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int PrintPreviewDataService::GetAvailableDraftPageCount( const std::string& preview_ui_addr_str) { if (data_store_map_.find(preview_ui_addr_str) != data_store_map_.end()) return data_store_map_[preview_ui_addr_str]->GetAvailableDraftPageCount(); return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: int BlockSizeLog2Min1() const { switch (block_size_) { case 16: return 3; case 8: return 2; default: 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: static void cqspi_configure_cs_and_sizes(struct spi_nor *nor) { struct cqspi_flash_pdata *f_pdata = nor->priv; struct cqspi_st *cqspi = f_pdata->cqspi; void __iomem *iobase = cqspi->iobase; unsigned int reg; /* configure page size and block size. */ reg = readl(iobase + CQSPI_REG_SIZE); reg &= ~(CQSPI_REG_SIZE_PAGE_MASK << CQSPI_REG_SIZE_PAGE_LSB); reg &= ~(CQSPI_REG_SIZE_BLOCK_MASK << CQSPI_REG_SIZE_BLOCK_LSB); reg &= ~CQSPI_REG_SIZE_ADDRESS_MASK; reg |= (nor->page_size << CQSPI_REG_SIZE_PAGE_LSB); reg |= (ilog2(nor->mtd.erasesize) << CQSPI_REG_SIZE_BLOCK_LSB); reg |= (nor->addr_width - 1); writel(reg, iobase + CQSPI_REG_SIZE); /* configure the chip select */ cqspi_chipselect(nor); /* Store the new configuration of the controller */ cqspi->current_page_size = nor->page_size; cqspi->current_erase_size = nor->mtd.erasesize; cqspi->current_addr_width = nor->addr_width; } 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 PaymentRequest::Show(bool is_user_gesture) { if (!client_.is_bound() || !binding_.is_bound()) { LOG(ERROR) << "Attempted Show(), but binding(s) missing."; OnConnectionTerminated(); return; } display_handle_ = display_manager_->TryShow(delegate_.get()); if (!display_handle_) { LOG(ERROR) << "A PaymentRequest UI is already showing"; journey_logger_.SetNotShown( JourneyLogger::NOT_SHOWN_REASON_CONCURRENT_REQUESTS); client_->OnError(mojom::PaymentErrorReason::ALREADY_SHOWING); OnConnectionTerminated(); return; } if (!delegate_->IsBrowserWindowActive()) { LOG(ERROR) << "Cannot show PaymentRequest UI in a background tab"; journey_logger_.SetNotShown(JourneyLogger::NOT_SHOWN_REASON_OTHER); client_->OnError(mojom::PaymentErrorReason::USER_CANCEL); OnConnectionTerminated(); return; } if (!state_) { AreRequestedMethodsSupportedCallback(false); return; } is_show_user_gesture_ = is_user_gesture; display_handle_->Show(this); state_->AreRequestedMethodsSupported( base::BindOnce(&PaymentRequest::AreRequestedMethodsSupportedCallback, weak_ptr_factory_.GetWeakPtr())); } CWE ID: CWE-189 Target: 1 Example 2: Code: ZEND_API zend_class_entry *zend_get_called_scope(zend_execute_data *ex) /* {{{ */ { while (ex) { if (ex->called_scope) { return ex->called_scope; } else if (ex->func) { if (ex->func->type != ZEND_INTERNAL_FUNCTION || ex->func->common.scope) { return ex->called_scope; } } ex = ex->prev_execute_data; } return NULL; } /* }}} */ 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: InputMethodStatusConnection() : current_input_method_changed_(NULL), register_ime_properties_(NULL), update_ime_property_(NULL), connection_change_handler_(NULL), language_library_(NULL), ibus_(NULL), ibus_config_(NULL) { } 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: long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x00) { // Display ID status = ParseDisplay(pReader, pos, size); if (status < 0) // error return status; } else if (id == 0x1654) { // StringUID ID status = UnserializeString(pReader, pos, size, m_string_uid); if (status < 0) // error return status; } else if (id == 0x33C4) { // UID ID long long val; status = UnserializeInt(pReader, pos, size, val); if (status < 0) // error return status; m_uid = static_cast<unsigned long long>(val); } else if (id == 0x11) { // TimeStart ID const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_start_timecode = val; } else if (id == 0x12) { // TimeEnd ID const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_stop_timecode = val; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int socket_open_listen(struct sockaddr_in *my_addr) { int server_fd, tmp; server_fd = socket(AF_INET,SOCK_STREAM,0); if (server_fd < 0) { perror ("socket"); return -1; } tmp = 1; if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp))) av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n"); my_addr->sin_family = AF_INET; if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) { char bindmsg[32]; snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port)); perror (bindmsg); goto fail; } if (listen (server_fd, 5) < 0) { perror ("listen"); goto fail; } if (ff_socket_nonblock(server_fd, 1) < 0) av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n"); return server_fd; fail: closesocket(server_fd); return -1; } 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 av_cold int flashsv2_decode_init(AVCodecContext *avctx) { FlashSVContext *s = avctx->priv_data; flashsv_decode_init(avctx); s->pal = ff_flashsv2_default_palette; s->ver = 2; return 0; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual InputMethodDescriptor previous_input_method() const { if (previous_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return previous_input_method_; } CWE ID: CWE-399 Target: 1 Example 2: Code: void RenderBlock::LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo, FloatingObject* lastFloatFromPreviousLine, LineWidth& width) { while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) { RenderObject* object = resolver.position().m_obj; if (object->isOutOfFlowPositioned()) { setStaticPositions(m_block, toRenderBox(object)); if (object->style()->isOriginalDisplayInlineType()) { resolver.runs().addRun(createRun(0, 1, object, resolver)); lineInfo.incrementRunsFromLeadingWhitespace(); } } else if (object->isFloating()) { LayoutUnit marginOffset = (!object->previousSibling() && m_block->isSelfCollapsingBlock() && m_block->style()->clear() && m_block->getClearDelta(m_block, LayoutUnit())) ? m_block->collapsedMarginBeforeForChild(m_block) : LayoutUnit(); LayoutUnit oldLogicalHeight = m_block->logicalHeight(); m_block->setLogicalHeight(oldLogicalHeight + marginOffset); m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, lineInfo, width); m_block->setLogicalHeight(oldLogicalHeight); } else if (object->isText() && object->style()->hasTextCombine() && object->isCombineText() && !toRenderCombineText(object)->isCombined()) { toRenderCombineText(object)->combineText(); if (toRenderCombineText(object)->isCombined()) continue; } resolver.increment(); } resolver.commitExplicitEmbedding(); } 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 AssertObserverCount(int added_count, int removed_count, int changed_count) { ASSERT_EQ(added_count, added_count_); ASSERT_EQ(removed_count, removed_count_); ASSERT_EQ(changed_count, changed_count_); } 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: TabGroupHeader::TabGroupHeader(const base::string16& group_title) { constexpr gfx::Insets kPlaceholderInsets = gfx::Insets(4, 27); SetBorder(views::CreateEmptyBorder(kPlaceholderInsets)); views::FlexLayout* layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetCollapseMargins(true) .SetMainAxisAlignment(views::LayoutAlignment::kStart) .SetCrossAxisAlignment(views::LayoutAlignment::kCenter); auto title = std::make_unique<views::Label>(group_title); title->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); title->SetElideBehavior(gfx::FADE_TAIL); auto* title_ptr = AddChildView(std::move(title)); layout->SetFlexForView(title_ptr, views::FlexSpecification::ForSizeRule( views::MinimumFlexSizeRule::kScaleToZero, views::MaximumFlexSizeRule::kUnbounded)); auto group_menu_button = views::CreateVectorImageButton(/*listener*/ nullptr); views::SetImageFromVectorIcon(group_menu_button.get(), kBrowserToolsIcon); AddChildView(std::move(group_menu_button)); } CWE ID: CWE-20 Target: 1 Example 2: Code: static bool lxc_cgmanager_create(const char *controller, const char *cgroup_path, int32_t *existed) { bool ret = true; if ( cgmanager_create_sync(NULL, cgroup_manager, controller, cgroup_path, existed) != 0) { NihError *nerr; nerr = nih_error_get(); ERROR("call to cgmanager_create_sync failed: %s", nerr->message); nih_free(nerr); ERROR("Failed to create %s:%s", controller, cgroup_path); ret = false; } return ret; } CWE ID: CWE-59 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: videobuf_vm_open(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; dprintk(2,"vm_open %p [count=%d,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count++; } 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: acc_ctx_cont(OM_uint32 *minstat, gss_buffer_t buf, gss_ctx_id_t *ctx, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 ret, tmpmin; gss_OID supportedMech; spnego_gss_ctx_id_t sc; unsigned int len; unsigned char *ptr, *bufstart; sc = (spnego_gss_ctx_id_t)*ctx; ret = GSS_S_DEFECTIVE_TOKEN; *negState = REJECT; *minstat = 0; supportedMech = GSS_C_NO_OID; *return_token = ERROR_TOKEN_SEND; *responseToken = *mechListMIC = GSS_C_NO_BUFFER; ptr = bufstart = buf->value; #define REMAIN (buf->length - (ptr - bufstart)) if (REMAIN > INT_MAX) return GSS_S_DEFECTIVE_TOKEN; /* * Attempt to work with old Sun SPNEGO. */ if (*ptr == HEADER_ID) { ret = g_verify_token_header(gss_mech_spnego, &len, &ptr, 0, REMAIN); if (ret) { *minstat = ret; return GSS_S_DEFECTIVE_TOKEN; } } if (*ptr != (CONTEXT | 0x01)) { return GSS_S_DEFECTIVE_TOKEN; } ret = get_negTokenResp(minstat, ptr, REMAIN, negState, &supportedMech, responseToken, mechListMIC); if (ret != GSS_S_COMPLETE) goto cleanup; if (*responseToken == GSS_C_NO_BUFFER && *mechListMIC == GSS_C_NO_BUFFER) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } if (supportedMech != GSS_C_NO_OID) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } sc->firstpass = 0; *negState = ACCEPT_INCOMPLETE; *return_token = CONT_TOKEN_SEND; cleanup: if (supportedMech != GSS_C_NO_OID) { generic_gss_release_oid(&tmpmin, &supportedMech); } return ret; #undef REMAIN } CWE ID: CWE-476 Target: 1 Example 2: Code: AXLayoutObject::~AXLayoutObject() { ASSERT(isDetached()); } 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 int btrfs_dentry_delete(const struct dentry *dentry) { struct btrfs_root *root; struct inode *inode = d_inode(dentry); if (!inode && !IS_ROOT(dentry)) inode = d_inode(dentry->d_parent); if (inode) { root = BTRFS_I(inode)->root; if (btrfs_root_refs(&root->root_item) == 0) return 1; if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return 1; } return 0; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void tg3_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct tg3 *tp = netdev_priv(dev); if (tg3_flag(tp, WOL_CAP) && device_can_wakeup(&tp->pdev->dev)) wol->supported = WAKE_MAGIC; else wol->supported = 0; wol->wolopts = 0; if (tg3_flag(tp, WOL_ENABLE) && device_can_wakeup(&tp->pdev->dev)) wol->wolopts = WAKE_MAGIC; memset(&wol->sopass, 0, sizeof(wol->sopass)); } 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: CheckDeviceGrabs(DeviceIntPtr device, DeviceEvent *event, WindowPtr ancestor) { int i; WindowPtr pWin = NULL; FocusClassPtr focus = IsPointerEvent((InternalEvent *) event) ? NULL : device->focus; BOOL sendCore = (IsMaster(device) && device->coreEvents); Bool ret = FALSE; if (event->type != ET_ButtonPress && event->type != ET_KeyPress) return FALSE; if (event->type == ET_ButtonPress && (device->button->buttonsDown != 1)) return FALSE; if (device->deviceGrab.grab) return FALSE; i = 0; if (ancestor) { while (i < device->spriteInfo->sprite->spriteTraceGood) if (device->spriteInfo->sprite->spriteTrace[i++] == ancestor) break; if (i == device->spriteInfo->sprite->spriteTraceGood) goto out; } if (focus) { for (; i < focus->traceGood; i++) { pWin = focus->trace[i]; if (CheckPassiveGrabsOnWindow(pWin, device, (InternalEvent *) event, sendCore, TRUE)) { ret = TRUE; goto out; } } if ((focus->win == NoneWin) || (i >= device->spriteInfo->sprite->spriteTraceGood) || (pWin && pWin != device->spriteInfo->sprite->spriteTrace[i - 1])) goto out; } for (; i < device->spriteInfo->sprite->spriteTraceGood; i++) { pWin = device->spriteInfo->sprite->spriteTrace[i]; if (CheckPassiveGrabsOnWindow(pWin, device, (InternalEvent *) event, sendCore, TRUE)) { ret = TRUE; goto out; } } out: if (ret == TRUE && event->type == ET_KeyPress) device->deviceGrab.activatingKey = event->detail.key; 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: long Cluster::CreateBlock( long long id, long long pos, //absolute pos of payload long long size, long long discard_padding) { assert((id == 0x20) || (id == 0x23)); //BlockGroup or SimpleBlock if (m_entries_count < 0) //haven't parsed anything yet { assert(m_entries == NULL); assert(m_entries_size == 0); m_entries_size = 1024; m_entries = new BlockEntry*[m_entries_size]; m_entries_count = 0; } else { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (m_entries_count >= m_entries_size) { const long entries_size = 2 * m_entries_size; BlockEntry** const entries = new BlockEntry*[entries_size]; assert(entries); BlockEntry** src = m_entries; BlockEntry** const src_end = src + m_entries_count; BlockEntry** dst = entries; while (src != src_end) *dst++ = *src++; delete[] m_entries; m_entries = entries; m_entries_size = entries_size; } } if (id == 0x20) //BlockGroup ID return CreateBlockGroup(pos, size, discard_padding); else //SimpleBlock ID return CreateSimpleBlock(pos, size); } CWE ID: CWE-119 Target: 1 Example 2: Code: TestRenderViewHost* RenderViewHostImplTestHarness::active_test_rvh() { return static_cast<TestRenderViewHost*>(active_rvh()); } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewImpl::ConvertWindowToViewport(blink::WebFloatRect* rect) { RenderWidget::ConvertWindowToViewport(rect); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i] << 8; } } } CWE ID: CWE-119 Target: 1 Example 2: Code: PassRefPtr<GraphicsContext3D> CCLayerTreeHost::createLayerTreeHostContext3D() { return m_client->createLayerTreeHostContext3D(); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { if (!cfs_bandwidth_used()) return false; if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0)) return false; /* * it's possible for a throttled entity to be forced into a running * state (e.g. set_curr_task), in this case we're finished. */ if (cfs_rq_throttled(cfs_rq)) return true; throttle_cfs_rq(cfs_rq); return true; } CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data, krb5_kvno mkvno) { struct berval **ret = NULL; int currkvno; int num_versions = 1; int i, j, last; krb5_error_code err = 0; krb5_key_data *key_data; if (n_key_data <= 0) return NULL; /* Make a shallow copy of the key data so we can alter it. */ key_data = k5calloc(n_key_data, sizeof(*key_data), &err); if (key_data_in == NULL) goto cleanup; memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data)); /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt * field. For compatibility, always encode a salt field. */ for (i = 0; i < n_key_data; i++) { if (key_data[i].key_data_ver == 1) { key_data[i].key_data_ver = 2; key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } } /* Find the number of key versions */ for (i = 0; i < n_key_data - 1; i++) if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno) num_versions++; ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *)); if (ret == NULL) { err = ENOMEM; goto cleanup; } for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) { krb5_data *code; if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) { ret[j] = k5alloc(sizeof(struct berval), &err); if (ret[j] == NULL) goto cleanup; err = asn1_encode_sequence_of_keys(key_data + last, (krb5_int16)i - last + 1, mkvno, &code); if (err) goto cleanup; /*CHECK_NULL(ret[j]); */ ret[j]->bv_len = code->length; ret[j]->bv_val = code->data; free(code); j++; last = i + 1; currkvno = key_data[i].key_data_kvno; } } ret[num_versions] = NULL; cleanup: free(key_data); if (err != 0) { if (ret != NULL) { for (i = 0; i <= num_versions; i++) if (ret[i] != NULL) free (ret[i]); free (ret); ret = NULL; } } return ret; } CWE ID: CWE-189 Target: 1 Example 2: Code: void PPAPITestBase::RunTestURL(const GURL& test_url) { TestFinishObserver observer( browser()->GetSelectedWebContents()->GetRenderViewHost(), kTimeoutMs); ui_test_utils::NavigateToURL(browser(), test_url); ASSERT_TRUE(observer.WaitForFinish()) << "Test timed out."; EXPECT_STREQ("PASS", observer.result().c_str()); } 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: file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, size_t nbytes) { union { int32_t l; char c[sizeof (int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum, notecount; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } if (S_ISREG(st.st_mode) || st.st_size != 0) fsize = st.st_size; else fsize = SIZE_UNKNOWN; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderWidgetHostViewAura::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& dst_size, const base::Callback<void(bool)>& callback, skia::PlatformBitmap* output) { base::ScopedClosureRunner scoped_callback_runner(base::Bind(callback, false)); std::map<uint64, scoped_refptr<ui::Texture> >::iterator it = image_transport_clients_.find(current_surface_); if (it == image_transport_clients_.end()) return; ui::Texture* container = it->second; DCHECK(container); gfx::Size dst_size_in_pixel = ConvertSizeToPixel(this, dst_size); if (!output->Allocate( dst_size_in_pixel.width(), dst_size_in_pixel.height(), true)) return; ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); GLHelper* gl_helper = factory->GetGLHelper(); if (!gl_helper) return; unsigned char* addr = static_cast<unsigned char*>( output->GetBitmap().getPixels()); scoped_callback_runner.Release(); base::Callback<void(bool)> wrapper_callback = base::Bind( &RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished, AsWeakPtr(), callback); ++pending_thumbnail_tasks_; gfx::Rect src_subrect_in_gl = src_subrect; src_subrect_in_gl.set_y(GetViewBounds().height() - src_subrect.bottom()); gfx::Rect src_subrect_in_pixel = ConvertRectToPixel(this, src_subrect_in_gl); gl_helper->CropScaleReadbackAndCleanTexture(container->PrepareTexture(), container->size(), src_subrect_in_pixel, dst_size_in_pixel, addr, wrapper_callback); } CWE ID: Target: 1 Example 2: Code: check_cv_name_str(mrb_state *mrb, mrb_value str) { const char *s = RSTRING_PTR(str); mrb_int len = RSTRING_LEN(str); if (len < 3 || !(s[0] == '@' && s[1] == '@')) { mrb_name_error(mrb, mrb_intern_str(mrb, str), "'%S' is not allowed as a class variable name", str); } } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ExtensionDevToolsClientHost::InfoBarDismissed() { detach_reason_ = api::debugger::DETACH_REASON_CANCELED_BY_USER; SendDetachedEvent(); Close(); } 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 InputHandlerProxy::InjectScrollbarGestureScroll( const WebInputEvent::Type type, const blink::WebFloatPoint& position_in_widget, const cc::InputHandlerPointerResult& pointer_result, const LatencyInfo& latency_info, const base::TimeTicks original_timestamp) { gfx::Vector2dF scroll_delta(pointer_result.scroll_offset.x(), pointer_result.scroll_offset.y()); std::unique_ptr<WebGestureEvent> synthetic_gesture_event = GenerateInjectedScrollGesture( type, original_timestamp, blink::WebGestureDevice::kScrollbar, position_in_widget, scroll_delta, pointer_result.scroll_units); WebScopedInputEvent web_scoped_gesture_event( synthetic_gesture_event.release()); LatencyInfo scrollbar_latency_info(latency_info); scrollbar_latency_info.set_source_event_type(ui::SourceEventType::SCROLLBAR); DCHECK(!scrollbar_latency_info.FindLatency( ui::INPUT_EVENT_LATENCY_RENDERING_SCHEDULED_IMPL_COMPONENT, nullptr)); if (type == WebInputEvent::Type::kGestureScrollBegin) { last_injected_gesture_was_begin_ = true; } else { if (type == WebInputEvent::Type::kGestureScrollUpdate) { scrollbar_latency_info.AddLatencyNumberWithTimestamp( (last_injected_gesture_was_begin_) ? ui::INPUT_EVENT_LATENCY_FIRST_SCROLL_UPDATE_ORIGINAL_COMPONENT : ui::INPUT_EVENT_LATENCY_SCROLL_UPDATE_ORIGINAL_COMPONENT, original_timestamp, 1); } last_injected_gesture_was_begin_ = false; } std::unique_ptr<EventWithCallback> gesture_event_with_callback_update = std::make_unique<EventWithCallback>( std::move(web_scoped_gesture_event), scrollbar_latency_info, original_timestamp, original_timestamp, nullptr); bool needs_animate_input = compositor_event_queue_->empty(); compositor_event_queue_->Queue(std::move(gesture_event_with_callback_update), original_timestamp); if (needs_animate_input) input_handler_->SetNeedsAnimateInput(); } CWE ID: CWE-281 Target: 1 Example 2: Code: mrb_class_get(mrb_state *mrb, const char *name) { return mrb_class_get_under(mrb, mrb->object_class, name); } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static MagickBooleanType IsWMF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\327\315\306\232",4) == 0) return(MagickTrue); if (memcmp(magick,"\001\000\011\000",4) == 0) return(MagickTrue); return(MagickFalse); } 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 WtsSessionProcessDelegate::Core::LaunchProcess( IPC::Listener* delegate, ScopedHandle* process_exit_event_out) { DCHECK(main_task_runner_->BelongsToCurrentThread()); CommandLine command_line(CommandLine::NO_PROGRAM); if (launch_elevated_) { if (!job_.IsValid()) { return false; } FilePath daemon_binary; if (!GetInstalledBinaryPath(kDaemonBinaryName, &daemon_binary)) return false; command_line.SetProgram(daemon_binary); command_line.AppendSwitchPath(kElevateSwitchName, binary_path_); CHECK(ResetEvent(process_exit_event_)); } else { command_line.SetProgram(binary_path_); } scoped_ptr<IPC::ChannelProxy> channel; std::string channel_name = GenerateIpcChannelName(this); if (!CreateIpcChannel(channel_name, channel_security_, io_task_runner_, delegate, &channel)) return false; command_line.AppendSwitchNative(kDaemonPipeSwitchName, UTF8ToWide(channel_name)); command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(), kCopiedSwitchNames, arraysize(kCopiedSwitchNames)); ScopedHandle worker_process; ScopedHandle worker_thread; if (!LaunchProcessWithToken(command_line.GetProgram(), command_line.GetCommandLineString(), session_token_, false, CREATE_SUSPENDED | CREATE_BREAKAWAY_FROM_JOB, &worker_process, &worker_thread)) { return false; } HANDLE local_process_exit_event; if (launch_elevated_) { if (!AssignProcessToJobObject(job_, worker_process)) { LOG_GETLASTERROR(ERROR) << "Failed to assign the worker to the job object"; TerminateProcess(worker_process, CONTROL_C_EXIT); return false; } local_process_exit_event = process_exit_event_; } else { worker_process_ = worker_process.Pass(); local_process_exit_event = worker_process_; } if (!ResumeThread(worker_thread)) { LOG_GETLASTERROR(ERROR) << "Failed to resume the worker thread"; KillProcess(CONTROL_C_EXIT); return false; } ScopedHandle process_exit_event; if (!DuplicateHandle(GetCurrentProcess(), local_process_exit_event, GetCurrentProcess(), process_exit_event.Receive(), SYNCHRONIZE, FALSE, 0)) { LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle"; KillProcess(CONTROL_C_EXIT); return false; } channel_ = channel.Pass(); *process_exit_event_out = process_exit_event.Pass(); return true; } CWE ID: CWE-399 Target: 1 Example 2: Code: VideoCaptureManager* MediaStreamManager::video_capture_manager() { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(video_capture_manager_.get()); return video_capture_manager_.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: static void vmsvga_fifo_run(struct vmsvga_state_s *s) { uint32_t cmd, colour; int args, len, maxloop = 1024; int x, y, dx, dy, width, height; struct vmsvga_cursor_definition_s cursor; uint32_t cmd_start; len = vmsvga_fifo_length(s); while (len > 0 && --maxloop > 0) { /* May need to go back to the start of the command if incomplete */ cmd_start = s->fifo_stop; switch (cmd = vmsvga_fifo_read(s)) { case SVGA_CMD_UPDATE: case SVGA_CMD_UPDATE_VERBOSE: len -= 5; if (len < 0) { goto rewind; } x = vmsvga_fifo_read(s); y = vmsvga_fifo_read(s); width = vmsvga_fifo_read(s); height = vmsvga_fifo_read(s); vmsvga_update_rect_delayed(s, x, y, width, height); break; case SVGA_CMD_RECT_FILL: len -= 6; if (len < 0) { goto rewind; } colour = vmsvga_fifo_read(s); x = vmsvga_fifo_read(s); y = vmsvga_fifo_read(s); width = vmsvga_fifo_read(s); height = vmsvga_fifo_read(s); #ifdef HW_FILL_ACCEL if (vmsvga_fill_rect(s, colour, x, y, width, height) == 0) { break; } #endif args = 0; goto badcmd; case SVGA_CMD_RECT_COPY: len -= 7; if (len < 0) { goto rewind; } x = vmsvga_fifo_read(s); y = vmsvga_fifo_read(s); dx = vmsvga_fifo_read(s); dy = vmsvga_fifo_read(s); width = vmsvga_fifo_read(s); height = vmsvga_fifo_read(s); #ifdef HW_RECT_ACCEL if (vmsvga_copy_rect(s, x, y, dx, dy, width, height) == 0) { break; } #endif args = 0; goto badcmd; case SVGA_CMD_DEFINE_CURSOR: len -= 8; if (len < 0) { goto rewind; } cursor.id = vmsvga_fifo_read(s); cursor.hot_x = vmsvga_fifo_read(s); cursor.hot_y = vmsvga_fifo_read(s); cursor.width = x = vmsvga_fifo_read(s); cursor.height = y = vmsvga_fifo_read(s); vmsvga_fifo_read(s); cursor.bpp = vmsvga_fifo_read(s); args = SVGA_BITMAP_SIZE(x, y) + SVGA_PIXMAP_SIZE(x, y, cursor.bpp); if (cursor.width > 256 || cursor.height > 256 || cursor.bpp > 32 || SVGA_BITMAP_SIZE(x, y) > sizeof cursor.mask || SVGA_PIXMAP_SIZE(x, y, cursor.bpp) > sizeof cursor.image) { goto badcmd; } goto rewind; } for (args = 0; args < SVGA_BITMAP_SIZE(x, y); args++) { cursor.mask[args] = vmsvga_fifo_read_raw(s); } for (args = 0; args < SVGA_PIXMAP_SIZE(x, y, cursor.bpp); args++) { cursor.image[args] = vmsvga_fifo_read_raw(s); } #ifdef HW_MOUSE_ACCEL vmsvga_cursor_define(s, &cursor); break; #else args = 0; goto badcmd; #endif /* * Other commands that we at least know the number of arguments * for so we can avoid FIFO desync if driver uses them illegally. */ case SVGA_CMD_DEFINE_ALPHA_CURSOR: len -= 6; if (len < 0) { goto rewind; } vmsvga_fifo_read(s); vmsvga_fifo_read(s); vmsvga_fifo_read(s); x = vmsvga_fifo_read(s); y = vmsvga_fifo_read(s); args = x * y; goto badcmd; case SVGA_CMD_RECT_ROP_FILL: args = 6; goto badcmd; case SVGA_CMD_RECT_ROP_COPY: args = 7; goto badcmd; case SVGA_CMD_DRAW_GLYPH_CLIPPED: len -= 4; if (len < 0) { goto rewind; } vmsvga_fifo_read(s); vmsvga_fifo_read(s); args = 7 + (vmsvga_fifo_read(s) >> 2); goto badcmd; case SVGA_CMD_SURFACE_ALPHA_BLEND: args = 12; goto badcmd; /* * Other commands that are not listed as depending on any * CAPABILITIES bits, but are not described in the README either. */ case SVGA_CMD_SURFACE_FILL: case SVGA_CMD_SURFACE_COPY: case SVGA_CMD_FRONT_ROP_FILL: case SVGA_CMD_FENCE: case SVGA_CMD_INVALID_CMD: break; /* Nop */ default: args = 0; badcmd: len -= args; if (len < 0) { goto rewind; } while (args--) { vmsvga_fifo_read(s); } printf("%s: Unknown command 0x%02x in SVGA command FIFO\n", __func__, cmd); break; rewind: s->fifo_stop = cmd_start; s->fifo[SVGA_FIFO_STOP] = cpu_to_le32(s->fifo_stop); break; } } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline int check_entry_size_and_hooks(struct arpt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || (unsigned char *)e + sizeof(struct arpt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct arpt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!arp_checkentry(&e->arp)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_ARP_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: static int imap_endofresp(struct pingpong *pp, int *resp) { char *line = pp->linestart_resp; size_t len = pp->nread_resp; struct imap_conn *imapc = &pp->conn->proto.imapc; const char *id = imapc->idstr; size_t id_len = strlen(id); if(len >= id_len + 3) { if(!memcmp(id, line, id_len) && (line[id_len] == ' ') ) { /* end of response */ *resp = line[id_len+1]; /* O, N or B */ return TRUE; } else if((imapc->state == IMAP_FETCH) && !memcmp("* ", line, 2) ) { /* FETCH response we're interested in */ *resp = '*'; return TRUE; } } return FALSE; /* nothing for us */ } CWE ID: CWE-89 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 WebResourceService::StartFetch() { ScheduleFetch(cache_update_delay_ms_); prefs_->SetString(last_update_time_pref_name_, base::DoubleToString(base::Time::Now().ToDoubleT())); if (in_fetch_) return; in_fetch_ = true; GURL web_resource_server = application_locale_.empty() ? web_resource_server_ : google_util::AppendGoogleLocaleParam(web_resource_server_, application_locale_); DVLOG(1) << "WebResourceService StartFetch " << web_resource_server; url_fetcher_ = net::URLFetcher::Create(web_resource_server, net::URLFetcher::GET, this); url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); url_fetcher_->SetRequestContext(request_context_.get()); url_fetcher_->Start(); } CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ivr_read_header(AVFormatContext *s) { unsigned tag, type, len, tlen, value; int i, j, n, count, nb_streams = 0, ret; uint8_t key[256], val[256]; AVIOContext *pb = s->pb; AVStream *st; int64_t pos, offset, temp; pos = avio_tell(pb); tag = avio_rl32(pb); if (tag == MKTAG('.','R','1','M')) { if (avio_rb16(pb) != 1) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); avio_skip(pb, 5); temp = avio_rb64(pb); while (!avio_feof(pb) && temp) { offset = temp; temp = avio_rb64(pb); } avio_skip(pb, offset - avio_tell(pb)); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); if (avio_r8(pb) != 2) return AVERROR_INVALIDDATA; avio_skip(pb, 16); pos = avio_tell(pb); tag = avio_rl32(pb); } if (tag != MKTAG('.','R','E','C')) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 0) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4) { av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) { nb_streams = value = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } for (n = 0; n < nb_streams; n++) { st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) { ret = ffio_ensure_seekback(pb, 4); if (ret < 0) return ret; if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, pb, st, NULL); } else { avio_seek(pb, -4, SEEK_CUR); ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); } if (ret < 0) return ret; } else if (type == 4) { int j; av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) { st->duration = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } } if (avio_r8(pb) != 6) return AVERROR_INVALIDDATA; avio_skip(pb, 12); avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb)); if (avio_r8(pb) != 8) return AVERROR_INVALIDDATA; avio_skip(pb, 8); return 0; } CWE ID: CWE-834 Target: 1 Example 2: Code: int write_file(struct inode *inode, char *pathname) { unsigned int file_fd, i; unsigned int *block_list; int file_end = inode->data / block_size; long long start = inode->start; TRACE("write_file: regular file, blocks %d\n", inode->blocks); file_fd = open_wait(pathname, O_CREAT | O_WRONLY | (force ? O_TRUNC : 0), (mode_t) inode->mode & 0777); if(file_fd == -1) { ERROR("write_file: failed to create file %s, because %s\n", pathname, strerror(errno)); return FALSE; } block_list = malloc(inode->blocks * sizeof(unsigned int)); if(block_list == NULL) EXIT_UNSQUASH("write_file: unable to malloc block list\n"); s_ops.read_block_list(block_list, inode->block_ptr, inode->blocks); /* * the writer thread is queued a squashfs_file structure describing the * file. If the file has one or more blocks or a fragment they are * queued separately (references to blocks in the cache). */ queue_file(pathname, file_fd, inode); for(i = 0; i < inode->blocks; i++) { int c_byte = SQUASHFS_COMPRESSED_SIZE_BLOCK(block_list[i]); struct file_entry *block = malloc(sizeof(struct file_entry)); if(block == NULL) EXIT_UNSQUASH("write_file: unable to malloc file\n"); block->offset = 0; block->size = i == file_end ? inode->data & (block_size - 1) : block_size; if(block_list[i] == 0) /* sparse block */ block->buffer = NULL; else { block->buffer = cache_get(data_cache, start, block_list[i]); start += c_byte; } queue_put(to_writer, block); } if(inode->frag_bytes) { int size; long long start; struct file_entry *block = malloc(sizeof(struct file_entry)); if(block == NULL) EXIT_UNSQUASH("write_file: unable to malloc file\n"); s_ops.read_fragment(inode->fragment, &start, &size); block->buffer = cache_get(fragment_cache, start, size); block->offset = inode->offset; block->size = inode->frag_bytes; queue_put(to_writer, block); } free(block_list); return TRUE; } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ext4_mark_dquot_dirty(struct dquot *dquot) { /* Are we journaling quotas? */ if (EXT4_SB(dquot->dq_sb)->s_qf_names[USRQUOTA] || EXT4_SB(dquot->dq_sb)->s_qf_names[GRPQUOTA]) { dquot_mark_dquot_dirty(dquot); return ext4_write_dquot(dquot); } else { return dquot_mark_dquot_dirty(dquot); } } 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: uch *readpng_get_image(double display_exponent, int *pChannels, ulg *pRowbytes) { ulg rowbytes; /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, * transparency chunks to full alpha channel; strip 16-bit-per-sample * images to 8 bits per sample; and convert grayscale to RGB[A] */ /* GRR WARNING: grayscale needs to be expanded and channels reset! */ *pRowbytes = rowbytes = channels*width; *pChannels = channels; if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) { return NULL; } Trace((stderr, "readpng_get_image: rowbytes = %ld, height = %ld\n", rowbytes, height)); /* now we can go ahead and just read the whole image */ fread(image_data, 1L, rowbytes*height, saved_infile); return image_data; } CWE ID: Target: 1 Example 2: Code: void WebLocalFrameImpl::UnmarkText() { GetFrame()->GetInputMethodController().CancelComposition(); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebBluetoothServiceImpl::ClearState() { characteristic_id_to_notify_session_.clear(); pending_primary_services_requests_.clear(); descriptor_id_to_characteristic_id_.clear(); characteristic_id_to_service_id_.clear(); service_id_to_device_address_.clear(); connected_devices_.reset( new FrameConnectedBluetoothDevices(render_frame_host_)); device_chooser_controller_.reset(); BluetoothAdapterFactoryWrapper::Get().ReleaseAdapter(this); } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ext2_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int name_index; void *value = NULL; size_t size = 0; int error; switch(type) { case ACL_TYPE_ACCESS: name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext2_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext2_xattr_set(inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } CWE ID: CWE-285 Target: 1 Example 2: Code: get_char_len_node1(Node* node, regex_t* reg, int* len, int level) { int tlen; int r = 0; level++; *len = 0; switch (NODE_TYPE(node)) { case NODE_LIST: do { r = get_char_len_node1(NODE_CAR(node), reg, &tlen, level); if (r == 0) *len = distance_add(*len, tlen); } while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))); break; case NODE_ALT: { int tlen2; int varlen = 0; r = get_char_len_node1(NODE_CAR(node), reg, &tlen, level); while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node))) { r = get_char_len_node1(NODE_CAR(node), reg, &tlen2, level); if (r == 0) { if (tlen != tlen2) varlen = 1; } } if (r == 0) { if (varlen != 0) { if (level == 1) r = GET_CHAR_LEN_TOP_ALT_VARLEN; else r = GET_CHAR_LEN_VARLEN; } else *len = tlen; } } break; case NODE_STRING: { StrNode* sn = STR_(node); UChar *s = sn->s; while (s < sn->end) { s += enclen(reg->enc, s); (*len)++; } } break; case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (qn->lower == qn->upper) { if (qn->upper == 0) { *len = 0; } else { r = get_char_len_node1(NODE_BODY(node), reg, &tlen, level); if (r == 0) *len = distance_multiply(tlen, qn->lower); } } else r = GET_CHAR_LEN_VARLEN; } break; #ifdef USE_CALL case NODE_CALL: if (! NODE_IS_RECURSION(node)) r = get_char_len_node1(NODE_BODY(node), reg, len, level); else r = GET_CHAR_LEN_VARLEN; break; #endif case NODE_CTYPE: case NODE_CCLASS: *len = 1; break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_MEMORY: #ifdef USE_CALL if (NODE_IS_CLEN_FIXED(node)) *len = en->char_len; else { r = get_char_len_node1(NODE_BODY(node), reg, len, level); if (r == 0) { en->char_len = *len; NODE_STATUS_ADD(node, CLEN_FIXED); } } break; #endif case BAG_OPTION: case BAG_STOP_BACKTRACK: r = get_char_len_node1(NODE_BODY(node), reg, len, level); break; case BAG_IF_ELSE: { int clen, elen; r = get_char_len_node1(NODE_BODY(node), reg, &clen, level); if (r == 0) { if (IS_NOT_NULL(en->te.Then)) { r = get_char_len_node1(en->te.Then, reg, &tlen, level); if (r != 0) break; } else tlen = 0; if (IS_NOT_NULL(en->te.Else)) { r = get_char_len_node1(en->te.Else, reg, &elen, level); if (r != 0) break; } else elen = 0; if (clen + tlen != elen) { r = GET_CHAR_LEN_VARLEN; } else { *len = elen; } } } break; } } break; case NODE_ANCHOR: case NODE_GIMMICK: break; case NODE_BACKREF: if (NODE_IS_CHECKER(node)) break; /* fall */ default: r = GET_CHAR_LEN_VARLEN; break; } return r; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ssl3_client_hello(SSL *s) { unsigned char *buf; unsigned char *p, *d; int i; unsigned long l; int al = 0; #ifndef OPENSSL_NO_COMP int j; SSL_COMP *comp; #endif buf = (unsigned char *)s->init_buf->data; if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { SSL_SESSION *sess = s->session; if ((sess == NULL) || (sess->ssl_version != s->version) || !sess->session_id_length || (sess->not_resumable)) { if (!ssl_get_new_session(s, 0)) goto err; } if (s->method->version == DTLS_ANY_VERSION) { /* Determine which DTLS version to use */ int options = s->options; /* If DTLS 1.2 disabled correct the version number */ if (options & SSL_OP_NO_DTLSv1_2) { if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } /* * Disabling all versions is silly: return an error. */ if (options & SSL_OP_NO_DTLSv1) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION); goto err; } /* * Update method so we don't use any DTLS 1.2 features. */ s->method = DTLSv1_client_method(); s->version = DTLS1_VERSION; } else { /* * We only support one version: update method */ if (options & SSL_OP_NO_DTLSv1) s->method = DTLSv1_2_client_method(); s->version = DTLS1_2_VERSION; } s->client_version = s->version; } /* else use the pre-loaded session */ p = s->s3->client_random; /* * for DTLS if client_random is initialized, reuse it, we are * required to use same upon reply to HelloVerify */ if (SSL_IS_DTLS(s)) { size_t idx; i = 1; for (idx = 0; idx < sizeof(s->s3->client_random); idx++) { if (p[idx]) { i = 0; break; } } } else i = 1; if (i) ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)); /* Do the message type and length last */ d = p = ssl_handshake_start(s); /*- * version indicates the negotiated version: for example from * an SSLv2/v3 compatible client hello). The client_version * field is the maximum version we permit and it is also * used in RSA encrypted premaster secrets. Some servers can * choke if we initially report a higher version then * renegotiate to a lower one in the premaster secret. This * didn't happen with TLS 1.0 as most servers supported it * but it can with TLS 1.1 or later if the server only supports * 1.0. * * Possible scenario with previous logic: * 1. Client hello indicates TLS 1.2 * 2. Server hello says TLS 1.0 * 3. RSA encrypted premaster secret uses 1.2. * 4. Handhaked proceeds using TLS 1.0. * 5. Server sends hello request to renegotiate. * 6. Client hello indicates TLS v1.0 as we now * know that is maximum server supports. * 7. Server chokes on RSA encrypted premaster secret * containing version 1.0. * * For interoperability it should be OK to always use the * maximum version we support in client hello and then rely * on the checking of version to ensure the servers isn't * being inconsistent: for example initially negotiating with * TLS 1.0 and renegotiating with TLS 1.2. We do this by using * client_version in client hello and not resetting it to * the negotiated version. */ *(p++) = s->client_version >> 8; *(p++) = s->client_version & 0xff; /* Random stuff */ memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* Session ID */ if (s->new_session) i = 0; else i = s->session->session_id_length; *(p++) = i; if (i != 0) { if (i > (int)sizeof(s->session->session_id)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } memcpy(p, s->session->session_id, i); p += i; } /* cookie stuff for DTLS */ if (SSL_IS_DTLS(s)) { if (s->d1->cookie_len > sizeof(s->d1->cookie)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } *(p++) = s->d1->cookie_len; memcpy(p, s->d1->cookie, s->d1->cookie_len); p += s->d1->cookie_len; } /* Ciphers supported */ i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0); if (i == 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE); goto err; } #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH /* * Some servers hang if client hello > 256 bytes as hack workaround * chop number of supported ciphers to keep it well below this if we * use TLS v1.2 */ if (TLS1_get_version(s) >= TLS1_2_VERSION && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; #endif s2n(i, p); p += i; /* COMPRESSION */ #ifdef OPENSSL_NO_COMP *(p++) = 1; #else if (!ssl_allow_compression(s) || !s->ctx->comp_methods) j = 0; else j = sk_SSL_COMP_num(s->ctx->comp_methods); *(p++) = 1 + j; for (i = 0; i < j; i++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, i); *(p++) = comp->id; } #endif *(p++) = 0; /* Add the NULL method */ #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (ssl_prepare_clienthello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } if ((p = ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) { ssl3_send_alert(s, SSL3_AL_FATAL, al); SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } #endif l = p - d; ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l); s->state = SSL3_ST_CW_CLNT_HELLO_B; } /* SSL3_ST_CW_CLNT_HELLO_B */ return ssl_do_write(s); err: return (-1); } CWE ID: CWE-310 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_scan_match_callback( uint8_t* match_data, int32_t match_length, int flags, void* args) { CALLBACK_ARGS* callback_args = (CALLBACK_ARGS*) args; YR_STRING* string = callback_args->string; YR_MATCH* new_match; int result = ERROR_SUCCESS; int tidx = callback_args->context->tidx; size_t match_offset = match_data - callback_args->data; match_length += callback_args->forward_matches; if (callback_args->full_word) { if (flags & RE_FLAGS_WIDE) { if (match_offset >= 2 && *(match_data - 1) == 0 && isalnum(*(match_data - 2))) return ERROR_SUCCESS; if (match_offset + match_length + 1 < callback_args->data_size && *(match_data + match_length + 1) == 0 && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } else { if (match_offset >= 1 && isalnum(*(match_data - 1))) return ERROR_SUCCESS; if (match_offset + match_length < callback_args->data_size && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } } if (STRING_IS_CHAIN_PART(string)) { result = _yr_scan_verify_chained_string_match( string, callback_args->context, match_data, callback_args->data_base, match_offset, match_length); } else { if (string->matches[tidx].count == 0) { FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matching_strings_arena, &string, sizeof(string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( callback_args->context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); if (result == ERROR_SUCCESS) { new_match->base = callback_args->data_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &string->matches[tidx], STRING_IS_GREEDY_REGEXP(string))); } } return result; } CWE ID: CWE-125 Target: 1 Example 2: Code: static plist_t parse_array_node(struct bplist_data *bplist, const char** bnode, uint64_t size) { uint64_t j; uint64_t str_j = 0; uint64_t index1; plist_data_t data = plist_new_plist_data(); const char *index1_ptr = NULL; data->type = PLIST_ARRAY; data->length = size; plist_t node = node_create(NULL, data); for (j = 0; j < data->length; j++) { str_j = j * bplist->ref_size; index1_ptr = (*bnode) + str_j; if (index1_ptr < bplist->data || index1_ptr + bplist->ref_size > bplist->offset_table) { plist_free(node); PLIST_BIN_ERR("%s: array item %" PRIu64 " is outside of valid range\n", __func__, j); return NULL; } index1 = UINT_TO_HOST(index1_ptr, bplist->ref_size); if (index1 >= bplist->num_objects) { plist_free(node); PLIST_BIN_ERR("%s: array item %" PRIu64 " object index (%" PRIu64 ") must be smaller than the number of objects (%" PRIu64 ")\n", __func__, j, index1, bplist->num_objects); return NULL; } /* process value node */ plist_t val = parse_bin_node_at_index(bplist, index1); if (!val) { plist_free(node); return NULL; } node_attach(node, val); } return node; } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int http_connect(http_subtransport *t) { int error; char *proxy_url; if (t->connected && http_should_keep_alive(&t->parser) && t->parse_finished) return 0; if (t->io) { git_stream_close(t->io); git_stream_free(t->io); t->io = NULL; t->connected = 0; } if (t->connection_data.use_ssl) { error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port); } else { #ifdef GIT_CURL error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #else error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #endif } if (error < 0) return error; GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream"); if (git_stream_supports_proxy(t->io) && !git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url)) { error = git_stream_set_proxy(t->io, proxy_url); git__free(proxy_url); if (error < 0) return error; } error = git_stream_connect(t->io); #if defined(GIT_OPENSSL) || defined(GIT_SECURE_TRANSPORT) || defined(GIT_CURL) if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL && git_stream_is_encrypted(t->io)) { git_cert *cert; int is_valid; if ((error = git_stream_certificate(&cert, t->io)) < 0) return error; giterr_clear(); is_valid = error != GIT_ECERTIFICATE; error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload); if (error < 0) { if (!giterr_last()) giterr_set(GITERR_NET, "user cancelled certificate check"); return error; } } #endif if (error < 0) return error; t->connected = 1; return 0; } CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfacePostSubBuffer"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(params.surface_id); if (!view) return; delayed_send.Cancel(); view->AcceleratedSurfacePostSubBuffer(params, host_id_); } CWE ID: Target: 1 Example 2: Code: static inline unsigned long copy_shmid_to_user(void __user *buf, struct shmid64_ds *in, int version) { switch (version) { case IPC_64: return copy_to_user(buf, in, sizeof(*in)); case IPC_OLD: { struct shmid_ds out; memset(&out, 0, sizeof(out)); ipc64_perm_to_ipc_perm(&in->shm_perm, &out.shm_perm); out.shm_segsz = in->shm_segsz; out.shm_atime = in->shm_atime; out.shm_dtime = in->shm_dtime; out.shm_ctime = in->shm_ctime; out.shm_cpid = in->shm_cpid; out.shm_lpid = in->shm_lpid; out.shm_nattch = in->shm_nattch; return copy_to_user(buf, &out, sizeof(out)); } default: return -EINVAL; } } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void EntrySync::remove(ExceptionState& exceptionState) const { RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create(); m_fileSystem->remove(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func) { irda_queue_t* queue; unsigned long flags = 0; int i; IRDA_ASSERT(hashbin != NULL, return -1;); IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;); /* Synchronize */ if ( hashbin->hb_type & HB_LOCK ) { spin_lock_irqsave_nested(&hashbin->hb_spinlock, flags, hashbin_lock_depth++); } /* * Free the entries in the hashbin, TODO: use hashbin_clear when * it has been shown to work */ for (i = 0; i < HASHBIN_SIZE; i ++ ) { queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]); while (queue ) { if (free_func) (*free_func)(queue); queue = dequeue_first( (irda_queue_t**) &hashbin->hb_queue[i]); } } /* Cleanup local data */ hashbin->hb_current = NULL; hashbin->magic = ~HB_MAGIC; /* Release lock */ if ( hashbin->hb_type & HB_LOCK) { spin_unlock_irqrestore(&hashbin->hb_spinlock, flags); #ifdef CONFIG_LOCKDEP hashbin_lock_depth--; #endif } /* * Free the hashbin structure */ kfree(hashbin); return 0; } CWE ID: Target: 1 Example 2: Code: static int http_get_line(HTTPContext *s, char *line, int line_size) { int ch; char *q; q = line; for (;;) { ch = http_getc(s); if (ch < 0) return ch; if (ch == '\n') { /* process line */ if (q > line && q[-1] == '\r') q--; *q = '\0'; return 0; } else { if ((q - line) < line_size - 1) *q++ = ch; } } } 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: long mkvparser::UnserializeString(IMkvReader* pReader, long long pos, long long size_, char*& str) { delete[] str; str = NULL; if (size_ >= LONG_MAX) // we need (size+1) chars return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); str = new (std::nothrow) char[size + 1]; if (str == NULL) return -1; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[size] = '\0'; return 0; // success } 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: GLboolean WebGL2RenderingContextBase::isVertexArray( WebGLVertexArrayObject* vertex_array) { if (isContextLost() || !vertex_array) return 0; if (!vertex_array->HasEverBeenBound()) return 0; return ContextGL()->IsVertexArrayOES(vertex_array->Object()); } CWE ID: CWE-119 Target: 1 Example 2: Code: static bool nfs_need_update_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid) { if (test_and_set_bit(NFS_OPEN_STATE, &state->flags) == 0) return true; if (!nfs4_stateid_match_other(stateid, &state->open_stateid)) { nfs_test_and_clear_all_open_stateid(state); return true; } if (nfs4_stateid_is_newer(stateid, &state->open_stateid)) 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: txid_snapshot_recv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); TxidSnapshot *snap; txid last = 0; int nxip; int i; int avail; int expect; txid xmin, xmax; /* * load nxip and check for nonsense. * * (nxip > avail) check is against int overflows in 'expect'. */ nxip = pq_getmsgint(buf, 4); avail = buf->len - buf->cursor; expect = 8 + 8 + nxip * 8; if (nxip < 0 || nxip > avail || expect > avail) goto bad_format; xmin = pq_getmsgint64(buf); xmax = pq_getmsgint64(buf); if (xmin == 0 || xmax == 0 || xmin > xmax || xmax > MAX_TXID) goto bad_format; snap = palloc(TXID_SNAPSHOT_SIZE(nxip)); snap->xmin = xmin; snap->xmax = xmax; snap->nxip = nxip; SET_VARSIZE(snap, TXID_SNAPSHOT_SIZE(nxip)); for (i = 0; i < nxip; i++) { txid cur = pq_getmsgint64(buf); if (cur <= last || cur < xmin || cur >= xmax) goto bad_format; snap->xip[i] = cur; last = cur; } PG_RETURN_POINTER(snap); bad_format: elog(ERROR, "invalid snapshot data"); return (Datum) NULL; } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: asmlinkage void __kprobes do_page_fault(struct pt_regs *regs, unsigned long writeaccess, unsigned long address) { unsigned long vec; struct task_struct *tsk; struct mm_struct *mm; struct vm_area_struct * vma; int si_code; int fault; siginfo_t info; tsk = current; mm = tsk->mm; si_code = SEGV_MAPERR; vec = lookup_exception_vector(); /* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd. * * NOTE! We MUST NOT take any locks for this case. We may * be in an interrupt or a critical region, and should * only copy the information from the master page table, * nothing more. */ if (unlikely(fault_in_kernel_space(address))) { if (vmalloc_fault(address) >= 0) return; if (notify_page_fault(regs, vec)) return; goto bad_area_nosemaphore; } if (unlikely(notify_page_fault(regs, vec))) return; /* Only enable interrupts if they were on before the fault */ if ((regs->sr & SR_IMASK) != SR_IMASK) local_irq_enable(); perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address); /* * If we're in an interrupt, have no user context or are running * in an atomic region then we must not take the fault: */ if (in_atomic() || !mm) goto no_context; down_read(&mm->mmap_sem); vma = find_vma(mm, address); if (!vma) goto bad_area; if (vma->vm_start <= address) goto good_area; if (!(vma->vm_flags & VM_GROWSDOWN)) goto bad_area; if (expand_stack(vma, address)) goto bad_area; /* * Ok, we have a good vm_area for this memory access, so * we can handle it.. */ good_area: si_code = SEGV_ACCERR; if (writeaccess) { if (!(vma->vm_flags & VM_WRITE)) goto bad_area; } else { if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))) goto bad_area; } /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault. */ fault = handle_mm_fault(mm, vma, address, writeaccess ? FAULT_FLAG_WRITE : 0); if (unlikely(fault & VM_FAULT_ERROR)) { if (fault & VM_FAULT_OOM) goto out_of_memory; else if (fault & VM_FAULT_SIGBUS) goto do_sigbus; BUG(); } if (fault & VM_FAULT_MAJOR) { tsk->maj_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, address); } else { tsk->min_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, address); } up_read(&mm->mmap_sem); return; /* * Something tried to access memory that isn't in our memory map.. * Fix it, but check if it's kernel or user first.. */ bad_area: up_read(&mm->mmap_sem); bad_area_nosemaphore: if (user_mode(regs)) { info.si_signo = SIGSEGV; info.si_errno = 0; info.si_code = si_code; info.si_addr = (void *) address; force_sig_info(SIGSEGV, &info, tsk); return; } no_context: /* Are we prepared to handle this kernel fault? */ if (fixup_exception(regs)) return; if (handle_trapped_io(regs, address)) return; /* * Oops. The kernel tried to access some bad page. We'll have to * terminate things with extreme prejudice. * */ bust_spinlocks(1); if (oops_may_print()) { unsigned long page; if (address < PAGE_SIZE) printk(KERN_ALERT "Unable to handle kernel NULL " "pointer dereference"); else printk(KERN_ALERT "Unable to handle kernel paging " "request"); printk(" at virtual address %08lx\n", address); printk(KERN_ALERT "pc = %08lx\n", regs->pc); page = (unsigned long)get_TTB(); if (page) { page = ((__typeof__(page) *)page)[address >> PGDIR_SHIFT]; printk(KERN_ALERT "*pde = %08lx\n", page); if (page & _PAGE_PRESENT) { page &= PAGE_MASK; address &= 0x003ff000; page = ((__typeof__(page) *) __va(page))[address >> PAGE_SHIFT]; printk(KERN_ALERT "*pte = %08lx\n", page); } } } die("Oops", regs, writeaccess); bust_spinlocks(0); do_exit(SIGKILL); /* * We ran out of memory, or some other thing happened to us that made * us unable to handle the page fault gracefully. */ out_of_memory: up_read(&mm->mmap_sem); if (!user_mode(regs)) goto no_context; pagefault_out_of_memory(); return; do_sigbus: up_read(&mm->mmap_sem); /* * Send a sigbus, regardless of whether we were in kernel * or user mode. */ info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_ADRERR; info.si_addr = (void *)address; force_sig_info(SIGBUS, &info, tsk); /* Kernel mode? Handle exceptions or die */ if (!user_mode(regs)) goto no_context; } CWE ID: CWE-399 Target: 1 Example 2: Code: OMX_ERRORTYPE omx_video::allocate_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_ERRORTYPE eRet = OMX_ErrorNone; // OMX return type DEBUG_PRINT_LOW("Allocate buffer of size = %u on port %d", (unsigned int)bytes, (int)port); if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: Allocate Buf in Invalid State"); return OMX_ErrorInvalidState; } if (port == PORT_INDEX_IN) { #ifdef _ANDROID_ICS_ if (meta_mode_enable) eRet = allocate_input_meta_buffer(hComp,bufferHdr,appData,bytes); else #endif eRet = allocate_input_buffer(hComp,bufferHdr,port,appData,bytes); } else if (port == PORT_INDEX_OUT) { eRet = allocate_output_buffer(hComp,bufferHdr,port,appData,bytes); } else { DEBUG_PRINT_ERROR("ERROR: Invalid Port Index received %d",(int)port); eRet = OMX_ErrorBadPortIndex; } DEBUG_PRINT_LOW("Checking for Output Allocate buffer Done"); if (eRet == OMX_ErrorNone) { if (allocate_done()) { if (BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) { BITMASK_CLEAR((&m_flags),OMX_COMPONENT_IDLE_PENDING); post_event(OMX_CommandStateSet,OMX_StateIdle, OMX_COMPONENT_GENERATE_EVENT); } } if (port == PORT_INDEX_IN && m_sInPortDef.bPopulated) { if (BITMASK_PRESENT(&m_flags,OMX_COMPONENT_INPUT_ENABLE_PENDING)) { BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_ENABLE_PENDING); post_event(OMX_CommandPortEnable, PORT_INDEX_IN, OMX_COMPONENT_GENERATE_EVENT); } } if (port == PORT_INDEX_OUT && m_sOutPortDef.bPopulated) { if (BITMASK_PRESENT(&m_flags,OMX_COMPONENT_OUTPUT_ENABLE_PENDING)) { BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_ENABLE_PENDING); post_event(OMX_CommandPortEnable, PORT_INDEX_OUT, OMX_COMPONENT_GENERATE_EVENT); m_event_port_settings_sent = false; } } } DEBUG_PRINT_LOW("Allocate Buffer exit with ret Code %d",eRet); return eRet; } 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 ceph_x_proc_ticket_reply(struct ceph_auth_client *ac, struct ceph_crypto_key *secret, void *buf, void *end) { void *p = buf; char *dbuf; char *ticket_buf; u8 reply_struct_v; u32 num; int ret; dbuf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS); if (!dbuf) return -ENOMEM; ret = -ENOMEM; ticket_buf = kmalloc(TEMP_TICKET_BUF_LEN, GFP_NOFS); if (!ticket_buf) goto out_dbuf; ceph_decode_8_safe(&p, end, reply_struct_v, bad); if (reply_struct_v != 1) return -EINVAL; ceph_decode_32_safe(&p, end, num, bad); dout("%d tickets\n", num); while (num--) { ret = process_one_ticket(ac, secret, &p, end, dbuf, ticket_buf); if (ret) goto out; } ret = 0; out: kfree(ticket_buf); out_dbuf: kfree(dbuf); return ret; bad: ret = -EINVAL; goto out; } 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: PHP_FUNCTION(mcrypt_module_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) array_init(return_value); key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); } CWE ID: CWE-190 Target: 1 Example 2: Code: static int get_classes_callback(void *k, void *d, void *args) { struct class_datum *datum = d; char *name = k, **classes = args; int value = datum->value - 1; classes[value] = kstrdup(name, GFP_ATOMIC); if (!classes[value]) return -ENOMEM; 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: void MessageService::OpenChannelToTab( int source_process_id, int source_routing_id, int receiver_port_id, int tab_id, const std::string& extension_id, const std::string& channel_name) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; Profile* profile = Profile::FromBrowserContext(source->GetBrowserContext()); WebContents* contents = NULL; scoped_ptr<MessagePort> receiver; if (ExtensionTabUtil::GetTabById(tab_id, profile, true, NULL, NULL, &contents, NULL)) { receiver.reset(new ExtensionMessagePort( contents->GetRenderProcessHost(), contents->GetRenderViewHost()->GetRoutingID(), extension_id)); } if (contents && contents->GetController().NeedsReload()) { ExtensionMessagePort port(source, MSG_ROUTING_CONTROL, extension_id); port.DispatchOnDisconnect(GET_OPPOSITE_PORT_ID(receiver_port_id), true); return; } WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<OpenChannelParams> params(new OpenChannelParams(source, tab_json, receiver.release(), receiver_port_id, extension_id, extension_id, channel_name)); OpenChannelImpl(params.Pass()); } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LockScreenMediaControlsView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (sender == close_button_) { Dismiss(); return; } if (!base::Contains(enabled_actions_, media_message_center::GetActionFromButtonTag(*sender)) || !media_session_id_.has_value()) { return; } media_session::PerformMediaSessionAction( media_message_center::GetActionFromButtonTag(*sender), media_controller_remote_); } CWE ID: CWE-200 Target: 1 Example 2: Code: static inline unsigned long *__fetch_reg_addr_kern(unsigned int reg, struct pt_regs *regs) { BUG_ON(reg >= 16); BUG_ON(regs->tstate & TSTATE_PRIV); return &regs->u_regs[reg]; } 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: MockAudioRendererHost(base::RunLoop* auth_run_loop, int render_process_id, media::AudioManager* audio_manager, AudioMirroringManager* mirroring_manager, MediaStreamManager* media_stream_manager, const std::string& salt) : AudioRendererHost(render_process_id, audio_manager, mirroring_manager, media_stream_manager, salt), shared_memory_length_(0), auth_run_loop_(auth_run_loop) { set_render_frame_id_validate_function_for_testing(&ValidateRenderFrameId); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void SetUpTestCase() { source_data_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBlockSize)); reference_data_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kDataBufferSize)); } CWE ID: CWE-119 Target: 1 Example 2: Code: AP_DECLARE(request_rec *) ap_sub_req_lookup_uri(const char *new_uri, const request_rec *r, ap_filter_t *next_filter) { return ap_sub_req_method_uri("GET", new_uri, r, next_filter); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void HTML_put_string(HTStructured * me, const char *s) { #ifdef USE_PRETTYSRC char *translated_string = NULL; #endif if (s == NULL || (LYMapsOnly && me->sp[0].tag_number != HTML_OBJECT)) return; #ifdef USE_PRETTYSRC if (psrc_convert_string) { StrAllocCopy(translated_string, s); TRANSLATE_AND_UNESCAPE_ENTITIES(&translated_string, TRUE, FALSE); s = (const char *) translated_string; } #endif switch (me->sp[0].tag_number) { case HTML_COMMENT: break; /* Do Nothing */ case HTML_TITLE: HTChunkPuts(&me->title, s); break; case HTML_STYLE: HTChunkPuts(&me->style_block, s); break; case HTML_SCRIPT: HTChunkPuts(&me->script, s); break; case HTML_PRE: /* Formatted text */ case HTML_LISTING: /* Literal text */ case HTML_XMP: case HTML_PLAINTEXT: /* * We guarantee that the style is up-to-date in begin_litteral */ HText_appendText(me->text, s); break; case HTML_OBJECT: HTChunkPuts(&me->object, s); break; case HTML_TEXTAREA: HTChunkPuts(&me->textarea, s); break; case HTML_SELECT: case HTML_OPTION: HTChunkPuts(&me->option, s); break; case HTML_MATH: HTChunkPuts(&me->math, s); break; default: /* Free format text? */ if (!me->sp->style->freeFormat) { /* * If we are within a preformatted text style not caught by the * cases above (HTML_PRE or similar may not be the last element * pushed on the style stack). - kw */ #ifdef USE_PRETTYSRC if (psrc_view) { /* * We do this so that a raw '\r' in the string will not be * interpreted as an internal request to break a line - passing * '\r' to HText_appendText is treated by it as a request to * insert a blank line - VH */ for (; *s; ++s) HTML_put_character(me, *s); } else #endif HText_appendText(me->text, s); break; } else { const char *p = s; char c; if (me->style_change) { for (; *p && ((*p == '\n') || (*p == '\r') || (*p == ' ') || (*p == '\t')); p++) ; /* Ignore leaders */ if (!*p) break; UPDATE_STYLE; } for (; *p; p++) { if (*p == 13 && p[1] != 10) { /* * Treat any '\r' which is not followed by '\n' as '\n', to * account for macintosh lineend in ALT attributes etc. - * kw */ c = '\n'; } else { c = *p; } if (me->style_change) { if ((c == '\n') || (c == ' ') || (c == '\t')) continue; /* Ignore it */ UPDATE_STYLE; } if (c == '\n') { if (!FIX_JAPANESE_SPACES) { if (me->in_word) { if (HText_getLastChar(me->text) != ' ') HText_appendCharacter(me->text, ' '); me->in_word = NO; } } } else if (c == ' ' || c == '\t') { if (HText_getLastChar(me->text) != ' ') HText_appendCharacter(me->text, ' '); } else if (c == '\r') { /* ignore */ } else { HText_appendCharacter(me->text, c); me->in_word = YES; } /* set the Last Character */ if (c == '\n' || c == '\t') { /* set it to a generic separator */ HText_setLastChar(me->text, ' '); } else if (c == '\r' && HText_getLastChar(me->text) == ' ') { /* * \r's are ignored. In order to keep collapsing spaces * correctly, we must default back to the previous * separator, if there was one. So we set LastChar to a * generic separator. */ HText_setLastChar(me->text, ' '); } else { HText_setLastChar(me->text, c); } } /* for */ } } /* end switch */ #ifdef USE_PRETTYSRC if (psrc_convert_string) { psrc_convert_string = FALSE; FREE(translated_string); } #endif } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void free_user(struct kref *ref) { struct ipmi_user *user = container_of(ref, struct ipmi_user, refcount); kfree(user); } CWE ID: CWE-416 Target: 1 Example 2: Code: void kvm_arch_hardware_disable(void) { kvm_x86_ops->hardware_disable(); drop_user_return_notifiers(); } 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 em_cmpxchg8b(struct x86_emulate_ctxt *ctxt) { u64 old = ctxt->dst.orig_val64; if (ctxt->dst.bytes == 16) return X86EMUL_UNHANDLEABLE; if (((u32) (old >> 0) != (u32) reg_read(ctxt, VCPU_REGS_RAX)) || ((u32) (old >> 32) != (u32) reg_read(ctxt, VCPU_REGS_RDX))) { *reg_write(ctxt, VCPU_REGS_RAX) = (u32) (old >> 0); *reg_write(ctxt, VCPU_REGS_RDX) = (u32) (old >> 32); ctxt->eflags &= ~X86_EFLAGS_ZF; } else { ctxt->dst.val64 = ((u64)reg_read(ctxt, VCPU_REGS_RCX) << 32) | (u32) reg_read(ctxt, VCPU_REGS_RBX); ctxt->eflags |= X86_EFLAGS_ZF; } return X86EMUL_CONTINUE; } 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 FrameSelection::Clear() { granularity_ = TextGranularity::kCharacter; if (granularity_strategy_) granularity_strategy_->Clear(); SetSelection(SelectionInDOMTree()); } CWE ID: CWE-119 Target: 1 Example 2: Code: CheckVirtualMotion(DeviceIntPtr pDev, QdEventPtr qe, WindowPtr pWin) { SpritePtr pSprite = pDev->spriteInfo->sprite; RegionPtr reg = NULL; DeviceEvent *ev = NULL; if (qe) { ev = &qe->event->device_event; switch (ev->type) { case ET_Motion: case ET_ButtonPress: case ET_ButtonRelease: case ET_KeyPress: case ET_KeyRelease: case ET_ProximityIn: case ET_ProximityOut: pSprite->hot.pScreen = qe->pScreen; pSprite->hot.x = ev->root_x; pSprite->hot.y = ev->root_y; pWin = pDev->deviceGrab.grab ? pDev->deviceGrab.grab-> confineTo : NullWindow; break; default: break; } } if (pWin) { BoxRec lims; #ifdef PANORAMIX if (!noPanoramiXExtension) { int x, y, off_x, off_y, i; if (!XineramaSetWindowPntrs(pDev, pWin)) return; i = PanoramiXNumScreens - 1; RegionCopy(&pSprite->Reg2, &pSprite->windows[i]->borderSize); off_x = screenInfo.screens[i]->x; off_y = screenInfo.screens[i]->y; while (i--) { x = off_x - screenInfo.screens[i]->x; y = off_y - screenInfo.screens[i]->y; if (x || y) RegionTranslate(&pSprite->Reg2, x, y); RegionUnion(&pSprite->Reg2, &pSprite->Reg2, &pSprite->windows[i]->borderSize); off_x = screenInfo.screens[i]->x; off_y = screenInfo.screens[i]->y; } } else #endif { if (pSprite->hot.pScreen != pWin->drawable.pScreen) { pSprite->hot.pScreen = pWin->drawable.pScreen; pSprite->hot.x = pSprite->hot.y = 0; } } lims = *RegionExtents(&pWin->borderSize); if (pSprite->hot.x < lims.x1) pSprite->hot.x = lims.x1; else if (pSprite->hot.x >= lims.x2) pSprite->hot.x = lims.x2 - 1; if (pSprite->hot.y < lims.y1) pSprite->hot.y = lims.y1; else if (pSprite->hot.y >= lims.y2) pSprite->hot.y = lims.y2 - 1; #ifdef PANORAMIX if (!noPanoramiXExtension) { if (RegionNumRects(&pSprite->Reg2) > 1) reg = &pSprite->Reg2; } else #endif { if (wBoundingShape(pWin)) reg = &pWin->borderSize; } if (reg) ConfineToShape(pDev, reg, &pSprite->hot.x, &pSprite->hot.y); if (qe && ev) { qe->pScreen = pSprite->hot.pScreen; ev->root_x = pSprite->hot.x; ev->root_y = pSprite->hot.y; } } #ifdef PANORAMIX if (noPanoramiXExtension) /* No typo. Only set the root win if disabled */ #endif RootWindow(pDev->spriteInfo->sprite) = pSprite->hot.pScreen->root; } 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 PageFormAnalyserLogger::Flush() { std::string text; for (ConsoleLevel level : {kError, kWarning, kVerbose}) { for (LogEntry& entry : node_buffer_[level]) { text.clear(); text += "[DOM] "; text += entry.message; for (unsigned i = 0; i < entry.nodes.size(); ++i) text += " %o"; blink::WebConsoleMessage message(level, blink::WebString::FromUTF8(text)); message.nodes = std::move(entry.nodes); // avoids copying node vectors. frame_->AddMessageToConsole(message); } } node_buffer_.clear(); } 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 SerializedScriptValue::transferArrayBuffers(v8::Isolate* isolate, const ArrayBufferArray& arrayBuffers, ExceptionState& exceptionState) { if (!arrayBuffers.size()) return; for (size_t i = 0; i < arrayBuffers.size(); ++i) { if (arrayBuffers[i]->isNeutered()) { exceptionState.throwDOMException(DataCloneError, "ArrayBuffer at index " + String::number(i) + " is already neutered."); return; } } OwnPtr<ArrayBufferContentsArray> contents = adoptPtr(new ArrayBufferContentsArray(arrayBuffers.size())); HeapHashSet<Member<DOMArrayBufferBase>> visited; for (size_t i = 0; i < arrayBuffers.size(); ++i) { if (visited.contains(arrayBuffers[i])) continue; visited.add(arrayBuffers[i]); if (arrayBuffers[i]->isShared()) { bool result = arrayBuffers[i]->shareContentsWith(contents->at(i)); if (!result) { exceptionState.throwDOMException(DataCloneError, "SharedArrayBuffer at index " + String::number(i) + " could not be transferred."); return; } } else { Vector<v8::Local<v8::ArrayBuffer>, 4> bufferHandles; v8::HandleScope handleScope(isolate); acculumateArrayBuffersForAllWorlds(isolate, static_cast<DOMArrayBuffer*>(arrayBuffers[i].get()), bufferHandles); bool isNeuterable = true; for (size_t j = 0; j < bufferHandles.size(); ++j) isNeuterable &= bufferHandles[j]->IsNeuterable(); DOMArrayBufferBase* toTransfer = arrayBuffers[i]; if (!isNeuterable) toTransfer = DOMArrayBuffer::create(arrayBuffers[i]->buffer()); bool result = toTransfer->transfer(contents->at(i)); if (!result) { exceptionState.throwDOMException(DataCloneError, "ArrayBuffer at index " + String::number(i) + " could not be transferred."); return; } if (isNeuterable) for (size_t j = 0; j < bufferHandles.size(); ++j) bufferHandles[j]->Neuter(); } } m_arrayBufferContentsArray = contents.release(); } CWE ID: Target: 1 Example 2: Code: static bool ExecuteMoveWordRightAndModifySelection(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.Selection().Modify(SelectionModifyAlteration::kExtend, SelectionModifyDirection::kRight, TextGranularity::kWord, SetSelectionBy::kUser); 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: PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame) : content::RenderFrameObserver(render_frame), logging_state_active_(false), was_username_autofilled_(false), was_password_autofilled_(false), weak_ptr_factory_(this) { Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id())); } 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 authz_status lua_authz_check(request_rec *r, const char *require_line, const void *parsed_require_line) { apr_pool_t *pool; ap_lua_vm_spec *spec; lua_State *L; ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config, &lua_module); const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config, &lua_module); const lua_authz_provider_spec *prov_spec = parsed_require_line; int result; int nargs = 0; spec = create_vm_spec(&pool, r, cfg, server_cfg, prov_spec->file_name, NULL, 0, prov_spec->function_name, "authz provider"); L = ap_lua_get_lua_state(pool, spec, r); if (L == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02314) "Unable to compile VM for authz provider %s", prov_spec->name); return AUTHZ_GENERAL_ERROR; } lua_getglobal(L, prov_spec->function_name); if (!lua_isfunction(L, -1)) { ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02319) "Unable to find entry function '%s' in %s (not a valid function)", prov_spec->function_name, prov_spec->file_name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } ap_lua_run_lua_request(L, r); if (prov_spec->args) { int i; if (!lua_checkstack(L, prov_spec->args->nelts)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02315) "Error: authz provider %s: too many arguments", prov_spec->name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } for (i = 0; i < prov_spec->args->nelts; i++) { const char *arg = APR_ARRAY_IDX(prov_spec->args, i, const char *); lua_pushstring(L, arg); } nargs = prov_spec->args->nelts; } if (lua_pcall(L, 1 + nargs, 1, 0)) { const char *err = lua_tostring(L, -1); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02316) "Error executing authz provider %s: %s", prov_spec->name, err); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } if (!lua_isnumber(L, -1)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02317) "Error: authz provider %s did not return integer", prov_spec->name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } result = lua_tointeger(L, -1); ap_lua_release_state(L, spec, r); switch (result) { case AUTHZ_DENIED: case AUTHZ_GRANTED: case AUTHZ_NEUTRAL: case AUTHZ_GENERAL_ERROR: case AUTHZ_DENIED_NO_USER: return result; default: ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02318) "Error: authz provider %s: invalid return value %d", prov_spec->name, result); } return AUTHZ_GENERAL_ERROR; } CWE ID: CWE-264 Target: 1 Example 2: Code: void *Type_S15Fixed16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsFloat64Number* array_double; cmsUInt32Number i, n; *nItems = 0; n = SizeOfTag / sizeof(cmsUInt32Number); array_double = (cmsFloat64Number*) _cmsCalloc(self ->ContextID, n, sizeof(cmsFloat64Number)); if (array_double == NULL) return NULL; for (i=0; i < n; i++) { if (!_cmsRead15Fixed16Number(io, &array_double[i])) { _cmsFree(self ->ContextID, array_double); return NULL; } } *nItems = n; return (void*) array_double; } 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: bool HTMLKeygenElement::isInteractiveContent() const { return true; } 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: struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata, const u8 *addr, gfp_t gfp) { struct ieee80211_local *local = sdata->local; struct sta_info *sta; struct timespec uptime; struct ieee80211_tx_latency_bin_ranges *tx_latency; int i; sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp); if (!sta) return NULL; rcu_read_lock(); tx_latency = rcu_dereference(local->tx_latency); /* init stations Tx latency statistics && TID bins */ if (tx_latency) { sta->tx_lat = kzalloc(IEEE80211_NUM_TIDS * sizeof(struct ieee80211_tx_latency_stat), GFP_ATOMIC); if (!sta->tx_lat) { rcu_read_unlock(); goto free; } if (tx_latency->n_ranges) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* size of bins is size of the ranges +1 */ sta->tx_lat[i].bin_count = tx_latency->n_ranges + 1; sta->tx_lat[i].bins = kcalloc(sta->tx_lat[i].bin_count, sizeof(u32), GFP_ATOMIC); if (!sta->tx_lat[i].bins) { rcu_read_unlock(); goto free; } } } } rcu_read_unlock(); spin_lock_init(&sta->lock); INIT_WORK(&sta->drv_unblock_wk, sta_unblock); INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work); mutex_init(&sta->ampdu_mlme.mtx); #ifdef CONFIG_MAC80211_MESH if (ieee80211_vif_is_mesh(&sdata->vif) && !sdata->u.mesh.user_mpm) init_timer(&sta->plink_timer); sta->nonpeer_pm = NL80211_MESH_POWER_ACTIVE; #endif memcpy(sta->sta.addr, addr, ETH_ALEN); sta->local = local; sta->sdata = sdata; sta->last_rx = jiffies; sta->sta_state = IEEE80211_STA_NONE; do_posix_clock_monotonic_gettime(&uptime); sta->last_connected = uptime.tv_sec; ewma_init(&sta->avg_signal, 1024, 8); for (i = 0; i < ARRAY_SIZE(sta->chain_signal_avg); i++) ewma_init(&sta->chain_signal_avg[i], 1024, 8); if (sta_prepare_rate_control(local, sta, gfp)) goto free; for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* * timer_to_tid must be initialized with identity mapping * to enable session_timer's data differentiation. See * sta_rx_agg_session_timer_expired for usage. */ sta->timer_to_tid[i] = i; } for (i = 0; i < IEEE80211_NUM_ACS; i++) { skb_queue_head_init(&sta->ps_tx_buf[i]); skb_queue_head_init(&sta->tx_filtered[i]); } for (i = 0; i < IEEE80211_NUM_TIDS; i++) sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX); sta->sta.smps_mode = IEEE80211_SMPS_OFF; if (sdata->vif.type == NL80211_IFTYPE_AP || sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { struct ieee80211_supported_band *sband = local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)]; u8 smps = (sband->ht_cap.cap & IEEE80211_HT_CAP_SM_PS) >> IEEE80211_HT_CAP_SM_PS_SHIFT; /* * Assume that hostapd advertises our caps in the beacon and * this is the known_smps_mode for a station that just assciated */ switch (smps) { case WLAN_HT_SMPS_CONTROL_DISABLED: sta->known_smps_mode = IEEE80211_SMPS_OFF; break; case WLAN_HT_SMPS_CONTROL_STATIC: sta->known_smps_mode = IEEE80211_SMPS_STATIC; break; case WLAN_HT_SMPS_CONTROL_DYNAMIC: sta->known_smps_mode = IEEE80211_SMPS_DYNAMIC; break; default: WARN_ON(1); } } sta_dbg(sdata, "Allocated STA %pM\n", sta->sta.addr); return sta; free: if (sta->tx_lat) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) kfree(sta->tx_lat[i].bins); kfree(sta->tx_lat); } kfree(sta); return NULL; } CWE ID: CWE-362 Target: 1 Example 2: Code: bool WebGLImageConversion::ComputeFormatAndTypeParameters( GLenum format, GLenum type, unsigned* components_per_pixel, unsigned* bytes_per_component) { switch (format) { case GL_ALPHA: case GL_LUMINANCE: case GL_RED: case GL_RED_INTEGER: case GL_DEPTH_COMPONENT: case GL_DEPTH_STENCIL: // Treat it as one component. *components_per_pixel = 1; break; case GL_LUMINANCE_ALPHA: case GL_RG: case GL_RG_INTEGER: *components_per_pixel = 2; break; case GL_RGB: case GL_RGB_INTEGER: case GL_SRGB_EXT: // GL_EXT_sRGB *components_per_pixel = 3; break; case GL_RGBA: case GL_RGBA_INTEGER: case GL_BGRA_EXT: // GL_EXT_texture_format_BGRA8888 case GL_SRGB_ALPHA_EXT: // GL_EXT_sRGB *components_per_pixel = 4; break; default: return false; } switch (type) { case GL_BYTE: *bytes_per_component = sizeof(GLbyte); break; case GL_UNSIGNED_BYTE: *bytes_per_component = sizeof(GLubyte); break; case GL_SHORT: *bytes_per_component = sizeof(GLshort); break; case GL_UNSIGNED_SHORT: *bytes_per_component = sizeof(GLushort); break; case GL_UNSIGNED_SHORT_5_6_5: case GL_UNSIGNED_SHORT_4_4_4_4: case GL_UNSIGNED_SHORT_5_5_5_1: *components_per_pixel = 1; *bytes_per_component = sizeof(GLushort); break; case GL_INT: *bytes_per_component = sizeof(GLint); break; case GL_UNSIGNED_INT: *bytes_per_component = sizeof(GLuint); break; case GL_UNSIGNED_INT_24_8_OES: case GL_UNSIGNED_INT_10F_11F_11F_REV: case GL_UNSIGNED_INT_5_9_9_9_REV: case GL_UNSIGNED_INT_2_10_10_10_REV: *components_per_pixel = 1; *bytes_per_component = sizeof(GLuint); break; case GL_FLOAT: // OES_texture_float *bytes_per_component = sizeof(GLfloat); break; case GL_HALF_FLOAT: case GL_HALF_FLOAT_OES: // OES_texture_half_float *bytes_per_component = sizeof(GLushort); break; default: return false; } return true; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread, weak_factory_.GetWeakPtr(), id)); } 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: tbGetBuffer(unsigned size) { char *rtrn; if (size >= BUFFER_SIZE) return NULL; if ((BUFFER_SIZE - tbNext) <= size) tbNext = 0; rtrn = &textBuffer[tbNext]; tbNext += size; return rtrn; } CWE ID: CWE-119 Target: 1 Example 2: Code: show_usage(char *name) { char *s; s = strrchr(name, '/'); s = s ? s+1 : name; printf("picocom v%s\n", VERSION_STR); printf("\nCompiled-in options:\n"); printf(" TTY_Q_SZ is %d\n", TTY_Q_SZ); #ifdef USE_HIGH_BAUD printf(" HIGH_BAUD is enabled\n"); #endif #ifdef USE_FLOCK printf(" USE_FLOCK is enabled\n"); #endif #ifdef UUCP_LOCK_DIR printf(" UUCP_LOCK_DIR is: %s\n", UUCP_LOCK_DIR); #endif #ifdef LINENOISE printf(" LINENOISE is enabled\n"); printf(" SEND_RECEIVE_HISTFILE is: %s\n", SEND_RECEIVE_HISTFILE); #endif printf("\nUsage is: %s [options] <tty device>\n", s); printf("Options are:\n"); printf(" --<b>aud <baudrate>\n"); printf(" --<f>low s (=soft) | h (=hard) | n (=none)\n"); printf(" --<p>arity o (=odd) | e (=even) | n (=none)\n"); printf(" --<d>atabits 5 | 6 | 7 | 8\n"); printf(" --<e>scape <char>\n"); printf(" --e<c>ho\n"); printf(" --no<i>nit\n"); printf(" --no<r>eset\n"); printf(" --no<l>ock\n"); printf(" --<s>end-cmd <command>\n"); printf(" --recei<v>e-cmd <command>\n"); printf(" --imap <map> (input mappings)\n"); printf(" --omap <map> (output mappings)\n"); printf(" --emap <map> (local-echo mappings)\n"); printf(" --<h>elp\n"); printf("<map> is a comma-separated list of one or more of:\n"); printf(" crlf : map CR --> LF\n"); printf(" crcrlf : map CR --> CR + LF\n"); printf(" igncr : ignore CR\n"); printf(" lfcr : map LF --> CR\n"); printf(" lfcrlf : map LF --> CR + LF\n"); printf(" ignlf : ignore LF\n"); printf(" bsdel : map BS --> DEL\n"); printf(" delbs : map DEL --> BS\n"); printf("<?> indicates the equivalent short option.\n"); printf("Short options are prefixed by \"-\" instead of by \"--\".\n"); } CWE ID: CWE-77 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 sd_try_rc16_first(struct scsi_device *sdp) { if (sdp->host->max_cmd_len < 16) return 0; if (sdp->scsi_level > SCSI_SPC_2) return 1; if (scsi_device_protection(sdp)) return 1; return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CheckValueType(const Value::ValueType expected, const Value* const actual) { DCHECK(actual != NULL) << "Expected value to be non-NULL"; DCHECK(expected == actual->GetType()) << "Expected " << print_valuetype(expected) << ", but was " << print_valuetype(actual->GetType()); } CWE ID: CWE-399 Target: 1 Example 2: Code: void DesktopSessionWin::OnSessionAttached(uint32 session_id) { DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK(launcher_.get() == NULL); if (desktop_binary_.empty()) { FilePath dir_path; if (!PathService::Get(base::DIR_EXE, &dir_path)) { LOG(ERROR) << "Failed to get the executable file name."; OnPermanentError(); return; } desktop_binary_ = dir_path.Append(kDesktopBinaryName); } scoped_ptr<WtsSessionProcessDelegate> delegate( new WtsSessionProcessDelegate(main_task_runner_, io_task_runner_, desktop_binary_, session_id, true, kDaemonIpcSecurityDescriptor)); launcher_.reset(new WorkerProcessLauncher( main_task_runner_, delegate.Pass(), this)); } 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 xen_blkbk_unmap_and_respond(struct pending_req *req) { struct gntab_unmap_queue_data* work = &req->gnttab_unmap_data; struct xen_blkif_ring *ring = req->ring; struct grant_page **pages = req->segments; unsigned int invcount; invcount = xen_blkbk_unmap_prepare(ring, pages, req->nr_segs, req->unmap, req->unmap_pages); work->data = req; work->done = xen_blkbk_unmap_and_respond_callback; work->unmap_ops = req->unmap; work->kunmap_ops = NULL; work->pages = req->unmap_pages; work->count = invcount; gnttab_unmap_refs_async(&req->gnttab_unmap_data); } 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: PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } CWE ID: CWE-190 Target: 1 Example 2: Code: void SupervisedUserService::LoadBlacklist(const base::FilePath& path, const GURL& url) { DCHECK(blacklist_state_ == BlacklistLoadState::NOT_LOADED); blacklist_state_ = BlacklistLoadState::LOAD_STARTED; base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&base::PathExists, path), base::BindOnce(&SupervisedUserService::OnBlacklistFileChecked, weak_ptr_factory_.GetWeakPtr(), path, url)); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen) { /* duplicates are ignored */ struct usb_cdc_union_desc *union_header = NULL; /* duplicates are not tolerated */ struct usb_cdc_header_desc *header = NULL; struct usb_cdc_ether_desc *ether = NULL; struct usb_cdc_mdlm_detail_desc *detail = NULL; struct usb_cdc_mdlm_desc *desc = NULL; unsigned int elength; int cnt = 0; memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header)); hdr->phonet_magic_present = false; while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, "skipping garbage byte\n"); elength = 1; goto next_desc; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, "More than one union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; hdr->usb_cdc_country_functional_desc = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: if (elength != sizeof(struct usb_cdc_header_desc)) goto next_desc; if (header) return -EINVAL; header = (struct usb_cdc_header_desc *)buffer; break; case USB_CDC_ACM_TYPE: if (elength < sizeof(struct usb_cdc_acm_descriptor)) goto next_desc; hdr->usb_cdc_acm_descriptor = (struct usb_cdc_acm_descriptor *)buffer; break; case USB_CDC_ETHERNET_TYPE: if (elength != sizeof(struct usb_cdc_ether_desc)) goto next_desc; if (ether) return -EINVAL; ether = (struct usb_cdc_ether_desc *)buffer; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor)) goto next_desc; hdr->usb_cdc_call_mgmt_descriptor = (struct usb_cdc_call_mgmt_descriptor *)buffer; break; case USB_CDC_DMM_TYPE: if (elength < sizeof(struct usb_cdc_dmm_desc)) goto next_desc; hdr->usb_cdc_dmm_desc = (struct usb_cdc_dmm_desc *)buffer; break; case USB_CDC_MDLM_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_desc *)) goto next_desc; if (desc) return -EINVAL; desc = (struct usb_cdc_mdlm_desc *)buffer; break; case USB_CDC_MDLM_DETAIL_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *)) goto next_desc; if (detail) return -EINVAL; detail = (struct usb_cdc_mdlm_detail_desc *)buffer; break; case USB_CDC_NCM_TYPE: if (elength < sizeof(struct usb_cdc_ncm_desc)) goto next_desc; hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer; break; case USB_CDC_MBIM_TYPE: if (elength < sizeof(struct usb_cdc_mbim_desc)) goto next_desc; hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer; break; case USB_CDC_MBIM_EXTENDED_TYPE: if (elength < sizeof(struct usb_cdc_mbim_extended_desc)) break; hdr->usb_cdc_mbim_extended_desc = (struct usb_cdc_mbim_extended_desc *)buffer; break; case CDC_PHONET_MAGIC_NUMBER: hdr->phonet_magic_present = true; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n", buffer[2], elength); goto next_desc; } cnt++; next_desc: buflen -= elength; buffer += elength; } hdr->usb_cdc_union_desc = union_header; hdr->usb_cdc_header_desc = header; hdr->usb_cdc_mdlm_detail_desc = detail; hdr->usb_cdc_mdlm_desc = desc; hdr->usb_cdc_ether_desc = ether; return cnt; } 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: SPL_METHOD(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } CWE ID: CWE-190 Target: 1 Example 2: Code: int arm_dma_get_sgtable(struct device *dev, struct sg_table *sgt, void *cpu_addr, dma_addr_t handle, size_t size, struct dma_attrs *attrs) { struct page *page = pfn_to_page(dma_to_pfn(dev, handle)); int ret; ret = sg_alloc_table(sgt, 1, GFP_KERNEL); if (unlikely(ret)) return ret; sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0); return 0; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __attribute__((no_instrument_function)) trace_swap_gd(void) { volatile void *temp_gd = trace_gd; trace_gd = gd; gd = temp_gd; } CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChunkToLayerMapper::SwitchToChunk(const PaintChunk& chunk) { outset_for_raster_effects_ = chunk.outset_for_raster_effects; const auto& new_chunk_state = chunk.properties.GetPropertyTreeState(); if (new_chunk_state == chunk_state_) return; if (new_chunk_state == layer_state_) { has_filter_that_moves_pixels_ = false; transform_ = TransformationMatrix().Translate(-layer_offset_.x(), -layer_offset_.y()); clip_rect_ = FloatClipRect(); chunk_state_ = new_chunk_state; return; } if (new_chunk_state.Transform() != chunk_state_.Transform()) { transform_ = GeometryMapper::SourceToDestinationProjection( new_chunk_state.Transform(), layer_state_.Transform()); transform_.PostTranslate(-layer_offset_.x(), -layer_offset_.y()); } bool new_has_filter_that_moves_pixels = has_filter_that_moves_pixels_; if (new_chunk_state.Effect() != chunk_state_.Effect()) { new_has_filter_that_moves_pixels = false; for (const auto* effect = new_chunk_state.Effect(); effect && effect != layer_state_.Effect(); effect = effect->Parent()) { if (effect->HasFilterThatMovesPixels()) { new_has_filter_that_moves_pixels = true; break; } } } bool needs_clip_recalculation = new_has_filter_that_moves_pixels != has_filter_that_moves_pixels_ || new_chunk_state.Clip() != chunk_state_.Clip(); if (needs_clip_recalculation) { clip_rect_ = GeometryMapper::LocalToAncestorClipRect(new_chunk_state, layer_state_); if (!clip_rect_.IsInfinite()) clip_rect_.MoveBy(FloatPoint(-layer_offset_.x(), -layer_offset_.y())); } chunk_state_ = new_chunk_state; has_filter_that_moves_pixels_ = new_has_filter_that_moves_pixels; } CWE ID: Target: 1 Example 2: Code: void AppCacheUpdateJob::DeleteSoon() { ClearPendingMasterEntries(); manifest_response_writer_.reset(); storage_->CancelDelegateCallbacks(this); service_->RemoveObserver(this); service_ = nullptr; if (group_) { group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE); group_ = nullptr; } base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool JSTestInterfaceConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticPropertySlot<JSTestInterfaceConstructor, JSDOMWrapper>(exec, &JSTestInterfaceConstructorTable, jsCast<JSTestInterfaceConstructor*>(cell), propertyName, slot); } 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 LoginHtmlDialog::GetDialogSize(gfx::Size* size) const { size->SetSize(width_, height_); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void handle_transaction_done(struct smi_info *smi_info) { struct ipmi_smi_msg *msg; debug_timestamp("Done"); switch (smi_info->si_state) { case SI_NORMAL: if (!smi_info->curr_msg) break; smi_info->curr_msg->rsp_size = smi_info->handlers->get_result( smi_info->si_sm, smi_info->curr_msg->rsp, IPMI_MAX_MSG_LENGTH); /* * Do this here becase deliver_recv_msg() releases the * lock, and a new message can be put in during the * time the lock is released. */ msg = smi_info->curr_msg; smi_info->curr_msg = NULL; deliver_recv_msg(smi_info, msg); break; case SI_GETTING_FLAGS: { unsigned char msg[4]; unsigned int len; /* We got the flags from the SMI, now handle them. */ len = smi_info->handlers->get_result(smi_info->si_sm, msg, 4); if (msg[2] != 0) { /* Error fetching flags, just give up for now. */ smi_info->si_state = SI_NORMAL; } else if (len < 4) { /* * Hmm, no flags. That's technically illegal, but * don't use uninitialized data. */ smi_info->si_state = SI_NORMAL; } else { smi_info->msg_flags = msg[3]; handle_flags(smi_info); } break; } case SI_CLEARING_FLAGS: { unsigned char msg[3]; /* We cleared the flags. */ smi_info->handlers->get_result(smi_info->si_sm, msg, 3); if (msg[2] != 0) { /* Error clearing flags */ dev_warn(smi_info->io.dev, "Error clearing flags: %2.2x\n", msg[2]); } smi_info->si_state = SI_NORMAL; break; } case SI_GETTING_EVENTS: { smi_info->curr_msg->rsp_size = smi_info->handlers->get_result( smi_info->si_sm, smi_info->curr_msg->rsp, IPMI_MAX_MSG_LENGTH); /* * Do this here becase deliver_recv_msg() releases the * lock, and a new message can be put in during the * time the lock is released. */ msg = smi_info->curr_msg; smi_info->curr_msg = NULL; if (msg->rsp[2] != 0) { /* Error getting event, probably done. */ msg->done(msg); /* Take off the event flag. */ smi_info->msg_flags &= ~EVENT_MSG_BUFFER_FULL; handle_flags(smi_info); } else { smi_inc_stat(smi_info, events); /* * Do this before we deliver the message * because delivering the message releases the * lock and something else can mess with the * state. */ handle_flags(smi_info); deliver_recv_msg(smi_info, msg); } break; } case SI_GETTING_MESSAGES: { smi_info->curr_msg->rsp_size = smi_info->handlers->get_result( smi_info->si_sm, smi_info->curr_msg->rsp, IPMI_MAX_MSG_LENGTH); /* * Do this here becase deliver_recv_msg() releases the * lock, and a new message can be put in during the * time the lock is released. */ msg = smi_info->curr_msg; smi_info->curr_msg = NULL; if (msg->rsp[2] != 0) { /* Error getting event, probably done. */ msg->done(msg); /* Take off the msg flag. */ smi_info->msg_flags &= ~RECEIVE_MSG_AVAIL; handle_flags(smi_info); } else { smi_inc_stat(smi_info, incoming_messages); /* * Do this before we deliver the message * because delivering the message releases the * lock and something else can mess with the * state. */ handle_flags(smi_info); deliver_recv_msg(smi_info, msg); } break; } case SI_CHECKING_ENABLES: { unsigned char msg[4]; u8 enables; bool irq_on; /* We got the flags from the SMI, now handle them. */ smi_info->handlers->get_result(smi_info->si_sm, msg, 4); if (msg[2] != 0) { dev_warn(smi_info->io.dev, "Couldn't get irq info: %x.\n", msg[2]); dev_warn(smi_info->io.dev, "Maybe ok, but ipmi might run very slowly.\n"); smi_info->si_state = SI_NORMAL; break; } enables = current_global_enables(smi_info, 0, &irq_on); if (smi_info->io.si_type == SI_BT) /* BT has its own interrupt enable bit. */ check_bt_irq(smi_info, irq_on); if (enables != (msg[3] & GLOBAL_ENABLES_MASK)) { /* Enables are not correct, fix them. */ msg[0] = (IPMI_NETFN_APP_REQUEST << 2); msg[1] = IPMI_SET_BMC_GLOBAL_ENABLES_CMD; msg[2] = enables | (msg[3] & ~GLOBAL_ENABLES_MASK); smi_info->handlers->start_transaction( smi_info->si_sm, msg, 3); smi_info->si_state = SI_SETTING_ENABLES; } else if (smi_info->supports_event_msg_buff) { smi_info->curr_msg = ipmi_alloc_smi_msg(); if (!smi_info->curr_msg) { smi_info->si_state = SI_NORMAL; break; } start_getting_events(smi_info); } else { smi_info->si_state = SI_NORMAL; } break; } case SI_SETTING_ENABLES: { unsigned char msg[4]; smi_info->handlers->get_result(smi_info->si_sm, msg, 4); if (msg[2] != 0) dev_warn(smi_info->io.dev, "Could not set the global enables: 0x%x.\n", msg[2]); if (smi_info->supports_event_msg_buff) { smi_info->curr_msg = ipmi_alloc_smi_msg(); if (!smi_info->curr_msg) { smi_info->si_state = SI_NORMAL; break; } start_getting_events(smi_info); } else { smi_info->si_state = SI_NORMAL; } break; } } } 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: currentbasecolor_cont(i_ctx_t *i_ctx_p) { ref arr, *parr = &arr; es_ptr ep = esp; int i, code = 0, stage, base, cont=1, stack_depth = 0, CIESubst=0; unsigned int depth; PS_colour_space_t *obj; stack_depth = (int)ep[-4].value.intval; base = (int)ep[-3].value.intval; depth = (unsigned int)ep[-2].value.intval; stage = (int)ep[-1].value.intval; /* This shouldn't be possible, all the procedures which call this should * set the depth to at *least* 1. */ if (depth < 1) return_error(gs_error_unknownerror); /* If we get a continuation from a sub-procedure, we will want to come back * here afterward, to do any remaining stages. We need to set up for that now. * so that our continuation is ahead of the sub-proc's continuation. */ check_estack(1); /* The push_op_estack macro increments esp before use, so we don't need to */ push_op_estack(currentbasecolor_cont); while (code == 0 && cont) { ref_assign(&arr, ep); parr = &arr; /* Run along the nested color spaces until we get to the lowest one * that we haven't yet processed (given by 'depth') */ for (i = 0;i < depth;i++) { code = get_space_object(i_ctx_p, parr, &obj); if (code < 0) return code; if (i < (depth - 1)) { if (!obj->alternateproc) { return_error(gs_error_typecheck); } code = obj->alternateproc(i_ctx_p, parr, &parr, &CIESubst); if (code < 0) return code; } } code = obj->basecolorproc(i_ctx_p, parr, base, &stage, &cont, &stack_depth); make_int(&ep[-4], stack_depth); make_int(&ep[-1], stage); if (code > 0) return code; /* Completed that space, increment the 'depth' */ make_int(&ep[-2], ++depth); } if (code <= 0) { /* Remove our next continuation and our data */ esp -= 7; code = o_pop_estack; } return code; } 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: int vrend_create_vertex_elements_state(struct vrend_context *ctx, uint32_t handle, unsigned num_elements, const struct pipe_vertex_element *elements) { struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array); const struct util_format_description *desc; GLenum type; int i; uint32_t ret_handle; if (!v) return ENOMEM; if (num_elements > PIPE_MAX_ATTRIBS) return EINVAL; v->count = num_elements; for (i = 0; i < num_elements; i++) { memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element)); desc = util_format_description(elements[i].src_format); if (!desc) { FREE(v); return EINVAL; } type = GL_FALSE; if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) { if (desc->channel[0].size == 32) type = GL_FLOAT; else if (desc->channel[0].size == 64) type = GL_DOUBLE; else if (desc->channel[0].size == 16) type = GL_HALF_FLOAT; } else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 8) type = GL_UNSIGNED_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 8) type = GL_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 16) type = GL_UNSIGNED_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 16) type = GL_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 32) type = GL_UNSIGNED_INT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 32) type = GL_INT; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM) type = GL_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM) type = GL_UNSIGNED_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) type = GL_UNSIGNED_INT_10F_11F_11F_REV; if (type == GL_FALSE) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format); FREE(v); return EINVAL; } v->elements[i].type = type; if (desc->channel[0].normalized) v->elements[i].norm = GL_TRUE; if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z) v->elements[i].nr_chan = GL_BGRA; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) v->elements[i].nr_chan = 3; else v->elements[i].nr_chan = desc->nr_channels; } if (vrend_state.have_vertex_attrib_binding) { glGenVertexArrays(1, &v->id); glBindVertexArray(v->id); for (i = 0; i < num_elements; i++) { struct vrend_vertex_element *ve = &v->elements[i]; if (util_format_is_pure_integer(ve->base.src_format)) glVertexAttribIFormat(i, ve->nr_chan, ve->type, ve->base.src_offset); else glVertexAttribFormat(i, ve->nr_chan, ve->type, ve->norm, ve->base.src_offset); glVertexAttribBinding(i, ve->base.vertex_buffer_index); glVertexBindingDivisor(i, ve->base.instance_divisor); glEnableVertexAttribArray(i); } } ret_handle = vrend_renderer_object_insert(ctx, v, sizeof(struct vrend_vertex_element), handle, VIRGL_OBJECT_VERTEX_ELEMENTS); if (!ret_handle) { FREE(v); return ENOMEM; } return 0; } CWE ID: CWE-772 Target: 1 Example 2: Code: void RenderFlexibleBox::layoutFlexItems(bool relayoutChildren) { Vector<LineContext> lineContexts; OrderedFlexItemList orderedChildren; LayoutUnit sumFlexBaseSize; double totalFlexGrow; double totalWeightedFlexShrink; LayoutUnit sumHypotheticalMainSize; Vector<LayoutUnit, 16> childSizes; m_orderIterator.first(); LayoutUnit crossAxisOffset = flowAwareBorderBefore() + flowAwarePaddingBefore(); bool hasInfiniteLineLength = false; while (computeNextFlexLine(orderedChildren, sumFlexBaseSize, totalFlexGrow, totalWeightedFlexShrink, sumHypotheticalMainSize, hasInfiniteLineLength, relayoutChildren)) { LayoutUnit containerMainInnerSize = mainAxisContentExtent(sumHypotheticalMainSize); LayoutUnit availableFreeSpace = containerMainInnerSize - sumFlexBaseSize; FlexSign flexSign = (sumHypotheticalMainSize < containerMainInnerSize) ? PositiveFlexibility : NegativeFlexibility; InflexibleFlexItemSize inflexibleItems; childSizes.reserveCapacity(orderedChildren.size()); while (!resolveFlexibleLengths(flexSign, orderedChildren, availableFreeSpace, totalFlexGrow, totalWeightedFlexShrink, inflexibleItems, childSizes, hasInfiniteLineLength)) { ASSERT(totalFlexGrow >= 0 && totalWeightedFlexShrink >= 0); ASSERT(inflexibleItems.size() > 0); } layoutAndPlaceChildren(crossAxisOffset, orderedChildren, childSizes, availableFreeSpace, relayoutChildren, lineContexts, hasInfiniteLineLength); } if (hasLineIfEmpty()) { LayoutUnit minHeight = borderAndPaddingLogicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes) + scrollbarLogicalHeight(); if (height() < minHeight) setLogicalHeight(minHeight); } updateLogicalHeight(); repositionLogicalHeightDependentFlexItems(lineContexts); } 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: file_check_mem(struct magic_set *ms, unsigned int level) { size_t len; if (level >= ms->c.len) { len = (ms->c.len += 20) * sizeof(*ms->c.li); ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ? malloc(len) : realloc(ms->c.li, len)); if (ms->c.li == NULL) { file_oomem(ms, len); return -1; } } ms->c.li[level].got_match = 0; #ifdef ENABLE_CONDITIONALS ms->c.li[level].last_match = 0; ms->c.li[level].last_cond = COND_NONE; #endif /* ENABLE_CONDITIONALS */ 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: long long Segment::CreateInstance(IMkvReader* pReader, long long pos, Segment*& pSegment) { assert(pReader); assert(pos >= 0); pSegment = NULL; long long total, available; const long status = pReader->Length(&total, &available); if (status < 0) // error return status; if (available < 0) return -1; if ((total >= 0) && (available > total)) return -1; for (;;) { if ((total >= 0) && (pos >= total)) return E_FILE_FORMAT_INVALID; long len; long long result = GetUIntLength(pReader, pos, len); if (result) // error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return id; pos += len; // consume ID result = GetUIntLength(pReader, pos, len); if (result) // error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return size; pos += len; // consume length of size of element const long long unknown_size = (1LL << (7 * len)) - 1; if (id == 0x08538067) { // Segment ID if (size == unknown_size) size = -1; else if (total < 0) size = -1; else if ((pos + size) > total) size = -1; pSegment = new (std::nothrow) Segment(pReader, idpos, pos, size); if (pSegment == 0) return -1; // generic error return 0; // success } if (size == unknown_size) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + size) > total)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; pos += size; // consume payload } } CWE ID: CWE-20 Target: 1 Example 2: Code: void LoadingPredictorTest::TearDown() { predictor_->Shutdown(); } 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 void perf_remove_from_owner(struct perf_event *event) { struct task_struct *owner; rcu_read_lock(); owner = ACCESS_ONCE(event->owner); /* * Matches the smp_wmb() in perf_event_exit_task(). If we observe * !owner it means the list deletion is complete and we can indeed * free this event, otherwise we need to serialize on * owner->perf_event_mutex. */ smp_read_barrier_depends(); if (owner) { /* * Since delayed_put_task_struct() also drops the last * task reference we can safely take a new reference * while holding the rcu_read_lock(). */ get_task_struct(owner); } rcu_read_unlock(); if (owner) { mutex_lock(&owner->perf_event_mutex); /* * We have to re-check the event->owner field, if it is cleared * we raced with perf_event_exit_task(), acquiring the mutex * ensured they're done, and we can proceed with freeing the * event. */ if (event->owner) list_del_init(&event->owner_entry); mutex_unlock(&owner->perf_event_mutex); put_task_struct(owner); } } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PlatformSensor::UpdateSharedBuffer(const SensorReading& reading) { ReadingBuffer* buffer = static_cast<ReadingBuffer*>(shared_buffer_mapping_.get()); auto& seqlock = buffer->seqlock.value(); seqlock.WriteBegin(); buffer->reading = reading; seqlock.WriteEnd(); } CWE ID: CWE-732 Target: 1 Example 2: Code: cib_process_request(xmlNode * request, gboolean force_synchronous, gboolean privileged, gboolean from_peer, cib_client_t * cib_client) { int call_type = 0; int call_options = 0; gboolean process = TRUE; gboolean is_update = TRUE; gboolean needs_reply = TRUE; gboolean local_notify = FALSE; gboolean needs_forward = FALSE; gboolean global_update = crm_is_true(crm_element_value(request, F_CIB_GLOBAL_UPDATE)); xmlNode *op_reply = NULL; xmlNode *result_diff = NULL; int rc = pcmk_ok; const char *op = crm_element_value(request, F_CIB_OPERATION); const char *originator = crm_element_value(request, F_ORIG); const char *host = crm_element_value(request, F_CIB_HOST); const char *client_id = crm_element_value(request, F_CIB_CLIENTID); crm_trace("%s Processing msg %s", cib_our_uname, crm_element_value(request, F_SEQ)); cib_num_ops++; if (cib_num_ops == 0) { cib_num_fail = 0; cib_num_local = 0; cib_num_updates = 0; crm_info("Stats wrapped around"); } if (host != NULL && strlen(host) == 0) { host = NULL; } crm_element_value_int(request, F_CIB_CALLOPTS, &call_options); if (force_synchronous) { call_options |= cib_sync_call; } crm_trace("Processing %s message (%s) for %s...", from_peer ? "peer" : "local", from_peer ? originator : cib_our_uname, host ? host : "master"); rc = cib_get_operation_id(op, &call_type); if (rc != pcmk_ok) { /* TODO: construct error reply? */ crm_err("Pre-processing of command failed: %s", pcmk_strerror(rc)); return; } is_update = cib_op_modifies(call_type); if (is_update) { cib_num_updates++; } if (from_peer == FALSE) { parse_local_options(cib_client, call_type, call_options, host, op, &local_notify, &needs_reply, &process, &needs_forward); } else if (parse_peer_options(call_type, request, &local_notify, &needs_reply, &process, &needs_forward) == FALSE) { return; } crm_trace("Finished determining processing actions"); if (call_options & cib_discard_reply) { needs_reply = is_update; local_notify = FALSE; } if (needs_forward) { forward_request(request, cib_client, call_options); return; } if (cib_status != pcmk_ok) { rc = cib_status; crm_err("Operation ignored, cluster configuration is invalid." " Please repair and restart: %s", pcmk_strerror(cib_status)); op_reply = cib_construct_reply(request, the_cib, cib_status); } else if (process) { int level = LOG_INFO; const char *section = crm_element_value(request, F_CIB_SECTION); cib_num_local++; rc = cib_process_command(request, &op_reply, &result_diff, privileged); if (global_update) { switch (rc) { case pcmk_ok: case -pcmk_err_old_data: case -pcmk_err_diff_resync: case -pcmk_err_diff_failed: level = LOG_DEBUG_2; break; default: level = LOG_ERR; } } else if (safe_str_eq(op, CIB_OP_QUERY)) { level = LOG_DEBUG_2; } else if (rc != pcmk_ok) { cib_num_fail++; level = LOG_WARNING; } else if (safe_str_eq(op, CIB_OP_SLAVE)) { level = LOG_DEBUG_2; } else if (safe_str_eq(section, XML_CIB_TAG_STATUS)) { level = LOG_DEBUG_2; } do_crm_log_unlikely(level, "Operation complete: op %s for section %s (origin=%s/%s/%s, version=%s.%s.%s): %s (rc=%d)", op, section ? section : "'all'", originator ? originator : "local", crm_element_value(request, F_CIB_CLIENTNAME), crm_element_value(request, F_CIB_CALLID), the_cib ? crm_element_value(the_cib, XML_ATTR_GENERATION_ADMIN) : "0", the_cib ? crm_element_value(the_cib, XML_ATTR_GENERATION) : "0", the_cib ? crm_element_value(the_cib, XML_ATTR_NUMUPDATES) : "0", pcmk_strerror(rc), rc); if (op_reply == NULL && (needs_reply || local_notify)) { crm_err("Unexpected NULL reply to message"); crm_log_xml_err(request, "null reply"); needs_reply = FALSE; local_notify = FALSE; } } crm_trace("processing response cases %.16x %.16x", call_options, cib_sync_call); /* from now on we are the server */ if (needs_reply == FALSE || stand_alone) { /* nothing more to do... * this was a non-originating slave update */ crm_trace("Completed slave update"); } else if (rc == pcmk_ok && result_diff != NULL && !(call_options & cib_inhibit_bcast)) { gboolean broadcast = FALSE; cib_local_bcast_num++; crm_xml_add_int(request, F_CIB_LOCAL_NOTIFY_ID, cib_local_bcast_num); broadcast = send_peer_reply(request, result_diff, originator, TRUE); if (broadcast && client_id && local_notify && op_reply) { /* If we have been asked to sync the reply, * and a bcast msg has gone out, we queue the local notify * until we know the bcast message has been received */ local_notify = FALSE; queue_local_notify(op_reply, client_id, (call_options & cib_sync_call), from_peer); op_reply = NULL; /* the reply is queued, so don't free here */ } } else if (call_options & cib_discard_reply) { crm_trace("Caller isn't interested in reply"); } else if (from_peer) { if (is_update == FALSE || result_diff == NULL) { crm_trace("Request not broadcast: R/O call"); } else if (call_options & cib_inhibit_bcast) { crm_trace("Request not broadcast: inhibited"); } else if (rc != pcmk_ok) { crm_trace("Request not broadcast: call failed: %s", pcmk_strerror(rc)); } else { crm_trace("Directing reply to %s", originator); } send_peer_reply(op_reply, result_diff, originator, FALSE); } if (local_notify && client_id) { if (process == FALSE) { do_local_notify(request, client_id, call_options & cib_sync_call, from_peer); } else { do_local_notify(op_reply, client_id, call_options & cib_sync_call, from_peer); } } free_xml(op_reply); free_xml(result_diff); return; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Clipboard::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { string16 url = UTF8ToUTF16(std::string(url_data, url_len) + "\n"); string16 title = UTF8ToUTF16(std::string(title_data, title_len)); int data_len = 2 * (title.length() + url.length()); char* data = new char[data_len]; memcpy(data, url.data(), 2 * url.length()); memcpy(data + 2 * url.length(), title.data(), 2 * title.length()); InsertMapping(kMimeTypeMozillaURL, data, data_len); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t len; uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) { return; } } n = r->iov.iov_len / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_req_complete(&r->req, GOOD); } else { len = r->sector_count * 512; if (len > SCSI_DMA_BUF_SIZE) { len = SCSI_DMA_BUF_SIZE; } r->iov.iov_len = len; DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, len); scsi_req_data(&r->req, len); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static bool ExecuteJustifyLeft(LocalFrame& frame, Event*, EditorCommandSource source, const String&) { return ExecuteApplyParagraphStyle(frame, source, InputEvent::InputType::kFormatJustifyLeft, CSSPropertyTextAlign, "left"); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void cirrus_write_hidden_dac(CirrusVGAState * s, int reg_value) { if (s->cirrus_hidden_dac_lockindex == 4) { s->cirrus_hidden_dac_data = reg_value; #if defined(DEBUG_CIRRUS) printf("cirrus: outport hidden DAC, value %02x\n", reg_value); #endif } s->cirrus_hidden_dac_lockindex = 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: MockRenderThread::MockRenderThread() : routing_id_(0), surface_id_(0), opener_id_(0) { } CWE ID: CWE-264 Target: 1 Example 2: Code: static netdev_features_t tg3_fix_features(struct net_device *dev, netdev_features_t features) { struct tg3 *tp = netdev_priv(dev); if (dev->mtu > ETH_DATA_LEN && tg3_flag(tp, 5780_CLASS)) features &= ~NETIF_F_ALL_TSO; return features; } 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 WebGLRenderingContextBase::deleteProgram(WebGLProgram* program) { DeleteObject(program); } 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: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭ] > t;" "[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;" "[єҽҿၔ] > e; ґ > r; ғ > f; [ҫင] > c;" "ұ > y; [χҳӽӿ] > x;" #if defined(OS_WIN) "ӏ > i;" #else "ӏ > l;" #endif "ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } CWE ID: Target: 1 Example 2: Code: void PaintController::GenerateRasterInvalidationsComparingChunks( PaintChunk& new_chunk, const PaintChunk& old_chunk) { DCHECK(RuntimeEnabledFeatures::SlimmingPaintV175Enabled()); struct OldAndNewDisplayItems { const DisplayItem* old_item = nullptr; const DisplayItem* new_item = nullptr; }; HashMap<const DisplayItemClient*, OldAndNewDisplayItems> clients_to_invalidate; size_t highest_moved_to_index = 0; for (size_t old_index = old_chunk.begin_index; old_index < old_chunk.end_index; ++old_index) { const DisplayItem& old_item = current_paint_artifact_.GetDisplayItemList()[old_index]; const DisplayItemClient* client_to_invalidate_old_visual_rect = nullptr; if (old_item.IsTombstone()) { size_t moved_to_index = items_moved_into_new_list_[old_index]; if (new_display_item_list_[moved_to_index].DrawsContent()) { if (moved_to_index < new_chunk.begin_index || moved_to_index >= new_chunk.end_index) { const auto& new_item = new_display_item_list_[moved_to_index]; PaintChunk& moved_to_chunk = new_paint_chunks_.FindChunkByDisplayItemIndex(moved_to_index); AddRasterInvalidation(new_item.Client(), moved_to_chunk, new_item.VisualRect(), PaintInvalidationReason::kAppeared); client_to_invalidate_old_visual_rect = &new_item.Client(); } else if (moved_to_index < highest_moved_to_index) { client_to_invalidate_old_visual_rect = &new_display_item_list_[moved_to_index].Client(); } else { highest_moved_to_index = moved_to_index; } } } else if (old_item.DrawsContent()) { client_to_invalidate_old_visual_rect = &old_item.Client(); } if (client_to_invalidate_old_visual_rect) { clients_to_invalidate .insert(client_to_invalidate_old_visual_rect, OldAndNewDisplayItems()) .stored_value->value.old_item = &old_item; } } for (size_t new_index = new_chunk.begin_index; new_index < new_chunk.end_index; ++new_index) { const DisplayItem& new_item = new_display_item_list_[new_index]; if (new_item.DrawsContent() && !ClientCacheIsValid(new_item.Client())) { clients_to_invalidate.insert(&new_item.Client(), OldAndNewDisplayItems()) .stored_value->value.new_item = &new_item; } } for (const auto& item : clients_to_invalidate) { GenerateRasterInvalidation(*item.key, new_chunk, item.value.old_item, item.value.new_item); } } 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 RenderProcessHostImpl::RemoveRoute(int32_t routing_id) { DCHECK(listeners_.Lookup(routing_id) != nullptr); listeners_.Remove(routing_id); Cleanup(); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void TreeNodesAdded(TreeModel* model, TreeModelNode* parent, int start, int count) { added_count_++; } CWE ID: CWE-119 Target: 1 Example 2: Code: static bool isMainDisplay(int32_t displayId) { return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE; } 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 xfer_initialsync(struct xfer_header *xfer) { unsigned flags = SYNC_FLAG_LOGGING | SYNC_FLAG_LOCALONLY; int r; if (xfer->userid) { struct xfer_item *item, *next; syslog(LOG_INFO, "XFER: initial sync of user %s", xfer->userid); r = sync_do_user(xfer->userid, xfer->topart, xfer->be, /*channelp*/NULL, flags); if (r) return r; /* User moves may take a while, do another non-blocking sync */ syslog(LOG_INFO, "XFER: second sync of user %s", xfer->userid); r = sync_do_user(xfer->userid, xfer->topart, xfer->be, /*channelp*/NULL, flags); if (r) return r; /* User may have renamed/deleted a mailbox while syncing, recreate the submailboxes list */ for (item = xfer->items; item; item = next) { next = item->next; mboxlist_entry_free(&item->mbentry); free(item); } xfer->items = NULL; r = mboxlist_usermboxtree(xfer->userid, xfer_addusermbox, xfer, MBOXTREE_DELETED); } else { struct sync_name_list *mboxname_list = sync_name_list_create(); syslog(LOG_INFO, "XFER: initial sync of mailbox %s", xfer->items->mbentry->name); sync_name_list_add(mboxname_list, xfer->items->mbentry->name); r = sync_do_mailboxes(mboxname_list, xfer->topart, xfer->be, /*channelp*/NULL, flags); sync_name_list_free(&mboxname_list); } return r; } 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 dn_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; switch (sock->type) { case SOCK_SEQPACKET: if (protocol != DNPROTO_NSP) return -EPROTONOSUPPORT; break; case SOCK_STREAM: break; default: return -ESOCKTNOSUPPORT; } if ((sk = dn_alloc_sock(net, sock, GFP_KERNEL, kern)) == NULL) return -ENOBUFS; sk->sk_protocol = protocol; return 0; } CWE ID: Target: 1 Example 2: Code: static void bmpmask16toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image, OPJ_UINT32 redMask, OPJ_UINT32 greenMask, OPJ_UINT32 blueMask, OPJ_UINT32 alphaMask) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; OPJ_BOOL hasAlpha; OPJ_UINT32 redShift, redPrec; OPJ_UINT32 greenShift, greenPrec; OPJ_UINT32 blueShift, bluePrec; OPJ_UINT32 alphaShift, alphaPrec; width = image->comps[0].w; height = image->comps[0].h; hasAlpha = image->numcomps > 3U; bmp_mask_get_shift_and_prec(redMask, &redShift, &redPrec); bmp_mask_get_shift_and_prec(greenMask, &greenShift, &greenPrec); bmp_mask_get_shift_and_prec(blueMask, &blueShift, &bluePrec); bmp_mask_get_shift_and_prec(alphaMask, &alphaShift, &alphaPrec); image->comps[0].bpp = redPrec; image->comps[0].prec = redPrec; image->comps[1].bpp = greenPrec; image->comps[1].prec = greenPrec; image->comps[2].bpp = bluePrec; image->comps[2].prec = bluePrec; if (hasAlpha) { image->comps[3].bpp = alphaPrec; image->comps[3].prec = alphaPrec; } index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { OPJ_UINT32 value = 0U; value |= ((OPJ_UINT32)pSrc[2*x+0]) << 0; value |= ((OPJ_UINT32)pSrc[2*x+1]) << 8; image->comps[0].data[index] = (OPJ_INT32)((value & redMask) >> redShift); /* R */ image->comps[1].data[index] = (OPJ_INT32)((value & greenMask) >> greenShift); /* G */ image->comps[2].data[index] = (OPJ_INT32)((value & blueMask) >> blueShift); /* B */ if (hasAlpha) { image->comps[3].data[index] = (OPJ_INT32)((value & alphaMask) >> alphaShift); /* A */ } index++; } pSrc -= stride; } } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __init perf_event_init_all_cpus(void) { struct swevent_htable *swhash; int cpu; for_each_possible_cpu(cpu) { swhash = &per_cpu(swevent_htable, cpu); mutex_init(&swhash->hlist_mutex); INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu)); INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu)); raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu)); #ifdef CONFIG_CGROUP_PERF INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu)); #endif INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu)); } } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: htmlParseNameComplex(xmlParserCtxtPtr ctxt) { int len = 0, l; int c; int count = 0; const xmlChar *base = ctxt->input->base; /* * Handler for more complex cases */ GROW; c = CUR_CHAR(l); if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!IS_LETTER(c) && (c != '_') && (c != ':'))) { return(NULL); } while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */ ((IS_LETTER(c)) || (IS_DIGIT(c)) || (c == '.') || (c == '-') || (c == '_') || (c == ':') || (IS_COMBINING(c)) || (IS_EXTENDER(c)))) { if (count++ > 100) { count = 0; GROW; } len += l; NEXTL(l); c = CUR_CHAR(l); if (ctxt->input->base != base) { /* * We changed encoding from an unknown encoding * Input buffer changed location, so we better start again */ return(htmlParseNameComplex(ctxt)); } } if (ctxt->input->base > ctxt->input->cur - len) return(NULL); return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len)); } CWE ID: CWE-787 Target: 1 Example 2: Code: static inline void mnt_inc_writers(struct mount *mnt) { #ifdef CONFIG_SMP this_cpu_inc(mnt->mnt_pcp->mnt_writers); #else mnt->mnt_writers++; #endif } 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: int seticc(i_ctx_t * i_ctx_p, int ncomps, ref *ICCdict, float *range_buff) { int code, k; gs_color_space * pcs; ref * pstrmval; stream * s = 0L; cmm_profile_t *picc_profile = NULL; int i, expected = 0; ref * pnameval; static const char *const icc_std_profile_names[] = { GSICC_STANDARD_PROFILES }; static const char *const icc_std_profile_keys[] = { GSICC_STANDARD_PROFILES_KEYS }; /* verify the DataSource entry */ if (dict_find_string(ICCdict, "DataSource", &pstrmval) <= 0) return_error(gs_error_undefined); check_read_file(i_ctx_p, s, pstrmval); /* build the color space object */ code = gs_cspace_build_ICC(&pcs, NULL, gs_gstate_memory(igs)); if (code < 0) return gs_rethrow(code, "building color space object"); /* For now, dump the profile into a buffer and obtain handle from the buffer when we need it. We may want to change this later. This depends to some degree on what the CMS is capable of doing. I don't want to get bogged down on stream I/O at this point. Note also, if we are going to be putting these into the clist we will want to have this buffer. */ /* Check if we have the /Name entry. This is used to associate with specs that have enumerated types to indicate sRGB sGray etc */ if (dict_find_string(ICCdict, "Name", &pnameval) > 0){ uint size = r_size(pnameval); char *str = (char *)gs_alloc_bytes(gs_gstate_memory(igs), size+1, "seticc"); memcpy(str, (const char *)pnameval->value.bytes, size); str[size] = 0; /* Compare this to the standard profile names */ for (k = 0; k < GSICC_NUMBER_STANDARD_PROFILES; k++) { if ( strcmp( str, icc_std_profile_keys[k] ) == 0 ) { picc_profile = gsicc_get_profile_handle_file(icc_std_profile_names[k], strlen(icc_std_profile_names[k]), gs_gstate_memory(igs)); break; } } gs_free_object(gs_gstate_memory(igs), str, "seticc"); } else { picc_profile = gsicc_profile_new(s, gs_gstate_memory(igs), NULL, 0); if (picc_profile == NULL) return gs_throw(gs_error_VMerror, "Creation of ICC profile failed"); /* We have to get the profile handle due to the fact that we need to know if it has a data space that is CIELAB */ picc_profile->profile_handle = gsicc_get_profile_handle_buffer(picc_profile->buffer, picc_profile->buffer_size, gs_gstate_memory(igs)); } if (picc_profile == NULL || picc_profile->profile_handle == NULL) { /* Free up everything, the profile is not valid. We will end up going ahead and using a default based upon the number of components */ rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return -1; } code = gsicc_set_gscs_profile(pcs, picc_profile, gs_gstate_memory(igs)); if (code < 0) { rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return code; } picc_profile->num_comps = ncomps; picc_profile->data_cs = gscms_get_profile_data_space(picc_profile->profile_handle, picc_profile->memory); switch (picc_profile->data_cs) { case gsCIEXYZ: case gsCIELAB: case gsRGB: expected = 3; break; case gsGRAY: expected = 1; break; case gsCMYK: expected = 4; break; case gsNCHANNEL: case gsNAMED: /* Silence warnings */ case gsUNDEFINED: /* Silence warnings */ break; } if (!expected || ncomps != expected) { rc_decrement(picc_profile,"seticc"); rc_decrement(pcs,"seticc"); return_error(gs_error_rangecheck); } /* Lets go ahead and get the hash code and check if we match one of the default spaces */ /* Later we may want to delay this, but for now lets go ahead and do it */ gsicc_init_hash_cs(picc_profile, igs); /* Set the range according to the data type that is associated with the ICC input color type. Occasionally, we will run into CIELAB to CIELAB profiles for spot colors in PDF documents. These spot colors are typically described as separation colors with tint transforms that go from a tint value to a linear mapping between the CIELAB white point and the CIELAB tint color. This results in a CIELAB value that we need to use to fill. We need to detect this to make sure we do the proper scaling of the data. For CIELAB images in PDF, the source is always normal 8 or 16 bit encoded data in the range from 0 to 255 or 0 to 65535. In that case, there should not be any encoding and decoding to CIELAB. The PDF content will not include an ICC profile but will set the color space to \Lab. In this case, we use our seticc_lab operation to install the LAB to LAB profile, but we detect that we did that through the use of the is_lab flag in the profile descriptor. When then avoid the CIELAB encode and decode */ if (picc_profile->data_cs == gsCIELAB) { /* If the input space to this profile is CIELAB, then we need to adjust the limits */ /* See ICC spec ICC.1:2004-10 Section 6.3.4.2 and 6.4. I don't believe we need to worry about CIEXYZ profiles or any of the other odds ones. Need to check that though at some point. */ picc_profile->Range.ranges[0].rmin = 0.0; picc_profile->Range.ranges[0].rmax = 100.0; picc_profile->Range.ranges[1].rmin = -128.0; picc_profile->Range.ranges[1].rmax = 127.0; picc_profile->Range.ranges[2].rmin = -128.0; picc_profile->Range.ranges[2].rmax = 127.0; picc_profile->islab = true; } else { for (i = 0; i < ncomps; i++) { picc_profile->Range.ranges[i].rmin = range_buff[2 * i]; picc_profile->Range.ranges[i].rmax = range_buff[2 * i + 1]; } } /* Now see if we are in an overide situation. We have to wait until now in case this is an LAB profile which we will not overide */ if (gs_currentoverrideicc(igs) && picc_profile->data_cs != gsCIELAB) { /* Free up the profile structure */ switch( picc_profile->data_cs ) { case gsRGB: pcs->cmm_icc_profile_data = igs->icc_manager->default_rgb; break; case gsGRAY: pcs->cmm_icc_profile_data = igs->icc_manager->default_gray; break; case gsCMYK: pcs->cmm_icc_profile_data = igs->icc_manager->default_cmyk; break; default: break; } /* Have one increment from the color space. Having these tied together is not really correct. Need to fix that. ToDo. MJV */ rc_adjust(picc_profile, -2, "seticc"); rc_increment(pcs->cmm_icc_profile_data); } /* Set the color space. We are done. No joint cache here... */ code = gs_setcolorspace(igs, pcs); /* The context has taken a reference to the colorspace. We no longer need * ours, so drop it. */ rc_decrement_only(pcs, "seticc"); /* In this case, we already have a ref count of 2 on the icc profile one for when it was created and one for when it was set. We really only want one here so adjust */ rc_decrement(picc_profile,"seticc"); /* Remove the ICC dict from the stack */ pop(1); return code; } 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: static void nlmclnt_unlock_callback(struct rpc_task *task, void *data) { struct nlm_rqst *req = data; u32 status = ntohl(req->a_res.status); if (RPC_ASSASSINATED(task)) goto die; if (task->tk_status < 0) { dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status); goto retry_rebind; } if (status == NLM_LCK_DENIED_GRACE_PERIOD) { rpc_delay(task, NLMCLNT_GRACE_WAIT); goto retry_unlock; } if (status != NLM_LCK_GRANTED) printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status); die: return; retry_rebind: nlm_rebind_host(req->a_host); retry_unlock: rpc_restart_call(task); } CWE ID: CWE-399 Target: 1 Example 2: Code: void ClassicPendingScript::Prefinalize() { CancelStreaming(); prefinalizer_called_ = true; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ShadowRoot* Element::ensureUserAgentShadowRoot() { if (ShadowRoot* shadowRoot = userAgentShadowRoot()) return shadowRoot; ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot); didAddUserAgentShadowRoot(shadowRoot); return shadowRoot; } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int filter_frame(AVFilterLink *inlink, AVFrame *frame) { AVFilterContext *ctx = inlink->dst; FieldOrderContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; int h, plane, line_step, line_size, line; uint8_t *data; if (!frame->interlaced_frame || frame->top_field_first == s->dst_tff) return ff_filter_frame(outlink, frame); av_dlog(ctx, "picture will move %s one line\n", s->dst_tff ? "up" : "down"); h = frame->height; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { line_step = frame->linesize[plane]; line_size = s->line_size[plane]; data = frame->data[plane]; if (s->dst_tff) { /** Move every line up one line, working from * the top to the bottom of the frame. * The original top line is lost. * The new last line is created as a copy of the * penultimate line from that field. */ for (line = 0; line < h; line++) { if (1 + line < frame->height) { memcpy(data, data + line_step, line_size); } else { memcpy(data, data - line_step - line_step, line_size); } data += line_step; } } else { /** Move every line down one line, working from * the bottom to the top of the frame. * The original bottom line is lost. * The new first line is created as a copy of the * second line from that field. */ data += (h - 1) * line_step; for (line = h - 1; line >= 0 ; line--) { if (line > 0) { memcpy(data, data - line_step, line_size); } else { memcpy(data, data + line_step + line_step, line_size); } data -= line_step; } } } frame->top_field_first = s->dst_tff; return ff_filter_frame(outlink, frame); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void remove_trailing_rmap_items(struct mm_slot *mm_slot, struct rmap_item **rmap_list) { while (*rmap_list) { struct rmap_item *rmap_item = *rmap_list; *rmap_list = rmap_item->rmap_list; remove_rmap_item_from_tree(rmap_item); free_rmap_item(rmap_item); } } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Document::SetReadyState(DocumentReadyState ready_state) { if (ready_state == ready_state_) return; switch (ready_state) { case kLoading: if (document_timing_.DomLoading().is_null()) { document_timing_.MarkDomLoading(); } break; case kInteractive: if (document_timing_.DomInteractive().is_null()) document_timing_.MarkDomInteractive(); break; case kComplete: if (document_timing_.DomComplete().is_null()) document_timing_.MarkDomComplete(); break; } ready_state_ = ready_state; DispatchEvent(*Event::Create(event_type_names::kReadystatechange)); } 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: jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend) { jas_matrix_t *matrix; assert(xstart <= xend && ystart <= yend); if (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) { return 0; } matrix->xstart_ = xstart; matrix->ystart_ = ystart; matrix->xend_ = xend; matrix->yend_ = yend; return matrix; } CWE ID: CWE-190 Target: 1 Example 2: Code: static bool name_is_device_color( char *cs_name ) { return( strcmp(cs_name, "DeviceGray") == 0 || strcmp(cs_name, "DeviceRGB") == 0 || strcmp(cs_name, "DeviceCMYK") == 0); } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int sha1_ssse3_init(struct shash_desc *desc) { struct sha1_state *sctx = shash_desc_ctx(desc); *sctx = (struct sha1_state){ .state = { SHA1_H0, SHA1_H1, SHA1_H2, SHA1_H3, SHA1_H4 }, }; return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; int item_num = avio_rb32(pb); int item_len = avio_rb32(pb); if (item_len != 18) { avpriv_request_sample(pb, "Primer pack item length %d", item_len); return AVERROR_PATCHWELCOME; } if (item_num > 65536) { av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num); return AVERROR_INVALIDDATA; } if (mxf->local_tags) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n"); av_free(mxf->local_tags); mxf->local_tags_count = 0; mxf->local_tags = av_calloc(item_num, item_len); if (!mxf->local_tags) return AVERROR(ENOMEM); mxf->local_tags_count = item_num; avio_read(pb, mxf->local_tags, item_num*item_len); return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options) { return(xmlCtxtUseOptionsInternal(ctxt, options, NULL)); } 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: void V8TestObject::RaisesExceptionVoidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_raisesExceptionVoidMethod"); test_object_v8_internal::RaisesExceptionVoidMethodMethod(info); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int nr_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; size_t copied; struct sk_buff *skb; int er; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ lock_sock(sk); if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) { release_sock(sk); return er; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (er < 0) { skb_free_datagram(sk, skb); release_sock(sk); return er; } if (sax != NULL) { memset(sax, 0, sizeof(sax)); sax->sax25_family = AF_NETROM; skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call, AX25_ADDR_LEN); } msg->msg_namelen = sizeof(*sax); skb_free_datagram(sk, skb); release_sock(sk); return copied; } CWE ID: CWE-200 Target: 1 Example 2: Code: bson_iter_document (const bson_iter_t *iter, /* IN */ uint32_t *document_len, /* OUT */ const uint8_t **document) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (document_len); BSON_ASSERT (document); *document = NULL; *document_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { memcpy (document_len, (iter->raw + iter->d1), sizeof (*document_len)); *document_len = BSON_UINT32_FROM_LE (*document_len); *document = (iter->raw + iter->d1); } } 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: SProcScreenSaverQueryInfo(ClientPtr client) { REQUEST(xScreenSaverQueryInfoReq); swaps(&stuff->length); REQUEST_SIZE_MATCH(xScreenSaverQueryInfoReq); swapl(&stuff->drawable); return ProcScreenSaverQueryInfo(client); } 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: OMX_ERRORTYPE SoftOpus::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch ((int)index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.opus", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAndroidOpus: { const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams = (const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params; if (opusParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline unsigned int next_commit_index(unsigned int idx) { static const unsigned int MIN_COMMITS = 100; static const unsigned int MAX_COMMITS = 5000; static const unsigned int MUST_REGION = 100; static const unsigned int MIN_REGION = 20000; unsigned int offset, next; if (idx <= MUST_REGION) return 0; if (idx <= MIN_REGION) { offset = idx - MUST_REGION; return (offset < MIN_COMMITS) ? offset : MIN_COMMITS; } offset = idx - MIN_REGION; next = (offset < MAX_COMMITS) ? offset : MAX_COMMITS; return (next > MIN_COMMITS) ? next : MIN_COMMITS; } 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 ChromeContentBrowserClientExtensionsPart::ShouldAllowOpenURL( content::SiteInstance* site_instance, const GURL& to_url, bool* result) { DCHECK(result); url::Origin to_origin(to_url); if (to_origin.scheme() != kExtensionScheme) { return false; } ExtensionRegistry* registry = ExtensionRegistry::Get(site_instance->GetBrowserContext()); const Extension* to_extension = registry->enabled_extensions().GetByID(to_origin.host()); if (!to_extension) { *result = true; return true; } GURL site_url(site_instance->GetSiteURL()); const Extension* from_extension = registry->enabled_extensions().GetExtensionOrAppByURL(site_url); if (from_extension && from_extension == to_extension) { *result = true; return true; } if (to_url.SchemeIsFileSystem() || to_url.SchemeIsBlob()) { if (to_url.SchemeIsFileSystem()) RecordShouldAllowOpenURLFailure(FAILURE_FILE_SYSTEM_URL, site_url); else RecordShouldAllowOpenURLFailure(FAILURE_BLOB_URL, site_url); char site_url_copy[256]; base::strlcpy(site_url_copy, site_url.spec().c_str(), arraysize(site_url_copy)); base::debug::Alias(&site_url_copy); char to_origin_copy[256]; base::strlcpy(to_origin_copy, to_origin.Serialize().c_str(), arraysize(to_origin_copy)); base::debug::Alias(&to_origin_copy); base::debug::DumpWithoutCrashing(); *result = false; return true; } if (site_url.SchemeIs(content::kChromeUIScheme) || site_url.SchemeIs(content::kChromeDevToolsScheme) || site_url.SchemeIs(chrome::kChromeSearchScheme)) { *result = true; return true; } if (site_url.SchemeIs(content::kGuestScheme)) { *result = true; return true; } if (WebAccessibleResourcesInfo::IsResourceWebAccessible(to_extension, to_url.path())) { *result = true; return true; } if (!site_url.SchemeIsHTTPOrHTTPS() && !site_url.SchemeIs(kExtensionScheme)) { RecordShouldAllowOpenURLFailure( FAILURE_SCHEME_NOT_HTTP_OR_HTTPS_OR_EXTENSION, site_url); } else { RecordShouldAllowOpenURLFailure(FAILURE_RESOURCE_NOT_WEB_ACCESSIBLE, site_url); } *result = false; return true; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int filter_frame(AVFilterLink *inlink, AVFrame *buf) { AVFilterContext *ctx = inlink->dst; FPSContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; int64_t delta; int i, ret; s->frames_in++; /* discard frames until we get the first timestamp */ if (s->pts == AV_NOPTS_VALUE) { if (buf->pts != AV_NOPTS_VALUE) { ret = write_to_fifo(s->fifo, buf); if (ret < 0) return ret; if (s->start_time != DBL_MAX && s->start_time != AV_NOPTS_VALUE) { double first_pts = s->start_time * AV_TIME_BASE; first_pts = FFMIN(FFMAX(first_pts, INT64_MIN), INT64_MAX); s->first_pts = s->pts = av_rescale_q(first_pts, AV_TIME_BASE_Q, inlink->time_base); av_log(ctx, AV_LOG_VERBOSE, "Set first pts to (in:%"PRId64" out:%"PRId64")\n", s->first_pts, av_rescale_q(first_pts, AV_TIME_BASE_Q, outlink->time_base)); } else { s->first_pts = s->pts = buf->pts; } } else { av_log(ctx, AV_LOG_WARNING, "Discarding initial frame(s) with no " "timestamp.\n"); av_frame_free(&buf); s->drop++; } return 0; } /* now wait for the next timestamp */ if (buf->pts == AV_NOPTS_VALUE) { return write_to_fifo(s->fifo, buf); } /* number of output frames */ delta = av_rescale_q_rnd(buf->pts - s->pts, inlink->time_base, outlink->time_base, s->rounding); if (delta < 1) { /* drop the frame and everything buffered except the first */ AVFrame *tmp; int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*); av_log(ctx, AV_LOG_DEBUG, "Dropping %d frame(s).\n", drop); s->drop += drop; av_fifo_generic_read(s->fifo, &tmp, sizeof(tmp), NULL); flush_fifo(s->fifo); ret = write_to_fifo(s->fifo, tmp); av_frame_free(&buf); return ret; } /* can output >= 1 frames */ for (i = 0; i < delta; i++) { AVFrame *buf_out; av_fifo_generic_read(s->fifo, &buf_out, sizeof(buf_out), NULL); /* duplicate the frame if needed */ if (!av_fifo_size(s->fifo) && i < delta - 1) { AVFrame *dup = av_frame_clone(buf_out); av_log(ctx, AV_LOG_DEBUG, "Duplicating frame.\n"); if (dup) ret = write_to_fifo(s->fifo, dup); else ret = AVERROR(ENOMEM); if (ret < 0) { av_frame_free(&buf_out); av_frame_free(&buf); return ret; } s->dup++; } buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base, outlink->time_base) + s->frames_out; if ((ret = ff_filter_frame(outlink, buf_out)) < 0) { av_frame_free(&buf); return ret; } s->frames_out++; } flush_fifo(s->fifo); ret = write_to_fifo(s->fifo, buf); s->pts = s->first_pts + av_rescale_q(s->frames_out, outlink->time_base, inlink->time_base); return ret; } CWE ID: CWE-399 Target: 1 Example 2: Code: int32_t VolumeGetStereoPosition(EffectContext *pContext, int16_t *position){ LVM_ControlParams_t ActiveParams; /* Current control Parameters */ LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */ LVM_INT16 balance; LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "VolumeGetStereoPosition") if(LvmStatus != LVM_SUCCESS) return -EINVAL; balance = VolumeConvertStereoPosition(pContext->pBundledContext->positionSaved); if(pContext->pBundledContext->bStereoPositionEnabled == LVM_TRUE){ if(balance != ActiveParams.VC_Balance){ return -EINVAL; } } *position = (LVM_INT16)pContext->pBundledContext->positionSaved; // Convert dB to millibels return 0; } /* end VolumeGetStereoPosition */ 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: ShellMainDelegate::ShellMainDelegate() { } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n" "\t[-r REPO]\n" "\n" "Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n" "ABRT system cache." ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = "build_ids"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")), OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")), OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")), OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")), OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp("-", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die("setregid(egid, rgid)"); if (setreuid(euid, ruid) < 0) perror_msg_and_die("setreuid(euid, ruid)"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die("setregid(rgid, egid)"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die("setreuid(ruid, euid)"); if (build_ids_fd < 0) perror_msg_and_die("Failed to open file '%s'", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd); } /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, --, NULL */ const char *args[11]; { const char *verbs[] = { "", "-v", "-vv", "-vvv" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = "--ids"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = "-y"; if ((opts & OPT_e)) { args[i++] = "--exact"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = "--repo"; args[i++] = repo; } args[i++] = "--"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 static const char *whitelist[] = { "REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave "LANG", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); clearenv(); for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = "LD_LIBRARY_PATH" "\0" "LD_PRELOAD" "\0" "LD_TRACE_LOADED_OBJECTS" "\0" "LD_BIND_NOW" "\0" "LD_AOUT_LIBRARY_PATH" "\0" "LD_AOUT_PRELOAD" "\0" "LD_NOWARN" "\0" "LD_KEEPDIR" "\0" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR; if (euid != 0) strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } execvp(EXECUTABLE, (char **)args); error_msg_and_die("Can't execute %s", EXECUTABLE); } CWE ID: CWE-59 Target: 1 Example 2: Code: void WebContentsImpl::OnDocumentLoadedInFrame(RenderFrameHostImpl* source) { for (auto& observer : observers_) observer.DocumentLoadedInFrame(source); } 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 build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k, const struct xfrm_selector *sel, u8 dir, u8 type) { const struct xfrm_migrate *mp; struct xfrm_userpolicy_id *pol_id; struct nlmsghdr *nlh; int i, err; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0); if (nlh == NULL) return -EMSGSIZE; pol_id = nlmsg_data(nlh); /* copy data from selector, dir, and type to the pol_id */ memset(pol_id, 0, sizeof(*pol_id)); memcpy(&pol_id->sel, sel, sizeof(pol_id->sel)); pol_id->dir = dir; if (k != NULL) { err = copy_to_user_kmaddress(k, skb); if (err) goto out_cancel; } err = copy_to_user_policy_type(type, skb); if (err) goto out_cancel; for (i = 0, mp = m ; i < num_migrate; i++, mp++) { err = copy_to_user_migrate(mp, skb); if (err) goto out_cancel; } return nlmsg_end(skb, nlh); out_cancel: nlmsg_cancel(skb, nlh); return err; } 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: php_stream *php_stream_zip_opener(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { int path_len; char *file_basename; size_t file_basename_len; char file_dirname[MAXPATHLEN]; struct zip *za; struct zip_file *zf = NULL; char *fragment; int fragment_len; int err; php_stream *stream = NULL; struct php_zip_stream_data_t *self; fragment = strchr(path, '#'); if (!fragment) { return NULL; } if (strncasecmp("zip://", path, 6) == 0) { path += 6; } fragment_len = strlen(fragment); if (fragment_len < 1) { return NULL; } path_len = strlen(path); if (path_len >= MAXPATHLEN || mode[0] != 'r') { return NULL; } memcpy(file_dirname, path, path_len - fragment_len); file_dirname[path_len - fragment_len] = '\0'; php_basename(path, path_len - fragment_len, NULL, 0, &file_basename, &file_basename_len TSRMLS_CC); fragment++; if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) { efree(file_basename); return NULL; } za = zip_open(file_dirname, ZIP_CREATE, &err); if (za) { zf = zip_fopen(za, fragment, 0); if (zf) { self = emalloc(sizeof(*self)); self->za = za; self->zf = zf; self->stream = NULL; self->cursor = 0; stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode); if (opened_path) { *opened_path = estrdup(path); } } else { zip_close(za); } } efree(file_basename); if (!stream) { return NULL; } else { return stream; } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref) { int is_valid; long start; char *c, buf[16]; memset(buf, 0, sizeof(buf)); is_valid = 0; start = ftell(fp); fseek(fp, xref->start, SEEK_SET); if (fgets(buf, 16, fp) == NULL) { ERR("Failed to load xref string."); exit(EXIT_FAILURE); } if (strncmp(buf, "xref", strlen("xref")) == 0) is_valid = 1; else { /* PDFv1.5+ allows for xref data to be stored in streams vs plaintext */ fseek(fp, xref->start, SEEK_SET); c = get_object_from_here(fp, NULL, &xref->is_stream); if (c && xref->is_stream) { free(c); pdf->has_xref_streams = 1; is_valid = 1; } } fseek(fp, start, SEEK_SET); return is_valid; } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DownloadItemImpl::SetLastAccessTime(base::Time last_access_time) { last_access_time_ = last_access_time; UpdateObservers(); } 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 AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id, int route_id, bool alive, bool did_swap) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU, host_id, route_id, alive, did_swap)); return; } GpuProcessHost* host = GpuProcessHost::FromID(host_id); if (host) { if (alive) host->Send(new AcceleratedSurfaceMsg_BufferPresented( route_id, did_swap, 0)); else host->ForceShutdown(); } } CWE ID: Target: 1 Example 2: Code: dissect_DRIVER_INFO_2(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { proto_tree *subtree; int struct_start = offset; subtree = proto_tree_add_subtree( tree, tvb, offset, 0, ett_DRIVER_INFO_2, NULL, "Driver info level 2"); offset = dissect_ndr_uint32(tvb, offset, pinfo, subtree, di, drep, hf_driverinfo_cversion, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_drivername, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_environment, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_driverpath, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_datafile, struct_start, NULL); offset = dissect_spoolss_relstr( tvb, offset, pinfo, subtree, di, drep, hf_configfile, struct_start, NULL); return offset; } 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: ssize_t nfsd_copy_file_range(struct file *src, u64 src_pos, struct file *dst, u64 dst_pos, u64 count) { /* * Limit copy to 4MB to prevent indefinitely blocking an nfsd * thread and client rpc slot. The choice of 4MB is somewhat * arbitrary. We might instead base this on r/wsize, or make it * tunable, or use a time instead of a byte limit, or implement * asynchronous copy. In theory a client could also recognize a * limit like this and pipeline multiple COPY requests. */ count = min_t(u64, count, 1 << 22); return vfs_copy_file_range(src, src_pos, dst, dst_pos, count, 0); } CWE ID: CWE-404 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) { sapi_header_struct sapi_header; char *colon_offset; char *header_line; uint header_line_len; int http_response_code; if (SG(headers_sent) && !SG(request_info).no_headers) { const char *output_start_filename = php_output_get_start_filename(TSRMLS_C); int output_start_lineno = php_output_get_start_lineno(TSRMLS_C); if (output_start_filename) { sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent by (output started at %s:%d)", output_start_filename, output_start_lineno); } else { sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent"); } return FAILURE; } switch (op) { case SAPI_HEADER_SET_STATUS: sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC); return SUCCESS; case SAPI_HEADER_ADD: case SAPI_HEADER_REPLACE: case SAPI_HEADER_DELETE: { sapi_header_line *p = arg; if (!p->line || !p->line_len) { return FAILURE; } header_line = p->line; header_line_len = p->line_len; http_response_code = p->response_code; break; } case SAPI_HEADER_DELETE_ALL: if (sapi_module.header_handler) { sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); } zend_llist_clean(&SG(sapi_headers).headers); return SUCCESS; default: return FAILURE; } header_line = estrndup(header_line, header_line_len); /* cut off trailing spaces, linefeeds and carriage-returns */ if (header_line_len && isspace(header_line[header_line_len-1])) { do { header_line_len--; } while(header_line_len && isspace(header_line[header_line_len-1])); header_line[header_line_len]='\0'; } if (op == SAPI_HEADER_DELETE) { if (strchr(header_line, ':')) { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon."); return FAILURE; } if (sapi_module.header_handler) { sapi_header.header = header_line; sapi_header.header_len = header_line_len; sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); } sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len); efree(header_line); return SUCCESS; } else { /* new line/NUL character safety check */ int i; for (i = 0; i < header_line_len; i++) { /* RFC 2616 allows new lines if followed by SP or HT */ int illegal_break = (header_line[i+1] != ' ' && header_line[i+1] != '\t') && ( header_line[i] == '\n' || (header_line[i] == '\r' && header_line[i+1] != '\n')); if (illegal_break) { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header may not contain " "more than a single header, new line detected"); return FAILURE; } if (header_line[i] == '\0') { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes"); return FAILURE; } } } sapi_header.header = header_line; sapi_header.header_len = header_line_len; /* Check the header for a few cases that we have special support for in SAPI */ if (header_line_len>=5 && !strncasecmp(header_line, "HTTP/", 5)) { /* filter out the response code */ sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC); /* sapi_update_response_code doesn't free the status line if the code didn't change */ if (SG(sapi_headers).http_status_line) { efree(SG(sapi_headers).http_status_line); } SG(sapi_headers).http_status_line = header_line; return SUCCESS; } else { colon_offset = strchr(header_line, ':'); if (colon_offset) { *colon_offset = 0; if (!STRCASECMP(header_line, "Content-Type")) { char *ptr = colon_offset+1, *mimetype = NULL, *newheader; size_t len = header_line_len - (ptr - header_line), newlen; while (*ptr == ' ') { ptr++; len--; } /* Disable possible output compression for images */ if (!strncmp(ptr, "image/", sizeof("image/")-1)) { zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); } mimetype = estrdup(ptr); newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC); if (!SG(sapi_headers).mimetype){ SG(sapi_headers).mimetype = estrdup(mimetype); } if (newlen != 0) { newlen += sizeof("Content-type: "); newheader = emalloc(newlen); PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1); strlcat(newheader, mimetype, newlen); sapi_header.header = newheader; sapi_header.header_len = newlen - 1; efree(header_line); } efree(mimetype); SG(sapi_headers).send_default_content_type = 0; } else if (!STRCASECMP(header_line, "Content-Length")) { /* Script is setting Content-length. The script cannot reasonably * know the size of the message body after compression, so it's best * do disable compression altogether. This contributes to making scripts * portable between setups that have and don't have zlib compression * enabled globally. See req #44164 */ zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); } else if (!STRCASECMP(header_line, "Location")) { if ((SG(sapi_headers).http_response_code < 300 || SG(sapi_headers).http_response_code > 399) && SG(sapi_headers).http_response_code != 201) { /* Return a Found Redirect if one is not already specified */ if (http_response_code) { /* user specified redirect code */ sapi_update_response_code(http_response_code TSRMLS_CC); } else if (SG(request_info).proto_num > 1000 && SG(request_info).request_method && strcmp(SG(request_info).request_method, "HEAD") && strcmp(SG(request_info).request_method, "GET")) { sapi_update_response_code(303 TSRMLS_CC); } else { sapi_update_response_code(302 TSRMLS_CC); } } } else if (!STRCASECMP(header_line, "WWW-Authenticate")) { /* HTTP Authentication */ sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */ } if (sapi_header.header==header_line) { *colon_offset = ':'; } } } if (http_response_code) { sapi_update_response_code(http_response_code TSRMLS_CC); } sapi_header_add_op(op, &sapi_header TSRMLS_CC); return SUCCESS; } CWE ID: CWE-79 Target: 1 Example 2: Code: void QQuickWebViewPrivate::didChangeBackForwardList() { navigationHistory->d->reset(); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { u32 idt_vectoring; unsigned int nr; if (vcpu->arch.exception.pending) { nr = vcpu->arch.exception.nr; idt_vectoring = nr | VECTORING_INFO_VALID_MASK; if (kvm_exception_is_soft(nr)) { vmcs12->vm_exit_instruction_len = vcpu->arch.event_exit_inst_len; idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION; } else idt_vectoring |= INTR_TYPE_HARD_EXCEPTION; if (vcpu->arch.exception.has_error_code) { idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK; vmcs12->idt_vectoring_error_code = vcpu->arch.exception.error_code; } vmcs12->idt_vectoring_info_field = idt_vectoring; } else if (vcpu->arch.nmi_pending) { vmcs12->idt_vectoring_info_field = INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR; } else if (vcpu->arch.interrupt.pending) { nr = vcpu->arch.interrupt.nr; idt_vectoring = nr | VECTORING_INFO_VALID_MASK; if (vcpu->arch.interrupt.soft) { idt_vectoring |= INTR_TYPE_SOFT_INTR; vmcs12->vm_entry_instruction_len = vcpu->arch.event_exit_inst_len; } else idt_vectoring |= INTR_TYPE_EXT_INTR; vmcs12->idt_vectoring_info_field = idt_vectoring; } } 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 ThreadableBlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData) { if (isMainThread()) blobRegistry().registerBlobURL(url, blobData); else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData)); callOnMainThread(&registerBlobURLTask, context.leakPtr()); } } CWE ID: Target: 1 Example 2: Code: bool DocumentInit::IsHostedInReservedIPRange() const { if (DocumentLoader* loader = MasterDocumentLoader()) { if (!loader->GetResponse().RemoteIPAddress().IsEmpty()) { return NetworkUtils::IsReservedIPAddress( loader->GetResponse().RemoteIPAddress()); } } 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: gss_name_to_string(gss_name_t gss_name, gss_buffer_desc *str) { OM_uint32 status, minor_stat; gss_OID gss_type; const char pref[] = KRB5_WELLKNOWN_NAMESTR "/" KRB5_ANONYMOUS_PRINCSTR "@"; const size_t preflen = sizeof(pref) - 1; status = gss_display_name(&minor_stat, gss_name, str, &gss_type); if (status != GSS_S_COMPLETE) return 1; if (gss_oid_equal(gss_type, GSS_C_NT_ANONYMOUS)) { /* Guard against non-krb5 mechs with different anonymous displays. */ if (str->length < preflen || memcmp(str->value, pref, preflen) != 0) return 1; } else if (!gss_oid_equal(gss_type, GSS_KRB5_NT_PRINCIPAL_NAME)) { return 1; } 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: cib_remote_dispatch(gpointer user_data) { cib_t *cib = user_data; cib_remote_opaque_t *private = cib->variant_opaque; xmlNode *msg = NULL; const char *type = NULL; crm_info("Message on callback channel"); msg = crm_recv_remote_msg(private->callback.session, private->callback.encrypted); type = crm_element_value(msg, F_TYPE); crm_trace("Activating %s callbacks...", type); if (safe_str_eq(type, T_CIB)) { cib_native_callback(cib, msg, 0, 0); } else if (safe_str_eq(type, T_CIB_NOTIFY)) { g_list_foreach(cib->notify_list, cib_native_notify, msg); } else { crm_err("Unknown message type: %s", type); } if (msg != NULL) { free_xml(msg); return 0; } return -1; } CWE ID: CWE-399 Target: 1 Example 2: Code: ImageData* BaseRenderingContext2D::getImageData( int sx, int sy, int sw, int sh, ExceptionState& exception_state) { if (!WTF::CheckMul(sw, sh).IsValid<int>()) { exception_state.ThrowRangeError("Out of memory at ImageData creation"); return nullptr; } usage_counters_.num_get_image_data_calls++; usage_counters_.area_get_image_data_calls += sw * sh; if (!OriginClean()) { exception_state.ThrowSecurityError( "The canvas has been tainted by cross-origin data."); } else if (!sw || !sh) { exception_state.ThrowDOMException( kIndexSizeError, String::Format("The source %s is 0.", sw ? "height" : "width")); } if (exception_state.HadException()) return nullptr; if (sw < 0) { sx += sw; sw = -sw; } if (sh < 0) { sy += sh; sh = -sh; } if (!WTF::CheckAdd(sx, sw).IsValid<int>() || !WTF::CheckAdd(sy, sh).IsValid<int>()) { exception_state.ThrowRangeError("Out of memory at ImageData creation"); return nullptr; } Optional<ScopedUsHistogramTimer> timer; if (!IsPaint2D()) { if (GetImageBuffer() && GetImageBuffer()->IsAccelerated()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_gpu, ("Blink.Canvas.GetImageData.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_gpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_cpu, ("Blink.Canvas.GetImageData.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_cpu); } } IntRect image_data_rect(sx, sy, sw, sh); ImageBuffer* buffer = GetImageBuffer(); ImageDataColorSettings color_settings = GetColorSettingsAsImageDataColorSettings(); if (!buffer || isContextLost()) { ImageData* result = ImageData::Create(image_data_rect.Size(), &color_settings); if (!result) exception_state.ThrowRangeError("Out of memory at ImageData creation"); return result; } WTF::ArrayBufferContents contents; bool is_gpu_readback_invoked = false; if (!buffer->GetImageData(image_data_rect, contents, &is_gpu_readback_invoked)) { exception_state.ThrowRangeError("Out of memory at ImageData creation"); return nullptr; } if (is_gpu_readback_invoked) { DidInvokeGPUReadbackInCurrentFrame(); } NeedsFinalizeFrame(); if (PixelFormat() != kRGBA8CanvasPixelFormat) { ImageDataStorageFormat storage_format = ImageData::GetImageDataStorageFormat(color_settings.storageFormat()); DOMArrayBufferView* array_buffer_view = ImageData::ConvertPixelsFromCanvasPixelFormatToImageDataStorageFormat( contents, PixelFormat(), storage_format); return ImageData::Create(image_data_rect.Size(), NotShared<DOMArrayBufferView>(array_buffer_view), &color_settings); } DOMArrayBuffer* array_buffer = DOMArrayBuffer::Create(contents); return ImageData::Create( image_data_rect.Size(), NotShared<DOMUint8ClampedArray>(DOMUint8ClampedArray::Create( array_buffer, 0, array_buffer->ByteLength())), &color_settings); } 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: jbig2_sd_list_referred(Jbig2Ctx *ctx, Jbig2Segment *segment) { int index; Jbig2Segment *rsegment; Jbig2SymbolDict **dicts; int n_dicts = jbig2_sd_count_referred(ctx, segment); int dindex = 0; dicts = jbig2_new(ctx, Jbig2SymbolDict *, n_dicts); if (dicts == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate referred list of symbol dictionaries"); return NULL; } for (index = 0; index < segment->referred_to_segment_count; index++) { rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]); if (rsegment && ((rsegment->flags & 63) == 0) && rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL)) { /* add this referred to symbol dictionary */ dicts[dindex++] = (Jbig2SymbolDict *) rsegment->result; } } if (dindex != n_dicts) { /* should never happen */ jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "counted %d symbol dictionaries but built a list with %d.\n", n_dicts, dindex); } return (dicts); } 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 Chapters::Edition::ShallowCopy(Edition& rhs) const { rhs.m_atoms = m_atoms; rhs.m_atoms_size = m_atoms_size; rhs.m_atoms_count = m_atoms_count; } CWE ID: CWE-119 Target: 1 Example 2: Code: free_Header(struct _7z_header_info *h) { free(h->emptyStreamBools); free(h->emptyFileBools); free(h->antiBools); free(h->attrBools); } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);} 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: OMX_ERRORTYPE SoftVideoDecoderOMXComponent::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamVideoPortFormat: { OMX_VIDEO_PARAM_PORTFORMATTYPE *formatParams = (OMX_VIDEO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > kMaxPortIndex) { return OMX_ErrorBadPortIndex; } if (formatParams->nIndex != 0) { return OMX_ErrorNoMore; } if (formatParams->nPortIndex == kInputPortIndex) { formatParams->eCompressionFormat = mCodingType; formatParams->eColorFormat = OMX_COLOR_FormatUnused; formatParams->xFramerate = 0; } else { CHECK_EQ(formatParams->nPortIndex, 1u); formatParams->eCompressionFormat = OMX_VIDEO_CodingUnused; formatParams->eColorFormat = OMX_COLOR_FormatYUV420Planar; formatParams->xFramerate = 0; } return OMX_ErrorNone; } case OMX_IndexParamVideoProfileLevelQuerySupported: { OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevel = (OMX_VIDEO_PARAM_PROFILELEVELTYPE *) params; if (profileLevel->nPortIndex != kInputPortIndex) { ALOGE("Invalid port index: %" PRIu32, profileLevel->nPortIndex); return OMX_ErrorUnsupportedIndex; } if (profileLevel->nProfileIndex >= mNumProfileLevels) { return OMX_ErrorNoMore; } profileLevel->eProfile = mProfileLevels[profileLevel->nProfileIndex].mProfile; profileLevel->eLevel = mProfileLevels[profileLevel->nProfileIndex].mLevel; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: vc4_wait_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { int ret; struct drm_vc4_wait_bo *args = data; struct drm_gem_object *gem_obj; struct vc4_bo *bo; if (args->pad != 0) return -EINVAL; gem_obj = drm_gem_object_lookup(file_priv, args->handle); if (!gem_obj) { DRM_ERROR("Failed to look up GEM BO %d\n", args->handle); return -EINVAL; } bo = to_vc4_bo(gem_obj); ret = vc4_wait_for_seqno_ioctl_helper(dev, bo->seqno, &args->timeout_ns); drm_gem_object_unreference_unlocked(gem_obj); return ret; } CWE ID: CWE-388 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Histogram::Histogram(const std::string& name, Sample minimum, Sample maximum, const BucketRanges* ranges) : HistogramBase(name), bucket_ranges_(ranges), declared_min_(minimum), declared_max_(maximum) { if (ranges) samples_.reset(new SampleVector(HashMetricName(name), ranges)); } 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: dhcpv4_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint8_t type, optlen; i = 0; while (i < length) { tlv = cp + i; type = (uint8_t)tlv[0]; optlen = (uint8_t)tlv[1]; value = tlv + 2; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 2 )); switch (type) { case DH4OPT_DNS_SERVERS: case DH4OPT_NTP_SERVERS: { if (optlen < 4 || optlen % 4 != 0) { return -1; } for (t = 0; t < optlen; t += 4) ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t))); } break; case DH4OPT_DOMAIN_SEARCH: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 2 + optlen; } return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: String createMarkup(const Range* range, Vector<Node*>* nodes, EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs) { DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">")); if (!range) return ""; Document* document = range->ownerDocument(); if (!document) return ""; Frame* frame = document->frame(); DeleteButtonController* deleteButton = frame ? frame->editor()->deleteButtonController() : 0; RefPtr<Range> updatedRange = avoidIntersectionWithNode(range, deleteButton ? deleteButton->containerElement() : 0); if (!updatedRange) return ""; if (deleteButton) deleteButton->disable(); ExceptionCode ec = 0; bool collapsed = updatedRange->collapsed(ec); ASSERT(!ec); if (collapsed) return ""; Node* commonAncestor = updatedRange->commonAncestorContainer(ec); ASSERT(!ec); if (!commonAncestor) return ""; document->updateLayoutIgnorePendingStylesheets(); Node* body = enclosingNodeWithTag(firstPositionInNode(commonAncestor), bodyTag); Node* fullySelectedRoot = 0; if (body && areRangesEqual(VisibleSelection::selectionFromContentsOfNode(body).toNormalizedRange().get(), range)) fullySelectedRoot = body; Node* specialCommonAncestor = highestAncestorToWrapMarkup(updatedRange.get(), shouldAnnotate); StyledMarkupAccumulator accumulator(nodes, shouldResolveURLs, shouldAnnotate, updatedRange.get(), specialCommonAncestor); Node* pastEnd = updatedRange->pastLastNode(); Node* startNode = updatedRange->firstNode(); VisiblePosition visibleStart(updatedRange->startPosition(), VP_DEFAULT_AFFINITY); VisiblePosition visibleEnd(updatedRange->endPosition(), VP_DEFAULT_AFFINITY); if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleStart)) { if (visibleStart == visibleEnd.previous()) { if (deleteButton) deleteButton->enable(); return interchangeNewlineString; } accumulator.appendString(interchangeNewlineString); startNode = visibleStart.next().deepEquivalent().deprecatedNode(); ExceptionCode ec = 0; if (pastEnd && Range::compareBoundaryPoints(startNode, 0, pastEnd, 0, ec) >= 0) { ASSERT(!ec); if (deleteButton) deleteButton->enable(); return interchangeNewlineString; } ASSERT(!ec); } Node* lastClosed = accumulator.serializeNodes(startNode, pastEnd); if (specialCommonAncestor && lastClosed) { for (ContainerNode* ancestor = lastClosed->parentNode(); ancestor; ancestor = ancestor->parentNode()) { if (ancestor == fullySelectedRoot && !convertBlocksToInlines) { RefPtr<EditingStyle> fullySelectedRootStyle = styleFromMatchedRulesAndInlineDecl(fullySelectedRoot); if ((!fullySelectedRootStyle || !fullySelectedRootStyle->style() || !fullySelectedRootStyle->style()->getPropertyCSSValue(CSSPropertyBackgroundImage)) && static_cast<Element*>(fullySelectedRoot)->hasAttribute(backgroundAttr)) fullySelectedRootStyle->style()->setProperty(CSSPropertyBackgroundImage, "url('" + static_cast<Element*>(fullySelectedRoot)->getAttribute(backgroundAttr) + "')"); if (fullySelectedRootStyle->style()) { if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyTextDecoration)) fullySelectedRootStyle->style()->setProperty(CSSPropertyTextDecoration, CSSValueNone); if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyWebkitTextDecorationsInEffect)) fullySelectedRootStyle->style()->setProperty(CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone); accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), document, true); } } else { accumulator.wrapWithNode(ancestor, convertBlocksToInlines, StyledMarkupAccumulator::DoesNotFullySelectNode); } if (nodes) nodes->append(ancestor); lastClosed = ancestor; if (ancestor == specialCommonAncestor) break; } } if (shouldAnnotate == AnnotateForInterchange && needInterchangeNewlineAfter(visibleEnd.previous())) accumulator.appendString(interchangeNewlineString); if (deleteButton) deleteButton->enable(); return accumulator.takeResults(); } 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: std::string SanitizeFrontendPath(const std::string& path) { for (size_t i = 0; i < path.length(); i++) { if (path[i] != '/' && path[i] != '-' && path[i] != '_' && path[i] != '.' && path[i] != '@' && !(path[i] >= '0' && path[i] <= '9') && !(path[i] >= 'a' && path[i] <= 'z') && !(path[i] >= 'A' && path[i] <= 'Z')) { return std::string(); } } return path; } 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 PassRefPtrWillBeRawPtr<CreateFileResult> create() { return adoptRefWillBeNoop(new CreateFileResult()); } CWE ID: CWE-119 Target: 1 Example 2: Code: ofputil_group_properties_copy(struct ofputil_group_props *to, const struct ofputil_group_props *from) { *to = *from; to->fields.values = xmemdup(from->fields.values, from->fields.values_size); } CWE ID: CWE-617 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int create_autodetect_quirks(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { int probed_ifnum = get_iface_desc(iface->altsetting)->bInterfaceNumber; int ifcount, ifnum, err; err = create_autodetect_quirk(chip, iface, driver); if (err < 0) return err; /* * ALSA PCM playback/capture devices cannot be registered in two steps, * so we have to claim the other corresponding interface here. */ ifcount = chip->dev->actconfig->desc.bNumInterfaces; for (ifnum = 0; ifnum < ifcount; ifnum++) { if (ifnum == probed_ifnum || quirk->ifnum >= 0) continue; iface = usb_ifnum_to_if(chip->dev, ifnum); if (!iface || usb_interface_claimed(iface) || get_iface_desc(iface->altsetting)->bInterfaceClass != USB_CLASS_VENDOR_SPEC) continue; err = create_autodetect_quirk(chip, iface, driver); if (err >= 0) usb_driver_claim_interface(driver, iface, (void *)-1L); } return 0; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int vp8_remove_decoder_instances(struct frame_buffers *fb) { if(!fb->use_frame_threads) { VP8D_COMP *pbi = fb->pbi[0]; if (!pbi) return VPX_CODEC_ERROR; #if CONFIG_MULTITHREAD if (pbi->b_multithreaded_rd) vp8mt_de_alloc_temp_buffers(pbi, pbi->common.mb_rows); vp8_decoder_remove_threads(pbi); #endif /* decoder instance for single thread mode */ remove_decompressor(pbi); } else { /* TODO : remove frame threads and decoder instances for each * thread here */ } return VPX_CODEC_OK; } CWE ID: Target: 1 Example 2: Code: script_security_handler(__attribute__((unused)) vector_t *strvec) { script_security = true; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y]); } } } 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: PHP_FUNCTION(mcrypt_module_is_block_algorithm) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) if (mcrypt_module_is_block_algorithm(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } CWE ID: CWE-190 Target: 1 Example 2: Code: BrowserPpapiHostImpl::BrowserPpapiHostImpl( IPC::Sender* sender, const ppapi::PpapiPermissions& permissions, const std::string& plugin_name, const base::FilePath& plugin_path, const base::FilePath& profile_data_directory, bool in_process, bool external_plugin) : ppapi_host_(new ppapi::host::PpapiHost(sender, permissions)), plugin_name_(plugin_name), plugin_path_(plugin_path), profile_data_directory_(profile_data_directory), in_process_(in_process), external_plugin_(external_plugin), ssl_context_helper_(new SSLContextHelper()) { message_filter_ = new HostMessageFilter(ppapi_host_.get(), this); ppapi_host_->AddHostFactoryFilter(std::unique_ptr<ppapi::host::HostFactory>( new ContentBrowserPepperHostFactory(this))); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void HTMLFormElement::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<NodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Node>& returnValue1) { { Vector<RefPtr<Node> > elements; getNamedElements(name, elements); if (elements.isEmpty()) return; } Vector<RefPtr<Node> > elements; getNamedElements(name, elements); ASSERT(!elements.isEmpty()); if (elements.size() == 1) { returnValue1Enabled = true; returnValue1 = elements.at(0); return; } returnValue0Enabled = true; returnValue0 = NamedNodesCollection::create(elements); } 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: EncodedJSValue JSC_HOST_CALL JSWorkerConstructor::constructJSWorker(ExecState* exec) { JSWorkerConstructor* jsConstructor = jsCast<JSWorkerConstructor*>(exec->callee()); if (!exec->argumentCount()) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); UString scriptURL = exec->argument(0).toString(exec)->value(exec); if (exec->hadException()) return JSValue::encode(JSValue()); DOMWindow* window = asJSDOMWindow(exec->lexicalGlobalObject())->impl(); ExceptionCode ec = 0; RefPtr<Worker> worker = Worker::create(window->document(), ustringToString(scriptURL), ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, jsConstructor->globalObject(), worker.release()))); } CWE ID: CWE-20 Target: 1 Example 2: Code: void InspectorResourceAgent::willSendRequest(unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo) { if (initiatorInfo.name == FetchInitiatorTypeNames::internal) return; String requestId = IdentifiersFactory::requestId(identifier); m_resourcesData->resourceCreated(requestId, m_pageAgent->loaderId(loader)); RefPtr<JSONObject> headers = m_state->getObject(ResourceAgentState::extraRequestHeaders); if (headers) { JSONObject::const_iterator end = headers->end(); for (JSONObject::const_iterator it = headers->begin(); it != end; ++it) { String value; if (it->value->asString(&value)) request.setHTTPHeaderField(AtomicString(it->key), AtomicString(value)); } } request.setReportLoadTiming(true); request.setReportRawHeaders(true); if (m_state->getBoolean(ResourceAgentState::cacheDisabled)) { request.setHTTPHeaderField("Pragma", "no-cache"); request.setCachePolicy(ReloadIgnoringCacheData); request.setHTTPHeaderField("Cache-Control", "no-cache"); } String frameId = m_pageAgent->frameId(loader->frame()); RefPtr<TypeBuilder::Network::Initiator> initiatorObject = buildInitiatorObject(loader->frame() ? loader->frame()->document() : 0, initiatorInfo); if (initiatorInfo.name == FetchInitiatorTypeNames::document) { FrameNavigationInitiatorMap::iterator it = m_frameNavigationInitiatorMap.find(frameId); if (it != m_frameNavigationInitiatorMap.end()) initiatorObject = it->value; } m_frontend->requestWillBeSent(requestId, frameId, m_pageAgent->loaderId(loader), urlWithoutFragment(loader->url()).string(), buildObjectForResourceRequest(request), currentTime(), initiatorObject, buildObjectForResourceResponse(redirectResponse, loader)); } 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 bool HasEntryImpl(Isolate* isolate, FixedArrayBase* parameters, uint32_t entry) { FixedArray* parameter_map = FixedArray::cast(parameters); uint32_t length = parameter_map->length() - 2; if (entry < length) { return HasParameterMapArg(parameter_map, entry); } FixedArrayBase* arguments = FixedArrayBase::cast(parameter_map->get(1)); return ArgumentsAccessor::HasEntryImpl(isolate, arguments, entry - length); } 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: static int mptsas_process_scsi_io_request(MPTSASState *s, MPIMsgSCSIIORequest *scsi_io, hwaddr addr) { MPTSASRequest *req; MPIMsgSCSIIOReply reply; SCSIDevice *sdev; int status; mptsas_fix_scsi_io_endianness(scsi_io); trace_mptsas_process_scsi_io_request(s, scsi_io->Bus, scsi_io->TargetID, scsi_io->LUN[1], scsi_io->DataLength); status = mptsas_scsi_device_find(s, scsi_io->Bus, scsi_io->TargetID, scsi_io->LUN, &sdev); if (status) { goto bad; } req = g_new(MPTSASRequest, 1); QTAILQ_INSERT_TAIL(&s->pending, req, next); req->scsi_io = *scsi_io; req->dev = s; status = mptsas_build_sgl(s, req, addr); if (status) { goto free_bad; } if (req->qsg.size < scsi_io->DataLength) { trace_mptsas_sgl_overflow(s, scsi_io->MsgContext, scsi_io->DataLength, req->qsg.size); status = MPI_IOCSTATUS_INVALID_SGL; goto free_bad; } req->sreq = scsi_req_new(sdev, scsi_io->MsgContext, scsi_io->LUN[1], scsi_io->CDB, req); if (req->sreq->cmd.xfer > scsi_io->DataLength) { goto overrun; } switch (scsi_io->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK) { case MPI_SCSIIO_CONTROL_NODATATRANSFER: if (req->sreq->cmd.mode != SCSI_XFER_NONE) { goto overrun; } break; case MPI_SCSIIO_CONTROL_WRITE: if (req->sreq->cmd.mode != SCSI_XFER_TO_DEV) { goto overrun; } break; case MPI_SCSIIO_CONTROL_READ: if (req->sreq->cmd.mode != SCSI_XFER_FROM_DEV) { goto overrun; } break; } if (scsi_req_enqueue(req->sreq)) { scsi_req_continue(req->sreq); } return 0; overrun: trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer, scsi_io->DataLength); status = MPI_IOCSTATUS_SCSI_DATA_OVERRUN; free_bad: mptsas_free_request(req); bad: memset(&reply, 0, sizeof(reply)); reply.TargetID = scsi_io->TargetID; reply.Bus = scsi_io->Bus; reply.MsgLength = sizeof(reply) / 4; reply.Function = scsi_io->Function; reply.CDBLength = scsi_io->CDBLength; reply.SenseBufferLength = scsi_io->SenseBufferLength; reply.MsgContext = scsi_io->MsgContext; reply.SCSIState = MPI_SCSI_STATE_NO_SCSI_STATUS; reply.IOCStatus = status; mptsas_fix_scsi_io_reply_endianness(&reply); mptsas_reply(s, (MPIDefaultReply *)&reply); return 0; } CWE ID: CWE-787 Target: 1 Example 2: Code: void PrintViewManagerBase::SendPrintingEnabled(bool enabled, content::RenderFrameHost* rfh) { rfh->Send(new PrintMsg_SetPrintingEnabled(rfh->GetRoutingID(), enabled)); } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WorkerProcessLauncher::Core::OnMessageReceived( const IPC::Message& message) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); if (!ipc_enabled_) return false; return worker_delegate_->OnMessageReceived(message); } 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: SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree, struct cifs_tcon *tcon, const struct nls_table *cp) { struct smb2_tree_connect_req *req; struct smb2_tree_connect_rsp *rsp = NULL; struct kvec iov[2]; int rc = 0; int resp_buftype; int unc_path_len; struct TCP_Server_Info *server; __le16 *unc_path = NULL; cifs_dbg(FYI, "TCON\n"); if ((ses->server) && tree) server = ses->server; else return -EIO; if (tcon && tcon->bad_network_name) return -ENOENT; unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL); if (unc_path == NULL) return -ENOMEM; unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1; unc_path_len *= 2; if (unc_path_len < 2) { kfree(unc_path); return -EINVAL; } rc = small_smb2_init(SMB2_TREE_CONNECT, tcon, (void **) &req); if (rc) { kfree(unc_path); return rc; } if (tcon == NULL) { /* since no tcon, smb2_init can not do this, so do here */ req->hdr.SessionId = ses->Suid; /* if (ses->server->sec_mode & SECMODE_SIGN_REQUIRED) req->hdr.Flags |= SMB2_FLAGS_SIGNED; */ } iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for pad */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* Testing shows that buffer offset must be at location of Buffer[0] */ req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req) - 1 /* pad */ - 4 /* do not count rfc1001 len field */); req->PathLength = cpu_to_le16(unc_path_len - 2); iov[1].iov_base = unc_path; iov[1].iov_len = unc_path_len; inc_rfc1001_len(req, unc_path_len - 1 /* pad */); rc = SendReceive2(xid, ses, iov, 2, &resp_buftype, 0); rsp = (struct smb2_tree_connect_rsp *)iov[0].iov_base; if (rc != 0) { if (tcon) { cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE); tcon->need_reconnect = true; } goto tcon_error_exit; } if (tcon == NULL) { ses->ipc_tid = rsp->hdr.TreeId; goto tcon_exit; } if (rsp->ShareType & SMB2_SHARE_TYPE_DISK) cifs_dbg(FYI, "connection to disk share\n"); else if (rsp->ShareType & SMB2_SHARE_TYPE_PIPE) { tcon->ipc = true; cifs_dbg(FYI, "connection to pipe share\n"); } else if (rsp->ShareType & SMB2_SHARE_TYPE_PRINT) { tcon->print = true; cifs_dbg(FYI, "connection to printer\n"); } else { cifs_dbg(VFS, "unknown share type %d\n", rsp->ShareType); rc = -EOPNOTSUPP; goto tcon_error_exit; } tcon->share_flags = le32_to_cpu(rsp->ShareFlags); tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */ tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess); tcon->tidStatus = CifsGood; tcon->need_reconnect = false; tcon->tid = rsp->hdr.TreeId; strlcpy(tcon->treeName, tree, sizeof(tcon->treeName)); if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) && ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0)) cifs_dbg(VFS, "DFS capability contradicts DFS flag\n"); init_copy_chunk_defaults(tcon); if (tcon->ses->server->ops->validate_negotiate) rc = tcon->ses->server->ops->validate_negotiate(xid, tcon); tcon_exit: free_rsp_buf(resp_buftype, rsp); kfree(unc_path); return rc; tcon_error_exit: if (rsp->hdr.Status == STATUS_BAD_NETWORK_NAME) { cifs_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree); tcon->bad_network_name = true; } goto tcon_exit; } CWE ID: CWE-399 Target: 1 Example 2: Code: static int asn1_write_element(sc_context_t *ctx, unsigned int tag, const u8 * data, size_t datalen, u8 ** out, size_t * outlen) { unsigned char t; unsigned char *buf, *p; int c = 0; unsigned short_tag; unsigned char tag_char[3] = {0, 0, 0}; size_t tag_len, ii; short_tag = tag & SC_ASN1_TAG_MASK; for (tag_len = 0; short_tag >> (8 * tag_len); tag_len++) tag_char[tag_len] = (short_tag >> (8 * tag_len)) & 0xFF; if (!tag_len) tag_len = 1; if (tag_len > 1) { if ((tag_char[tag_len - 1] & SC_ASN1_TAG_PRIMITIVE) != SC_ASN1_TAG_ESCAPE_MARKER) SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "First byte of the long tag is not 'escape marker'"); for (ii = 1; ii < tag_len - 1; ii++) if (!(tag_char[ii] & 0x80)) SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit expected to be 'one'"); if (tag_char[0] & 0x80) SC_TEST_RET(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_INVALID_DATA, "MS bit of the last byte expected to be 'zero'"); } t = tag_char[tag_len - 1] & 0x1F; switch (tag & SC_ASN1_CLASS_MASK) { case SC_ASN1_UNI: break; case SC_ASN1_APP: t |= SC_ASN1_TAG_APPLICATION; break; case SC_ASN1_CTX: t |= SC_ASN1_TAG_CONTEXT; break; case SC_ASN1_PRV: t |= SC_ASN1_TAG_PRIVATE; break; } if (tag & SC_ASN1_CONS) t |= SC_ASN1_TAG_CONSTRUCTED; if (datalen > 127) { c = 1; while (datalen >> (c << 3)) c++; } *outlen = tag_len + 1 + c + datalen; buf = malloc(*outlen); if (buf == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_ASN1, SC_ERROR_OUT_OF_MEMORY); *out = p = buf; *p++ = t; for (ii=1;ii<tag_len;ii++) *p++ = tag_char[tag_len - ii - 1]; if (c) { *p++ = 0x80 | c; while (c--) *p++ = (datalen >> (c << 3)) & 0xFF; } else { *p++ = datalen & 0x7F; } memcpy(p, data, datalen); return SC_SUCCESS; } 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 void nlmclnt_cancel_callback(struct rpc_task *task, void *data) { struct nlm_rqst *req = data; u32 status = ntohl(req->a_res.status); if (RPC_ASSASSINATED(task)) goto die; if (task->tk_status < 0) { dprintk("lockd: CANCEL call error %d, retrying.\n", task->tk_status); goto retry_cancel; } dprintk("lockd: cancel status %u (task %u)\n", status, task->tk_pid); switch (status) { case NLM_LCK_GRANTED: case NLM_LCK_DENIED_GRACE_PERIOD: case NLM_LCK_DENIED: /* Everything's good */ break; case NLM_LCK_DENIED_NOLOCKS: dprintk("lockd: CANCEL failed (server has no locks)\n"); goto retry_cancel; default: printk(KERN_NOTICE "lockd: weird return %d for CANCEL call\n", status); } die: return; retry_cancel: /* Don't ever retry more than 3 times */ if (req->a_retries++ >= NLMCLNT_MAX_RETRIES) goto die; nlm_rebind_host(req->a_host); rpc_restart_call(task); rpc_delay(task, 30 * HZ); } 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: construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len, unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type) { size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8); unsigned char mac[4096] = { 0 }; size_t mac_len; unsigned char icv[16] = { 0 }; int i = (KEY_TYPE_AES == key_type ? 15 : 7); epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; if (0 == data_tlv_len && 0 == le_tlv_len) { mac_len = block_size; } else { /* padding */ *(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80; if ((data_tlv_len + le_tlv_len + 1) % block_size) mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) + 1) * block_size + block_size; else mac_len = data_tlv_len + le_tlv_len + 1 + block_size; memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1), 0, (mac_len - (data_tlv_len + le_tlv_len + 1))); } /* increase icv */ for (; i >= 0; i--) { if (exdata->icv_mac[i] == 0xff) { exdata->icv_mac[i] = 0; } else { exdata->icv_mac[i]++; break; } } /* calculate MAC */ memset(icv, 0, sizeof(icv)); memcpy(icv, exdata->icv_mac, 16); if (KEY_TYPE_AES == key_type) { aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac); memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); } else { unsigned char iv[8] = { 0 }; unsigned char tmp[8] = { 0 }; des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac); des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp); memset(iv, 0x00, 8); des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); } *mac_tlv_len = 2 + 8; return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoScheduleCALayerInUseQueryCHROMIUM( GLuint n, const volatile GLuint* textures) { NOTIMPLEMENTED(); return error::kNoError; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void comps_mrtree_unite(COMPS_MRTree *rt1, COMPS_MRTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it, *it2; struct Pair { COMPS_HSList * subnodes; char * key; char added; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; free(it); pair->added = 0; for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_MRTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key+strlen(parent_pair->key), ((COMPS_MRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_MRTreeData*)it->data)->key) + 1)); memcpy(pair->key, ((COMPS_MRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_MRTreeData*)it->data)->data->first != NULL) { for (it2 = ((COMPS_MRTreeData*)it->data)->data->first; it2 != NULL; it2 = it2->next) { comps_mrtree_set(rt1, pair->key, it2->data); } if (((COMPS_MRTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } /* current node hasn't data */ } else { if (((COMPS_MRTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval, unsigned int optlen) { int val; struct sctp_sock *sp = sctp_sk(sk); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; if (!sctp_is_ep_boundall(sk) && val) return -EINVAL; if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf)) return 0; if (val == 0 && sp->do_auto_asconf) { list_del(&sp->auto_asconf_list); sp->do_auto_asconf = 0; } else if (val && !sp->do_auto_asconf) { list_add_tail(&sp->auto_asconf_list, &sock_net(sk)->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; } return 0; } CWE ID: CWE-362 Target: 1 Example 2: Code: static int compat_do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; struct compat_ebt_replace tmp; struct ebt_table *t; if (!capable(CAP_NET_ADMIN)) return -EPERM; /* try real handler in case userland supplied needed padding */ if ((cmd == EBT_SO_GET_INFO || cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp)) return do_ebt_get_ctl(sk, cmd, user, len); if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex); if (!t) return ret; xt_compat_lock(NFPROTO_BRIDGE); switch (cmd) { case EBT_SO_GET_INFO: tmp.nentries = t->private->nentries; ret = compat_table_info(t->private, &tmp); if (ret) goto out; tmp.valid_hooks = t->valid_hooks; if (copy_to_user(user, &tmp, *len) != 0) { ret = -EFAULT; break; } ret = 0; break; case EBT_SO_GET_INIT_INFO: tmp.nentries = t->table->nentries; tmp.entries_size = t->table->entries_size; tmp.valid_hooks = t->table->valid_hooks; if (copy_to_user(user, &tmp, *len) != 0) { ret = -EFAULT; break; } ret = 0; break; case EBT_SO_GET_ENTRIES: case EBT_SO_GET_INIT_ENTRIES: /* * try real handler first in case of userland-side padding. * in case we are dealing with an 'ordinary' 32 bit binary * without 64bit compatibility padding, this will fail right * after copy_from_user when the *len argument is validated. * * the compat_ variant needs to do one pass over the kernel * data set to adjust for size differences before it the check. */ if (copy_everything_to_user(t, user, len, cmd) == 0) ret = 0; else ret = compat_copy_everything_to_user(t, user, len, cmd); break; default: ret = -EINVAL; } out: xt_compat_flush_offsets(NFPROTO_BRIDGE); xt_compat_unlock(NFPROTO_BRIDGE); mutex_unlock(&ebt_mutex); return ret; } 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: bgp_attr_extra_new (void) { return XCALLOC (MTYPE_ATTR_EXTRA, sizeof (struct attr_extra)); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AppListController::Init(Profile* initial_profile) { if (win8::IsSingleWindowMetroMode()) return; PrefService* prefs = g_browser_process->local_state(); if (prefs->HasPrefPath(prefs::kRestartWithAppList) && prefs->GetBoolean(prefs::kRestartWithAppList)) { prefs->SetBoolean(prefs::kRestartWithAppList, false); AppListController::GetInstance()-> ShowAppListDuringModeSwitch(initial_profile); } AppListController::GetInstance(); ScheduleWarmup(); MigrateAppLauncherEnabledPref(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppList)) EnableAppList(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppList)) DisableAppList(); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void derive_permissions_locked(struct fuse* fuse, struct node *parent, struct node *node) { appid_t appid; /* By default, each node inherits from its parent */ node->perm = PERM_INHERIT; node->userid = parent->userid; node->uid = parent->uid; node->under_android = parent->under_android; /* Derive custom permissions based on parent and current node */ switch (parent->perm) { case PERM_INHERIT: /* Already inherited above */ break; case PERM_PRE_ROOT: /* Legacy internal layout places users at top level */ node->perm = PERM_ROOT; node->userid = strtoul(node->name, NULL, 10); break; case PERM_ROOT: /* Assume masked off by default. */ if (!strcasecmp(node->name, "Android")) { /* App-specific directories inside; let anyone traverse */ node->perm = PERM_ANDROID; node->under_android = true; } break; case PERM_ANDROID: if (!strcasecmp(node->name, "data")) { /* App-specific directories inside; let anyone traverse */ node->perm = PERM_ANDROID_DATA; } else if (!strcasecmp(node->name, "obb")) { /* App-specific directories inside; let anyone traverse */ node->perm = PERM_ANDROID_OBB; /* Single OBB directory is always shared */ node->graft_path = fuse->global->obb_path; node->graft_pathlen = strlen(fuse->global->obb_path); } else if (!strcasecmp(node->name, "media")) { /* App-specific directories inside; let anyone traverse */ node->perm = PERM_ANDROID_MEDIA; } break; case PERM_ANDROID_DATA: case PERM_ANDROID_OBB: case PERM_ANDROID_MEDIA: appid = (appid_t) (uintptr_t) hashmapGet(fuse->global->package_to_appid, node->name); if (appid != 0) { node->uid = multiuser_get_uid(parent->userid, appid); } break; } } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: create_spnego_ctx(void) { spnego_gss_ctx_id_t spnego_ctx = NULL; spnego_ctx = (spnego_gss_ctx_id_t) malloc(sizeof (spnego_gss_ctx_id_rec)); if (spnego_ctx == NULL) { return (NULL); } spnego_ctx->magic_num = SPNEGO_MAGIC_ID; spnego_ctx->ctx_handle = GSS_C_NO_CONTEXT; spnego_ctx->mech_set = NULL; spnego_ctx->internal_mech = NULL; spnego_ctx->optionStr = NULL; spnego_ctx->DER_mechTypes.length = 0; spnego_ctx->DER_mechTypes.value = NULL; spnego_ctx->default_cred = GSS_C_NO_CREDENTIAL; spnego_ctx->mic_reqd = 0; spnego_ctx->mic_sent = 0; spnego_ctx->mic_rcvd = 0; spnego_ctx->mech_complete = 0; spnego_ctx->nego_done = 0; spnego_ctx->internal_name = GSS_C_NO_NAME; spnego_ctx->actual_mech = GSS_C_NO_OID; check_spnego_options(spnego_ctx); return (spnego_ctx); } CWE ID: CWE-18 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickExport void *ResizeQuantumMemory(void *memory,const size_t count, const size_t quantum) { size_t extent; if (CheckMemoryOverflow(count,quantum) != MagickFalse) { memory=RelinquishMagickMemory(memory); return((void *) NULL); } extent=count*quantum; return(ResizeMagickMemory(memory,extent)); } CWE ID: CWE-119 Target: 1 Example 2: Code: int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event, bool line_status) { if (!irqchip_in_kernel(kvm)) return -ENXIO; irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID, irq_event->irq, irq_event->level, line_status); 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: void LayerTreeHost::TriggerPrepaint() { prepaint_callback_.Cancel(); TRACE_EVENT0("cc", "LayerTreeHost::TriggerPrepaint"); SetNeedsCommit(); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct dentry *aio_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { static const struct dentry_operations ops = { .d_dname = simple_dname, }; return mount_pseudo(fs_type, "aio:", NULL, &ops, AIO_RING_MAGIC); } CWE ID: CWE-264 Target: 1 Example 2: Code: static void setInjectedScriptContextDebugId(v8::Handle<v8::Context> targetContext, int debugId) { V8PerContextDebugData::setContextDebugData(targetContext, "injected", debugId); } 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 snd_seq_control_queue(struct snd_seq_event *ev, int atomic, int hop) { struct snd_seq_queue *q; if (snd_BUG_ON(!ev)) return -EINVAL; q = queueptr(ev->data.queue.queue); if (q == NULL) return -EINVAL; if (! queue_access_lock(q, ev->source.client)) { queuefree(q); return -EPERM; } snd_seq_queue_process_event(q, ev, atomic, hop); queue_access_unlock(q); queuefree(q); return 0; } CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: jas_image_t *jas_image_create0() { jas_image_t *image; if (!(image = jas_malloc(sizeof(jas_image_t)))) { return 0; } image->tlx_ = 0; image->tly_ = 0; image->brx_ = 0; image->bry_ = 0; image->clrspc_ = JAS_CLRSPC_UNKNOWN; image->numcmpts_ = 0; image->maxcmpts_ = 0; image->cmpts_ = 0; image->inmem_ = true; //// image->inmem_ = true; image->cmprof_ = 0; return image; } CWE ID: CWE-190 Target: 1 Example 2: Code: GF_Err moof_Size(GF_Box *s) { GF_Err e; GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *)s; if (ptr->mfhd) { e = gf_isom_box_size((GF_Box *)ptr->mfhd); if (e) return e; ptr->size += ptr->mfhd->size; } return gf_isom_box_array_size(s, ptr->TrackList); } 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: parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; DebugLog(("parse_wbxml_attr (level = %u, offset = %u)\n", level, offset)); /* Parse attributes */ while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("ATTR: (top of while) level = %3u, peek = 0x%02X, " "off = %u, tvb_len = %u\n", level, peek, off, tvb_len)); if ((peek & 0x3F) < 5) switch (peek) { /* Global tokens in state = ATTR */ case 0x00: /* SWITCH_PAGE */ *codepage_attr = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Attr | A -->%3d " "| SWITCH_PAGE (Attr code page) |", *codepage_attr); off += 2; break; case 0x01: /* END */ /* BEWARE * The Attribute END token means either ">" or "/>" * and as a consequence both must be treated separately. * This is done in the TAG state parser. */ off++; DebugLog(("ATTR: level = %u, Return: len = %u\n", level, off - offset)); return (off - offset); case 0x02: /* ENTITY */ ent = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| ENTITY " "| %s'&#%u;'", level, *codepage_attr, Indent (level), ent); off += 1+len; break; case 0x03: /* STR_I */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| STR_I (Inline string) " "| %s\'%s\'", level, *codepage_attr, Indent (level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x04: /* LITERAL */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| LITERAL (Literal Attribute) " "| %s<%s />", level, *codepage_attr, Indent (level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; case 0x40: /* EXT_I_0 */ case 0x41: /* EXT_I_1 */ case 0x42: /* EXT_I_2 */ /* Extension tokens */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| EXT_I_%1x (Extension Token) " "| %s(Inline string extension: \'%s\')", level, *codepage_attr, peek & 0x0f, Indent (level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; /* 0x43 impossible in ATTR state */ /* 0x44 impossible in ATTR state */ case 0x80: /* EXT_T_0 */ case 0x81: /* EXT_T_1 */ case 0x82: /* EXT_T_2 */ /* Extension tokens */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| EXT_T_%1x (Extension Token) " "| %s(Extension Token, integer value: %u)", level, *codepage_attr, peek & 0x0f, Indent (level), idx); off += 1+len; break; case 0x83: /* STR_T */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Attr | A %3d " "| STR_T (Tableref string) " "| %s\'%s\'", level, *codepage_attr, Indent (level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; /* 0x84 impossible in ATTR state */ case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| EXT_%1x (Extension Token) " "| %s(Single-byte extension)", level, *codepage_attr, peek & 0x0f, Indent (level)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1 + len + idx, " %3d | Attr | A %3d " "| OPAQUE (Opaque data) " "| %s(%d bytes of opaque data)", level, *codepage_attr, Indent (level), idx); off += 1+len+idx; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", level, *codepage_attr); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("ATTR: level = %u, Return: len = %u\n", level, off - offset)); return (off - offset); } break; /* 0xC4 impossible in ATTR state */ default: proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| %-10s (Invalid Token!) " "| WBXML parsing stops here.", level, *codepage_attr, val_to_str_ext (peek, &vals_wbxml1x_global_tokens_ext, "(unknown 0x%x)")); /* Move to end of buffer */ off = tvb_len; break; } else { /* Known atribute token */ if (peek & 0x80) { /* attrValue */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| Known attrValue 0x%02X " "| %sattrValue_0x%02X", level, *codepage_attr, peek & 0x7f, Indent (level), peek); off++; } else { /* attrStart */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Attr | A %3d " "| Known attrStart 0x%02X " "| %sattrStart_0x%02X", level, *codepage_attr, peek & 0x7f, Indent (level), peek); off++; } } } /* End WHILE */ DebugLog(("ATTR: level = %u, Return: len = %u (end of function body)\n", level, off - offset)); return (off - offset); } CWE ID: CWE-119 Output:
1