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: lex(struct scanner *s, union lvalue *val) { skip_more_whitespace_and_comments: /* Skip spaces. */ while (is_space(peek(s))) if (next(s) == '\n') return TOK_END_OF_LINE; /* Skip comments. */ if (chr(s, '#')) { skip_to_eol(s); goto skip_more_whitespace_and_comments; } /* See if we're done. */ if (eof(s)) return TOK_END_OF_FILE; /* New token. */ s->token_line = s->line; s->token_column = s->column; s->buf_pos = 0; /* LHS Keysym. */ if (chr(s, '<')) { while (peek(s) != '>' && !eol(s)) buf_append(s, next(s)); if (!chr(s, '>')) { scanner_err(s, "unterminated keysym literal"); return TOK_ERROR; } if (!buf_append(s, '\0')) { scanner_err(s, "keysym literal is too long"); return TOK_ERROR; } val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_LHS_KEYSYM; } /* Colon. */ if (chr(s, ':')) return TOK_COLON; if (chr(s, '!')) return TOK_BANG; if (chr(s, '~')) return TOK_TILDE; /* String literal. */ if (chr(s, '\"')) { while (!eof(s) && !eol(s) && peek(s) != '\"') { if (chr(s, '\\')) { uint8_t o; if (chr(s, '\\')) { buf_append(s, '\\'); } else if (chr(s, '"')) { buf_append(s, '"'); } else if (chr(s, 'x') || chr(s, 'X')) { if (hex(s, &o)) buf_append(s, (char) o); else scanner_warn(s, "illegal hexadecimal escape sequence in string literal"); } else if (oct(s, &o)) { buf_append(s, (char) o); } else { scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s)); /* Ignore. */ } } else { buf_append(s, next(s)); } } if (!chr(s, '\"')) { scanner_err(s, "unterminated string literal"); return TOK_ERROR; } if (!buf_append(s, '\0')) { scanner_err(s, "string literal is too long"); return TOK_ERROR; } if (!is_valid_utf8(s->buf, s->buf_pos - 1)) { scanner_err(s, "string literal is not a valid UTF-8 string"); return TOK_ERROR; } val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_STRING; } /* Identifier or include. */ if (is_alpha(peek(s)) || peek(s) == '_') { s->buf_pos = 0; while (is_alnum(peek(s)) || peek(s) == '_') buf_append(s, next(s)); if (!buf_append(s, '\0')) { scanner_err(s, "identifier is too long"); return TOK_ERROR; } if (streq(s->buf, "include")) return TOK_INCLUDE; val->string.str = s->buf; val->string.len = s->buf_pos; return TOK_IDENT; } /* Discard rest of line. */ skip_to_eol(s); scanner_err(s, "unrecognized token"); return TOK_ERROR; } CWE ID: CWE-835 Target: 1 Example 2: Code: static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size) { VP56RangeCoder *c = &s->c; int header_size, hscale, vscale, ret; int width = s->avctx->width; int height = s->avctx->height; if (buf_size < 3) { av_log(s->avctx, AV_LOG_ERROR, "Insufficent data (%d) for header\n", buf_size); return AVERROR_INVALIDDATA; } s->keyframe = !(buf[0] & 1); s->profile = (buf[0]>>1) & 7; s->invisible = !(buf[0] & 0x10); header_size = AV_RL24(buf) >> 5; buf += 3; buf_size -= 3; if (s->profile > 3) av_log(s->avctx, AV_LOG_WARNING, "Unknown profile %d\n", s->profile); if (!s->profile) memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, sizeof(s->put_pixels_tab)); else // profile 1-3 use bilinear, 4+ aren't defined so whatever memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_bilinear_pixels_tab, sizeof(s->put_pixels_tab)); if (header_size > buf_size - 7 * s->keyframe) { av_log(s->avctx, AV_LOG_ERROR, "Header size larger than data provided\n"); return AVERROR_INVALIDDATA; } if (s->keyframe) { if (AV_RL24(buf) != 0x2a019d) { av_log(s->avctx, AV_LOG_ERROR, "Invalid start code 0x%x\n", AV_RL24(buf)); return AVERROR_INVALIDDATA; } width = AV_RL16(buf + 3) & 0x3fff; height = AV_RL16(buf + 5) & 0x3fff; hscale = buf[4] >> 6; vscale = buf[6] >> 6; buf += 7; buf_size -= 7; if (hscale || vscale) avpriv_request_sample(s->avctx, "Upscaling"); s->update_golden = s->update_altref = VP56_FRAME_CURRENT; vp78_reset_probability_tables(s); memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter, sizeof(s->prob->pred16x16)); memcpy(s->prob->pred8x8c, vp8_pred8x8c_prob_inter, sizeof(s->prob->pred8x8c)); memcpy(s->prob->mvc, vp8_mv_default_prob, sizeof(s->prob->mvc)); memset(&s->segmentation, 0, sizeof(s->segmentation)); memset(&s->lf_delta, 0, sizeof(s->lf_delta)); } ret = ff_vp56_init_range_decoder(c, buf, header_size); if (ret < 0) return ret; buf += header_size; buf_size -= header_size; if (s->keyframe) { s->colorspace = vp8_rac_get(c); if (s->colorspace) av_log(s->avctx, AV_LOG_WARNING, "Unspecified colorspace\n"); s->fullrange = vp8_rac_get(c); } if ((s->segmentation.enabled = vp8_rac_get(c))) parse_segment_info(s); else s->segmentation.update_map = 0; // FIXME: move this to some init function? s->filter.simple = vp8_rac_get(c); s->filter.level = vp8_rac_get_uint(c, 6); s->filter.sharpness = vp8_rac_get_uint(c, 3); if ((s->lf_delta.enabled = vp8_rac_get(c))) if (vp8_rac_get(c)) update_lf_deltas(s); if (setup_partitions(s, buf, buf_size)) { av_log(s->avctx, AV_LOG_ERROR, "Invalid partitions\n"); return AVERROR_INVALIDDATA; } if (!s->macroblocks_base || /* first frame */ width != s->avctx->width || height != s->avctx->height || (width+15)/16 != s->mb_width || (height+15)/16 != s->mb_height) if ((ret = vp8_update_dimensions(s, width, height)) < 0) return ret; vp8_get_quants(s); if (!s->keyframe) { update_refs(s); s->sign_bias[VP56_FRAME_GOLDEN] = vp8_rac_get(c); s->sign_bias[VP56_FRAME_GOLDEN2 /* altref */] = vp8_rac_get(c); } if (!(s->update_probabilities = vp8_rac_get(c))) s->prob[1] = s->prob[0]; s->update_last = s->keyframe || vp8_rac_get(c); vp78_update_probability_tables(s); if ((s->mbskip_enabled = vp8_rac_get(c))) s->prob->mbskip = vp8_rac_get_uint(c, 8); if (!s->keyframe) { s->prob->intra = vp8_rac_get_uint(c, 8); s->prob->last = vp8_rac_get_uint(c, 8); s->prob->golden = vp8_rac_get_uint(c, 8); vp78_update_pred16x16_pred8x8_mvc_probabilities(s, VP8_MVC_SIZE); } 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: SynchronousCompositorOutputSurface::DemandDrawHw( gfx::Size surface_size, const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { DCHECK(CalledOnValidThread()); DCHECK(HasClient()); DCHECK(context_provider_.get()); surface_size_ = surface_size; InvokeComposite(transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority, true); return frame_holder_.Pass(); } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void reflectStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); Element* impl = V8Element::toImpl(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::reflectstringattributeAttr), info.GetIsolate()); } CWE ID: CWE-189 Target: 1 Example 2: Code: static int sched_cpu_inactive(struct notifier_block *nfb, unsigned long action, void *hcpu) { unsigned long flags; long cpu = (long)hcpu; switch (action & ~CPU_TASKS_FROZEN) { case CPU_DOWN_PREPARE: set_cpu_active(cpu, false); /* explicitly allow suspend */ if (!(action & CPU_TASKS_FROZEN)) { struct dl_bw *dl_b = dl_bw_of(cpu); bool overflow; int cpus; raw_spin_lock_irqsave(&dl_b->lock, flags); cpus = dl_bw_cpus(cpu); overflow = __dl_overflow(dl_b, cpus, 0, 0); raw_spin_unlock_irqrestore(&dl_b->lock, flags); if (overflow) return notifier_from_errno(-EBUSY); } return NOTIFY_OK; } return NOTIFY_DONE; } 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 masq_inet_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = ((struct in_ifaddr *)ptr)->ifa_dev->dev; struct netdev_notifier_info info; netdev_notifier_info_init(&info, dev); return masq_device_event(this, event, &info); } 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: views::NonClientFrameView* ShellWindowViews::CreateNonClientFrameView( views::Widget* widget) { ShellWindowFrameView* frame_view = new ShellWindowFrameView(); frame_view->Init(window_); return frame_view; } CWE ID: CWE-79 Target: 1 Example 2: Code: int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, STACK_OF(X509) *certs, X509_STORE *store, unsigned int flags) { int r; flags &= ~(CMS_DETACHED | CMS_TEXT); r = CMS_verify(rcms, certs, store, NULL, NULL, flags); if (r <= 0) return r; return cms_Receipt_verify(rcms, ocms); } CWE ID: CWE-311 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewHostImpl::StopFinding(StopFindAction action) { Send(new ViewMsg_StopFinding(GetRoutingID(), action)); } 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 uint32_t readU16(const uint8_t* data, size_t offset) { return data[offset] << 8 | data[offset + 1]; } CWE ID: CWE-19 Target: 1 Example 2: Code: static void crypto_cbc_exit_tfm(struct crypto_tfm *tfm) { struct crypto_cbc_ctx *ctx = crypto_tfm_ctx(tfm); crypto_free_cipher(ctx->child); } 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 acl_mask_perm_str(acl_t acl, char *str) { acl_entry_t entry; str[0] = '\0'; if (acl_get_entry(acl, ACL_FIRST_ENTRY, &entry) != 1) return; for(;;) { acl_tag_t tag; acl_get_tag_type(entry, &tag); if (tag == ACL_MASK) { acl_perm_str(entry, str); return; } if (acl_get_entry(acl, ACL_NEXT_ENTRY, &entry) != 1) return; } } 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: GLOzone* X11SurfaceFactory::GetGLOzone(gl::GLImplementation implementation) { switch (implementation) { case gl::kGLImplementationDesktopGL: return glx_implementation_.get(); case gl::kGLImplementationEGLGLES2: return egl_implementation_.get(); default: return nullptr; } } CWE ID: CWE-284 Target: 1 Example 2: Code: int main(int argc, uschar **argv) { int i; uschar buffer[1024]; debug_selector = D_v; debug_file = stderr; debug_fd = fileno(debug_file); big_buffer = malloc(big_buffer_size); for (i = 1; i < argc; i++) { if (argv[i][0] == '+') { debug_trace_memory = 2; argv[i]++; } if (isdigit(argv[i][0])) debug_selector = Ustrtol(argv[i], NULL, 0); else if (Ustrspn(argv[i], "abcdefghijklmnopqrtsuvwxyz0123456789-.:/") == Ustrlen(argv[i])) { #ifdef LOOKUP_LDAP eldap_default_servers = argv[i]; #endif #ifdef LOOKUP_MYSQL mysql_servers = argv[i]; #endif #ifdef LOOKUP_PGSQL pgsql_servers = argv[i]; #endif #ifdef EXPERIMENTAL_REDIS redis_servers = argv[i]; #endif } #ifdef EXIM_PERL else opt_perl_startup = argv[i]; #endif } printf("Testing string expansion: debug_level = %d\n\n", debug_level); expand_nstring[1] = US"string 1...."; expand_nlength[1] = 8; expand_nmax = 1; #ifdef EXIM_PERL if (opt_perl_startup != NULL) { uschar *errstr; printf("Starting Perl interpreter\n"); errstr = init_perl(opt_perl_startup); if (errstr != NULL) { printf("** error in perl_startup code: %s\n", errstr); return EXIT_FAILURE; } } #endif /* EXIM_PERL */ while (fgets(buffer, sizeof(buffer), stdin) != NULL) { void *reset_point = store_get(0); uschar *yield = expand_string(buffer); if (yield != NULL) { printf("%s\n", yield); store_reset(reset_point); } else { if (search_find_defer) printf("search_find deferred\n"); printf("Failed: %s\n", expand_string_message); if (expand_string_forcedfail) printf("Forced failure\n"); printf("\n"); } } search_tidyup(); return 0; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ImageTransportFactory::Initialize() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kTestCompositor)) { ui::SetupTestCompositor(); } if (ui::IsTestCompositorEnabled()) { g_factory = new DefaultTransportFactory(); WebKitPlatformSupportImpl::SetOffscreenContextFactoryForTest( CreateTestContext); } else { g_factory = new GpuProcessTransportFactory(); } ui::ContextFactory::SetInstance(g_factory->AsContextFactory()); } 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 DocumentLoader::DidInstallNewDocument( Document* document, const ContentSecurityPolicy* previous_csp) { document->SetReadyState(Document::kLoading); if (content_security_policy_) { document->InitContentSecurityPolicy(content_security_policy_.Release(), nullptr, previous_csp); } if (history_item_ && IsBackForwardLoadType(load_type_)) document->SetStateForNewFormElements(history_item_->GetDocumentState()); DCHECK(document->GetFrame()); document->GetFrame()->GetClientHintsPreferences().UpdateFrom( client_hints_preferences_); Settings* settings = document->GetSettings(); fetcher_->SetImagesEnabled(settings->GetImagesEnabled()); fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically()); const AtomicString& dns_prefetch_control = response_.HttpHeaderField(http_names::kXDNSPrefetchControl); if (!dns_prefetch_control.IsEmpty()) document->ParseDNSPrefetchControlHeader(dns_prefetch_control); String header_content_language = response_.HttpHeaderField(http_names::kContentLanguage); if (!header_content_language.IsEmpty()) { wtf_size_t comma_index = header_content_language.find(','); header_content_language.Truncate(comma_index); header_content_language = header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>); if (!header_content_language.IsEmpty()) document->SetContentLanguage(AtomicString(header_content_language)); } String referrer_policy_header = response_.HttpHeaderField(http_names::kReferrerPolicy); if (!referrer_policy_header.IsNull()) { UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader); document->ParseAndSetReferrerPolicy(referrer_policy_header); } if (response_.IsSignedExchangeInnerResponse()) UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse); GetLocalFrameClient().DidCreateNewDocument(); } CWE ID: CWE-20 Target: 1 Example 2: Code: StateStore* ExtensionSystemImpl::Shared::rules_store() { return rules_store_.get(); } 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: hook_config (struct t_weechat_plugin *plugin, const char *option, t_hook_callback_config *callback, void *callback_data) { struct t_hook *new_hook; struct t_hook_config *new_hook_config; int priority; const char *ptr_option; if (!callback) return NULL; new_hook = malloc (sizeof (*new_hook)); if (!new_hook) return NULL; new_hook_config = malloc (sizeof (*new_hook_config)); if (!new_hook_config) { free (new_hook); return NULL; } hook_get_priority_and_name (option, &priority, &ptr_option); hook_init_data (new_hook, plugin, HOOK_TYPE_CONFIG, priority, callback_data); new_hook->hook_data = new_hook_config; new_hook_config->callback = callback; new_hook_config->option = strdup ((ptr_option) ? ptr_option : ((option) ? option : "")); hook_add_to_list (new_hook); return new_hook; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Chapters::Display::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 == 0x05) { // ChapterString ID status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) { // ChapterLanguage ID status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) { // ChapterCountry ID status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: void ewk_frame_redirect_provisional_load(Evas_Object* ewkFrame) { evas_object_smart_callback_call(ewkFrame, "redirect,load,provisional", 0); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( const ModelTypeSet enabled_types) { if (initialized_ && enabled_types.Has(syncable::SESSIONS)) { WriteTransaction trans(FROM_HERE, GetUserShare()); WriteNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { LOG(WARNING) << "Unable to set 'sync_tabs' bit because Nigori node not " << "found."; return; } sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics()); specifics.set_sync_tabs(true); node.SetNigoriSpecifics(specifics); } } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void sas_resume_port(struct asd_sas_phy *phy) { struct domain_device *dev; struct asd_sas_port *port = phy->port; struct sas_ha_struct *sas_ha = phy->ha; struct sas_internal *si = to_sas_internal(sas_ha->core.shost->transportt); if (si->dft->lldd_port_formed) si->dft->lldd_port_formed(phy); if (port->suspended) port->suspended = 0; else { /* we only need to handle "link returned" actions once */ return; } /* if the port came back: * 1/ presume every device came back * 2/ force the next revalidation to check all expander phys */ list_for_each_entry(dev, &port->dev_list, dev_list_node) { int i, rc; rc = sas_notify_lldd_dev_found(dev); if (rc) { sas_unregister_dev(port, dev); continue; } if (dev->dev_type == SAS_EDGE_EXPANDER_DEVICE || dev->dev_type == SAS_FANOUT_EXPANDER_DEVICE) { dev->ex_dev.ex_change_count = -1; for (i = 0; i < dev->ex_dev.num_phys; i++) { struct ex_phy *phy = &dev->ex_dev.ex_phy[i]; phy->phy_change_count = -1; } } } sas_discover_event(port, DISCE_RESUME); } CWE ID: Target: 1 Example 2: Code: LayoutTestContentBrowserClient::~LayoutTestContentBrowserClient() { g_layout_test_browser_client = nullptr; } 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 IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) { if (U_FAILURE(*status)) return; const icu::UnicodeSet* recommended_set = uspoof_getRecommendedUnicodeSet(status); icu::UnicodeSet allowed_set; allowed_set.addAll(*recommended_set); const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status); allowed_set.addAll(*inclusion_set); allowed_set.remove(0x338u); allowed_set.remove(0x58au); // Armenian Hyphen allowed_set.remove(0x2010u); allowed_set.remove(0x2019u); // Right Single Quotation Mark allowed_set.remove(0x2027u); allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe #if defined(OS_MACOSX) allowed_set.remove(0x0620u); allowed_set.remove(0x0F8Cu); allowed_set.remove(0x0F8Du); allowed_set.remove(0x0F8Eu); allowed_set.remove(0x0F8Fu); #endif allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status); } 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: bool ID3::removeUnsynchronizationV2_4(bool iTunesHack) { size_t oldSize = mSize; size_t offset = 0; while (mSize >= 10 && offset <= mSize - 10) { if (!memcmp(&mData[offset], "\0\0\0\0", 4)) { break; } size_t dataSize; if (iTunesHack) { dataSize = U32_AT(&mData[offset + 4]); } else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) { return false; } if (dataSize > mSize - 10 - offset) { return false; } uint16_t flags = U16_AT(&mData[offset + 8]); uint16_t prevFlags = flags; if (flags & 1) { if (mSize < 14 || mSize - 14 < offset || dataSize < 4) { return false; } memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14); mSize -= 4; dataSize -= 4; flags &= ~1; } if ((flags & 2) && (dataSize >= 2)) { size_t readOffset = offset + 11; size_t writeOffset = offset + 11; for (size_t i = 0; i + 1 < dataSize; ++i) { if (mData[readOffset - 1] == 0xff && mData[readOffset] == 0x00) { ++readOffset; --mSize; --dataSize; } mData[writeOffset++] = mData[readOffset++]; } if (readOffset <= oldSize) { memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset); } else { ALOGE("b/34618607 (%zu %zu %zu %zu)", readOffset, writeOffset, oldSize, mSize); android_errorWriteLog(0x534e4554, "34618607"); } } flags &= ~2; if (flags != prevFlags || iTunesHack) { WriteSyncsafeInteger(&mData[offset + 4], dataSize); mData[offset + 8] = flags >> 8; mData[offset + 9] = flags & 0xff; } offset += 10 + dataSize; } memset(&mData[mSize], 0, oldSize - mSize); return true; } CWE ID: CWE-200 Target: 1 Example 2: Code: void ssl2_clear(SSL *s) { SSL2_STATE *s2; unsigned char *rbuf, *wbuf; s2 = s->s2; rbuf = s2->rbuf; wbuf = s2->wbuf; memset(s2, 0, sizeof *s2); s2->rbuf = rbuf; s2->wbuf = wbuf; s2->clear_text = 1; s->packet = s2->rbuf; s->version = SSL2_VERSION; s->packet_length = 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: bool InputType::TypeMismatch() const { return false; } 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 ssize_t k90_show_current_profile(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct usb_interface *usbif = to_usb_interface(dev->parent); struct usb_device *usbdev = interface_to_usbdev(usbif); int current_profile; char data[8]; ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), K90_REQUEST_STATUS, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, data, 8, USB_CTRL_SET_TIMEOUT); if (ret < 0) { dev_warn(dev, "Failed to get K90 initial state (error %d).\n", ret); return -EIO; } current_profile = data[7]; if (current_profile < 1 || current_profile > 3) { dev_warn(dev, "Read invalid current profile: %02hhx.\n", data[7]); return -EIO; } return snprintf(buf, PAGE_SIZE, "%d\n", current_profile); } CWE ID: CWE-119 Target: 1 Example 2: Code: int __init ap_module_init(void) { int rc, i; if (ap_domain_index < -1 || ap_domain_index >= AP_DOMAINS) { pr_warning("%d is not a valid cryptographic domain\n", ap_domain_index); return -EINVAL; } /* In resume callback we need to know if the user had set the domain. * If so, we can not just reset it. */ if (ap_domain_index >= 0) user_set_domain = 1; if (ap_instructions_available() != 0) { pr_warning("The hardware system does not support " "AP instructions\n"); return -ENODEV; } if (ap_interrupts_available()) { rc = register_adapter_interrupt(&ap_airq); ap_airq_flag = (rc == 0); } register_reset_call(&ap_reset_call); /* Create /sys/bus/ap. */ rc = bus_register(&ap_bus_type); if (rc) goto out; for (i = 0; ap_bus_attrs[i]; i++) { rc = bus_create_file(&ap_bus_type, ap_bus_attrs[i]); if (rc) goto out_bus; } /* Create /sys/devices/ap. */ ap_root_device = root_device_register("ap"); rc = PTR_RET(ap_root_device); if (rc) goto out_bus; ap_work_queue = create_singlethread_workqueue("kapwork"); if (!ap_work_queue) { rc = -ENOMEM; goto out_root; } ap_query_configuration(); if (ap_select_domain() == 0) ap_scan_bus(NULL); /* Setup the AP bus rescan timer. */ init_timer(&ap_config_timer); ap_config_timer.function = ap_config_timeout; ap_config_timer.data = 0; ap_config_timer.expires = jiffies + ap_config_time * HZ; add_timer(&ap_config_timer); /* Setup the high resultion poll timer. * If we are running under z/VM adjust polling to z/VM polling rate. */ if (MACHINE_IS_VM) poll_timeout = 1500000; spin_lock_init(&ap_poll_timer_lock); hrtimer_init(&ap_poll_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS); ap_poll_timer.function = ap_poll_timeout; /* Start the low priority AP bus poll thread. */ if (ap_thread_flag) { rc = ap_poll_thread_start(); if (rc) goto out_work; } return 0; out_work: del_timer_sync(&ap_config_timer); hrtimer_cancel(&ap_poll_timer); destroy_workqueue(ap_work_queue); out_root: root_device_unregister(ap_root_device); out_bus: while (i--) bus_remove_file(&ap_bus_type, ap_bus_attrs[i]); bus_unregister(&ap_bus_type); out: unregister_reset_call(&ap_reset_call); if (ap_using_interrupts()) unregister_adapter_interrupt(&ap_airq); return rc; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SYSCALL_DEFINE1(setuid, uid_t, uid) { struct user_namespace *ns = current_user_ns(); const struct cred *old; struct cred *new; int retval; kuid_t kuid; kuid = make_kuid(ns, uid); if (!uid_valid(kuid)) return -EINVAL; new = prepare_creds(); if (!new) return -ENOMEM; old = current_cred(); retval = -EPERM; if (nsown_capable(CAP_SETUID)) { new->suid = new->uid = kuid; if (!uid_eq(kuid, old->uid)) { retval = set_user(new); if (retval < 0) goto error; } } else if (!uid_eq(kuid, old->uid) && !uid_eq(kuid, new->suid)) { goto error; } new->fsuid = new->euid = kuid; retval = security_task_fix_setuid(new, old, LSM_SETID_ID); if (retval < 0) goto error; return commit_creds(new); error: abort_creds(new); return retval; } CWE ID: CWE-16 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync( content::CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kUnconnected || gpu_channel_->state() == GpuChannelHost::kConnected) return GetGpuChannel(); gpu_channel_ = NULL; } int client_id = 0; IPC::ChannelHandle channel_handle; base::ProcessHandle renderer_process_for_gpu; content::GPUInfo gpu_info; if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch, &client_id, &channel_handle, &renderer_process_for_gpu, &gpu_info)) || channel_handle.name.empty() || #if defined(OS_POSIX) channel_handle.socket.fd == -1 || #endif renderer_process_for_gpu == base::kNullProcessHandle) { gpu_channel_ = NULL; return NULL; } gpu_channel_ = new GpuChannelHost(this, 0, client_id); gpu_channel_->set_gpu_info(gpu_info); content::GetContentClient()->SetGpuInfo(gpu_info); gpu_channel_->Connect(channel_handle, renderer_process_for_gpu); return GetGpuChannel(); } CWE ID: Target: 1 Example 2: Code: QTextCharFormat IRCView::getFormat(ObjectFormats x) { QTextCharFormat f; f.setObjectType(x); return f; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __init sha512_generic_mod_init(void) { return crypto_register_shashes(sha512_algs, ARRAY_SIZE(sha512_algs)); } 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: display_sigset( const char *msg, sigset_t *mask ) { int signo; NameTableIterator next_sig( SigNames ); if( msg ) { dprintf( D_ALWAYS, msg ); } while( (signo = next_sig()) != -1 ) { if( sigismember(mask,signo) ) { dprintf( D_ALWAYS | D_NOHEADER, "%s ", SigNames.get_name(signo) ); } } dprintf( D_ALWAYS | D_NOHEADER, "\n" ); } CWE ID: CWE-134 Target: 1 Example 2: Code: void addReplyHumanLongDouble(client *c, long double d) { robj *o = createStringObjectFromLongDouble(d,1); addReplyBulk(c,o); decrRefCount(o); } 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: virtual status_t allocateBufferWithBackup( node_id node, OMX_U32 port_index, const sp<IMemory> &params, buffer_id *buffer, OMX_U32 allottedSize) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeInt32(port_index); data.writeStrongBinder(IInterface::asBinder(params)); data.writeInt32(allottedSize); remote()->transact(ALLOC_BUFFER_WITH_BACKUP, data, &reply); status_t err = reply.readInt32(); if (err != OK) { *buffer = 0; return err; } *buffer = (buffer_id)reply.readInt32(); return err; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ int step=n/book->dim; ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j,o; if (!v) return -1; for (j=0;j<step;j++){ if(decode_map(book,b,v,point))return -1; for(i=0,o=j;i<book->dim;i++,o+=step) a[o]+=v[i]; } } return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: void OutOfProcessInstance::SelectFindResult(bool forward) { engine_->SelectFindResult(forward); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool ExecuteDeleteToEndOfParagraph(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.GetEditor().DeleteWithDirection(DeleteDirection::kForward, TextGranularity::kParagraphBoundary, true, false); return true; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool WebRequestPermissions::HideRequest( const extensions::InfoMap* extension_info_map, const extensions::WebRequestInfo& request) { if (request.is_web_view) return false; if (request.is_pac_request) return true; bool is_request_from_browser = request.render_process_id == -1; bool is_request_from_webui_renderer = false; if (!is_request_from_browser) { if (request.is_web_view) return false; if (extension_info_map && extension_info_map->process_map().Contains(extensions::kWebStoreAppId, request.render_process_id)) { return true; } is_request_from_webui_renderer = content::ChildProcessSecurityPolicy::GetInstance()->HasWebUIBindings( request.render_process_id); } return IsSensitiveURL(request.url, is_request_from_browser || is_request_from_webui_renderer) || !HasWebRequestScheme(request.url); } CWE ID: CWE-200 Target: 1 Example 2: Code: void ip_mc_dec_group(struct in_device *in_dev, __be32 addr) { struct ip_mc_list *i; struct ip_mc_list __rcu **ip; ASSERT_RTNL(); for (ip = &in_dev->mc_list; (i = rtnl_dereference(*ip)) != NULL; ip = &i->next_rcu) { if (i->multiaddr == addr) { if (--i->users == 0) { *ip = i->next_rcu; in_dev->mc_count--; igmp_group_dropped(i); ip_mc_clear_src(i); if (!in_dev->dead) ip_rt_multicast_event(in_dev); ip_ma_put(i); return; } break; } } } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int msg_parse_fetch(struct ImapHeader *h, char *s) { char tmp[SHORT_STRING]; char *ptmp = NULL; if (!s) return -1; while (*s) { SKIPWS(s); if (mutt_str_strncasecmp("FLAGS", s, 5) == 0) { s = msg_parse_flags(h, s); if (!s) return -1; } else if (mutt_str_strncasecmp("UID", s, 3) == 0) { s += 3; SKIPWS(s); if (mutt_str_atoui(s, &h->data->uid) < 0) return -1; s = imap_next_word(s); } else if (mutt_str_strncasecmp("INTERNALDATE", s, 12) == 0) { s += 12; SKIPWS(s); if (*s != '\"') { mutt_debug(1, "bogus INTERNALDATE entry: %s\n", s); return -1; } s++; ptmp = tmp; while (*s && *s != '\"') *ptmp++ = *s++; if (*s != '\"') return -1; s++; /* skip past the trailing " */ *ptmp = '\0'; h->received = mutt_date_parse_imap(tmp); } else if (mutt_str_strncasecmp("RFC822.SIZE", s, 11) == 0) { s += 11; SKIPWS(s); ptmp = tmp; while (isdigit((unsigned char) *s)) *ptmp++ = *s++; *ptmp = '\0'; if (mutt_str_atol(tmp, &h->content_length) < 0) return -1; } else if ((mutt_str_strncasecmp("BODY", s, 4) == 0) || (mutt_str_strncasecmp("RFC822.HEADER", s, 13) == 0)) { /* handle above, in msg_fetch_header */ return -2; } else if (*s == ')') s++; /* end of request */ else if (*s) { /* got something i don't understand */ imap_error("msg_parse_fetch", s); return -1; } } 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: OMX_ERRORTYPE SimpleSoftOMXComponent::useBuffer( OMX_BUFFERHEADERTYPE **header, OMX_U32 portIndex, OMX_PTR appPrivate, OMX_U32 size, OMX_U8 *ptr) { Mutex::Autolock autoLock(mLock); CHECK_LT(portIndex, mPorts.size()); *header = new OMX_BUFFERHEADERTYPE; (*header)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*header)->nVersion.s.nVersionMajor = 1; (*header)->nVersion.s.nVersionMinor = 0; (*header)->nVersion.s.nRevision = 0; (*header)->nVersion.s.nStep = 0; (*header)->pBuffer = ptr; (*header)->nAllocLen = size; (*header)->nFilledLen = 0; (*header)->nOffset = 0; (*header)->pAppPrivate = appPrivate; (*header)->pPlatformPrivate = NULL; (*header)->pInputPortPrivate = NULL; (*header)->pOutputPortPrivate = NULL; (*header)->hMarkTargetComponent = NULL; (*header)->pMarkData = NULL; (*header)->nTickCount = 0; (*header)->nTimeStamp = 0; (*header)->nFlags = 0; (*header)->nOutputPortIndex = portIndex; (*header)->nInputPortIndex = portIndex; PortInfo *port = &mPorts.editItemAt(portIndex); CHECK(mState == OMX_StateLoaded || port->mDef.bEnabled == OMX_FALSE); CHECK_LT(port->mBuffers.size(), port->mDef.nBufferCountActual); port->mBuffers.push(); BufferInfo *buffer = &port->mBuffers.editItemAt(port->mBuffers.size() - 1); buffer->mHeader = *header; buffer->mOwnedByUs = false; if (port->mBuffers.size() == port->mDef.nBufferCountActual) { port->mDef.bPopulated = OMX_TRUE; checkTransitions(); } return OMX_ErrorNone; } CWE ID: CWE-200 Target: 1 Example 2: Code: void WebUIBidiCheckerBrowserTestRTL::SetUpOnMainThread() { WebUIBidiCheckerBrowserTest::SetUpOnMainThread(); FilePath pak_path; app_locale_ = base::i18n::GetConfiguredLocale(); ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path)); pak_path = pak_path.DirName(); pak_path = pak_path.AppendASCII("pseudo_locales"); pak_path = pak_path.AppendASCII("fake-bidi"); pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak")); ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path); ResourceBundle::GetSharedInstance().ReloadLocaleResources("he"); base::i18n::SetICUDefaultLocale("he"); #if defined(OS_POSIX) && defined(TOOLKIT_GTK) gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL); #endif } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int do_video_set_spu_palette(unsigned int fd, unsigned int cmd, struct compat_video_spu_palette __user *up) { struct video_spu_palette __user *up_native; compat_uptr_t palp; int length, err; err = get_user(palp, &up->palette); err |= get_user(length, &up->length); up_native = compat_alloc_user_space(sizeof(struct video_spu_palette)); err = put_user(compat_ptr(palp), &up_native->palette); err |= put_user(length, &up_native->length); if (err) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) up_native); return err; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ int remaining = s->icy_metaint - s->icy_data_read; if (remaining < 0) return AVERROR_INVALIDDATA; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header * which sets the length of the packet (divided by 16). If it's 0, * the metadata doesn't change. After the packet, icy_metaint bytes * of normal data follows. */ uint8_t ch; int len = http_read_stream_all(h, &ch, 1); if (len < 0) return len; if (ch > 0) { char data[255 * 16 + 1]; int ret; len = ch * 16; ret = http_read_stream_all(h, data, len); if (ret < 0) return ret; data[len + 1] = 0; if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0) return ret; update_metadata(s, data); } s->icy_data_read = 0; remaining = s->icy_metaint; } return FFMIN(size, remaining); } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int ovl_check_sticky(struct dentry *dentry) { struct inode *dir = ovl_dentry_real(dentry->d_parent)->d_inode; struct inode *inode = ovl_dentry_real(dentry)->d_inode; if (check_sticky(dir, inode)) return -EPERM; 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: JSValue JSWebKitMutationObserver::observe(ExecState* exec) { if (exec->argumentCount() < 2) return throwError(exec, createTypeError(exec, "Not enough arguments")); Node* target = toNode(exec->argument(0)); if (exec->hadException()) return jsUndefined(); JSObject* optionsObject = exec->argument(1).getObject(); if (!optionsObject) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } JSDictionary dictionary(exec, optionsObject); MutationObserverOptions options = 0; for (unsigned i = 0; i < numBooleanOptions; ++i) { bool option = false; if (!dictionary.tryGetProperty(booleanOptions[i].name, option)) return jsUndefined(); if (option) options |= booleanOptions[i].value; } HashSet<AtomicString> attributeFilter; if (!dictionary.tryGetProperty("attributeFilter", attributeFilter)) return jsUndefined(); if (!attributeFilter.isEmpty()) options |= WebKitMutationObserver::AttributeFilter; ExceptionCode ec = 0; impl()->observe(target, options, attributeFilter, ec); if (ec) setDOMException(exec, ec); return jsUndefined(); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool AXNodeObject::isRequired() const { Node* n = this->getNode(); if (n && (n->isElementNode() && toElement(n)->isFormControlElement()) && hasAttribute(requiredAttr)) return toHTMLFormControlElement(n)->isRequired(); if (equalIgnoringCase(getAttribute(aria_requiredAttr), "true")) return true; return false; } CWE ID: CWE-254 Target: 1 Example 2: Code: sync_pb::EntitySpecifics DefaultBookmarkSpecifics() { sync_pb::EntitySpecifics result; AddDefaultFieldValue(syncable::BOOKMARKS, &result); return result; } 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 inline __kprobes int notify_page_fault(struct pt_regs *regs) { int ret = 0; /* kprobe_running() needs smp_processor_id() */ if (kprobes_built_in() && !user_mode(regs)) { preempt_disable(); if (kprobe_running() && kprobe_fault_handler(regs, 0)) ret = 1; preempt_enable(); } return ret; } 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 comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; COMPS_ObjListIt *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_ObjMRTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_ObjMRTreeData*)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_ObjMRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_ObjMRTreeData*)it->data)->key) + 1)); memcpy(pair->key, ((COMPS_ObjMRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_ObjMRTreeData*)it->data)->data->first != NULL) { for (it2 = ((COMPS_ObjMRTreeData*)it->data)->data->first; it2 != NULL; it2 = it2->next) { comps_objmrtree_set(rt1, pair->key, it2->comps_obj); } if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } /* current node hasn't data */ } else { if (((COMPS_ObjMRTreeData*)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 Target: 1 Example 2: Code: bool WebContentsImpl::ShouldPreserveAbortedURLs() { if (!delegate_) return false; return delegate_->ShouldPreserveAbortedURLs(this); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void idAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectPythonV8Internal::idAttributeGetter(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: status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || data_size < 8) { return ERROR_MALFORMED; } mSyncSampleOffset = data_offset; uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mNumSyncSamples = U32_AT(&header[4]); if (mNumSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } mSyncSamples = new uint32_t[mNumSyncSamples]; size_t size = mNumSyncSamples * sizeof(uint32_t); if (mDataSource->readAt(mSyncSampleOffset + 8, mSyncSamples, size) != (ssize_t)size) { return ERROR_IO; } for (size_t i = 0; i < mNumSyncSamples; ++i) { mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } return OK; } CWE ID: CWE-189 Target: 1 Example 2: Code: static void pmac_ide_writel (void *opaque, hwaddr addr, uint32_t val) { MACIOIDEState *d = opaque; addr = (addr & 0xFFF) >> 4; val = bswap32(val); if (addr == 0) { ide_data_writel(&d->bus, 0, val); } } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int hmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; struct shash_alg *salg; int err; int ds; int ss; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; salg = shash_attr_alg(tb[1], 0, 0); if (IS_ERR(salg)) return PTR_ERR(salg); err = -EINVAL; ds = salg->digestsize; ss = salg->statesize; alg = &salg->base; if (ds > alg->cra_blocksize || ss < alg->cra_blocksize) goto out_put_alg; inst = shash_alloc_instance("hmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_shash_spawn(shash_instance_ctx(inst), salg, shash_crypto_instance(inst)); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = alg->cra_blocksize; inst->alg.base.cra_alignmask = alg->cra_alignmask; ss = ALIGN(ss, alg->cra_alignmask + 1); inst->alg.digestsize = ds; inst->alg.statesize = ss; inst->alg.base.cra_ctxsize = sizeof(struct hmac_ctx) + ALIGN(ss * 2, crypto_tfm_ctx_alignment()); inst->alg.base.cra_init = hmac_init_tfm; inst->alg.base.cra_exit = hmac_exit_tfm; inst->alg.init = hmac_init; inst->alg.update = hmac_update; inst->alg.final = hmac_final; inst->alg.finup = hmac_finup; inst->alg.export = hmac_export; inst->alg.import = hmac_import; inst->alg.setkey = hmac_setkey; err = shash_register_instance(tmpl, inst); if (err) { out_free_inst: shash_free_instance(shash_crypto_instance(inst)); } out_put_alg: crypto_mod_put(alg); return err; } 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: int venc_dev::venc_input_log_buffers(OMX_BUFFERHEADERTYPE *pbuffer, int fd, int plane_offset) { if (!m_debug.infile) { int size = snprintf(m_debug.infile_name, PROPERTY_VALUE_MAX, "%s/input_enc_%lu_%lu_%p.yuv", m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); if ((size > PROPERTY_VALUE_MAX) && (size < 0)) { DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d", m_debug.infile_name, size); } m_debug.infile = fopen (m_debug.infile_name, "ab"); if (!m_debug.infile) { DEBUG_PRINT_HIGH("Failed to open input file: %s for logging", m_debug.infile_name); m_debug.infile_name[0] = '\0'; return -1; } } if (m_debug.infile && pbuffer && pbuffer->nFilledLen) { unsigned long i, msize; int stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, m_sVenc_cfg.input_width); int scanlines = VENUS_Y_SCANLINES(COLOR_FMT_NV12, m_sVenc_cfg.input_height); unsigned char *pvirt,*ptemp; char *temp = (char *)pbuffer->pBuffer; msize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height); if (metadatamode == 1) { pvirt= (unsigned char *)mmap(NULL, msize, PROT_READ|PROT_WRITE,MAP_SHARED, fd, plane_offset); if (pvirt) { ptemp = pvirt; for (i = 0; i < m_sVenc_cfg.input_height; i++) { fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile); ptemp += stride; } ptemp = pvirt + (stride * scanlines); for(i = 0; i < m_sVenc_cfg.input_height/2; i++) { fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile); ptemp += stride; } munmap(pvirt, msize); } else if (pvirt == MAP_FAILED) { DEBUG_PRINT_ERROR("%s mmap failed", __func__); return -1; } } else { for (i = 0; i < m_sVenc_cfg.input_height; i++) { fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile); temp += stride; } temp = (char *)pbuffer->pBuffer + (stride * scanlines); for(i = 0; i < m_sVenc_cfg.input_height/2; i++) { fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile); temp += stride; } } } return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: ecryptfs_write_header_metadata(char *virt, struct ecryptfs_crypt_stat *crypt_stat, size_t *written) { u32 header_extent_size; u16 num_header_extents_at_front; header_extent_size = (u32)crypt_stat->extent_size; num_header_extents_at_front = (u16)(crypt_stat->metadata_size / crypt_stat->extent_size); put_unaligned_be32(header_extent_size, virt); virt += 4; put_unaligned_be16(num_header_extents_at_front, virt); (*written) = 6; } 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: base::string16 GoogleChromeDistribution::GetPublisherName() { const base::string16& publisher_name = installer::GetLocalizedString(IDS_ABOUT_VERSION_COMPANY_NAME_BASE); return publisher_name; } 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 Encoder::EncodeFrameInternal(const VideoSource &video, const unsigned long frame_flags) { vpx_codec_err_t res; const vpx_image_t *img = video.img(); if (!encoder_.priv) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; cfg_.g_timebase = video.timebase(); cfg_.rc_twopass_stats_in = stats_->buf(); res = vpx_codec_enc_init(&encoder_, CodecInterface(), &cfg_, init_flags_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; res = vpx_codec_enc_config_set(&encoder_, &cfg_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } REGISTER_STATE_CHECK( res = vpx_codec_encode(&encoder_, video.img(), video.pts(), video.duration(), frame_flags, deadline_)); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } CWE ID: CWE-119 Target: 1 Example 2: Code: void WebGL2RenderingContextBase::endTransformFeedback() { if (isContextLost()) return; ContextGL()->EndTransformFeedback(); if (current_program_) current_program_->DecreaseActiveTransformFeedbackCount(); } 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 Browser::ShowHistoryTab() { UserMetrics::RecordAction(UserMetricsAction("ShowHistory"), profile_); ShowSingletonTab(GURL(chrome::kChromeUIHistoryURL)); } 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: kg_unseal_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_gss_ctx_id_rec *ctx; OM_uint32 code; ctx = (krb5_gss_ctx_id_rec *)context_handle; if (!ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) { code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } else { code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } return code; } CWE ID: Target: 1 Example 2: Code: static int fsmReadLink(const char *path, char *buf, size_t bufsize, size_t *linklen) { ssize_t llen = readlink(path, buf, bufsize - 1); int rc = RPMERR_READLINK_FAILED; if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, buf, %d) %s\n", __func__, path, (int)(bufsize -1), (llen < 0 ? strerror(errno) : "")); } if (llen >= 0) { buf[llen] = '\0'; rc = 0; *linklen = llen; } return rc; } 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: PepperDeviceEnumerationHostHelperTest() : ppapi_host_(&sink_, ppapi::PpapiPermissions()), resource_host_(&ppapi_host_, 12345, 67890), device_enumeration_(&resource_host_, &delegate_, PP_DEVICETYPE_DEV_AUDIOCAPTURE, GURL("http://example.com")) {} 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: ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr, bool *set_rtrn) { bool ok = false; const char *ident; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) { log_err(ctx, "Found constant of type %s where boolean was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *set_rtrn = expr->boolean.set; return true; case EXPR_IDENT: ident = xkb_atom_text(ctx, expr->ident.ident); if (ident) { if (istreq(ident, "true") || istreq(ident, "yes") || istreq(ident, "on")) { *set_rtrn = true; return true; } else if (istreq(ident, "false") || istreq(ident, "no") || istreq(ident, "off")) { *set_rtrn = false; return true; } } log_err(ctx, "Identifier \"%s\" of type boolean is unknown\n", ident); return false; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type boolean is unknown\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_INVERT: case EXPR_NOT: ok = ExprResolveBoolean(ctx, expr, set_rtrn); if (ok) *set_rtrn = !*set_rtrn; return ok; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: case EXPR_ASSIGN: case EXPR_NEGATE: case EXPR_UNARY_PLUS: log_err(ctx, "%s of boolean values not permitted\n", expr_op_type_to_string(expr->expr.op)); break; default: log_wsgo(ctx, "Unknown operator %d in ResolveBoolean\n", expr->expr.op); break; } return false; } CWE ID: CWE-400 Target: 1 Example 2: Code: void RenderFrameHostImpl::OnCreateChildFrame( int new_routing_id, service_manager::mojom::InterfaceProviderRequest new_interface_provider_provider_request, blink::WebTreeScopeType scope, const std::string& frame_name, const std::string& frame_unique_name, bool is_created_by_script, const base::UnguessableToken& devtools_frame_token, const blink::FramePolicy& frame_policy, const FrameOwnerProperties& frame_owner_properties) { DCHECK(!frame_unique_name.empty()); DCHECK(new_interface_provider_provider_request.is_pending()); if (!is_active() || !IsCurrent() || !render_frame_created_) return; frame_tree_->AddFrame(frame_tree_node_, GetProcess()->GetID(), new_routing_id, std::move(new_interface_provider_provider_request), scope, frame_name, frame_unique_name, is_created_by_script, devtools_frame_token, frame_policy, frame_owner_properties); } 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: SVGDocumentExtensions* Document::accessSVGExtensions() { if (!m_svgExtensions) m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this)); return m_svgExtensions.get(); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up) { size_t n; uint32_t types = up->types; p->types = types; for (n = 0; n < TEE_NUM_PARAMS; n++) { uintptr_t a = up->vals[n * 2]; size_t b = up->vals[n * 2 + 1]; switch (TEE_PARAM_TYPE_GET(types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: p->u[n].mem.mobj = &mobj_virt; p->u[n].mem.offs = a; p->u[n].mem.size = b; break; case TEE_PARAM_TYPE_VALUE_INPUT: case TEE_PARAM_TYPE_VALUE_INOUT: p->u[n].val.a = a; p->u[n].val.b = b; break; default: memset(&p->u[n], 0, sizeof(p->u[n])); break; } } } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline sector_t logical_to_blk(struct inode *inode, loff_t offset) { return (offset >> inode->i_blkbits); } 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 long media_device_enum_entities(struct media_device *mdev, struct media_entity_desc __user *uent) { struct media_entity *ent; struct media_entity_desc u_ent; if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id))) return -EFAULT; ent = find_entity(mdev, u_ent.id); if (ent == NULL) return -EINVAL; u_ent.id = ent->id; if (ent->name) { strncpy(u_ent.name, ent->name, sizeof(u_ent.name)); u_ent.name[sizeof(u_ent.name) - 1] = '\0'; } else { memset(u_ent.name, 0, sizeof(u_ent.name)); } u_ent.type = ent->type; u_ent.revision = ent->revision; u_ent.flags = ent->flags; u_ent.group_id = ent->group_id; u_ent.pads = ent->num_pads; u_ent.links = ent->num_links - ent->num_backlinks; memcpy(&u_ent.raw, &ent->info, sizeof(ent->info)); if (copy_to_user(uent, &u_ent, sizeof(u_ent))) return -EFAULT; return 0; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CoordinatorImpl::PerformNextQueuedGlobalMemoryDump() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (request == nullptr) return; std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); if (pid == base::kNullProcessId) { VLOG(1) << "Couldn't find a PID for client \"" << client_identity.name() << "." << client_identity.instance() << "\""; continue; } clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } auto chrome_callback = base::Bind( &CoordinatorImpl::OnChromeMemoryDumpResponse, base::Unretained(this)); auto os_callback = base::Bind(&CoordinatorImpl::OnOSMemoryDumpResponse, base::Unretained(this), request->dump_guid); QueuedRequestDispatcher::SetUpAndDispatch(request, clients, chrome_callback, os_callback); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnQueuedRequestTimedOut, base::Unretained(this), request->dump_guid), client_process_timeout_); if (request->args.add_to_trace && heap_profiler_) { request->heap_dump_in_progress = true; bool strip_path_from_mapped_files = base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( strip_path_from_mapped_files, base::BindRepeating(&CoordinatorImpl::OnDumpProcessesForTracing, base::Unretained(this), request->dump_guid)); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnHeapDumpTimeOut, base::Unretained(this), request->dump_guid), kHeapDumpTimeout); } FinalizeGlobalMemoryDumpIfAllManagersReplied(); } CWE ID: CWE-416 Target: 1 Example 2: Code: static inline int SlabFrozen(struct page *page) { return page->flags & FROZEN; } 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 WebsiteSettingsPopupAndroid::RegisterWebsiteSettingsPopupAndroid( JNIEnv* env) { return RegisterNativesImpl(env); } 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 rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct ipv6_txoptions opt_space; DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name); struct in6_addr *daddr, *final_p, final; struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct raw6_sock *rp = raw6_sk(sk); struct ipv6_txoptions *opt = NULL; struct ip6_flowlabel *flowlabel = NULL; struct dst_entry *dst = NULL; struct raw6_frag_vec rfv; struct flowi6 fl6; int addr_len = msg->msg_namelen; int hlimit = -1; int tclass = -1; int dontfrag = -1; u16 proto; int err; /* Rough check on arithmetic overflow, better check is made in ip6_append_data(). */ if (len > INT_MAX) return -EMSGSIZE; /* Mirror BSD error message compatibility */ if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; /* * Get and verify the address. */ memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_mark = sk->sk_mark; if (sin6) { if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (sin6->sin6_family && sin6->sin6_family != AF_INET6) return -EAFNOSUPPORT; /* port is the proto value [0..255] carried in nexthdr */ proto = ntohs(sin6->sin6_port); if (!proto) proto = inet->inet_num; else if (proto != inet->inet_num) return -EINVAL; if (proto > 255) return -EINVAL; daddr = &sin6->sin6_addr; if (np->sndflow) { fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } } /* * Otherwise it will be difficult to maintain * sk->sk_dst_cache. */ if (sk->sk_state == TCP_ESTABLISHED && ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) daddr = &sk->sk_v6_daddr; if (addr_len >= sizeof(struct sockaddr_in6) && sin6->sin6_scope_id && __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr))) fl6.flowi6_oif = sin6->sin6_scope_id; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; proto = inet->inet_num; daddr = &sk->sk_v6_daddr; fl6.flowlabel = np->flow_label; } if (fl6.flowi6_oif == 0) fl6.flowi6_oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { opt = &opt_space; memset(opt, 0, sizeof(struct ipv6_txoptions)); opt->tot_len = sizeof(struct ipv6_txoptions); err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, &hlimit, &tclass, &dontfrag); if (err < 0) { fl6_sock_release(flowlabel); return err; } if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } if (!(opt->opt_nflen|opt->opt_flen)) opt = NULL; } if (!opt) opt = np->opt; if (flowlabel) opt = fl6_merge_options(&opt_space, flowlabel, opt); opt = ipv6_fixup_options(&opt_space, opt); fl6.flowi6_proto = proto; rfv.msg = msg; rfv.hlen = 0; err = rawv6_probe_proto_opt(&rfv, &fl6); if (err) goto out; if (!ipv6_addr_any(daddr)) fl6.daddr = *daddr; else fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) fl6.saddr = np->saddr; final_p = fl6_update_dst(&fl6, opt, &final); if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) fl6.flowi6_oif = np->mcast_oif; else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); if (inet->hdrincl) fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH; dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); goto out; } if (hlimit < 0) hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); if (tclass < 0) tclass = np->tclass; if (dontfrag < 0) dontfrag = np->dontfrag; if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: if (inet->hdrincl) err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags); else { lock_sock(sk); err = ip6_append_data(sk, raw6_getfrag, &rfv, len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, msg->msg_flags, dontfrag); if (err) ip6_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) err = rawv6_push_pending_frames(sk, &fl6, rp); release_sock(sk); } done: dst_release(dst); out: fl6_sock_release(flowlabel); return err < 0 ? err : len; do_confirm: dst_confirm(dst); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } CWE ID: CWE-416 Target: 1 Example 2: Code: static void burl_normalize_qs20_to_plus_fix (buffer *b, int i) { char * const s = b->ptr; const int used = (int)buffer_string_length(b); int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == '0') { s[j] = '+'; i+=2; } } buffer_string_set_length(b, j); } 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: interlace_row(png_bytep buffer, png_const_bytep imageRow, unsigned int pixel_size, png_uint_32 w, int pass) { png_uint_32 xin, xout, xstep; /* Note that this can, trivially, be optimized to a memcpy on pass 7, the * code is presented this way to make it easier to understand. In practice * consult the code in the libpng source to see other ways of doing this. */ xin = PNG_PASS_START_COL(pass); xstep = 1U<<PNG_PASS_COL_SHIFT(pass); for (xout=0; xin<w; xin+=xstep) { pixel_copy(buffer, xout, imageRow, xin, pixel_size); ++xout; } } 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: BGD_DECLARE(void *) gdImageWebpPtrEx (gdImagePtr im, int *size, int quality) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (out == NULL) { return NULL; } gdImageWebpCtx(im, out, quality); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } CWE ID: CWE-415 Target: 1 Example 2: Code: void RenderFrameImpl::AllowBindings(int32_t enabled_bindings_flags) { if (IsMainFrame() && (enabled_bindings_flags & BINDINGS_POLICY_WEB_UI) && !(enabled_bindings_ & BINDINGS_POLICY_WEB_UI)) { new WebUIExtensionData(render_view_); } enabled_bindings_ |= enabled_bindings_flags; RenderProcess::current()->AddBindings(enabled_bindings_flags); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void tipc_sk_timeout(unsigned long data) { struct tipc_sock *tsk = (struct tipc_sock *)data; struct sock *sk = &tsk->sk; struct sk_buff *skb = NULL; u32 peer_port, peer_node; u32 own_node = tsk_own_node(tsk); bh_lock_sock(sk); if (!tsk->connected) { bh_unlock_sock(sk); goto exit; } peer_port = tsk_peer_port(tsk); peer_node = tsk_peer_node(tsk); if (tsk->probing_state == TIPC_CONN_PROBING) { if (!sock_owned_by_user(sk)) { sk->sk_socket->state = SS_DISCONNECTING; tsk->connected = 0; tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk), tsk_peer_port(tsk)); sk->sk_state_change(sk); } else { /* Try again later */ sk_reset_timer(sk, &sk->sk_timer, (HZ / 20)); } } else { skb = tipc_msg_create(CONN_MANAGER, CONN_PROBE, INT_H_SIZE, 0, peer_node, own_node, peer_port, tsk->portid, TIPC_OK); tsk->probing_state = TIPC_CONN_PROBING; sk_reset_timer(sk, &sk->sk_timer, jiffies + tsk->probing_intv); } bh_unlock_sock(sk); if (skb) tipc_node_xmit_skb(sock_net(sk), skb, peer_node, tsk->portid); exit: sock_put(sk); } 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: UnacceleratedStaticBitmapImage::UnacceleratedStaticBitmapImage( sk_sp<SkImage> image) { CHECK(image); DCHECK(!image->isLazyGenerated()); paint_image_ = CreatePaintImageBuilder() .set_image(std::move(image), cc::PaintImage::GetNextContentId()) .TakePaintImage(); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool InspectorClientImpl::overridesShowPaintRects() { return m_inspectedWebView->isAcceleratedCompositingActive(); } 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 AddChunk(sk_sp<PaintRecord> record, const TransformPaintPropertyNode* t, const ClipPaintPropertyNode* c, const EffectPaintPropertyNode* e, const FloatRect& bounds = FloatRect(0, 0, 100, 100)) { size_t i = items.size(); items.AllocateAndConstruct<DrawingDisplayItem>( DefaultId().client, DefaultId().type, std::move(record)); chunks.emplace_back(i, i + 1, DefaultId(), PropertyTreeState(t, c, e)); chunks.back().bounds = bounds; } 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: DOMFileSystemSync* WorkerGlobalScopeFileSystem::webkitRequestFileSystemSync(WorkerGlobalScope& worker, int type, long long size, ExceptionState& exceptionState) { ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem()) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } FileSystemType fileSystemType = static_cast<FileSystemType>(type); if (!DOMFileSystemBase::isValidType(fileSystemType)) { exceptionState.throwDOMException(InvalidModificationError, "the type must be TEMPORARY or PERSISTENT."); return 0; } RefPtr<FileSystemSyncCallbackHelper> helper = FileSystemSyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = FileSystemCallbacks::create(helper->successCallback(), helper->errorCallback(), &worker, fileSystemType); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->requestFileSystem(&worker, fileSystemType, size, callbacks.release()); return helper->getResult(exceptionState); } CWE ID: CWE-119 Target: 1 Example 2: Code: ext4_ext_new_meta_block(handle_t *handle, struct inode *inode, struct ext4_ext_path *path, struct ext4_extent *ex, int *err, unsigned int flags) { ext4_fsblk_t goal, newblock; goal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block)); newblock = ext4_new_meta_blocks(handle, inode, goal, flags, NULL, err); return newblock; } 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: TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() { return touchpad_lib_.GetDefaultImpl(use_stub_impl_); } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ImageCapture::ResolveWithMediaTrackConstraints( MediaTrackConstraints constraints, ScriptPromiseResolver* resolver) { DCHECK(resolver); resolver->Resolve(constraints); } CWE ID: CWE-416 Target: 1 Example 2: Code: static inline IntSize adjustedScrollDelta(const IntSize& delta) { return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height())); } 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 voidMethodDefaultUndefinedStringArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::voidMethodDefaultUndefinedStringArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WtsSessionProcessDelegate::Core::OnJobNotification(DWORD message, DWORD pid) { DCHECK(main_task_runner_->BelongsToCurrentThread()); switch (message) { case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: CHECK(SetEvent(process_exit_event_)); break; case JOB_OBJECT_MSG_NEW_PROCESS: worker_process_.Set(OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid)); break; } } CWE ID: CWE-399 Target: 1 Example 2: Code: static inline void unlock_timer(struct k_itimer *timr, unsigned long flags) { spin_unlock_irqrestore(&timr->it_lock, flags); } 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: void DevToolsWindow::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CHECK(web_contents_->GetURL().SchemeIs(chrome::kChromeDevToolsScheme)); if (!file_helper_->IsFileSystemAdded(file_system_path)) { SearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } file_system_indexer_->SearchInPath(file_system_path, query, Bind(&DevToolsWindow::SearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } 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: DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents) : profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_)), web_contents_(web_contents), delegate_(new DefaultBindingsDelegate(web_contents_)), devices_updates_enabled_(false), frontend_loaded_(false), reloading_(false), weak_factory_(this) { g_instances.Get().push_back(this); frontend_contents_observer_.reset(new FrontendWebContentsObserver(this)); web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false; file_helper_.reset(new DevToolsFileHelper(web_contents_, profile_, this)); file_system_indexer_ = new DevToolsFileSystemIndexer(); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_); embedder_message_dispatcher_.reset( DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); frontend_host_.reset(content::DevToolsFrontendHost::Create( web_contents_->GetMainFrame(), base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, base::Unretained(this)))); } CWE ID: CWE-200 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; struct net *net = sock_net(sk); if (!ns_capable(net->user_ns, 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; tmp.name[sizeof(tmp.name) - 1] = '\0'; t = find_table_lock(net, 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-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 Document::detach(const AttachContext& context) { TRACE_EVENT0("blink", "Document::detach"); ASSERT(!m_frame || m_frame->tree().childCount() == 0); if (!isActive()) return; FrameNavigationDisabler navigationDisabler(*m_frame); HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates; ScriptForbiddenScope forbidScript; view()->dispose(); m_markers->prepareForDestruction(); if (LocalDOMWindow* window = this->domWindow()) window->willDetachDocumentFromFrame(); m_lifecycle.advanceTo(DocumentLifecycle::Stopping); if (page()) page()->documentDetached(this); InspectorInstrumentation::documentDetached(this); if (m_frame->loader().client()->sharedWorkerRepositoryClient()) m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this); stopActiveDOMObjects(); if (m_scriptedAnimationController) m_scriptedAnimationController->clearDocumentPointer(); m_scriptedAnimationController.clear(); m_scriptedIdleTaskController.clear(); if (svgExtensions()) accessSVGExtensions().pauseAnimations(); if (m_domWindow) m_domWindow->clearEventQueue(); if (m_layoutView) m_layoutView->setIsInWindow(false); if (registrationContext()) registrationContext()->documentWasDetached(); m_hoverNode = nullptr; m_activeHoverElement = nullptr; m_autofocusElement = nullptr; if (m_focusedElement.get()) { RefPtrWillBeRawPtr<Element> oldFocusedElement = m_focusedElement; m_focusedElement = nullptr; if (frameHost()) frameHost()->chromeClient().focusedNodeChanged(oldFocusedElement.get(), nullptr); } if (this == &axObjectCacheOwner()) clearAXObjectCache(); m_layoutView = nullptr; ContainerNode::detach(context); if (this != &axObjectCacheOwner()) { if (AXObjectCache* cache = existingAXObjectCache()) { for (Node& node : NodeTraversal::descendantsOf(*this)) { cache->remove(&node); } } } styleEngine().didDetach(); frameHost()->eventHandlerRegistry().documentDetached(*this); m_frame->inputMethodController().documentDetached(); if (!loader()) m_fetcher->clearContext(); if (m_importsController) HTMLImportsController::removeFrom(*this); m_timers.setTimerTaskRunner( Platform::current()->currentThread()->scheduler()->timerTaskRunner()->adoptClone()); m_frame = nullptr; if (m_mediaQueryMatcher) m_mediaQueryMatcher->documentDetached(); DocumentLifecycleNotifier::notifyDocumentWasDetached(); m_lifecycle.advanceTo(DocumentLifecycle::Stopped); DocumentLifecycleNotifier::notifyContextDestroyed(); ExecutionContext::notifyContextDestroyed(); } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; uint32_t addr; mcf_fec_bd bd; int frame_size; int len; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; ptr = frame; ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (1) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } } CWE ID: CWE-399 Target: 1 Example 2: Code: static void mark_reg_unknown_value_and_range(struct bpf_reg_state *regs, u32 regno) { mark_reg_unknown_value(regs, regno); reset_reg_range_values(regs, regno); } 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: local void help(void) { int n; if (g.verbosity == 0) return; for (n = 0; n < (int)(sizeof(helptext) / sizeof(char *)); n++) fprintf(stderr, "%s\n", helptext[n]); fflush(stderr); exit(0); } CWE ID: CWE-22 Output:
0
Here are some example code snippets. Analyze the following 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 ChromeOSSetImeConfig(InputMethodStatusConnection* connection, const char* section, const char* config_name, const ImeConfigValue& value) { DCHECK(section); DCHECK(config_name); g_return_val_if_fail(connection, FALSE); return connection->SetImeConfig(section, config_name, value); } CWE ID: CWE-399 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoCreateTransferCacheEntryINTERNAL( GLuint entry_type, GLuint entry_id, GLuint handle_shm_id, GLuint handle_shm_offset, GLuint data_shm_id, GLuint data_shm_offset, GLuint data_size) { 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: static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */ 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: NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { } CWE ID: CWE-20 Target: 1 Example 2: Code: int32_t SiteInstanceImpl::GetId() { return id_; } CWE ID: CWE-285 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameHostImpl::ExecuteMediaPlayerActionAtLocation( const gfx::Point& location, const blink::WebMediaPlayerAction& action) { gfx::PointF point_in_view = GetView()->TransformRootPointToViewCoordSpace( gfx::PointF(location.x(), location.y())); Send(new FrameMsg_MediaPlayerActionAt(routing_id_, point_in_view, action)); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags) { struct mem_cgroup *memcg; struct page *page; spinlock_t *ptl; pte_t entry; pte_unmap(page_table); /* Check if we need to add a guard page to the stack */ if (check_stack_guard_page(vma, address) < 0) return VM_FAULT_SIGSEGV; /* Use the zero-page for reads */ if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm)) { entry = pte_mkspecial(pfn_pte(my_zero_pfn(address), vma->vm_page_prot)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto unlock; goto setpte; } /* Allocate our own private page. */ if (unlikely(anon_vma_prepare(vma))) goto oom; page = alloc_zeroed_user_highpage_movable(vma, address); if (!page) goto oom; if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg)) goto oom_free_page; /* * The memory barrier inside __SetPageUptodate makes sure that * preceeding stores to the page contents become visible before * the set_pte_at() write. */ __SetPageUptodate(page); entry = mk_pte(page, vma->vm_page_prot); if (vma->vm_flags & VM_WRITE) entry = pte_mkwrite(pte_mkdirty(entry)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto release; inc_mm_counter_fast(mm, MM_ANONPAGES); page_add_new_anon_rmap(page, vma, address); mem_cgroup_commit_charge(page, memcg, false); lru_cache_add_active_or_unevictable(page, vma); setpte: set_pte_at(mm, address, page_table, entry); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); return 0; release: mem_cgroup_cancel_charge(page, memcg); page_cache_release(page); goto unlock; oom_free_page: page_cache_release(page); oom: return VM_FAULT_OOM; } CWE ID: CWE-20 Target: 1 Example 2: Code: std::unique_ptr<TracedValue> InspectorRecalculateStylesEvent::Data( LocalFrame* frame) { std::unique_ptr<TracedValue> value = TracedValue::Create(); value->SetString("frame", ToHexString(frame)); SetCallStack(value.get()); return value; } 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: rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail) { struct rar *rar = (struct rar *)(a->format->data); const void *h = __archive_read_ahead(a, min, avail); int ret; if (avail) { if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested) *avail = a->archive.read_data_requested; if (*avail > rar->bytes_remaining) *avail = (ssize_t)rar->bytes_remaining; if (*avail < 0) return NULL; else if (*avail == 0 && rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER) { ret = archive_read_format_rar_read_header(a, a->entry); if (ret == (ARCHIVE_EOF)) { rar->has_endarc_header = 1; ret = archive_read_format_rar_read_header(a, a->entry); } if (ret != (ARCHIVE_OK)) return NULL; return rar_read_ahead(a, min, avail); } } return h; } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void color_cmyk_to_rgb(opj_image_t *image) { float C, M, Y, K; float sC, sM, sY, sK; unsigned int w, h, max, i; w = image->comps[0].w; h = image->comps[0].h; if(image->numcomps < 4) return; max = w * h; sC = 1.0F / (float)((1 << image->comps[0].prec) - 1); sM = 1.0F / (float)((1 << image->comps[1].prec) - 1); sY = 1.0F / (float)((1 << image->comps[2].prec) - 1); sK = 1.0F / (float)((1 << image->comps[3].prec) - 1); for(i = 0; i < max; ++i) { /* CMYK values from 0 to 1 */ C = (float)(image->comps[0].data[i]) * sC; M = (float)(image->comps[1].data[i]) * sM; Y = (float)(image->comps[2].data[i]) * sY; K = (float)(image->comps[3].data[i]) * sK; /* Invert all CMYK values */ C = 1.0F - C; M = 1.0F - M; Y = 1.0F - Y; K = 1.0F - K; /* CMYK -> RGB : RGB results from 0 to 255 */ image->comps[0].data[i] = (int)(255.0F * C * K); /* R */ image->comps[1].data[i] = (int)(255.0F * M * K); /* G */ image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */ } free(image->comps[3].data); image->comps[3].data = NULL; image->comps[0].prec = 8; image->comps[1].prec = 8; image->comps[2].prec = 8; image->numcomps -= 1; image->color_space = OPJ_CLRSPC_SRGB; for (i = 3; i < image->numcomps; ++i) { memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i])); } }/* color_cmyk_to_rgb() */ CWE ID: CWE-119 Target: 1 Example 2: Code: WebContentsAndroid::~WebContentsAndroid() { Java_WebContentsImpl_clearNativePtr(AttachCurrentThread(), obj_.obj()); } 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: MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t extent, packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; default: break; } extent=MagickMax(image->columns,image->rows); if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*extent*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*extent*quantum_info->depth+7)/8)); } 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 SoftVPXEncoder::onQueueFilled(OMX_U32 /* portIndex */) { if (mCodecContext == NULL) { if (OK != initEncoder()) { ALOGE("Failed to initialize encoder"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } } vpx_codec_err_t codec_return; List<BufferInfo *> &inputBufferInfoQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outputBufferInfoQueue = getPortQueue(kOutputPortIndex); while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) { BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader; BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin(); OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader; if ((inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) && inputBufferHeader->nFilledLen == 0) { inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); inputBufferInfo->mOwnedByUs = false; notifyEmptyBufferDone(inputBufferHeader); outputBufferHeader->nFilledLen = 0; outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); outputBufferInfo->mOwnedByUs = false; notifyFillBufferDone(outputBufferHeader); return; } const uint8_t *source = inputBufferHeader->pBuffer + inputBufferHeader->nOffset; if (mInputDataIsMeta) { source = extractGraphicBuffer( mConversionBuffer, mWidth * mHeight * 3 / 2, source, inputBufferHeader->nFilledLen, mWidth, mHeight); if (source == NULL) { ALOGE("Unable to extract gralloc buffer in metadata mode"); notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); return; } } else if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { ConvertYUV420SemiPlanarToYUV420Planar( source, mConversionBuffer, mWidth, mHeight); source = mConversionBuffer; } vpx_image_t raw_frame; vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight, kInputBufferAlignment, (uint8_t *)source); vpx_enc_frame_flags_t flags = 0; if (mTemporalPatternLength > 0) { flags = getEncodeFlags(); } if (mKeyFrameRequested) { flags |= VPX_EFLAG_FORCE_KF; mKeyFrameRequested = false; } if (mBitrateUpdated) { mCodecConfiguration->rc_target_bitrate = mBitrate/1000; vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext, mCodecConfiguration); if (res != VPX_CODEC_OK) { ALOGE("vp8 encoder failed to update bitrate: %s", vpx_codec_err_to_string(res)); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer } mBitrateUpdated = false; } uint32_t frameDuration; if (inputBufferHeader->nTimeStamp > mLastTimestamp) { frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp); } else { frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate); } mLastTimestamp = inputBufferHeader->nTimeStamp; codec_return = vpx_codec_encode( mCodecContext, &raw_frame, inputBufferHeader->nTimeStamp, // in timebase units frameDuration, // frame duration in timebase units flags, // frame flags VPX_DL_REALTIME); // encoding deadline if (codec_return != VPX_CODEC_OK) { ALOGE("vpx encoder failed to encode frame"); notify(OMX_EventError, OMX_ErrorUndefined, 0, // Extra notification data NULL); // Notification data pointer return; } vpx_codec_iter_t encoded_packet_iterator = NULL; const vpx_codec_cx_pkt_t* encoded_packet; while ((encoded_packet = vpx_codec_get_cx_data( mCodecContext, &encoded_packet_iterator))) { if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) { outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts; outputBufferHeader->nFlags = 0; if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY) outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; outputBufferHeader->nOffset = 0; outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz; memcpy(outputBufferHeader->pBuffer, encoded_packet->data.frame.buf, encoded_packet->data.frame.sz); outputBufferInfo->mOwnedByUs = false; outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) { outputBufferHeader->nFlags |= OMX_BUFFERFLAG_EOS; } notifyFillBufferDone(outputBufferHeader); } } inputBufferInfo->mOwnedByUs = false; inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); notifyEmptyBufferDone(inputBufferHeader); } } CWE ID: CWE-264 Target: 1 Example 2: Code: void PostNextAfterDraw(LayerTreeHostImpl* host_impl) { if (posted_) return; posted_ = true; ImplThreadTaskRunner()->PostDelayedTask( FROM_HERE, base::Bind(&LayerTreeHostTestCrispUpAfterPinchEnds::Next, base::Unretained(this), host_impl), base::TimeDelta::FromMilliseconds(16 * 4)); } 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: int Chapters::Edition::GetAtomCount() const { return m_atoms_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: xscale1pmu_handle_irq(int irq_num, void *dev) { unsigned long pmnc; struct perf_sample_data data; struct cpu_hw_events *cpuc; struct pt_regs *regs; int idx; /* * NOTE: there's an A stepping erratum that states if an overflow * bit already exists and another occurs, the previous * Overflow bit gets cleared. There's no workaround. * Fixed in B stepping or later. */ pmnc = xscale1pmu_read_pmnc(); /* * Write the value back to clear the overflow flags. Overflow * flags remain in pmnc for use below. We also disable the PMU * while we process the interrupt. */ xscale1pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE); if (!(pmnc & XSCALE1_OVERFLOWED_MASK)) return IRQ_NONE; regs = get_irq_regs(); perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); for (idx = 0; idx <= armpmu->num_events; ++idx) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc; if (!test_bit(idx, cpuc->active_mask)) continue; if (!xscale1_pmnc_counter_has_overflowed(pmnc, idx)) continue; hwc = &event->hw; armpmu_event_update(event, hwc, idx, 1); data.period = event->hw.last_period; if (!armpmu_event_set_period(event, hwc, idx)) continue; if (perf_event_overflow(event, 0, &data, regs)) armpmu->disable(hwc, idx); } irq_work_run(); /* * Re-enable the PMU. */ pmnc = xscale1pmu_read_pmnc() | XSCALE_PMU_ENABLE; xscale1pmu_write_pmnc(pmnc); return IRQ_HANDLED; } CWE ID: CWE-399 Target: 1 Example 2: Code: base::Time CaptivePortalDetector::GetCurrentTime() const { if (time_for_testing_.is_null()) return base::Time::Now(); else return time_for_testing_; } 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 vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); int max_irr; void *vapic_page; u16 status; if (vmx->nested.pi_desc && vmx->nested.pi_pending) { vmx->nested.pi_pending = false; if (!pi_test_and_clear_on(vmx->nested.pi_desc)) return 0; max_irr = find_last_bit( (unsigned long *)vmx->nested.pi_desc->pir, 256); if (max_irr == 256) return 0; vapic_page = kmap(vmx->nested.virtual_apic_page); if (!vapic_page) { WARN_ON(1); return -ENOMEM; } __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page); kunmap(vmx->nested.virtual_apic_page); status = vmcs_read16(GUEST_INTR_STATUS); if ((u8)max_irr > ((u8)status & 0xff)) { status &= ~0xff; status |= (u8)max_irr; vmcs_write16(GUEST_INTR_STATUS, status); } } 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: static v8::Handle<v8::Value> convert5Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert5"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(e*, , V8e::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8e::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert5(); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: void Document::sharedObjectPoolClearTimerFired(Timer<Document>*) { m_sharedObjectPool.clear(); } 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 RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) { current_content_source_id_ = next_source_id; did_receive_first_frame_after_navigation_ = false; if (enable_surface_synchronization_) { visual_properties_ack_pending_ = false; viz::LocalSurfaceId old_surface_id = view_->GetLocalSurfaceId(); if (view_) view_->DidNavigate(); viz::LocalSurfaceId new_surface_id = view_->GetLocalSurfaceId(); if (old_surface_id == new_surface_id) return; } else { if (last_received_content_source_id_ >= current_content_source_id_) return; } if (!new_content_rendering_timeout_) return; new_content_rendering_timeout_->Start(new_content_rendering_delay_); } 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: bool Chapters::ExpandEditionsArray() { if (m_editions_size > m_editions_count) return true; // nothing else to do const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size; Edition* const editions = new (std::nothrow) Edition[size]; if (editions == NULL) return false; for (int idx = 0; idx < m_editions_count; ++idx) { m_editions[idx].ShallowCopy(editions[idx]); } delete[] m_editions; m_editions = editions; m_editions_size = size; return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int __net_init sctp_proc_init(struct net *net) { #ifdef CONFIG_PROC_FS net->sctp.proc_net_sctp = proc_net_mkdir(net, "sctp", net->proc_net); if (!net->sctp.proc_net_sctp) goto out_proc_net_sctp; if (sctp_snmp_proc_init(net)) goto out_snmp_proc_init; if (sctp_eps_proc_init(net)) goto out_eps_proc_init; if (sctp_assocs_proc_init(net)) goto out_assocs_proc_init; if (sctp_remaddr_proc_init(net)) goto out_remaddr_proc_init; return 0; out_remaddr_proc_init: sctp_assocs_proc_exit(net); out_assocs_proc_init: sctp_eps_proc_exit(net); out_eps_proc_init: sctp_snmp_proc_exit(net); out_snmp_proc_init: remove_proc_entry("sctp", net->proc_net); net->sctp.proc_net_sctp = NULL; out_proc_net_sctp: return -ENOMEM; #endif /* CONFIG_PROC_FS */ 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: send_results(struct iperf_test *test) { int r = 0; cJSON *j; cJSON *j_streams; struct iperf_stream *sp; cJSON *j_stream; int sender_has_retransmits; iperf_size_t bytes_transferred; int retransmits; j = cJSON_CreateObject(); if (j == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddFloatToObject(j, "cpu_util_total", test->cpu_util[0]); cJSON_AddFloatToObject(j, "cpu_util_user", test->cpu_util[1]); cJSON_AddFloatToObject(j, "cpu_util_system", test->cpu_util[2]); if ( ! test->sender ) sender_has_retransmits = -1; else sender_has_retransmits = test->sender_has_retransmits; cJSON_AddIntToObject(j, "sender_has_retransmits", sender_has_retransmits); /* If on the server and sending server output, then do this */ if (test->role == 's' && test->get_server_output) { if (test->json_output) { /* Add JSON output */ cJSON_AddItemReferenceToObject(j, "server_output_json", test->json_top); } else { /* Add textual output */ size_t buflen = 0; /* Figure out how much room we need to hold the complete output string */ struct iperf_textline *t; TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) { buflen += strlen(t->line); } /* Allocate and build it up from the component lines */ char *output = calloc(buflen + 1, 1); TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) { strncat(output, t->line, buflen); buflen -= strlen(t->line); } cJSON_AddStringToObject(j, "server_output_text", output); } } j_streams = cJSON_CreateArray(); if (j_streams == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddItemToObject(j, "streams", j_streams); SLIST_FOREACH(sp, &test->streams, streams) { j_stream = cJSON_CreateObject(); if (j_stream == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddItemToArray(j_streams, j_stream); bytes_transferred = test->sender ? sp->result->bytes_sent : sp->result->bytes_received; retransmits = (test->sender && test->sender_has_retransmits) ? sp->result->stream_retrans : -1; cJSON_AddIntToObject(j_stream, "id", sp->id); cJSON_AddIntToObject(j_stream, "bytes", bytes_transferred); cJSON_AddIntToObject(j_stream, "retransmits", retransmits); cJSON_AddFloatToObject(j_stream, "jitter", sp->jitter); cJSON_AddIntToObject(j_stream, "errors", sp->cnt_error); cJSON_AddIntToObject(j_stream, "packets", sp->packet_count); } } if (r == 0 && test->debug) { printf("send_results\n%s\n", cJSON_Print(j)); } if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) { i_errno = IESENDRESULTS; r = -1; } } cJSON_Delete(j); } return r; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ CWE ID: CWE-190 Target: 1 Example 2: Code: xfs_attr3_leaf_hdr_to_disk( struct xfs_da_geometry *geo, struct xfs_attr_leafblock *to, struct xfs_attr3_icleaf_hdr *from) { int i; ASSERT(from->magic == XFS_ATTR_LEAF_MAGIC || from->magic == XFS_ATTR3_LEAF_MAGIC); if (from->magic == XFS_ATTR3_LEAF_MAGIC) { struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)to; hdr3->info.hdr.forw = cpu_to_be32(from->forw); hdr3->info.hdr.back = cpu_to_be32(from->back); hdr3->info.hdr.magic = cpu_to_be16(from->magic); hdr3->count = cpu_to_be16(from->count); hdr3->usedbytes = cpu_to_be16(from->usedbytes); xfs_attr3_leaf_firstused_to_disk(geo, to, from); hdr3->holes = from->holes; hdr3->pad1 = 0; for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { hdr3->freemap[i].base = cpu_to_be16(from->freemap[i].base); hdr3->freemap[i].size = cpu_to_be16(from->freemap[i].size); } return; } to->hdr.info.forw = cpu_to_be32(from->forw); to->hdr.info.back = cpu_to_be32(from->back); to->hdr.info.magic = cpu_to_be16(from->magic); to->hdr.count = cpu_to_be16(from->count); to->hdr.usedbytes = cpu_to_be16(from->usedbytes); xfs_attr3_leaf_firstused_to_disk(geo, to, from); to->hdr.holes = from->holes; to->hdr.pad1 = 0; for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { to->hdr.freemap[i].base = cpu_to_be16(from->freemap[i].base); to->hdr.freemap[i].size = cpu_to_be16(from->freemap[i].size); } } 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: explicit RoundedCornersImageSource(const gfx::ImageSkia& icon) : gfx::CanvasImageSource(icon.size(), false), icon_(icon) { } 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 bool tailmatch(const char *little, const char *bigone) { size_t littlelen = strlen(little); size_t biglen = strlen(bigone); if(littlelen > biglen) return FALSE; return Curl_raw_equal(little, bigone+biglen-littlelen) ? TRUE : FALSE; } CWE ID: CWE-200 Target: 1 Example 2: Code: static void convert_32s_P3C3(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust) { OPJ_SIZE_T i; const OPJ_INT32* pSrc0 = pSrc[0]; const OPJ_INT32* pSrc1 = pSrc[1]; const OPJ_INT32* pSrc2 = pSrc[2]; for (i = 0; i < length; i++) { pDst[3 * i + 0] = pSrc0[i] + adjust; pDst[3 * i + 1] = pSrc1[i] + adjust; pDst[3 * i + 2] = pSrc2[i] + adjust; } } 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 move_node_page(struct page *node_page, int gc_type) { if (gc_type == FG_GC) { struct f2fs_sb_info *sbi = F2FS_P_SB(node_page); struct writeback_control wbc = { .sync_mode = WB_SYNC_ALL, .nr_to_write = 1, .for_reclaim = 0, }; set_page_dirty(node_page); f2fs_wait_on_page_writeback(node_page, NODE, true); f2fs_bug_on(sbi, PageWriteback(node_page)); if (!clear_page_dirty_for_io(node_page)) goto out_page; if (NODE_MAPPING(sbi)->a_ops->writepage(node_page, &wbc)) unlock_page(node_page); goto release_page; } else { /* set page dirty and write it */ if (!PageWriteback(node_page)) set_page_dirty(node_page); } out_page: unlock_page(node_page); release_page: f2fs_put_page(node_page, 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: push_decoder_state (DECODER_STATE ds) { if (ds->idx >= ds->stacksize) { fprintf (stderr, "ERROR: decoder stack overflow!\n"); abort (); } ds->stack[ds->idx++] = ds->cur; } CWE ID: CWE-20 Target: 1 Example 2: Code: float GetVisualViewportScale(FrameTreeNode* node) { double scale; EXPECT_TRUE(ExecuteScriptAndExtractDouble( node, "window.domAutomationController.send(visualViewport.scale);", &scale)); return static_cast<float>(scale); } 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: static int do_timer_create(clockid_t which_clock, struct sigevent *event, timer_t __user *created_timer_id) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct k_itimer *new_timer; int error, new_timer_id; int it_id_set = IT_ID_NOT_SET; if (!kc) return -EINVAL; if (!kc->timer_create) return -EOPNOTSUPP; new_timer = alloc_posix_timer(); if (unlikely(!new_timer)) return -EAGAIN; spin_lock_init(&new_timer->it_lock); new_timer_id = posix_timer_add(new_timer); if (new_timer_id < 0) { error = new_timer_id; goto out; } it_id_set = IT_ID_SET; new_timer->it_id = (timer_t) new_timer_id; new_timer->it_clock = which_clock; new_timer->kclock = kc; new_timer->it_overrun = -1; if (event) { rcu_read_lock(); new_timer->it_pid = get_pid(good_sigevent(event)); rcu_read_unlock(); if (!new_timer->it_pid) { error = -EINVAL; goto out; } new_timer->it_sigev_notify = event->sigev_notify; new_timer->sigq->info.si_signo = event->sigev_signo; new_timer->sigq->info.si_value = event->sigev_value; } else { new_timer->it_sigev_notify = SIGEV_SIGNAL; new_timer->sigq->info.si_signo = SIGALRM; memset(&new_timer->sigq->info.si_value, 0, sizeof(sigval_t)); new_timer->sigq->info.si_value.sival_int = new_timer->it_id; new_timer->it_pid = get_pid(task_tgid(current)); } new_timer->sigq->info.si_tid = new_timer->it_id; new_timer->sigq->info.si_code = SI_TIMER; if (copy_to_user(created_timer_id, &new_timer_id, sizeof (new_timer_id))) { error = -EFAULT; goto out; } error = kc->timer_create(new_timer); if (error) goto out; spin_lock_irq(&current->sighand->siglock); new_timer->it_signal = current->signal; list_add(&new_timer->list, &current->signal->posix_timers); spin_unlock_irq(&current->sighand->siglock); return 0; /* * In the case of the timer belonging to another task, after * the task is unlocked, the timer is owned by the other task * and may cease to exist at any time. Don't use or modify * new_timer after the unlock call. */ out: release_posix_timer(new_timer, it_id_set); return error; } 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: int key_update(key_ref_t key_ref, const void *payload, size_t plen) { struct key_preparsed_payload prep; struct key *key = key_ref_to_ptr(key_ref); int ret; key_check(key); /* the key must be writable */ ret = key_permission(key_ref, KEY_NEED_WRITE); if (ret < 0) return ret; /* attempt to update it if supported */ if (!key->type->update) return -EOPNOTSUPP; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = key->type->def_datalen; prep.expiry = TIME_T_MAX; if (key->type->preparse) { ret = key->type->preparse(&prep); if (ret < 0) goto error; } down_write(&key->sem); ret = key->type->update(key, &prep); if (ret == 0) /* updating a negative key instantiates it */ clear_bit(KEY_FLAG_NEGATIVE, &key->flags); up_write(&key->sem); error: if (key->type->preparse) key->type->free_preparse(&prep); return ret; } CWE ID: CWE-20 Target: 1 Example 2: Code: LayerWebKitThread::~LayerWebKitThread() { if (m_tiler) m_tiler->layerWebKitThreadDestroyed(); ASSERT(!superlayer()); removeAll(m_sublayers); removeAll(m_overlays); } 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 __init acpi_debugfs_init(void) { acpi_debugfs_dir = debugfs_create_dir("acpi", NULL); acpi_custom_method_init(); } 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: swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc) { uint32* wp = (uint32*) cp0; tmsize_t wc = cc / 4; horDiff32(tif, cp0, cc); TIFFSwabArrayOfLong(wp, wc); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int sideband_progress_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_progress *pkt; size_t alloclen; line++; len--; GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len); pkt = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_PROGRESS; pkt->len = (int) len; memcpy(pkt->data, line, len); *out = (git_pkt *) pkt; return 0; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: AtomicString PerformanceNavigationTiming::GetNavigationType( NavigationType type, const Document* document) { if (document && document->GetPageVisibilityState() == mojom::PageVisibilityState::kPrerender) { return "prerender"; } switch (type) { case kNavigationTypeReload: return "reload"; case kNavigationTypeBackForward: return "back_forward"; case kNavigationTypeLinkClicked: case kNavigationTypeFormSubmitted: case kNavigationTypeFormResubmitted: case kNavigationTypeOther: return "navigate"; } NOTREACHED(); return "navigate"; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool BaseSessionService::RestoreUpdateTabNavigationCommand( const SessionCommand& command, TabNavigation* navigation, SessionID::id_type* tab_id) { scoped_ptr<Pickle> pickle(command.PayloadAsPickle()); if (!pickle.get()) return false; void* iterator = NULL; std::string url_spec; if (!pickle->ReadInt(&iterator, tab_id) || !pickle->ReadInt(&iterator, &(navigation->index_)) || !pickle->ReadString(&iterator, &url_spec) || !pickle->ReadString16(&iterator, &(navigation->title_)) || !pickle->ReadString(&iterator, &(navigation->state_)) || !pickle->ReadInt(&iterator, reinterpret_cast<int*>(&(navigation->transition_)))) return false; bool has_type_mask = pickle->ReadInt(&iterator, &(navigation->type_mask_)); if (has_type_mask) { std::string referrer_spec; pickle->ReadString(&iterator, &referrer_spec); int policy_int; WebReferrerPolicy policy; if (pickle->ReadInt(&iterator, &policy_int)) policy = static_cast<WebReferrerPolicy>(policy_int); else policy = WebKit::WebReferrerPolicyDefault; navigation->referrer_ = content::Referrer( referrer_spec.empty() ? GURL() : GURL(referrer_spec), policy); std::string content_state; if (CompressDataHelper::ReadAndDecompressStringFromPickle( *pickle.get(), &iterator, &content_state) && !content_state.empty()) { navigation->state_ = content_state; } } navigation->virtual_url_ = GURL(url_spec); return true; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int nf_tables_getgen(struct sock *nlsk, struct sk_buff *skb, const struct nlmsghdr *nlh, const struct nlattr * const nla[]) { struct net *net = sock_net(skb->sk); struct sk_buff *skb2; int err; skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (skb2 == NULL) return -ENOMEM; err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid, nlh->nlmsg_seq); if (err < 0) goto err; return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid); err: kfree_skb(skb2); return err; } 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: int ramfs_nommu_expand_for_mapping(struct inode *inode, size_t newsize) { unsigned long npages, xpages, loop; struct page *pages; unsigned order; void *data; int ret; /* make various checks */ order = get_order(newsize); if (unlikely(order >= MAX_ORDER)) return -EFBIG; ret = inode_newsize_ok(inode, newsize); if (ret) return ret; i_size_write(inode, newsize); /* allocate enough contiguous pages to be able to satisfy the * request */ pages = alloc_pages(mapping_gfp_mask(inode->i_mapping), order); if (!pages) return -ENOMEM; /* split the high-order page into an array of single pages */ xpages = 1UL << order; npages = (newsize + PAGE_SIZE - 1) >> PAGE_SHIFT; split_page(pages, order); /* trim off any pages we don't actually require */ for (loop = npages; loop < xpages; loop++) __free_page(pages + loop); /* clear the memory we allocated */ newsize = PAGE_SIZE * npages; data = page_address(pages); memset(data, 0, newsize); /* attach all the pages to the inode's address space */ for (loop = 0; loop < npages; loop++) { struct page *page = pages + loop; ret = add_to_page_cache_lru(page, inode->i_mapping, loop, GFP_KERNEL); if (ret < 0) goto add_error; /* prevent the page from being discarded on memory pressure */ SetPageDirty(page); SetPageUptodate(page); unlock_page(page); put_page(page); } return 0; add_error: while (loop < npages) __free_page(pages + loop++); return ret; } 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 handle_emulation_failure(struct kvm_vcpu *vcpu) { ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; kvm_queue_exception(vcpu, UD_VECTOR); return EMULATE_FAIL; } CWE ID: CWE-362 Target: 1 Example 2: Code: int do_execve(const char *filename, const char __user *const __user *__argv, const char __user *const __user *__envp) { struct user_arg_ptr argv = { .ptr.native = __argv }; struct user_arg_ptr envp = { .ptr.native = __envp }; return do_execve_common(filename, argv, envp); } 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 DownloadItemImpl::OnIntermediatePathDetermined( DownloadFileManager* file_manager, const FilePath& intermediate_path, bool ok_to_overwrite) { DownloadFileManager::RenameCompletionCallback callback = base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName, weak_ptr_factory_.GetWeakPtr()); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::RenameInProgressDownloadFile, file_manager, GetGlobalId(), intermediate_path, ok_to_overwrite, callback)); } 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: OMX_ERRORTYPE omx_video::free_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_U32 port, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { (void)hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned int nPortIndex; DEBUG_PRINT_LOW("In for encoder free_buffer"); if (m_state == OMX_StateIdle && (BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) { DEBUG_PRINT_LOW(" free buffer while Component in Loading pending"); } else if ((m_sInPortDef.bEnabled == OMX_FALSE && port == PORT_INDEX_IN)|| (m_sOutPortDef.bEnabled == OMX_FALSE && port == PORT_INDEX_OUT)) { DEBUG_PRINT_LOW("Free Buffer while port %u disabled", (unsigned int)port); } else if (m_state == OMX_StateExecuting || m_state == OMX_StatePause) { DEBUG_PRINT_ERROR("ERROR: Invalid state to free buffer,ports need to be disabled"); post_event(OMX_EventError, OMX_ErrorPortUnpopulated, OMX_COMPONENT_GENERATE_EVENT); return eRet; } else { DEBUG_PRINT_ERROR("ERROR: Invalid state to free buffer,port lost Buffers"); post_event(OMX_EventError, OMX_ErrorPortUnpopulated, OMX_COMPONENT_GENERATE_EVENT); } if (port == PORT_INDEX_IN) { nPortIndex = buffer - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr); DEBUG_PRINT_LOW("free_buffer on i/p port - Port idx %u, actual cnt %u", nPortIndex, (unsigned int)m_sInPortDef.nBufferCountActual); if (nPortIndex < m_sInPortDef.nBufferCountActual) { BITMASK_CLEAR(&m_inp_bm_count,nPortIndex); free_input_buffer (buffer); m_sInPortDef.bPopulated = OMX_FALSE; /*Free the Buffer Header*/ if (release_input_done() #ifdef _ANDROID_ICS_ && !meta_mode_enable #endif ) { input_use_buffer = false; if (m_inp_mem_ptr) { DEBUG_PRINT_LOW("Freeing m_inp_mem_ptr"); free (m_inp_mem_ptr); m_inp_mem_ptr = NULL; } if (m_pInput_pmem) { DEBUG_PRINT_LOW("Freeing m_pInput_pmem"); free(m_pInput_pmem); m_pInput_pmem = NULL; } #ifdef USE_ION if (m_pInput_ion) { DEBUG_PRINT_LOW("Freeing m_pInput_ion"); free(m_pInput_ion); m_pInput_ion = NULL; } #endif } } else { DEBUG_PRINT_ERROR("ERROR: free_buffer ,Port Index Invalid"); eRet = OMX_ErrorBadPortIndex; } if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING) && release_input_done()) { DEBUG_PRINT_LOW("MOVING TO DISABLED STATE"); BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING); post_event(OMX_CommandPortDisable, PORT_INDEX_IN, OMX_COMPONENT_GENERATE_EVENT); } } else if (port == PORT_INDEX_OUT) { nPortIndex = buffer - (OMX_BUFFERHEADERTYPE*)m_out_mem_ptr; DEBUG_PRINT_LOW("free_buffer on o/p port - Port idx %u, actual cnt %u", nPortIndex, (unsigned int)m_sOutPortDef.nBufferCountActual); if (nPortIndex < m_sOutPortDef.nBufferCountActual) { BITMASK_CLEAR(&m_out_bm_count,nPortIndex); m_sOutPortDef.bPopulated = OMX_FALSE; free_output_buffer (buffer); if (release_output_done()) { output_use_buffer = false; if (m_out_mem_ptr) { DEBUG_PRINT_LOW("Freeing m_out_mem_ptr"); free (m_out_mem_ptr); m_out_mem_ptr = NULL; } if (m_pOutput_pmem) { DEBUG_PRINT_LOW("Freeing m_pOutput_pmem"); free(m_pOutput_pmem); m_pOutput_pmem = NULL; } #ifdef USE_ION if (m_pOutput_ion) { DEBUG_PRINT_LOW("Freeing m_pOutput_ion"); free(m_pOutput_ion); m_pOutput_ion = NULL; } #endif } } else { DEBUG_PRINT_ERROR("ERROR: free_buffer , Port Index Invalid"); eRet = OMX_ErrorBadPortIndex; } if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING) && release_output_done() ) { DEBUG_PRINT_LOW("FreeBuffer : If any Disable event pending,post it"); DEBUG_PRINT_LOW("MOVING TO DISABLED STATE"); BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING); post_event(OMX_CommandPortDisable, PORT_INDEX_OUT, OMX_COMPONENT_GENERATE_EVENT); } } else { eRet = OMX_ErrorBadPortIndex; } if ((eRet == OMX_ErrorNone) && (BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) { if (release_done()) { if (dev_stop() != 0) { DEBUG_PRINT_ERROR("ERROR: dev_stop() FAILED"); eRet = OMX_ErrorHardware; } BITMASK_CLEAR((&m_flags),OMX_COMPONENT_LOADING_PENDING); post_event(OMX_CommandStateSet, OMX_StateLoaded, OMX_COMPONENT_GENERATE_EVENT); } else { DEBUG_PRINT_HIGH("in free buffer, release not done, need to free more buffers input %" PRIx64" output %" PRIx64, m_out_bm_count, m_inp_bm_count); } } return eRet; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool RecordDismissAndEmbargo(const GURL& url, ContentSettingsType permission) { return autoblocker_->RecordDismissAndEmbargo(url, permission); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_RINIT_FUNCTION(pgsql) { PGG(default_link) = NULL; PGG(num_links) = PGG(num_persistent); return SUCCESS; } 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 jboolean enableNative(JNIEnv* env, jobject obj) { ALOGV("%s:",__FUNCTION__); jboolean result = JNI_FALSE; if (!sBluetoothInterface) return result; int ret = sBluetoothInterface->enable(); result = (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE : JNI_FALSE; return result; } CWE ID: CWE-20 Target: 1 Example 2: Code: SYSCALL_DEFINE2(kill, pid_t, pid, int, sig) { struct siginfo info; info.si_signo = sig; info.si_errno = 0; info.si_code = SI_USER; info.si_pid = task_tgid_vnr(current); info.si_uid = current_uid(); return kill_something_info(sig, &info, pid); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf) { struct super_block *sb = dentry->d_sb; struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; ext4_fsblk_t overhead = 0, resv_blocks; u64 fsid; s64 bfree; resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters)); if (!test_opt(sb, MINIX_DF)) overhead = sbi->s_overhead; buf->f_type = EXT4_SUPER_MAGIC; buf->f_bsize = sb->s_blocksize; buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead); bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) - percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter); /* prevent underflow in case that few free space is available */ buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0)); buf->f_bavail = buf->f_bfree - (ext4_r_blocks_count(es) + resv_blocks); if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks)) buf->f_bavail = 0; buf->f_files = le32_to_cpu(es->s_inodes_count); buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter); buf->f_namelen = EXT4_NAME_LEN; fsid = le64_to_cpup((void *)es->s_uuid) ^ le64_to_cpup((void *)es->s_uuid + sizeof(u64)); buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL; buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL; 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: MediaMetadataRetriever::MediaMetadataRetriever() { ALOGV("constructor"); const sp<IMediaPlayerService>& service(getService()); if (service == 0) { ALOGE("failed to obtain MediaMetadataRetrieverService"); return; } sp<IMediaMetadataRetriever> retriever(service->createMetadataRetriever()); if (retriever == 0) { ALOGE("failed to create IMediaMetadataRetriever object from server"); } mRetriever = retriever; } CWE ID: CWE-119 Target: 1 Example 2: Code: const SerializedResource* getResource(const char* url, const char* mimeType) { KURL kURL = KURL(m_baseUrl, url); String mime(mimeType); for (size_t i = 0; i < m_resources.size(); ++i) { const SerializedResource& resource = m_resources[i]; if (resource.url == kURL && !resource.data->isEmpty() && (mime.isNull() || equalIgnoringCase(resource.mimeType, mime))) return &resource; } 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 IW_INLINE iw_tmpsample linear_to_rec709_sample(iw_tmpsample v_linear) { if(v_linear < 0.020) { return 4.5*v_linear; } return 1.099*pow(v_linear,0.45) - 0.099; } 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: static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, nbuf; bool input_wakeup = false; retry: ret = ipipe_prep(ipipe, flags); if (ret) return ret; ret = opipe_prep(opipe, flags); if (ret) return ret; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } if (!ipipe->nrbufs && !ipipe->writers) break; /* * Cannot make any progress, because either the input * pipe is empty or the output pipe is full. */ if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) { /* Already processed some buffers, break */ if (ret) break; if (flags & SPLICE_F_NONBLOCK) { ret = -EAGAIN; break; } /* * We raced with another reader/writer and haven't * managed to process any buffers. A zero return * value means EOF, so retry instead. */ pipe_unlock(ipipe); pipe_unlock(opipe); goto retry; } ibuf = ipipe->bufs + ipipe->curbuf; nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); obuf = opipe->bufs + nbuf; if (len >= ibuf->len) { /* * Simply move the whole buffer from ipipe to opipe */ *obuf = *ibuf; ibuf->ops = NULL; opipe->nrbufs++; ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1); ipipe->nrbufs--; input_wakeup = true; } else { /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ pipe_buf_get(ipipe, ibuf); *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = len; opipe->nrbufs++; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } ret += obuf->len; len -= obuf->len; } while (len); pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); if (input_wakeup) wakeup_pipe_writers(ipipe); return ret; } CWE ID: CWE-416 Target: 1 Example 2: Code: DEFINE_RUN_ONCE_STATIC(ossl_init_engine_dynamic) { # ifdef OPENSSL_INIT_DEBUG fprintf(stderr, "OPENSSL_INIT: ossl_init_engine_dynamic: " "engine_load_dynamic_int()\n"); # endif engine_load_dynamic_int(); return 1; } CWE ID: CWE-330 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst, const xmlChar *propName, int mandatory, int *hasProp, const xmlChar **nsName, const xmlChar** localName) { const xmlChar *prop; if (nsName) *nsName = NULL; if (localName) *localName = NULL; if (hasProp) *hasProp = 0; prop = xsltGetCNsProp(style, inst, propName, XSLT_NAMESPACE); if (prop == NULL) { if (mandatory) { xsltTransformError(NULL, style, inst, "The attribute '%s' is missing.\n", propName); style->errors++; return; } } else { const xmlChar *URI; if (xmlValidateQName(prop, 0)) { xsltTransformError(NULL, style, inst, "The value '%s' of the attribute " "'%s' is not a valid QName.\n", prop, propName); style->errors++; return; } else { /* * @prop will be in the string dict afterwards, @URI not. */ URI = xsltGetQNameURI2(style, inst, &prop); if (prop == NULL) { style->errors++; } else { *localName = prop; if (hasProp) *hasProp = 1; if (URI != NULL) { /* * Fixes bug #308441: Put the ns-name in the dict * in order to pointer compare names during XPath's * variable lookup. */ if (nsName) *nsName = xmlDictLookup(style->dict, URI, -1); /* comp->has_ns = 1; */ } } } } return; } 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 persistent_prepare_exception(struct dm_exception_store *store, struct dm_exception *e) { struct pstore *ps = get_info(store); uint32_t stride; chunk_t next_free; sector_t size = get_dev_size(dm_snap_cow(store->snap)->bdev); /* Is there enough room ? */ if (size < ((ps->next_free + 1) * store->chunk_size)) return -ENOSPC; e->new_chunk = ps->next_free; /* * Move onto the next free pending, making sure to take * into account the location of the metadata chunks. */ stride = (ps->exceptions_per_area + 1); next_free = ++ps->next_free; if (sector_div(next_free, stride) == 1) ps->next_free++; atomic_inc(&ps->pending_count); return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: net::Error NavigationRequest::CheckCSPDirectives( RenderFrameHostImpl* parent, bool is_redirect, bool url_upgraded_after_redirect, bool is_response_check, CSPContext::CheckCSPDisposition disposition) { bool navigate_to_allowed = IsAllowedByCSPDirective( initiator_csp_context_.get(), CSPDirective::NavigateTo, is_redirect, url_upgraded_after_redirect, is_response_check, disposition); bool frame_src_allowed = true; if (parent) { frame_src_allowed = IsAllowedByCSPDirective( parent, CSPDirective::FrameSrc, is_redirect, url_upgraded_after_redirect, is_response_check, disposition); } if (navigate_to_allowed && frame_src_allowed) return net::OK; if (!frame_src_allowed) return net::ERR_BLOCKED_BY_CLIENT; return net::ERR_ABORTED; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Browser::OpenBugReportDialog() { UserMetrics::RecordAction(UserMetricsAction("ReportBug")); browser::ShowHtmlBugReportView(this, std::string(), 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 void webkit_web_view_update_settings(WebKitWebView* webView) { WebKitWebViewPrivate* priv = webView->priv; WebKitWebSettings* webSettings = priv->webSettings.get(); Settings* settings = core(webView)->settings(); gchar* defaultEncoding, *cursiveFontFamily, *defaultFontFamily, *fantasyFontFamily, *monospaceFontFamily, *sansSerifFontFamily, *serifFontFamily, *userStylesheetUri, *defaultSpellCheckingLanguages; gboolean autoLoadImages, autoShrinkImages, printBackgrounds, enableScripts, enablePlugins, enableDeveloperExtras, resizableTextAreas, enablePrivateBrowsing, enableCaretBrowsing, enableHTML5Database, enableHTML5LocalStorage, enableXSSAuditor, enableSpatialNavigation, enableFrameFlattening, javascriptCanOpenWindows, javaScriptCanAccessClipboard, enableOfflineWebAppCache, enableUniversalAccessFromFileURI, enableFileAccessFromFileURI, enableDOMPaste, tabKeyCyclesThroughElements, enableWebGL, enableSiteSpecificQuirks, usePageCache, enableJavaApplet, enableHyperlinkAuditing, enableFullscreen, enableDNSPrefetching; WebKitEditingBehavior editingBehavior; g_object_get(webSettings, "default-encoding", &defaultEncoding, "cursive-font-family", &cursiveFontFamily, "default-font-family", &defaultFontFamily, "fantasy-font-family", &fantasyFontFamily, "monospace-font-family", &monospaceFontFamily, "sans-serif-font-family", &sansSerifFontFamily, "serif-font-family", &serifFontFamily, "auto-load-images", &autoLoadImages, "auto-shrink-images", &autoShrinkImages, "print-backgrounds", &printBackgrounds, "enable-scripts", &enableScripts, "enable-plugins", &enablePlugins, "resizable-text-areas", &resizableTextAreas, "user-stylesheet-uri", &userStylesheetUri, "enable-developer-extras", &enableDeveloperExtras, "enable-private-browsing", &enablePrivateBrowsing, "enable-caret-browsing", &enableCaretBrowsing, "enable-html5-database", &enableHTML5Database, "enable-html5-local-storage", &enableHTML5LocalStorage, "enable-xss-auditor", &enableXSSAuditor, "enable-spatial-navigation", &enableSpatialNavigation, "enable-frame-flattening", &enableFrameFlattening, "javascript-can-open-windows-automatically", &javascriptCanOpenWindows, "javascript-can-access-clipboard", &javaScriptCanAccessClipboard, "enable-offline-web-application-cache", &enableOfflineWebAppCache, "editing-behavior", &editingBehavior, "enable-universal-access-from-file-uris", &enableUniversalAccessFromFileURI, "enable-file-access-from-file-uris", &enableFileAccessFromFileURI, "enable-dom-paste", &enableDOMPaste, "tab-key-cycles-through-elements", &tabKeyCyclesThroughElements, "enable-site-specific-quirks", &enableSiteSpecificQuirks, "enable-page-cache", &usePageCache, "enable-java-applet", &enableJavaApplet, "enable-hyperlink-auditing", &enableHyperlinkAuditing, "spell-checking-languages", &defaultSpellCheckingLanguages, "enable-fullscreen", &enableFullscreen, "enable-dns-prefetching", &enableDNSPrefetching, "enable-webgl", &enableWebGL, NULL); settings->setDefaultTextEncodingName(defaultEncoding); settings->setCursiveFontFamily(cursiveFontFamily); settings->setStandardFontFamily(defaultFontFamily); settings->setFantasyFontFamily(fantasyFontFamily); settings->setFixedFontFamily(monospaceFontFamily); settings->setSansSerifFontFamily(sansSerifFontFamily); settings->setSerifFontFamily(serifFontFamily); settings->setLoadsImagesAutomatically(autoLoadImages); settings->setShrinksStandaloneImagesToFit(autoShrinkImages); settings->setShouldPrintBackgrounds(printBackgrounds); settings->setJavaScriptEnabled(enableScripts); settings->setPluginsEnabled(enablePlugins); settings->setTextAreasAreResizable(resizableTextAreas); settings->setUserStyleSheetLocation(KURL(KURL(), userStylesheetUri)); settings->setDeveloperExtrasEnabled(enableDeveloperExtras); settings->setPrivateBrowsingEnabled(enablePrivateBrowsing); settings->setCaretBrowsingEnabled(enableCaretBrowsing); #if ENABLE(DATABASE) AbstractDatabase::setIsAvailable(enableHTML5Database); #endif settings->setLocalStorageEnabled(enableHTML5LocalStorage); settings->setXSSAuditorEnabled(enableXSSAuditor); settings->setSpatialNavigationEnabled(enableSpatialNavigation); settings->setFrameFlatteningEnabled(enableFrameFlattening); settings->setJavaScriptCanOpenWindowsAutomatically(javascriptCanOpenWindows); settings->setJavaScriptCanAccessClipboard(javaScriptCanAccessClipboard); settings->setOfflineWebApplicationCacheEnabled(enableOfflineWebAppCache); settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(editingBehavior)); settings->setAllowUniversalAccessFromFileURLs(enableUniversalAccessFromFileURI); settings->setAllowFileAccessFromFileURLs(enableFileAccessFromFileURI); settings->setDOMPasteAllowed(enableDOMPaste); settings->setNeedsSiteSpecificQuirks(enableSiteSpecificQuirks); settings->setUsesPageCache(usePageCache); settings->setJavaEnabled(enableJavaApplet); settings->setHyperlinkAuditingEnabled(enableHyperlinkAuditing); settings->setDNSPrefetchingEnabled(enableDNSPrefetching); #if ENABLE(FULLSCREEN_API) settings->setFullScreenEnabled(enableFullscreen); #endif #if ENABLE(SPELLCHECK) WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient()); static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(defaultSpellCheckingLanguages); #endif #if ENABLE(WEBGL) settings->setWebGLEnabled(enableWebGL); #endif Page* page = core(webView); if (page) page->setTabKeyCyclesThroughElements(tabKeyCyclesThroughElements); g_free(defaultEncoding); g_free(cursiveFontFamily); g_free(defaultFontFamily); g_free(fantasyFontFamily); g_free(monospaceFontFamily); g_free(sansSerifFontFamily); g_free(serifFontFamily); g_free(userStylesheetUri); webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL); } CWE ID: CWE-399 Target: 1 Example 2: Code: ModuleExport size_t RegisterCINImage(void) { MagickInfo *entry; entry=SetMagickInfo("CIN"); entry->decoder=(DecodeImageHandler *) ReadCINImage; entry->encoder=(EncodeImageHandler *) WriteCINImage; entry->magick=(IsImageFormatHandler *) IsCIN; entry->adjoin=MagickFalse; entry->description=ConstantString("Cineon Image File"); entry->module=ConstantString("CIN"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Browser::ProcessPendingUIUpdates() { #ifndef NDEBUG for (UpdateMap::const_iterator i = scheduled_updates_.begin(); i != scheduled_updates_.end(); ++i) { bool found = false; for (int tab = 0; tab < tab_count(); tab++) { if (GetTabContentsAt(tab) == i->first) { found = true; break; } } DCHECK(found); } #endif chrome_updater_factory_.RevokeAll(); for (UpdateMap::const_iterator i = scheduled_updates_.begin(); i != scheduled_updates_.end(); ++i) { const TabContents* contents = i->first; unsigned flags = i->second; if (contents == GetSelectedTabContents()) { if (flags & TabContents::INVALIDATE_PAGE_ACTIONS) window()->GetLocationBar()->UpdatePageActions(); if (flags & TabContents::INVALIDATE_LOAD && GetStatusBubble()) GetStatusBubble()->SetStatus(contents->GetStatusText()); if (flags & (TabContents::INVALIDATE_TAB | TabContents::INVALIDATE_TITLE)) { #if !defined(OS_MACOSX) command_updater_.UpdateCommandEnabled(IDC_CREATE_SHORTCUTS, web_app::IsValidUrl(contents->GetURL())); #endif window_->UpdateTitleBar(); } } if (flags & (TabContents::INVALIDATE_TAB | TabContents::INVALIDATE_TITLE)) { tab_handler_->GetTabStripModel()->UpdateTabContentsStateAt( tab_handler_->GetTabStripModel()->GetWrapperIndex(contents), TabStripModelObserver::ALL); } } scheduled_updates_.clear(); } 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 WebsiteSettings::OnUIClosing() { if (show_info_bar_) WebsiteSettingsInfoBarDelegate::Create(infobar_service_); SSLCertificateDecisionsDidRevoke user_decision = did_revoke_user_ssl_decisions_ ? USER_CERT_DECISIONS_REVOKED : USER_CERT_DECISIONS_NOT_REVOKED; UMA_HISTOGRAM_ENUMERATION("interstitial.ssl.did_user_revoke_decisions", user_decision, END_OF_SSL_CERTIFICATE_DECISIONS_DID_REVOKE_ENUM); } CWE ID: Target: 1 Example 2: Code: static inline uint32_t ne2000_mem_readl(NE2000State *s, uint32_t addr) { addr &= ~1; /* XXX: check exact behaviour if not even */ if (addr < 32 || (addr >= NE2000_PMEM_START && addr + sizeof(uint32_t) <= NE2000_MEM_SIZE)) { return ldl_le_p(s->mem + addr); } else { return 0xffffffff; } } 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: SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { len ++; } chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 )); len = 0; while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; chr[ len ++ ] = 0; return chr; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; } CWE ID: CWE-125 Target: 1 Example 2: Code: int ShellWindowFrameView::NonClientHitTest(const gfx::Point& point) { if (frame_->IsFullscreen()) return HTCLIENT; #if defined(USE_ASH) gfx::Rect expanded_bounds = bounds(); int outside_bounds = ui::GetDisplayLayout() == ui::LAYOUT_TOUCH ? kResizeOutsideBoundsSizeTouch : kResizeOutsideBoundsSize; expanded_bounds.Inset(-outside_bounds, -outside_bounds); if (!expanded_bounds.Contains(point)) return HTNOWHERE; #endif bool can_ever_resize = frame_->widget_delegate() ? frame_->widget_delegate()->CanResize() : false; int resize_border = frame_->IsMaximized() || frame_->IsFullscreen() ? 0 : kResizeInsideBoundsSize; int frame_component = GetHTComponentForFrame(point, resize_border, resize_border, kResizeAreaCornerSize, kResizeAreaCornerSize, can_ever_resize); if (frame_component != HTNOWHERE) return frame_component; int client_component = frame_->client_view()->NonClientHitTest(point); if (client_component != HTNOWHERE) return client_component; if (close_button_->visible() && close_button_->GetMirroredBounds().Contains(point)) return HTCLOSE; return HTCAPTION; } CWE ID: CWE-79 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: smb_send_rqst(struct TCP_Server_Info *server, struct smb_rqst *rqst) { int rc; struct kvec *iov = rqst->rq_iov; int n_vec = rqst->rq_nvec; unsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base); unsigned int i; size_t total_len = 0, sent; struct socket *ssocket = server->ssocket; int val = 1; cFYI(1, "Sending smb: smb_len=%u", smb_buf_length); dump_smb(iov[0].iov_base, iov[0].iov_len); /* cork the socket */ kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK, (char *)&val, sizeof(val)); rc = smb_send_kvec(server, iov, n_vec, &sent); if (rc < 0) goto uncork; total_len += sent; /* now walk the page array and send each page in it */ for (i = 0; i < rqst->rq_npages; i++) { struct kvec p_iov; cifs_rqst_page_to_kvec(rqst, i, &p_iov); rc = smb_send_kvec(server, &p_iov, 1, &sent); kunmap(rqst->rq_pages[i]); if (rc < 0) break; total_len += sent; } uncork: /* uncork it */ val = 0; kernel_setsockopt(ssocket, SOL_TCP, TCP_CORK, (char *)&val, sizeof(val)); if ((total_len > 0) && (total_len != smb_buf_length + 4)) { cFYI(1, "partial send (wanted=%u sent=%zu): terminating " "session", smb_buf_length + 4, total_len); /* * If we have only sent part of an SMB then the next SMB could * be taken as the remainder of this one. We need to kill the * socket so the server throws away the partial SMB */ server->tcpStatus = CifsNeedReconnect; } if (rc < 0 && rc != -EINTR) cERROR(1, "Error %d sending data on socket to server", rc); else rc = 0; return rc; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void NetworkHandler::ClearBrowserCookies( std::unique_ptr<ClearBrowserCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &ClearCookiesOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), std::move(callback))); } CWE ID: CWE-20 Target: 1 Example 2: Code: PassRefPtr<ExecutableMemoryHandle> ExecutableAllocator::allocate(JSGlobalData& globalData, size_t sizeInBytes, void* ownerUID, JITCompilationEffort effort) { RefPtr<ExecutableMemoryHandle> result = allocator->allocate(sizeInBytes, ownerUID); if (!result) { if (effort == JITCompilationCanFail) return result; releaseExecutableMemory(globalData); result = allocator->allocate(sizeInBytes, ownerUID); if (!result) CRASH(); } return result.release(); } 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 SetDefaultX11ErrorHandlers() { SetX11ErrorHandlers(NULL, NULL); } 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 LaunchServiceProcessControl(bool wait) { ServiceProcessControl::GetInstance()->Launch( base::Bind(&ServiceProcessControlBrowserTest::ProcessControlLaunched, base::Unretained(this)), base::Bind( &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed, base::Unretained(this))); if (wait) content::RunMessageLoop(); } CWE ID: CWE-94 Target: 1 Example 2: Code: const char *security_get_initial_sid_context(u32 sid) { if (unlikely(sid > SECINITSID_NUM)) return NULL; return initial_sid_to_string[sid]; } 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 oz_plat_probe(struct platform_device *dev) { int i; int err; struct usb_hcd *hcd; struct oz_hcd *ozhcd; hcd = usb_create_hcd(&g_oz_hc_drv, &dev->dev, dev_name(&dev->dev)); if (hcd == NULL) { oz_dbg(ON, "Failed to created hcd object OK\n"); return -ENOMEM; } ozhcd = oz_hcd_private(hcd); memset(ozhcd, 0, sizeof(*ozhcd)); INIT_LIST_HEAD(&ozhcd->urb_pending_list); INIT_LIST_HEAD(&ozhcd->urb_cancel_list); INIT_LIST_HEAD(&ozhcd->orphanage); ozhcd->hcd = hcd; ozhcd->conn_port = -1; spin_lock_init(&ozhcd->hcd_lock); for (i = 0; i < OZ_NB_PORTS; i++) { struct oz_port *port = &ozhcd->ports[i]; port->ozhcd = ozhcd; port->flags = 0; port->status = 0; port->bus_addr = 0xff; spin_lock_init(&port->port_lock); } err = usb_add_hcd(hcd, 0, 0); if (err) { oz_dbg(ON, "Failed to add hcd object OK\n"); usb_put_hcd(hcd); return -1; } device_wakeup_enable(hcd->self.controller); spin_lock_bh(&g_hcdlock); g_ozhcd = ozhcd; spin_unlock_bh(&g_hcdlock); return 0; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static PHP_FUNCTION(readgzfile) { char *filename; int filename_len; int flags = REPORT_ERRORS; php_stream *stream; int size; long use_include_path = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &filename, &filename_len, &use_include_path) == FAILURE) { return; } if (use_include_path) { flags |= USE_PATH; } stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC TSRMLS_CC); if (!stream) { RETURN_FALSE; } size = php_stream_passthru(stream); php_stream_close(stream); RETURN_LONG(size); } CWE ID: CWE-254 Target: 1 Example 2: Code: void ipc_rcu_putref(void *ptr, void (*func)(struct rcu_head *head)) { struct ipc_rcu *p = ((struct ipc_rcu *)ptr) - 1; if (!atomic_dec_and_test(&p->refcount)) return; call_rcu(&p->rcu, func); } 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 void cvarinit(JF, js_Ast *list) { while (list) { js_Ast *var = list->a; if (var->b) { cexp(J, F, var->b); emitline(J, F, var); emitlocal(J, F, OP_SETLOCAL, OP_SETVAR, var->a); emit(J, F, OP_POP); } list = list->b; } } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: HeapVector<NotificationAction> Notification::actions() const { HeapVector<NotificationAction> actions; actions.grow(m_data.actions.size()); for (size_t i = 0; i < m_data.actions.size(); ++i) { actions[i].setAction(m_data.actions[i].action); actions[i].setTitle(m_data.actions[i].title); } return actions; } CWE ID: Target: 1 Example 2: Code: int __init ip_rt_init(void) { int rc = 0; ip_idents = kmalloc(IP_IDENTS_SZ * sizeof(*ip_idents), GFP_KERNEL); if (!ip_idents) panic("IP: failed to allocate ip_idents\n"); prandom_bytes(ip_idents, IP_IDENTS_SZ * sizeof(*ip_idents)); #ifdef CONFIG_IP_ROUTE_CLASSID ip_rt_acct = __alloc_percpu(256 * sizeof(struct ip_rt_acct), __alignof__(struct ip_rt_acct)); if (!ip_rt_acct) panic("IP: failed to allocate ip_rt_acct\n"); #endif ipv4_dst_ops.kmem_cachep = kmem_cache_create("ip_dst_cache", sizeof(struct rtable), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); ipv4_dst_blackhole_ops.kmem_cachep = ipv4_dst_ops.kmem_cachep; if (dst_entries_init(&ipv4_dst_ops) < 0) panic("IP: failed to allocate ipv4_dst_ops counter\n"); if (dst_entries_init(&ipv4_dst_blackhole_ops) < 0) panic("IP: failed to allocate ipv4_dst_blackhole_ops counter\n"); ipv4_dst_ops.gc_thresh = ~0; ip_rt_max_size = INT_MAX; devinet_init(); ip_fib_init(); if (ip_rt_proc_init()) pr_err("Unable to create route proc files\n"); #ifdef CONFIG_XFRM xfrm_init(); xfrm4_init(); #endif rtnl_register(PF_INET, RTM_GETROUTE, inet_rtm_getroute, NULL, NULL); #ifdef CONFIG_SYSCTL register_pernet_subsys(&sysctl_route_ops); #endif register_pernet_subsys(&rt_genid_ops); register_pernet_subsys(&ipv4_inetpeer_ops); return rc; } CWE ID: CWE-17 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 RenderWidgetHostImpl::ScheduleComposite() { if (is_hidden_ || current_size_.IsEmpty() || repaint_ack_pending_ || resize_ack_pending_) { return false; } repaint_start_time_ = TimeTicks::Now(); repaint_ack_pending_ = true; TRACE_EVENT_ASYNC_BEGIN0( "renderer_host", "RenderWidgetHostImpl::repaint_ack_pending_", this); Send(new ViewMsg_Repaint(routing_id_, current_size_)); return true; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: wiki_handle_http_request(HttpRequest *req) { HttpResponse *res = http_response_new(req); char *page = http_request_get_path_info(req); char *command = http_request_get_query_string(req); char *wikitext = ""; util_dehttpize(page); /* remove any encoding on the requested page name. */ if (!strcmp(page, "/")) { if (access("WikiHome", R_OK) != 0) wiki_redirect(res, "/WikiHome?create"); page = "/WikiHome"; } if (!strcmp(page, "/styles.css")) { /* Return CSS page */ http_response_set_content_type(res, "text/css"); http_response_printf(res, "%s", CssData); http_response_send(res); exit(0); } if (!strcmp(page, "/favicon.ico")) { /* Return favicon */ http_response_set_content_type(res, "image/ico"); http_response_set_data(res, FaviconData, FaviconDataLen); http_response_send(res); exit(0); } page = page + 1; /* skip slash */ if (!strncmp(page, "api/", 4)) { char *p; page += 4; for (p=page; *p != '\0'; p++) if (*p=='?') { *p ='\0'; break; } wiki_handle_rest_call(req, res, page); exit(0); } /* A little safety. issue a malformed request for any paths, * There shouldn't need to be any.. */ if (strchr(page, '/')) { http_response_set_status(res, 404, "Not Found"); http_response_printf(res, "<html><body>404 Not Found</body></html>\n"); http_response_send(res); exit(0); } if (!strcmp(page, "Changes")) { wiki_show_changes_page(res); } else if (!strcmp(page, "ChangesRss")) { wiki_show_changes_page_rss(res); } else if (!strcmp(page, "Search")) { wiki_show_search_results_page(res, http_request_param_get(req, "expr")); } else if (!strcmp(page, "Create")) { if ( (wikitext = http_request_param_get(req, "title")) != NULL) { /* create page and redirect */ wiki_redirect(res, http_request_param_get(req, "title")); } else { /* show create page form */ wiki_show_create_page(res); } } else { /* TODO: dont blindly write wikitext data to disk */ if ( (wikitext = http_request_param_get(req, "wikitext")) != NULL) { file_write(page, wikitext); } if (access(page, R_OK) == 0) /* page exists */ { wikitext = file_read(page); if (!strcmp(command, "edit")) { /* print edit page */ wiki_show_edit_page(res, wikitext, page); } else { wiki_show_page(res, wikitext, page); } } else { if (!strcmp(command, "create")) { wiki_show_edit_page(res, NULL, page); } else { char buf[1024]; snprintf(buf, 1024, "%s?create", page); wiki_redirect(res, buf); } } } } CWE ID: CWE-22 Target: 1 Example 2: Code: int test_gf2m_mod(BIO *bp) { BIGNUM *a, *b[2], *c, *d, *e; int i, j, ret = 0; int p0[] = { 163, 7, 6, 3, 0, -1 }; int p1[] = { 193, 15, 0, -1 }; a = BN_new(); b[0] = BN_new(); b[1] = BN_new(); c = BN_new(); d = BN_new(); e = BN_new(); BN_GF2m_arr2poly(p0, b[0]); BN_GF2m_arr2poly(p1, b[1]); for (i = 0; i < num0; i++) { BN_bntest_rand(a, 1024, 0, 0); for (j = 0; j < 2; j++) { BN_GF2m_mod(c, a, b[j]); # if 0 /* make test uses ouput in bc but bc can't * handle GF(2^m) arithmetic */ if (bp != NULL) { if (!results) { BN_print(bp, a); BIO_puts(bp, " % "); BN_print(bp, b[j]); BIO_puts(bp, " - "); BN_print(bp, c); BIO_puts(bp, "\n"); } } # endif BN_GF2m_add(d, a, c); BN_GF2m_mod(e, d, b[j]); /* Test that a + (a mod p) mod p == 0. */ if (!BN_is_zero(e)) { fprintf(stderr, "GF(2^m) modulo test failed!\n"); goto err; } } } ret = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); BN_free(e); return ret; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WT_VoiceFilter (S_FILTER_CONTROL *pFilter, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pAudioBuffer; EAS_I32 k; EAS_I32 b1; EAS_I32 b2; EAS_I32 z1; EAS_I32 z2; EAS_I32 acc0; EAS_I32 acc1; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pAudioBuffer = pWTIntFrame->pAudioBuffer; z1 = pFilter->z1; z2 = pFilter->z2; b1 = -pWTIntFrame->frame.b1; /*lint -e{702} <avoid divide> */ b2 = -pWTIntFrame->frame.b2 >> 1; /*lint -e{702} <avoid divide> */ k = pWTIntFrame->frame.k >> 1; while (numSamples--) { /* do filter calculations */ acc0 = *pAudioBuffer; acc1 = z1 * b1; acc1 += z2 * b2; acc0 = acc1 + k * acc0; z2 = z1; /*lint -e{702} <avoid divide> */ z1 = acc0 >> 14; *pAudioBuffer++ = (EAS_I16) z1; } /* save delay values */ pFilter->z1 = (EAS_I16) z1; pFilter->z2 = (EAS_I16) z2; } 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 cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto exit; } buf[1] &= ~(1 << offset); buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto exit; } ret = 0; exit: mutex_unlock(&dev->lock); return ret <= 0 ? ret : -EIO; } CWE ID: CWE-388 Target: 1 Example 2: Code: void open_logs(void) { int access_log; /* if error_log_name is set, dup2 stderr to it */ /* otherwise, leave stderr alone */ /* we don't want to tie stderr to /dev/null */ if (error_log_name) { int error_log; /* open the log file */ error_log = open_gen_fd(error_log_name); if (error_log < 0) { DIE("unable to open error log"); } /* redirect stderr to error_log */ if (dup2(error_log, STDERR_FILENO) == -1) { DIE("unable to dup2 the error log"); } close(error_log); } if (access_log_name) { access_log = open_gen_fd(access_log_name); } else { access_log = open("/dev/null", 0); } if (access_log < 0) { DIE("unable to open access log"); } if (dup2(access_log, STDOUT_FILENO) == -1) { DIE("can't dup2 /dev/null to STDOUT_FILENO"); } if (fcntl(access_log, F_SETFD, 1) == -1) { DIE("unable to set close-on-exec flag for access_log"); } close(access_log); if (cgi_log_name) { cgi_log_fd = open_gen_fd(cgi_log_name); if (cgi_log_fd == -1) { WARN("open cgi_log"); free(cgi_log_name); cgi_log_name = NULL; cgi_log_fd = 0; } else { if (fcntl(cgi_log_fd, F_SETFD, 1) == -1) { WARN("unable to set close-on-exec flag for cgi_log"); free(cgi_log_name); cgi_log_name = NULL; close(cgi_log_fd); cgi_log_fd = 0; } } } #ifdef SETVBUF_REVERSED setvbuf(stderr, _IONBF, (char *) NULL, 0); setvbuf(stdout, _IOLBF, (char *) NULL, 0); #else setvbuf(stderr, (char *) NULL, _IONBF, 0); setvbuf(stdout, (char *) NULL, _IOLBF, 0); #endif } 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: load_fake(png_charp param, png_bytepp profile) { char *endptr = NULL; unsigned long long int size = strtoull(param, &endptr, 0/*base*/); /* The 'fake' format is <number>*[string] */ if (endptr != NULL && *endptr == '*') { size_t len = strlen(++endptr); size_t result = (size_t)size; if (len == 0) len = 1; /* capture the terminating '\0' */ /* Now repeat that string to fill 'size' bytes. */ if (result == size && (*profile = malloc(result)) != NULL) { png_bytep out = *profile; if (len == 1) memset(out, *endptr, result); else { while (size >= len) { memcpy(out, endptr, len); out += len; size -= len; } memcpy(out, endptr, size); } return result; } else { fprintf(stderr, "%s: size exceeds system limits\n", param); exit(1); } } return 0; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int mif_process_cmpt(mif_hdr_t *hdr, char *buf) { jas_tvparser_t *tvp; mif_cmpt_t *cmpt; int id; cmpt = 0; tvp = 0; if (!(cmpt = mif_cmpt_create())) { goto error; } cmpt->tlx = 0; cmpt->tly = 0; cmpt->sampperx = 0; cmpt->samppery = 0; cmpt->width = 0; cmpt->height = 0; cmpt->prec = 0; cmpt->sgnd = -1; cmpt->data = 0; if (!(tvp = jas_tvparser_create(buf))) { goto error; } while (!(id = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags, jas_tvparser_gettag(tvp)))->id) { case MIF_TLX: cmpt->tlx = atoi(jas_tvparser_getval(tvp)); break; case MIF_TLY: cmpt->tly = atoi(jas_tvparser_getval(tvp)); break; case MIF_WIDTH: cmpt->width = atoi(jas_tvparser_getval(tvp)); break; case MIF_HEIGHT: cmpt->height = atoi(jas_tvparser_getval(tvp)); break; case MIF_HSAMP: cmpt->sampperx = atoi(jas_tvparser_getval(tvp)); break; case MIF_VSAMP: cmpt->samppery = atoi(jas_tvparser_getval(tvp)); break; case MIF_PREC: cmpt->prec = atoi(jas_tvparser_getval(tvp)); break; case MIF_SGND: cmpt->sgnd = atoi(jas_tvparser_getval(tvp)); break; case MIF_DATA: if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) { return -1; } break; } } jas_tvparser_destroy(tvp); if (!cmpt->sampperx || !cmpt->samppery) { goto error; } if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) { goto error; } return 0; error: if (cmpt) { mif_cmpt_destroy(cmpt); } if (tvp) { jas_tvparser_destroy(tvp); } return -1; } CWE ID: CWE-416 Target: 1 Example 2: Code: struct blk_flush_queue *blk_alloc_flush_queue(struct request_queue *q, int node, int cmd_size) { struct blk_flush_queue *fq; int rq_sz = sizeof(struct request); fq = kzalloc_node(sizeof(*fq), GFP_KERNEL, node); if (!fq) goto fail; if (q->mq_ops) { spin_lock_init(&fq->mq_flush_lock); rq_sz = round_up(rq_sz + cmd_size, cache_line_size()); } fq->flush_rq = kzalloc_node(rq_sz, GFP_KERNEL, node); if (!fq->flush_rq) goto fail_rq; INIT_LIST_HEAD(&fq->flush_queue[0]); INIT_LIST_HEAD(&fq->flush_queue[1]); INIT_LIST_HEAD(&fq->flush_data_in_flight); return fq; fail_rq: kfree(fq); fail: return NULL; } 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 QQuickWebView::mouseReleaseEvent(QMouseEvent* event) { Q_D(QQuickWebView); d->handleMouseEvent(event); } 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 cmd_parse_status(struct ImapData *idata, char *s) { char *value = NULL; struct Buffy *inc = NULL; struct ImapMbox mx; struct ImapStatus *status = NULL; unsigned int olduv, oldun; unsigned int litlen; short new = 0; short new_msg_count = 0; char *mailbox = imap_next_word(s); /* We need a real tokenizer. */ if (imap_get_literal_count(mailbox, &litlen) == 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { idata->status = IMAP_FATAL; return; } mailbox = idata->buf; s = mailbox + litlen; *s = '\0'; s++; SKIPWS(s); } else { s = imap_next_word(mailbox); *(s - 1) = '\0'; imap_unmunge_mbox_name(idata, mailbox); } status = imap_mboxcache_get(idata, mailbox, 1); olduv = status->uidvalidity; oldun = status->uidnext; if (*s++ != '(') { mutt_debug(1, "Error parsing STATUS\n"); return; } while (*s && *s != ')') { value = imap_next_word(s); errno = 0; const unsigned long ulcount = strtoul(value, &value, 10); if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount)) { mutt_debug(1, "Error parsing STATUS number\n"); return; } const unsigned int count = (unsigned int) ulcount; if (mutt_str_strncmp("MESSAGES", s, 8) == 0) { status->messages = count; new_msg_count = 1; } else if (mutt_str_strncmp("RECENT", s, 6) == 0) status->recent = count; else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0) status->uidnext = count; else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0) status->uidvalidity = count; else if (mutt_str_strncmp("UNSEEN", s, 6) == 0) status->unseen = count; s = value; if (*s && *s != ')') s = imap_next_word(s); } mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n", status->name, status->uidvalidity, status->uidnext, status->messages, status->recent, status->unseen); /* caller is prepared to handle the result herself */ if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS) { memcpy(idata->cmddata, status, sizeof(struct ImapStatus)); return; } mutt_debug(3, "Running default STATUS handler\n"); /* should perhaps move this code back to imap_buffy_check */ for (inc = Incoming; inc; inc = inc->next) { if (inc->magic != MUTT_IMAP) continue; if (imap_parse_path(inc->path, &mx) < 0) { mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path); continue; } if (imap_account_match(&idata->conn->account, &mx.account)) { if (mx.mbox) { value = mutt_str_strdup(mx.mbox); imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1); FREE(&mx.mbox); } else value = mutt_str_strdup("INBOX"); if (value && (imap_mxcmp(mailbox, value) == 0)) { mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox, olduv, oldun, status->unseen); if (MailCheckRecent) { if (olduv && olduv == status->uidvalidity) { if (oldun < status->uidnext) new = (status->unseen > 0); } else if (!olduv && !oldun) { /* first check per session, use recent. might need a flag for this. */ new = (status->recent > 0); } else new = (status->unseen > 0); } else new = (status->unseen > 0); #ifdef USE_SIDEBAR if ((inc->new != new) || (inc->msg_count != status->messages) || (inc->msg_unread != status->unseen)) { mutt_menu_set_current_redraw(REDRAW_SIDEBAR); } #endif inc->new = new; if (new_msg_count) inc->msg_count = status->messages; inc->msg_unread = status->unseen; if (inc->new) { /* force back to keep detecting new mail until the mailbox is opened */ status->uidnext = oldun; } FREE(&value); return; } FREE(&value); } FREE(&mx.mbox); } } CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer) { updateGraphicsLayersMappedToRenderLayer(layer); #if !ASSERT_DISABLED LayerListMutationDetector mutationChecker(layer->stackingNode()); #endif RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren); while (RenderLayerStackingNode* curNode = iterator.next()) updateLayerTreeGeometry(curNode->layer()); } 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: status_t MPEG4Source::parseSampleAuxiliaryInformationSizes( off64_t offset, off64_t /* size */) { ALOGV("parseSampleAuxiliaryInformationSizes"); uint8_t version; if (mDataSource->readAt( offset, &version, sizeof(version)) < (ssize_t)sizeof(version)) { return ERROR_IO; } if (version != 0) { return ERROR_UNSUPPORTED; } offset++; uint32_t flags; if (!mDataSource->getUInt24(offset, &flags)) { return ERROR_IO; } offset += 3; if (flags & 1) { uint32_t tmp; if (!mDataSource->getUInt32(offset, &tmp)) { return ERROR_MALFORMED; } mCurrentAuxInfoType = tmp; offset += 4; if (!mDataSource->getUInt32(offset, &tmp)) { return ERROR_MALFORMED; } mCurrentAuxInfoTypeParameter = tmp; offset += 4; } uint8_t defsize; if (mDataSource->readAt(offset, &defsize, 1) != 1) { return ERROR_MALFORMED; } mCurrentDefaultSampleInfoSize = defsize; offset++; uint32_t smplcnt; if (!mDataSource->getUInt32(offset, &smplcnt)) { return ERROR_MALFORMED; } mCurrentSampleInfoCount = smplcnt; offset += 4; if (mCurrentDefaultSampleInfoSize != 0) { ALOGV("@@@@ using default sample info size of %d", mCurrentDefaultSampleInfoSize); return OK; } if (smplcnt > mCurrentSampleInfoAllocSize) { mCurrentSampleInfoSizes = (uint8_t*) realloc(mCurrentSampleInfoSizes, smplcnt); mCurrentSampleInfoAllocSize = smplcnt; } mDataSource->readAt(offset, mCurrentSampleInfoSizes, smplcnt); return OK; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr, unsigned long, data) { struct task_struct *child; long ret; if (request == PTRACE_TRACEME) { ret = ptrace_traceme(); if (!ret) arch_ptrace_attach(current); goto out; } child = ptrace_get_task_struct(pid); if (IS_ERR(child)) { ret = PTR_ERR(child); goto out; } if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) { ret = ptrace_attach(child, request, addr, data); /* * Some architectures need to do book-keeping after * a ptrace attach. */ if (!ret) arch_ptrace_attach(child); goto out_put_task_struct; } ret = ptrace_check_attach(child, request == PTRACE_KILL || request == PTRACE_INTERRUPT); if (ret < 0) goto out_put_task_struct; ret = arch_ptrace(child, request, addr, data); out_put_task_struct: put_task_struct(child); out: return ret; } CWE ID: CWE-362 Target: 1 Example 2: Code: vips_foreign_save_build( VipsObject *object ) { VipsForeignSave *save = VIPS_FOREIGN_SAVE( object ); if( save->in ) { VipsForeignSaveClass *class = VIPS_FOREIGN_SAVE_GET_CLASS( save ); VipsImage *ready; if( vips__foreign_convert_saveable( save->in, &ready, class->saveable, class->format_table, class->coding, save->background ) ) return( -1 ); if( save->page_height ) vips_image_set_int( ready, VIPS_META_PAGE_HEIGHT, save->page_height ); VIPS_UNREF( save->ready ); save->ready = ready; } if( VIPS_OBJECT_CLASS( vips_foreign_save_parent_class )-> build( object ) ) return( -1 ); return( 0 ); } 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: removeDevice(const struct header * headers) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { syslog(LOG_INFO, "remove device : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); *pp = p->next; free(p); return -1; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_WARNING, "device not found for removing : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); return 0; } CWE ID: CWE-388 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int dpcm_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; const uint8_t *buf_end = buf + buf_size; DPCMContext *s = avctx->priv_data; int out = 0, ret; int predictor[2]; int ch = 0; int stereo = s->channels - 1; int16_t *output_samples; /* calculate output size */ switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: case CODEC_ID_XAN_DPCM: out = buf_size - 2 * s->channels; break; case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) out = buf_size * 2; else out = buf_size; break; } if (out <= 0) { av_log(avctx, AV_LOG_ERROR, "packet is too small\n"); return AVERROR(EINVAL); } /* get output buffer */ s->frame.nb_samples = out / s->channels; if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); return ret; } output_samples = (int16_t *)s->frame.data[0]; switch(avctx->codec->id) { case CODEC_ID_ROQ_DPCM: buf += 6; if (stereo) { predictor[1] = (int16_t)(bytestream_get_byte(&buf) << 8); predictor[0] = (int16_t)(bytestream_get_byte(&buf) << 8); } else { predictor[0] = (int16_t)bytestream_get_le16(&buf); } /* decode the samples */ while (buf < buf_end) { predictor[ch] += s->roq_square_array[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_INTERPLAY_DPCM: buf += 6; /* skip over the stream mask and stream length */ for (ch = 0; ch < s->channels; ch++) { predictor[ch] = (int16_t)bytestream_get_le16(&buf); *output_samples++ = predictor[ch]; } ch = 0; while (buf < buf_end) { predictor[ch] += interplay_delta_table[*buf++]; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; case CODEC_ID_XAN_DPCM: { int shift[2] = { 4, 4 }; for (ch = 0; ch < s->channels; ch++) predictor[ch] = (int16_t)bytestream_get_le16(&buf); ch = 0; while (buf < buf_end) { uint8_t n = *buf++; int16_t diff = (n & 0xFC) << 8; if ((n & 0x03) == 3) shift[ch]++; else shift[ch] -= (2 * (n & 3)); /* saturate the shifter to a lower limit of 0 */ if (shift[ch] < 0) shift[ch] = 0; diff >>= shift[ch]; predictor[ch] += diff; predictor[ch] = av_clip_int16(predictor[ch]); *output_samples++ = predictor[ch]; /* toggle channel */ ch ^= stereo; } break; } case CODEC_ID_SOL_DPCM: if (avctx->codec_tag != 3) { uint8_t *output_samples_u8 = s->frame.data[0]; while (buf < buf_end) { uint8_t n = *buf++; s->sample[0] += s->sol_table[n >> 4]; s->sample[0] = av_clip_uint8(s->sample[0]); *output_samples_u8++ = s->sample[0]; s->sample[stereo] += s->sol_table[n & 0x0F]; s->sample[stereo] = av_clip_uint8(s->sample[stereo]); *output_samples_u8++ = s->sample[stereo]; } } else { while (buf < buf_end) { uint8_t n = *buf++; if (n & 0x80) s->sample[ch] -= sol_table_16[n & 0x7F]; else s->sample[ch] += sol_table_16[n & 0x7F]; s->sample[ch] = av_clip_int16(s->sample[ch]); *output_samples++ = s->sample[ch]; /* toggle channel */ ch ^= stereo; } } break; } *got_frame_ptr = 1; *(AVFrame *)data = s->frame; return buf_size; } CWE ID: CWE-119 Target: 1 Example 2: Code: GURL AddUberHost(const GURL& url) { const std::string uber_host = chrome::kChromeUIUberHost; const std::string new_path = url.host() + url.path(); return ReplaceURLHostAndPath(url, uber_host, new_path); } 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 struct sctp_association *__sctp_lookup_association( const union sctp_addr *local, const union sctp_addr *peer, struct sctp_transport **pt) { struct sctp_hashbucket *head; struct sctp_ep_common *epb; struct sctp_association *asoc; struct sctp_transport *transport; struct hlist_node *node; int hash; /* Optimize here for direct hit, only listening connections can * have wildcards anyways. */ hash = sctp_assoc_hashfn(ntohs(local->v4.sin_port), ntohs(peer->v4.sin_port)); head = &sctp_assoc_hashtable[hash]; read_lock(&head->lock); sctp_for_each_hentry(epb, node, &head->chain) { asoc = sctp_assoc(epb); transport = sctp_assoc_is_match(asoc, local, peer); if (transport) goto hit; } read_unlock(&head->lock); return NULL; hit: *pt = transport; sctp_association_hold(asoc); read_unlock(&head->lock); return asoc; } 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: UserSelectionScreen::UpdateAndReturnUserListForWebUI() { std::unique_ptr<base::ListValue> users_list = std::make_unique<base::ListValue>(); const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (user_manager::UserList::const_iterator it = users_to_send_.begin(); it != users_to_send_.end(); ++it) { const AccountId& account_id = (*it)->GetAccountId(); bool is_owner = (account_id == owner); const bool is_public_account = ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(*it) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; auto user_dict = std::make_unique<base::DictionaryValue>(); const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; FillUserDictionary(*it, is_owner, is_signin_to_add, initial_auth_type, public_session_recommended_locales, user_dict.get()); user_dict->SetBoolean(kKeyCanRemove, CanRemoveUser(*it)); users_list->Append(std::move(user_dict)); } return users_list; } CWE ID: Target: 1 Example 2: Code: static int transfer_xor(struct loop_device *lo, int cmd, struct page *raw_page, unsigned raw_off, struct page *loop_page, unsigned loop_off, int size, sector_t real_block) { char *raw_buf = kmap_atomic(raw_page) + raw_off; char *loop_buf = kmap_atomic(loop_page) + loop_off; char *in, *out, *key; int i, keysize; if (cmd == READ) { in = raw_buf; out = loop_buf; } else { in = loop_buf; out = raw_buf; } key = lo->lo_encrypt_key; keysize = lo->lo_encrypt_key_size; for (i = 0; i < size; i++) *out++ = *in++ ^ key[(i & 511) % keysize]; kunmap_atomic(loop_buf); kunmap_atomic(raw_buf); cond_resched(); return 0; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int setup_initrd(struct boot_params *params, unsigned long initrd_load_addr, unsigned long initrd_len) { params->hdr.ramdisk_image = initrd_load_addr & 0xffffffffUL; params->hdr.ramdisk_size = initrd_len & 0xffffffffUL; params->ext_ramdisk_image = initrd_load_addr >> 32; params->ext_ramdisk_size = initrd_len >> 32; return 0; } CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), 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; transliterator_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d; ӏ > l; [кĸκ] > k; п > n;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } CWE ID: CWE-20 Target: 1 Example 2: Code: static MagickBooleanType WriteUYVYImage(const ImageInfo *image_info, Image *image) { MagickPixelPacket pixel; Image *uyvy_image; MagickBooleanType full, status; register const PixelPacket *p; register ssize_t x; ssize_t y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns % 2) != 0) image->columns++; status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Accumulate two pixels, then output. */ uyvy_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (uyvy_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,image->exception.reason); (void) TransformImageColorspace(uyvy_image,YCbCrColorspace); full=MagickFalse; (void) ResetMagickMemory(&pixel,0,sizeof(MagickPixelPacket)); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(uyvy_image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (full != MagickFalse) { pixel.green=(pixel.green+GetPixelGreen(p))/2; pixel.blue=(pixel.blue+GetPixelBlue(p))/2; (void) WriteBlobByte(image,ScaleQuantumToChar((Quantum) pixel.green)); (void) WriteBlobByte(image,ScaleQuantumToChar((Quantum) pixel.red)); (void) WriteBlobByte(image,ScaleQuantumToChar((Quantum) pixel.blue)); (void) WriteBlobByte(image,ScaleQuantumToChar( GetPixelRed(p))); } pixel.red=(double) GetPixelRed(p); pixel.green=(double) GetPixelGreen(p); pixel.blue=(double) GetPixelBlue(p); full=full == MagickFalse ? MagickTrue : MagickFalse; p++; } status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } uyvy_image=DestroyImage(uyvy_image); (void) CloseBlob(image); return(MagickTrue); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void nbd_recv_coroutines_enter_all(NBDClientSession *s) { int i; for (i = 0; i < MAX_NBD_REQUESTS; i++) { qemu_coroutine_enter(s->recv_coroutine[i]); qemu_coroutine_enter(s->recv_coroutine[i]); } } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> convert2Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert2"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(b*, , V8b::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8b::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert2(); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp) { BDRVQcowState *s = bs->opaque; int flags = s->flags; AES_KEY aes_encrypt_key; AES_KEY aes_decrypt_key; uint32_t crypt_method = 0; QDict *options; Error *local_err = NULL; int ret; /* * Backing files are read-only which makes all of their metadata immutable, * that means we don't have to worry about reopening them here. */ if (s->crypt_method) { crypt_method = s->crypt_method; memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key)); memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key)); } qcow2_close(bs); bdrv_invalidate_cache(bs->file, &local_err); if (local_err) { error_propagate(errp, local_err); return; } memset(s, 0, sizeof(BDRVQcowState)); options = qdict_clone_shallow(bs->options); ret = qcow2_open(bs, options, flags, &local_err); if (local_err) { error_setg(errp, "Could not reopen qcow2 layer: %s", error_get_pretty(local_err)); error_free(local_err); return; } else if (ret < 0) { error_setg_errno(errp, -ret, "Could not reopen qcow2 layer"); return; } QDECREF(options); if (crypt_method) { s->crypt_method = crypt_method; memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key)); memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key)); } } 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: pvscsi_convert_sglist(PVSCSIRequest *r) { int chunk_size; uint64_t data_length = r->req.dataLen; PVSCSISGState sg = r->sg; while (data_length) { while (!sg.resid) { pvscsi_get_next_sg_elem(&sg); trace_pvscsi_convert_sglist(r->req.context, r->sg.dataAddr, r->sg.resid); } assert(data_length > 0); chunk_size = MIN((unsigned) data_length, sg.resid); if (chunk_size) { qemu_sglist_add(&r->sgl, sg.dataAddr, chunk_size); } sg.dataAddr += chunk_size; data_length -= chunk_size; sg.resid -= chunk_size; } } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int link_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, i = 0, nbuf; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } /* * If we have iterated all input buffers or ran out of * output room, break. */ if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) break; ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1)); nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ pipe_buf_get(ipipe, ibuf); obuf = opipe->bufs + nbuf; *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; if (obuf->len > len) obuf->len = len; opipe->nrbufs++; ret += obuf->len; len -= obuf->len; i++; } while (len); /* * return EAGAIN if we have the potential of some data in the * future, otherwise just return 0 */ if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK)) ret = -EAGAIN; pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); return ret; } CWE ID: CWE-416 Target: 1 Example 2: Code: int register_android_net_wifi_WifiNative(JNIEnv* env) { return AndroidRuntime::registerNativeMethods(env, "com/android/server/wifi/WifiNative", gWifiMethods, NELEM(gWifiMethods)); } 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 param_set_mode(const char *val, struct kernel_param *kp) { int i; if (!capable(CAP_MAC_ADMIN)) return -EPERM; if (!apparmor_enabled) return -EINVAL; if (!val) return -EINVAL; for (i = 0; i < APPARMOR_MODE_NAMES_MAX_INDEX; i++) { if (strcmp(val, aa_profile_mode_names[i]) == 0) { aa_g_profile_mode = i; return 0; } } return -EINVAL; } 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 migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); if (PageDirty(page)) { clear_page_dirty_for_io(page); /* * Want to mark the page and the radix tree as dirty, and * redo the accounting that clear_page_dirty_for_io undid, * but we can't use set_page_dirty because that function * is actually a signal that all of the page has become dirty. * Whereas only part of our page may be dirty. */ if (PageSwapBacked(page)) SetPageDirty(newpage); else __set_page_dirty_nobuffers(newpage); } if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); } CWE ID: CWE-476 Target: 1 Example 2: Code: void IndexedDBTransaction::Start() { DCHECK_EQ(CREATED, state_); state_ = STARTED; diagnostics_.start_time = base::Time::Now(); if (!used_) { if (commit_pending_) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&CommitUnused, ptr_factory_.GetWeakPtr())); } return; } RunTasksIfStarted(); } 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: raptor_libxml_resolveEntity(void* user_data, const xmlChar *publicId, const xmlChar *systemId) { raptor_sax2* sax2 = (raptor_sax2*)user_data; return libxml2_resolveEntity(sax2->xc, publicId, systemId); } 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 Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; size_t length; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Convert HRZ raster image to pixel packets. */ image->columns=256; image->rows=240; image->depth=8; pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) (3*image->columns); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(4**p++)); SetPixelGreen(q,ScaleCharToQuantum(4**p++)); SetPixelBlue(q,ScaleCharToQuantum(4**p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void usbip_dump_pipe(unsigned int p) { unsigned char type = usb_pipetype(p); unsigned char ep = usb_pipeendpoint(p); unsigned char dev = usb_pipedevice(p); unsigned char dir = usb_pipein(p); pr_debug("dev(%d) ep(%d) [%s] ", dev, ep, dir ? "IN" : "OUT"); switch (type) { case PIPE_ISOCHRONOUS: pr_debug("ISO\n"); break; case PIPE_INTERRUPT: pr_debug("INT\n"); break; case PIPE_CONTROL: pr_debug("CTRL\n"); break; case PIPE_BULK: pr_debug("BULK\n"); break; default: pr_debug("ERR\n"); break; } } 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: StyleResolver::~StyleResolver() { m_fontSelector->unregisterForInvalidationCallbacks(this); m_fontSelector->clearDocument(); m_viewportStyleResolver->clearDocument(); } 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 Encoder::Flush() { const vpx_codec_err_t res = vpx_codec_encode(&encoder_, NULL, 0, 0, 0, deadline_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void release_one_tty(struct work_struct *work) { struct tty_struct *tty = container_of(work, struct tty_struct, hangup_work); struct tty_driver *driver = tty->driver; struct module *owner = driver->owner; if (tty->ops->cleanup) tty->ops->cleanup(tty); tty->magic = 0; tty_driver_kref_put(driver); module_put(owner); spin_lock(&tty_files_lock); list_del_init(&tty->tty_files); spin_unlock(&tty_files_lock); put_pid(tty->pgrp); put_pid(tty->session); free_tty_struct(tty); } 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 sha512_neon_init(struct shash_desc *desc) { struct sha512_state *sctx = shash_desc_ctx(desc); sctx->state[0] = SHA512_H0; sctx->state[1] = SHA512_H1; sctx->state[2] = SHA512_H2; sctx->state[3] = SHA512_H3; sctx->state[4] = SHA512_H4; sctx->state[5] = SHA512_H5; sctx->state[6] = SHA512_H6; sctx->state[7] = SHA512_H7; sctx->count[0] = sctx->count[1] = 0; 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: fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count = cc; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; while (count > stride) { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++) count -= stride; } _TIFFmemcpy(tmp, cp0, cc); cp = (uint8 *) cp0; for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[bps * count + byte] = tmp[byte * wc + count]; #else cp[bps * count + byte] = tmp[(bps - byte - 1) * wc + count]; #endif } } _TIFFfree(tmp); } CWE ID: CWE-119 Target: 1 Example 2: Code: static double filter_hermite(const double x1) { const double x = x1 < 0.0 ? -x1 : x1; if (x < 1.0) return ((2.0 * x - 3) * x * x + 1.0 ); return 0.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: static int filter_addr(struct sockaddr *sa) { struct ifsock *ifs; struct sockaddr_in *sin = (struct sockaddr_in *)sa; if (!sa) return 1; if (sa->sa_family != AF_INET) return 1; if (sin->sin_addr.s_addr == htonl(INADDR_ANY)) return 1; if (sin->sin_addr.s_addr == htonl(INADDR_LOOPBACK)) return 1; ifs = find_outbound(sa); if (ifs) { if (ifs->addr.sin_addr.s_addr != htonl(INADDR_ANY)) 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: int64 GetOriginalListPrefValue(size_t index) { return ListPrefInt64Value(*original_update_, index); } CWE ID: CWE-416 Target: 1 Example 2: Code: ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo( int child_id, int route_id, bool download, ResourceContext* context) { return new ResourceRequestInfoImpl( PROCESS_TYPE_RENDERER, child_id, route_id, 0, request_id_, false, // is_main_frame -1, // frame_id false, // parent_is_main_frame -1, // parent_frame_id ResourceType::SUB_RESOURCE, PAGE_TRANSITION_LINK, 0, // upload_size download, // is_download download, // allow_download false, // has_user_gesture WebKit::WebReferrerPolicyDefault, context); } 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 X509_STORE * setup_verify(zval * calist TSRMLS_DC) { X509_STORE *store; X509_LOOKUP * dir_lookup, * file_lookup; HashPosition pos; int ndirs = 0, nfiles = 0; store = X509_STORE_new(); if (store == NULL) { return NULL; } if (calist && (Z_TYPE_P(calist) == IS_ARRAY)) { zend_hash_internal_pointer_reset_ex(HASH_OF(calist), &pos); for (;; zend_hash_move_forward_ex(HASH_OF(calist), &pos)) { zval ** item; struct stat sb; if (zend_hash_get_current_data_ex(HASH_OF(calist), (void**)&item, &pos) == FAILURE) { break; } convert_to_string_ex(item); if (VCWD_STAT(Z_STRVAL_PP(item), &sb) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to stat %s", Z_STRVAL_PP(item)); continue; } if ((sb.st_mode & S_IFREG) == S_IFREG) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup == NULL || !X509_LOOKUP_load_file(file_lookup, Z_STRVAL_PP(item), X509_FILETYPE_PEM)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "error loading file %s", Z_STRVAL_PP(item)); } else { nfiles++; } file_lookup = NULL; } else { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup == NULL || !X509_LOOKUP_add_dir(dir_lookup, Z_STRVAL_PP(item), X509_FILETYPE_PEM)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "error loading directory %s", Z_STRVAL_PP(item)); } else { ndirs++; } dir_lookup = NULL; } } } if (nfiles == 0) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup) { X509_LOOKUP_load_file(file_lookup, NULL, X509_FILETYPE_DEFAULT); } } if (ndirs == 0) { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup) { X509_LOOKUP_add_dir(dir_lookup, NULL, X509_FILETYPE_DEFAULT); } } return store; } CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ParseRequestInfo(const struct mg_request_info* const request_info, std::string* method, std::vector<std::string>* path_segments, DictionaryValue** parameters, Response* const response) { *method = request_info->request_method; if (*method == "HEAD") *method = "GET"; else if (*method == "PUT") *method = "POST"; std::string uri(request_info->uri); SessionManager* manager = SessionManager::GetInstance(); uri = uri.substr(manager->url_base().length()); base::SplitString(uri, '/', path_segments); if (*method == "POST" && request_info->post_data_len > 0) { VLOG(1) << "...parsing request body"; std::string json(request_info->post_data, request_info->post_data_len); std::string error; if (!ParseJSONDictionary(json, parameters, &error)) { response->SetError(new Error( kBadRequest, "Failed to parse command data: " + error + "\n Data: " + json)); return false; } } VLOG(1) << "Parsed " << method << " " << uri << std::string(request_info->post_data, request_info->post_data_len); return true; } CWE ID: CWE-399 Target: 1 Example 2: Code: void idt_invalidate(void *addr) { struct desc_ptr idt = { .address = (unsigned long) addr, .size = 0 }; load_idt(&idt); } 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 sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev) { struct swap_info_struct *sis; struct swap_extent *start_se; struct swap_extent *se; pgoff_t offset; sis = swap_info[swp_type(entry)]; *bdev = sis->bdev; offset = swp_offset(entry); start_se = sis->curr_swap_extent; se = start_se; for ( ; ; ) { struct list_head *lh; if (se->start_page <= offset && offset < (se->start_page + se->nr_pages)) { return se->start_block + (offset - se->start_page); } lh = se->list.next; se = list_entry(lh, struct swap_extent, list); sis->curr_swap_extent = se; BUG_ON(se == start_se); /* It *must* be present */ } } 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: spnego_gss_unwrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t input_assoc_buffer, gss_buffer_t output_payload_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_unwrap_aead(minor_status, context_handle, input_message_buffer, input_assoc_buffer, output_payload_buffer, conf_state, qop_state); return (ret); } CWE ID: CWE-18 Target: 1 Example 2: Code: static int encode_attrs(struct xdr_stream *xdr, const struct iattr *iap, const struct nfs_server *server) { char owner_name[IDMAP_NAMESZ]; char owner_group[IDMAP_NAMESZ]; int owner_namelen = 0; int owner_grouplen = 0; __be32 *p; __be32 *q; int len; uint32_t bmval0 = 0; uint32_t bmval1 = 0; int status; /* * We reserve enough space to write the entire attribute buffer at once. * In the worst-case, this would be * 12(bitmap) + 4(attrlen) + 8(size) + 4(mode) + 4(atime) + 4(mtime) * = 36 bytes, plus any contribution from variable-length fields * such as owner/group. */ len = 16; /* Sigh */ if (iap->ia_valid & ATTR_SIZE) len += 8; if (iap->ia_valid & ATTR_MODE) len += 4; if (iap->ia_valid & ATTR_UID) { owner_namelen = nfs_map_uid_to_name(server->nfs_client, iap->ia_uid, owner_name); if (owner_namelen < 0) { dprintk("nfs: couldn't resolve uid %d to string\n", iap->ia_uid); /* XXX */ strcpy(owner_name, "nobody"); owner_namelen = sizeof("nobody") - 1; /* goto out; */ } len += 4 + (XDR_QUADLEN(owner_namelen) << 2); } if (iap->ia_valid & ATTR_GID) { owner_grouplen = nfs_map_gid_to_group(server->nfs_client, iap->ia_gid, owner_group); if (owner_grouplen < 0) { dprintk("nfs: couldn't resolve gid %d to string\n", iap->ia_gid); strcpy(owner_group, "nobody"); owner_grouplen = sizeof("nobody") - 1; /* goto out; */ } len += 4 + (XDR_QUADLEN(owner_grouplen) << 2); } if (iap->ia_valid & ATTR_ATIME_SET) len += 16; else if (iap->ia_valid & ATTR_ATIME) len += 4; if (iap->ia_valid & ATTR_MTIME_SET) len += 16; else if (iap->ia_valid & ATTR_MTIME) len += 4; RESERVE_SPACE(len); /* * We write the bitmap length now, but leave the bitmap and the attribute * buffer length to be backfilled at the end of this routine. */ WRITE32(2); q = p; p += 3; if (iap->ia_valid & ATTR_SIZE) { bmval0 |= FATTR4_WORD0_SIZE; WRITE64(iap->ia_size); } if (iap->ia_valid & ATTR_MODE) { bmval1 |= FATTR4_WORD1_MODE; WRITE32(iap->ia_mode & S_IALLUGO); } if (iap->ia_valid & ATTR_UID) { bmval1 |= FATTR4_WORD1_OWNER; WRITE32(owner_namelen); WRITEMEM(owner_name, owner_namelen); } if (iap->ia_valid & ATTR_GID) { bmval1 |= FATTR4_WORD1_OWNER_GROUP; WRITE32(owner_grouplen); WRITEMEM(owner_group, owner_grouplen); } if (iap->ia_valid & ATTR_ATIME_SET) { bmval1 |= FATTR4_WORD1_TIME_ACCESS_SET; WRITE32(NFS4_SET_TO_CLIENT_TIME); WRITE32(0); WRITE32(iap->ia_mtime.tv_sec); WRITE32(iap->ia_mtime.tv_nsec); } else if (iap->ia_valid & ATTR_ATIME) { bmval1 |= FATTR4_WORD1_TIME_ACCESS_SET; WRITE32(NFS4_SET_TO_SERVER_TIME); } if (iap->ia_valid & ATTR_MTIME_SET) { bmval1 |= FATTR4_WORD1_TIME_MODIFY_SET; WRITE32(NFS4_SET_TO_CLIENT_TIME); WRITE32(0); WRITE32(iap->ia_mtime.tv_sec); WRITE32(iap->ia_mtime.tv_nsec); } else if (iap->ia_valid & ATTR_MTIME) { bmval1 |= FATTR4_WORD1_TIME_MODIFY_SET; WRITE32(NFS4_SET_TO_SERVER_TIME); } /* * Now we backfill the bitmap and the attribute buffer length. */ if (len != ((char *)p - (char *)q) + 4) { printk(KERN_ERR "nfs: Attr length error, %u != %Zu\n", len, ((char *)p - (char *)q) + 4); BUG(); } len = (char *)p - (char *)q - 12; *q++ = htonl(bmval0); *q++ = htonl(bmval1); *q++ = htonl(len); status = 0; /* out: */ return status; } 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 PDEVICE_OBJECT FindVolumeWithHighestUniqueId (int maxUniqueId) { PDEVICE_OBJECT highestIdDevice = NULL; int highestId = -1; int drive; for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { PDEVICE_OBJECT device = GetVirtualVolumeDeviceObject (drive); if (device) { PEXTENSION extension = (PEXTENSION) device->DeviceExtension; if (extension->UniqueVolumeId > highestId && extension->UniqueVolumeId <= maxUniqueId) { highestId = extension->UniqueVolumeId; highestIdDevice = device; } } } return highestIdDevice; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int pit_ioport_read(struct kvm_io_device *this, gpa_t addr, int len, void *data) { struct kvm_pit *pit = dev_to_pit(this); struct kvm_kpit_state *pit_state = &pit->pit_state; struct kvm *kvm = pit->kvm; int ret, count; struct kvm_kpit_channel_state *s; if (!pit_in_range(addr)) return -EOPNOTSUPP; addr &= KVM_PIT_CHANNEL_MASK; s = &pit_state->channels[addr]; mutex_lock(&pit_state->lock); if (s->status_latched) { s->status_latched = 0; ret = s->status; } else if (s->count_latched) { switch (s->count_latched) { default: case RW_STATE_LSB: ret = s->latched_count & 0xff; s->count_latched = 0; break; case RW_STATE_MSB: ret = s->latched_count >> 8; s->count_latched = 0; break; case RW_STATE_WORD0: ret = s->latched_count & 0xff; s->count_latched = RW_STATE_MSB; break; } } else { switch (s->read_state) { default: case RW_STATE_LSB: count = pit_get_count(kvm, addr); ret = count & 0xff; break; case RW_STATE_MSB: count = pit_get_count(kvm, addr); ret = (count >> 8) & 0xff; break; case RW_STATE_WORD0: count = pit_get_count(kvm, addr); ret = count & 0xff; s->read_state = RW_STATE_WORD1; break; case RW_STATE_WORD1: count = pit_get_count(kvm, addr); ret = (count >> 8) & 0xff; s->read_state = RW_STATE_WORD0; break; } } if (len > sizeof(ret)) len = sizeof(ret); memcpy(data, (char *)&ret, len); mutex_unlock(&pit_state->lock); return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void pdftex_warn(const char *fmt, ...) { va_list args; va_start(args, fmt); fputs("\nWarning: module writet1 of dvips", stderr); if (cur_file_name) fprintf(stderr, " (file %s)", cur_file_name); fputs(": ", stderr); vsprintf(print_buf, fmt, args); fputs(print_buf, stderr); fputs("\n", stderr); va_end(args); } 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: kdc_handle_protected_negotiation(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, const krb5_keyblock *reply_key, krb5_pa_data ***out_enc_padata) { krb5_error_code retval = 0; krb5_checksum checksum; krb5_data *out = NULL; krb5_pa_data pa, *pa_in; pa_in = krb5int_find_pa_data(context, request->padata, KRB5_ENCPADATA_REQ_ENC_PA_REP); if (pa_in == NULL) return 0; pa.magic = KV5M_PA_DATA; pa.pa_type = KRB5_ENCPADATA_REQ_ENC_PA_REP; memset(&checksum, 0, sizeof(checksum)); retval = krb5_c_make_checksum(context,0, reply_key, KRB5_KEYUSAGE_AS_REQ, req_pkt, &checksum); if (retval != 0) goto cleanup; retval = encode_krb5_checksum(&checksum, &out); if (retval != 0) goto cleanup; pa.contents = (krb5_octet *) out->data; pa.length = out->length; retval = add_pa_data_element(context, &pa, out_enc_padata, FALSE); if (retval) goto cleanup; out->data = NULL; pa.magic = KV5M_PA_DATA; pa.pa_type = KRB5_PADATA_FX_FAST; pa.length = 0; pa.contents = NULL; retval = add_pa_data_element(context, &pa, out_enc_padata, FALSE); cleanup: if (checksum.contents) krb5_free_checksum_contents(context, &checksum); if (out != NULL) krb5_free_data(context, out); return retval; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static BT_HDR *create_pbuf(UINT16 len, UINT8 *data) { BT_HDR* p_buf = GKI_getbuf((UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR))); if (p_buf) { UINT8* pbuf_data; p_buf->len = len; p_buf->offset = BTA_HH_MIN_OFFSET; pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset; memcpy(pbuf_data, data, len); } return p_buf; } CWE ID: CWE-119 Target: 1 Example 2: Code: Editor::Command Editor::CreateCommand(const String& command_name, EditorCommandSource source) { return Command(InternalCommand(command_name), source, frame_); } 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 SynchronousCompositorImpl::DidDestroyRendererObjects() { DCHECK(output_surface_); DCHECK(begin_frame_source_); if (registered_with_client_) { output_surface_->SetTreeActivationCallback(base::Closure()); compositor_client_->DidDestroyCompositor(this); registered_with_client_ = false; } begin_frame_source_->SetClient(nullptr); output_surface_->SetSyncClient(nullptr); synchronous_input_handler_proxy_->SetOnlySynchronouslyAnimateRootFlings( nullptr); synchronous_input_handler_proxy_ = nullptr; begin_frame_source_ = nullptr; output_surface_ = nullptr; need_animate_input_ = false; } 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 nfc_llcp_build_gb(struct nfc_llcp_local *local) { u8 *gb_cur, *version_tlv, version, version_length; u8 *lto_tlv, lto_length; u8 *wks_tlv, wks_length; u8 *miux_tlv, miux_length; __be16 wks = cpu_to_be16(local->local_wks); u8 gb_len = 0; int ret = 0; version = LLCP_VERSION_11; version_tlv = nfc_llcp_build_tlv(LLCP_TLV_VERSION, &version, 1, &version_length); gb_len += version_length; lto_tlv = nfc_llcp_build_tlv(LLCP_TLV_LTO, &local->lto, 1, &lto_length); gb_len += lto_length; pr_debug("Local wks 0x%lx\n", local->local_wks); wks_tlv = nfc_llcp_build_tlv(LLCP_TLV_WKS, (u8 *)&wks, 2, &wks_length); gb_len += wks_length; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&local->miux, 0, &miux_length); gb_len += miux_length; gb_len += ARRAY_SIZE(llcp_magic); if (gb_len > NFC_MAX_GT_LEN) { ret = -EINVAL; goto out; } gb_cur = local->gb; memcpy(gb_cur, llcp_magic, ARRAY_SIZE(llcp_magic)); gb_cur += ARRAY_SIZE(llcp_magic); memcpy(gb_cur, version_tlv, version_length); gb_cur += version_length; memcpy(gb_cur, lto_tlv, lto_length); gb_cur += lto_length; memcpy(gb_cur, wks_tlv, wks_length); gb_cur += wks_length; memcpy(gb_cur, miux_tlv, miux_length); gb_cur += miux_length; local->gb_len = gb_len; out: kfree(version_tlv); kfree(lto_tlv); kfree(wks_tlv); kfree(miux_tlv); return ret; } CWE ID: CWE-476 Target: 1 Example 2: Code: void AutocompleteEditModel::StartAutocomplete( bool has_selected_text, bool prevent_inline_autocomplete) const { ClearPopupKeywordMode(); bool keyword_is_selected = KeywordIsSelected(); popup_->SetHoveredLine(AutocompletePopupModel::kNoMatch); autocomplete_controller_->Start( user_text_, GetDesiredTLD(), prevent_inline_autocomplete || just_deleted_text_ || (has_selected_text && inline_autocomplete_text_.empty()) || (paste_state_ != NONE), keyword_is_selected, keyword_is_selected || allow_exact_keyword_match_, AutocompleteInput::ALL_MATCHES); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Document::writeln(LocalDOMWindow* calling_window, TrustedHTML* text, ExceptionState& exception_state) { DCHECK(calling_window); DCHECK(RuntimeEnabledFeatures::TrustedDOMTypesEnabled()); writeln(text->toString(), calling_window->document(), exception_state); } 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 __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; unsigned long i; struct kvm_memory_slot *memslot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* Disallow changing a memory slot's size. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; for (i = 0; i < KVM_MEMORY_SLOTS; ++i) { struct kvm_memory_slot *s = &kvm->memslots->memslots[i]; if (s == memslot || !s->npages) continue; if (!((base_gfn + npages <= s->base_gfn) || (base_gfn >= s->base_gfn + s->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* Allocate if a slot is being created */ if (npages && !old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted * memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); /* * If the new memory slot is created, we need to clear all * mmio sptes. */ if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) kvm_arch_flush_shadow_all(kvm); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; } CWE ID: CWE-399 Target: 1 Example 2: Code: static void p4_pmu_enable_event(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; int thread = p4_ht_config_thread(hwc->config); u64 escr_conf = p4_config_unpack_escr(p4_clear_ht_bit(hwc->config)); unsigned int idx = p4_config_unpack_event(hwc->config); struct p4_event_bind *bind; u64 escr_addr, cccr; bind = &p4_event_bind_map[idx]; escr_addr = (u64)bind->escr_msr[thread]; /* * - we dont support cascaded counters yet * - and counter 1 is broken (erratum) */ WARN_ON_ONCE(p4_is_event_cascaded(hwc->config)); WARN_ON_ONCE(hwc->idx == 1); /* we need a real Event value */ escr_conf &= ~P4_ESCR_EVENT_MASK; escr_conf |= P4_ESCR_EVENT(P4_OPCODE_EVNT(bind->opcode)); cccr = p4_config_unpack_cccr(hwc->config); /* * it could be Cache event so we need to write metrics * into additional MSRs */ p4_pmu_enable_pebs(hwc->config); (void)checking_wrmsrl(escr_addr, escr_conf); (void)checking_wrmsrl(hwc->config_base, (cccr & ~P4_CCCR_RESERVED) | P4_CCCR_ENABLE); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int detect_datev( sc_pkcs15_card_t *p15card ){ if(insert_cert(p15card,"3000C500", 0x45, 0, "Signatur Zertifikat")) return 1; p15card->tokeninfo->manufacturer_id = strdup("DATEV"); p15card->tokeninfo->label = strdup("DATEV Classic"); insert_cert(p15card,"DF02C200", 0x46, 0, "Verschluesselungs Zertifikat"); insert_cert(p15card,"DF02C500", 0x47, 0, "Authentifizierungs Zertifikat"); insert_key(p15card,"30005371", 0x45, 0x82, 1024, 1, "Signatur Schluessel"); insert_key(p15card,"DF0253B1", 0x46, 0x81, 1024, 1, "Verschluesselungs Schluessel"); insert_key(p15card,"DF025371", 0x47, 0x82, 1024, 1, "Authentifizierungs Schluessel"); insert_pin(p15card,"5001", 1, 0, 0x01, 6, "PIN", SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED ); return 0; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PasswordAutofillManager::OnShowPasswordSuggestions( int key, base::i18n::TextDirection text_direction, const base::string16& typed_username, int options, const gfx::RectF& bounds) { std::vector<autofill::Suggestion> suggestions; LoginToPasswordInfoMap::const_iterator fill_data_it = login_to_password_info_.find(key); if (fill_data_it == login_to_password_info_.end()) { NOTREACHED(); return; } GetSuggestions(fill_data_it->second, typed_username, &suggestions, (options & autofill::SHOW_ALL) != 0, (options & autofill::IS_PASSWORD_FIELD) != 0); form_data_key_ = key; if (suggestions.empty()) { autofill_client_->HideAutofillPopup(); return; } if (options & autofill::IS_PASSWORD_FIELD) { autofill::Suggestion password_field_suggestions(l10n_util::GetStringUTF16( IDS_AUTOFILL_PASSWORD_FIELD_SUGGESTIONS_TITLE)); password_field_suggestions.frontend_id = autofill::POPUP_ITEM_ID_TITLE; suggestions.insert(suggestions.begin(), password_field_suggestions); } GURL origin = (fill_data_it->second).origin; bool is_context_secure = autofill_client_->IsContextSecure() && (!origin.is_valid() || !origin.SchemeIs("http")); if (!is_context_secure && security_state::IsHttpWarningInFormEnabled()) { std::string icon_str; if (origin.is_valid() && origin.SchemeIs("http")) { icon_str = "httpWarning"; } else { icon_str = "httpsInvalid"; } autofill::Suggestion http_warning_suggestion( l10n_util::GetStringUTF8(IDS_AUTOFILL_LOGIN_HTTP_WARNING_MESSAGE), l10n_util::GetStringUTF8(IDS_AUTOFILL_HTTP_WARNING_LEARN_MORE), icon_str, autofill::POPUP_ITEM_ID_HTTP_NOT_SECURE_WARNING_MESSAGE); #if !defined(OS_ANDROID) suggestions.insert(suggestions.begin(), autofill::Suggestion()); suggestions.front().frontend_id = autofill::POPUP_ITEM_ID_SEPARATOR; #endif suggestions.insert(suggestions.begin(), http_warning_suggestion); if (!did_show_form_not_secure_warning_) { did_show_form_not_secure_warning_ = true; metrics_util::LogShowedFormNotSecureWarningOnCurrentNavigation(); } } if (ShouldShowManualFallbackForPreLollipop( autofill_client_->GetSyncService())) { if (base::FeatureList::IsEnabled( password_manager::features::kEnableManualFallbacksFilling) && (options & autofill::IS_PASSWORD_FIELD) && password_client_ && password_client_->IsFillingFallbackEnabledForCurrentPage()) { AddSimpleSuggestionWithSeparatorOnTop( IDS_AUTOFILL_SHOW_ALL_SAVED_FALLBACK, autofill::POPUP_ITEM_ID_ALL_SAVED_PASSWORDS_ENTRY, &suggestions); show_all_saved_passwords_shown_context_ = metrics_util::SHOW_ALL_SAVED_PASSWORDS_CONTEXT_PASSWORD; metrics_util::LogContextOfShowAllSavedPasswordsShown( show_all_saved_passwords_shown_context_); } if (base::FeatureList::IsEnabled( password_manager::features::kEnableManualFallbacksGeneration) && password_manager_util::GetPasswordSyncState( autofill_client_->GetSyncService()) == SYNCING_NORMAL_ENCRYPTION) { AddSimpleSuggestionWithSeparatorOnTop( IDS_AUTOFILL_GENERATE_PASSWORD_FALLBACK, autofill::POPUP_ITEM_ID_GENERATE_PASSWORD_ENTRY, &suggestions); } } autofill_client_->ShowAutofillPopup(bounds, text_direction, suggestions, weak_ptr_factory_.GetWeakPtr()); } CWE ID: CWE-264 Target: 1 Example 2: Code: CSSStyleSheetResource::CSSStyleSheetResource( const ResourceRequest& resource_request, const ResourceLoaderOptions& options, const TextResourceDecoderOptions& decoder_options) : TextResource(resource_request, ResourceType::kCSSStyleSheet, options, decoder_options) {} 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 unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct *desc; unsigned long limit; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return 0; if (user_64bit_mode(regs) || v8086_mode(regs)) return -1L; if (!sel) return 0; desc = get_desc(sel); if (!desc) return 0; /* * If the granularity bit is set, the limit is given in multiples * of 4096. This also means that the 12 least significant bits are * not tested when checking the segment limits. In practice, * this means that the segment ends in (limit << 12) + 0xfff. */ limit = get_desc_limit(desc); if (desc->g) limit = (limit << 12) + 0xfff; return limit; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int hugetlbfs_statfs(struct dentry *dentry, struct kstatfs *buf) { struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(dentry->d_sb); struct hstate *h = hstate_inode(dentry->d_inode); buf->f_type = HUGETLBFS_MAGIC; buf->f_bsize = huge_page_size(h); if (sbinfo) { spin_lock(&sbinfo->stat_lock); /* If no limits set, just report 0 for max/free/used * blocks, like simple_statfs() */ if (sbinfo->max_blocks >= 0) { buf->f_blocks = sbinfo->max_blocks; buf->f_bavail = buf->f_bfree = sbinfo->free_blocks; buf->f_files = sbinfo->max_inodes; buf->f_ffree = sbinfo->free_inodes; } spin_unlock(&sbinfo->stat_lock); } buf->f_namelen = NAME_MAX; return 0; } CWE ID: CWE-399 Target: 1 Example 2: Code: cifs_writedata_release(struct kref *refcount) { struct cifs_writedata *wdata = container_of(refcount, struct cifs_writedata, refcount); if (wdata->cfile) cifsFileInfo_put(wdata->cfile); kfree(wdata); } 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: Track::~Track() { Info& info = const_cast<Info&>(m_info); info.Clear(); ContentEncoding** i = content_encoding_entries_; ContentEncoding** const j = content_encoding_entries_end_; while (i != j) { ContentEncoding* const encoding = *i++; delete encoding; } delete [] content_encoding_entries_; } 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 parseOperand(RAsm *a, const char *str, Operand *op, bool isrepop) { size_t pos, nextpos = 0; x86newTokenType last_type; int size_token = 1; bool explicit_size = false; int reg_index = 0; op->type = 0; while (size_token) { pos = nextpos; last_type = getToken (str, &pos, &nextpos); if (!r_str_ncasecmp (str + pos, "ptr", 3)) { continue; } else if (!r_str_ncasecmp (str + pos, "byte", 4)) { op->type |= OT_MEMORY | OT_BYTE; op->dest_size = OT_BYTE; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "word", 4)) { op->type |= OT_MEMORY | OT_WORD; op->dest_size = OT_WORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "dword", 5)) { op->type |= OT_MEMORY | OT_DWORD; op->dest_size = OT_DWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "qword", 5)) { op->type |= OT_MEMORY | OT_QWORD; op->dest_size = OT_QWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "oword", 5)) { op->type |= OT_MEMORY | OT_OWORD; op->dest_size = OT_OWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "tbyte", 5)) { op->type |= OT_MEMORY | OT_TBYTE; op->dest_size = OT_TBYTE; explicit_size = true; } else { // the current token doesn't denote a size size_token = 0; } } if (str[pos] == '[') { if (!op->type) { op->type = OT_MEMORY; } op->offset = op->scale[0] = op->scale[1] = 0; ut64 temp = 1; Register reg = X86R_UNDEFINED; bool first_reg = true; while (str[pos] != ']') { if (pos > nextpos) { break; } pos = nextpos; if (!str[pos]) { break; } last_type = getToken (str, &pos, &nextpos); if (last_type == TT_SPECIAL) { if (str[pos] == '+' || str[pos] == '-' || str[pos] == ']') { if (reg != X86R_UNDEFINED) { op->regs[reg_index] = reg; op->scale[reg_index] = temp; ++reg_index; } else { op->offset += temp; op->regs[reg_index] = X86R_UNDEFINED; } temp = 1; reg = X86R_UNDEFINED; } else if (str[pos] == '*') { } } else if (last_type == TT_WORD) { ut32 reg_type = 0; if (reg != X86R_UNDEFINED) { op->type = 0; // Make the result invalid } nextpos = pos; reg = parseReg (a, str, &nextpos, &reg_type); if (first_reg) { op->extended = false; if (reg > 8) { op->extended = true; op->reg = reg - 9; } first_reg = false; } else if (reg > 8) { op->reg = reg - 9; } if (reg_type & OT_REGTYPE & OT_SEGMENTREG) { op->reg = reg; op->type = reg_type; parse_segment_offset (a, str, &nextpos, op, reg_index); return nextpos; } if (!explicit_size) { op->type |= reg_type; } op->reg_size = reg_type; op->explicit_size = explicit_size; if (!(reg_type & OT_GPREG)) { op->type = 0; // Make the result invalid } } else { char *p = strchr (str, '+'); op->offset_sign = 1; if (!p) { p = strchr (str, '-'); if (p) { op->offset_sign = -1; } } char * plus = strchr (str, '+'); char * minus = strchr (str, '-'); char * closeB = strchr (str, ']'); if (plus && minus && plus < closeB && minus < closeB) { op->offset_sign = -1; } char *tmp; tmp = malloc (strlen (str + pos) + 1); strcpy (tmp, str + pos); strtok (tmp, "+-"); st64 read = getnum (a, tmp); free (tmp); temp *= read; } } } else if (last_type == TT_WORD) { // register nextpos = pos; RFlagItem *flag; if (isrepop) { op->is_good_flag = false; strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1); op->rep_op[MAX_REPOP_LENGTH - 1] = '\0'; return nextpos; } op->reg = parseReg (a, str, &nextpos, &op->type); op->extended = false; if (op->reg > 8) { op->extended = true; op->reg -= 9; } if (op->type & OT_REGTYPE & OT_SEGMENTREG) { parse_segment_offset (a, str, &nextpos, op, reg_index); return nextpos; } if (op->reg == X86R_UNDEFINED) { op->is_good_flag = false; if (a->num && a->num->value == 0) { return nextpos; } op->type = OT_CONSTANT; RCore *core = a->num? (RCore *)(a->num->userptr): NULL; if (core && (flag = r_flag_get (core->flags, str))) { op->is_good_flag = true; } char *p = strchr (str, '-'); if (p) { op->sign = -1; str = ++p; } op->immediate = getnum (a, str); } else if (op->reg < X86R_UNDEFINED) { strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1); op->rep_op[MAX_REPOP_LENGTH - 1] = '\0'; } } else { // immediate op->type = OT_CONSTANT; op->sign = 1; char *p = strchr (str, '-'); if (p) { op->sign = -1; str = ++p; } op->immediate = getnum (a, str); } return nextpos; } CWE ID: CWE-125 Target: 1 Example 2: Code: int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 pid, unsigned int group, int report, gfp_t flags) { int err = 0; if (group) { int exclude_pid = 0; if (report) { atomic_inc(&skb->users); exclude_pid = pid; } /* errors reported via destination sk->sk_err, but propagate * delivery errors if NETLINK_BROADCAST_ERROR flag is set */ err = nlmsg_multicast(sk, skb, exclude_pid, group, flags); } if (report) { int err2; err2 = nlmsg_unicast(sk, skb, pid); if (!err || err == -ESRCH) err = err2; } return err; } CWE ID: CWE-287 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 TestURLLoader::TestFollowURLRedirect() { pp::URLRequestInfo request(instance_); std::string redirect_prefix("/server-redirect?"); std::string redirect_url = GetReachableAbsoluteURL("test_url_loader_data/hello.txt"); request.SetURL(redirect_prefix.append(redirect_url)); return LoadAndCompareBody(request, "hello\n"); } CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void bta_hl_co_put_rx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle, UINT16 data_size, UINT8 *p_data, UINT16 evt) { UINT8 app_idx, mcl_idx, mdl_idx; btif_hl_mdl_cb_t *p_dcb; tBTA_HL_STATUS status = BTA_HL_STATUS_FAIL; int r; BTIF_TRACE_DEBUG("%s app_id=%d mdl_handle=0x%x data_size=%d", __FUNCTION__,app_id, mdl_handle, data_size); if (btif_hl_find_mdl_idx_using_handle(mdl_handle, &app_idx, &mcl_idx, &mdl_idx)) { p_dcb = BTIF_HL_GET_MDL_CB_PTR(app_idx, mcl_idx, mdl_idx); if ((p_dcb->p_rx_pkt = (UINT8 *)btif_hl_get_buf(data_size)) != NULL) { memcpy(p_dcb->p_rx_pkt, p_data, data_size); if (p_dcb->p_scb) { BTIF_TRACE_DEBUG("app_idx=%d mcl_idx=0x%x mdl_idx=0x%x data_size=%d", app_idx, mcl_idx, mdl_idx, data_size); r = send(p_dcb->p_scb->socket_id[1], p_dcb->p_rx_pkt, data_size, 0); if (r == data_size) { BTIF_TRACE_DEBUG("socket send success data_size=%d", data_size); status = BTA_HL_STATUS_OK; } else { BTIF_TRACE_ERROR("socket send failed r=%d data_size=%d",r, data_size); } } btif_hl_free_buf((void **) &p_dcb->p_rx_pkt); } } bta_hl_ci_put_rx_data(mdl_handle, status, evt); } CWE ID: CWE-284 Target: 1 Example 2: Code: int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu) { struct page *page; struct kvm *kvm; int r; BUG_ON(vcpu->kvm == NULL); kvm = vcpu->kvm; vcpu->arch.pv.pv_unhalted = false; vcpu->arch.emulate_ctxt.ops = &emulate_ops; if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_reset_bsp(vcpu)) vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; else vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED; page = alloc_page(GFP_KERNEL | __GFP_ZERO); if (!page) { r = -ENOMEM; goto fail; } vcpu->arch.pio_data = page_address(page); kvm_set_tsc_khz(vcpu, max_tsc_khz); r = kvm_mmu_create(vcpu); if (r < 0) goto fail_free_pio_data; if (irqchip_in_kernel(kvm)) { r = kvm_create_lapic(vcpu); if (r < 0) goto fail_mmu_destroy; } else static_key_slow_inc(&kvm_no_apic_vcpu); vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4, GFP_KERNEL); if (!vcpu->arch.mce_banks) { r = -ENOMEM; goto fail_free_lapic; } vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS; if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) { r = -ENOMEM; goto fail_free_mce_banks; } fx_init(vcpu); vcpu->arch.ia32_tsc_adjust_msr = 0x0; vcpu->arch.pv_time_enabled = false; vcpu->arch.guest_supported_xcr0 = 0; vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET; vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu); vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT; kvm_async_pf_hash_reset(vcpu); kvm_pmu_init(vcpu); vcpu->arch.pending_external_vector = -1; return 0; fail_free_mce_banks: kfree(vcpu->arch.mce_banks); fail_free_lapic: kvm_free_lapic(vcpu); fail_mmu_destroy: kvm_mmu_destroy(vcpu); fail_free_pio_data: free_page((unsigned long)vcpu->arch.pio_data); fail: return r; } 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 LargeObjectArena::freeLargeObjectPage(LargeObjectPage* object) { ASAN_UNPOISON_MEMORY_REGION(object->payload(), object->payloadSize()); object->heapObjectHeader()->finalize(object->payload(), object->payloadSize()); getThreadState()->heap().heapStats().decreaseAllocatedSpace(object->size()); ASAN_UNPOISON_MEMORY_REGION(object->heapObjectHeader(), sizeof(HeapObjectHeader)); ASAN_UNPOISON_MEMORY_REGION(object->getAddress() + object->size(), allocationGranularity); PageMemory* memory = object->storage(); object->~LargeObjectPage(); delete memory; } 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 InputDispatcher::enqueueDispatchEntryLocked( const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode) { int32_t inputTargetFlags = inputTarget->flags; if (!(inputTargetFlags & dispatchMode)) { return; } inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode; DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset, inputTarget->scaleFactor); switch (eventEntry->type) { case EventEntry::TYPE_KEY: { KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry); dispatchEntry->resolvedAction = keyEntry->action; dispatchEntry->resolvedFlags = keyEntry->flags; if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event", connection->getInputChannelName()); #endif delete dispatchEntry; return; // skip the inconsistent event } break; } case EventEntry::TYPE_MOTION: { MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry); if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN; } else { dispatchEntry->resolvedAction = motionEntry->action; } if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE && !connection->inputState.isHovering( motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event", connection->getInputChannelName()); #endif dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; } dispatchEntry->resolvedFlags = motionEntry->flags; if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) { dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED; } if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event", connection->getInputChannelName()); #endif delete dispatchEntry; return; // skip the inconsistent event } break; } } if (dispatchEntry->hasForegroundTarget()) { incrementPendingForegroundDispatchesLocked(eventEntry); } connection->outboundQueue.enqueueAtTail(dispatchEntry); traceOutboundQueueLengthLocked(connection); } CWE ID: CWE-264 Target: 1 Example 2: Code: void WebMediaPlayerImpl::SetSinkId(const blink::WebString& sink_id, blink::WebSetSinkIdCallbacks* web_callback) { DCHECK(main_task_runner_->BelongsToCurrentThread()); DVLOG(1) << __func__; media::OutputDeviceStatusCB callback = media::ConvertToOutputDeviceStatusCB(web_callback); media_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SetSinkIdOnMediaThread, audio_source_provider_, sink_id.Utf8(), callback)); } 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: mysqlnd_switch_to_ssl_if_needed( MYSQLND_CONN_DATA * conn, const MYSQLND_PACKET_GREET * const greet_packet, const MYSQLND_OPTIONS * const options, unsigned long mysql_flags TSRMLS_DC ) { enum_func_status ret = FAIL; const MYSQLND_CHARSET * charset; MYSQLND_PACKET_AUTH * auth_packet; DBG_ENTER("mysqlnd_switch_to_ssl_if_needed"); auth_packet = conn->protocol->m.get_auth_packet(conn->protocol, FALSE TSRMLS_CC); if (!auth_packet) { SET_OOM_ERROR(*conn->error_info); goto end; } auth_packet->client_flags = mysql_flags; auth_packet->max_packet_size = MYSQLND_ASSEMBLED_PACKET_MAX_SIZE; if (options->charset_name && (charset = mysqlnd_find_charset_name(options->charset_name))) { auth_packet->charset_no = charset->nr; } else { #if MYSQLND_UNICODE auth_packet->charset_no = 200;/* utf8 - swedish collation, check mysqlnd_charset.c */ #else auth_packet->charset_no = greet_packet->charset_no; #endif } #ifdef MYSQLND_SSL_SUPPORTED if ((greet_packet->server_capabilities & CLIENT_SSL) && (mysql_flags & CLIENT_SSL)) { zend_bool verify = mysql_flags & CLIENT_SSL_VERIFY_SERVER_CERT? TRUE:FALSE; DBG_INF("Switching to SSL"); if (!PACKET_WRITE(auth_packet, conn)) { CONN_SET_STATE(conn, CONN_QUIT_SENT); SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone); goto end; } conn->net->m.set_client_option(conn->net, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (const char *) &verify TSRMLS_CC); if (FAIL == conn->net->m.enable_ssl(conn->net TSRMLS_CC)) { goto end; } } #endif ret = PASS; end: PACKET_FREE(auth_packet); DBG_RETURN(ret); } CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: std::string* GetTestingDMToken() { static std::string dm_token; return &dm_token; } CWE ID: CWE-20 Target: 1 Example 2: Code: json_recv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); char *str; int nbytes; JsonLexContext *lex; str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes); /* Validate it. */ lex = makeJsonLexContextCstringLen(str, nbytes, false); pg_parse_json(lex, &nullSemAction); PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes)); } 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 UnloadController::TabDetachedAt(TabContents* contents, int index) { TabDetachedImpl(contents); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int usb_enumerate_device_otg(struct usb_device *udev) { int err = 0; #ifdef CONFIG_USB_OTG /* * OTG-aware devices on OTG-capable root hubs may be able to use SRP, * to wake us after we've powered off VBUS; and HNP, switching roles * "host" to "peripheral". The OTG descriptor helps figure this out. */ if (!udev->bus->is_b_host && udev->config && udev->parent == udev->bus->root_hub) { struct usb_otg_descriptor *desc = NULL; struct usb_bus *bus = udev->bus; unsigned port1 = udev->portnum; /* descriptor may appear anywhere in config */ err = __usb_get_extra_descriptor(udev->rawdescriptors[0], le16_to_cpu(udev->config[0].desc.wTotalLength), USB_DT_OTG, (void **) &desc); if (err || !(desc->bmAttributes & USB_OTG_HNP)) return 0; dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n", (port1 == bus->otg_port) ? "" : "non-"); /* enable HNP before suspend, it's simpler */ if (port1 == bus->otg_port) { bus->b_hnp_enable = 1; err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, 0, USB_DEVICE_B_HNP_ENABLE, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (err < 0) { /* * OTG MESSAGE: report errors here, * customize to match your product. */ dev_err(&udev->dev, "can't set HNP mode: %d\n", err); bus->b_hnp_enable = 0; } } else if (desc->bLength == sizeof (struct usb_otg_descriptor)) { /* Set a_alt_hnp_support for legacy otg device */ err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, 0, USB_DEVICE_A_ALT_HNP_SUPPORT, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (err < 0) dev_err(&udev->dev, "set a_alt_hnp_support failed: %d\n", err); } } #endif return err; } CWE ID: CWE-400 Target: 1 Example 2: Code: void ChromeClientImpl::AttachRootGraphicsLayer(GraphicsLayer* root_layer, LocalFrame* local_frame) { DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV2Enabled()); WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(local_frame)->LocalRoot(); DCHECK(web_frame->FrameWidget() || !root_layer); if (web_frame->FrameWidget()) web_frame->FrameWidget()->SetRootGraphicsLayer(root_layer); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; VpxVideoReader *reader = NULL; const VpxVideoInfo *info = NULL; const VpxInterface *decoder = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->interface())); if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder"); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame"); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { unsigned char digest[16]; get_image_md5(img, digest); print_md5(outfile, digest); fprintf(outfile, " img-%dx%d-%04d.i420\n", img->d_w, img->d_h, ++frame_cnt); } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cJSON *cJSON_CreateNull( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_NULL; return item; } CWE ID: CWE-119 Target: 1 Example 2: Code: void TabStripModel::InsertTabContentsAt(int index, TabContents* contents, int add_types) { bool active = add_types & ADD_ACTIVE; extensions::TabHelper* extensions_tab_helper = extensions::TabHelper::FromWebContents(contents->web_contents()); bool pin = extensions_tab_helper->is_app() || add_types & ADD_PINNED; index = ConstrainInsertionIndex(index, pin); closing_all_ = false; WebContents* active_contents = GetActiveWebContents(); WebContentsData* data = new WebContentsData(contents->web_contents()); data->pinned = pin; if ((add_types & ADD_INHERIT_GROUP) && active_contents) { if (active) { ForgetAllOpeners(); } data->SetGroup(active_contents); } else if ((add_types & ADD_INHERIT_OPENER) && active_contents) { if (active) { ForgetAllOpeners(); } data->opener = active_contents; } contents_data_.insert(contents_data_.begin() + index, data); selection_model_.IncrementFrom(index); FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabInsertedAt(contents->web_contents(), index, active)); if (active) { TabStripSelectionModel new_model; new_model.Copy(selection_model_); new_model.SetSelectedIndex(index); SetSelection(new_model, NOTIFY_DEFAULT); } } 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 Texture::Destroy() { if (id_ != 0) { ScopedGLErrorSuppressor suppressor(decoder_); glDeleteTextures(1, &id_); id_ = 0; memory_tracker_.UpdateMemRepresented(0); TRACE_BACKBUFFER_MEMORY_TOTAL(decoder_); } } 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: png_write_start_row(png_structp png_ptr) { #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif png_size_t buf_size; png_debug(1, "in png_write_start_row"); buf_size = (png_size_t)(PNG_ROWBYTES( png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1); /* Set up row buffer */ png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size); png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE; #ifdef PNG_WRITE_FILTER_SUPPORTED /* Set up filtering buffer, if using this filter */ if (png_ptr->do_filter & PNG_FILTER_SUB) { png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB; } /* We only need to keep the previous row if we are using one of these. */ if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) { /* Set up previous row buffer */ png_ptr->prev_row = (png_bytep)png_calloc(png_ptr, (png_uint_32)buf_size); if (png_ptr->do_filter & PNG_FILTER_UP) { png_ptr->up_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->up_row[0] = PNG_FILTER_VALUE_UP; } if (png_ptr->do_filter & PNG_FILTER_AVG) { png_ptr->avg_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG; } if (png_ptr->do_filter & PNG_FILTER_PAETH) { png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_ptr->rowbytes + 1)); png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH; } } #endif /* PNG_WRITE_FILTER_SUPPORTED */ #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced, we need to set up width and height of pass */ if (png_ptr->interlaced) { if (!(png_ptr->transformations & PNG_INTERLACE)) { png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 - png_pass_start[0]) / png_pass_inc[0]; } else { png_ptr->num_rows = png_ptr->height; png_ptr->usr_width = png_ptr->width; } } else #endif { png_ptr->num_rows = png_ptr->height; png_ptr->usr_width = png_ptr->width; } png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_ptr->zstream.next_out = png_ptr->zbuf; } CWE ID: CWE-119 Target: 1 Example 2: Code: void Respond(const WebURLResponse& response) { EXPECT_TRUE(active_loader()); data_provider()->DidReceiveResponse(response); base::RunLoop().RunUntilIdle(); } 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 vp8_decoder_remove_threads(VP8D_COMP *pbi) { /* shutdown MB Decoding thread; */ if (pbi->b_multithreaded_rd) { int i; pbi->b_multithreaded_rd = 0; /* allow all threads to exit */ for (i = 0; i < pbi->allocated_decoding_thread_count; i++) { sem_post(&pbi->h_event_start_decoding[i]); pthread_join(pbi->h_decoding_thread[i], NULL); } for (i = 0; i < pbi->allocated_decoding_thread_count; i++) { sem_destroy(&pbi->h_event_start_decoding[i]); } sem_destroy(&pbi->h_event_end_decoding); vpx_free(pbi->h_decoding_thread); pbi->h_decoding_thread = NULL; vpx_free(pbi->h_event_start_decoding); pbi->h_event_start_decoding = NULL; vpx_free(pbi->mb_row_di); pbi->mb_row_di = NULL ; vpx_free(pbi->de_thread_data); pbi->de_thread_data = NULL; } } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PageInfo::PresentSiteIdentity() { DCHECK_NE(site_identity_status_, SITE_IDENTITY_STATUS_UNKNOWN); DCHECK_NE(site_connection_status_, SITE_CONNECTION_STATUS_UNKNOWN); PageInfoUI::IdentityInfo info; if (site_identity_status_ == SITE_IDENTITY_STATUS_EV_CERT) info.site_identity = UTF16ToUTF8(organization_name()); else info.site_identity = UTF16ToUTF8(GetSimpleSiteName(site_url_)); info.connection_status = site_connection_status_; info.connection_status_description = UTF16ToUTF8(site_connection_details_); info.identity_status = site_identity_status_; info.safe_browsing_status = safe_browsing_status_; info.identity_status_description = UTF16ToUTF8(site_details_message_); info.certificate = certificate_; info.show_ssl_decision_revoke_button = show_ssl_decision_revoke_button_; info.show_change_password_buttons = show_change_password_buttons_; ui_->SetIdentityInfo(info); } CWE ID: CWE-311 Target: 1 Example 2: Code: void ResourceFetcher::requestPreload(Resource::Type type, FetchRequest& request, const String& charset) { if (type == Resource::MainResource) return; String encoding; if (type == Resource::Script || type == Resource::CSSStyleSheet) encoding = charset.isEmpty() ? m_document->charset().string() : charset; request.setCharset(encoding); request.setForPreload(true); ResourcePtr<Resource> resource = requestResource(type, request); if (!resource || (m_preloads && m_preloads->contains(resource.get()))) return; TRACE_EVENT_ASYNC_STEP_INTO0("net", "Resource", resource.get(), "Preload"); resource->increasePreloadCount(); if (!m_preloads) m_preloads = adoptPtr(new ListHashSet<Resource*>); m_preloads->add(resource.get()); #if PRELOAD_DEBUG printf("PRELOADING %s\n", resource->url().string().latin1().data()); #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: static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET; if (!track->entry) { flags |= MOV_TFHD_DURATION_IS_EMPTY; } else { flags |= MOV_TFHD_DEFAULT_FLAGS; } if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET) flags &= ~MOV_TFHD_BASE_DATA_OFFSET; if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) { flags &= ~MOV_TFHD_BASE_DATA_OFFSET; flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF; } /* Don't set a default sample size, the silverlight player refuses * to play files with that set. Don't set a default sample duration, * WMP freaks out if it is set. Don't set a base data offset, PIFF * file format says it MUST NOT be set. */ if (track->mode == MODE_ISM) flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET); avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfhd"); avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, track->track_id); /* track-id */ if (flags & MOV_TFHD_BASE_DATA_OFFSET) avio_wb64(pb, moof_offset); if (flags & MOV_TFHD_DEFAULT_DURATION) { track->default_duration = get_cluster_duration(track, 0); avio_wb32(pb, track->default_duration); } if (flags & MOV_TFHD_DEFAULT_SIZE) { track->default_size = track->entry ? track->cluster[0].size : 1; avio_wb32(pb, track->default_size); } else track->default_size = -1; if (flags & MOV_TFHD_DEFAULT_FLAGS) { /* Set the default flags based on the second sample, if available. * If the first sample is different, that can be signaled via a separate field. */ if (track->entry > 1) track->default_sample_flags = get_sample_flags(track, &track->cluster[1]); else track->default_sample_flags = track->par->codec_type == AVMEDIA_TYPE_VIDEO ? (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) : MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO; avio_wb32(pb, track->default_sample_flags); } return update_size(pb, pos); } CWE ID: CWE-369 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { mpeg4_decode_profile_level(s, gb); if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (s->avctx->level > 0 && s->avctx->level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); } CWE ID: CWE-476 Target: 1 Example 2: Code: void TakeOwnership() { target_contents_owner_.reset(params_->target_contents); } 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 xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; int err; struct xfrm_user_expire *ue = nlmsg_data(nlh); struct xfrm_usersa_info *p = &ue->state; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family); err = -ENOENT; if (x == NULL) return err; spin_lock_bh(&x->lock); err = -EINVAL; if (x->km.state != XFRM_STATE_VALID) goto out; km_state_expired(x, ue->hard, current->pid); if (ue->hard) { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); __xfrm_state_delete(x); xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid); } err = 0; out: spin_unlock_bh(&x->lock); xfrm_state_put(x); 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: static void onEndTest(void* self) { ASSERT(isMainThread()); webkit_support::QuitMessageLoop(); CCLayerTreeHostTest* test = static_cast<CCLayerTreeHostTest*>(self); ASSERT(test); test->m_layerTreeHost.clear(); } CWE ID: CWE-119 Target: 1 Example 2: Code: u32 ip_idents_reserve(u32 hash, int segs) { u32 *p_tstamp = ip_tstamps + hash % IP_IDENTS_SZ; atomic_t *p_id = ip_idents + hash % IP_IDENTS_SZ; u32 old = ACCESS_ONCE(*p_tstamp); u32 now = (u32)jiffies; u32 new, delta = 0; if (old != now && cmpxchg(p_tstamp, old, now) == old) delta = prandom_u32_max(now - old); /* Do not use atomic_add_return() as it makes UBSAN unhappy */ do { old = (u32)atomic_read(p_id); new = old + delta + segs; } while (atomic_cmpxchg(p_id, old, new) != old); return new - segs; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */ int i; if (heap->count+1 > heap->max_size) { /* we need to allocate more memory */ heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size))); heap->max_size *= 2; } heap->ctor(elem TSRMLS_CC); /* sifting up */ for(i = heap->count++; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) { heap->elements[i] = heap->elements[(i-1)/2]; } if (EG(exception)) { /* exception thrown during comparison */ } heap->elements[i] = elem; } /* }}} */ CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AudioInputRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, const std::string& device_id, bool automatic_gain_control) { VLOG(1) << "AudioInputRendererHost::OnCreateStream(stream_id=" << stream_id << ")"; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(LookupById(stream_id) == NULL); media::AudioParameters audio_params(params); if (media_stream_manager_->audio_input_device_manager()-> ShouldUseFakeDevice()) { audio_params.Reset(media::AudioParameters::AUDIO_FAKE, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } else if (WebContentsCaptureUtil::IsWebContentsDeviceId(device_id)) { audio_params.Reset(media::AudioParameters::AUDIO_VIRTUAL, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } DCHECK_GT(audio_params.frames_per_buffer(), 0); uint32 buffer_size = audio_params.GetBytesPerBuffer(); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 mem_size = sizeof(media::AudioInputBufferParameters) + buffer_size; if (!entry->shared_memory.CreateAndMapAnonymous(mem_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioInputSyncWriter> writer( new AudioInputSyncWriter(&entry->shared_memory)); if (!writer->Init()) { SendErrorMessage(stream_id); return; } entry->writer.reset(writer.release()); entry->controller = media::AudioInputController::CreateLowLatency( audio_manager_, this, audio_params, device_id, entry->writer.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } if (params.format() == media::AudioParameters::AUDIO_PCM_LOW_LATENCY) entry->controller->SetAutomaticGainControl(automatic_gain_control); entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); } CWE ID: CWE-189 Target: 1 Example 2: Code: SPICE_GNUC_VISIBLE const char** spice_server_char_device_recognized_subtypes(void) { return spice_server_char_device_recognized_subtypes_list; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ocfs2_set_acl(handle_t *handle, struct inode *inode, struct buffer_head *di_bh, int type, struct posix_acl *acl, struct ocfs2_alloc_context *meta_ac, struct ocfs2_alloc_context *data_ac) { int name_index; void *value = NULL; size_t size = 0; int ret; if (S_ISLNK(inode->i_mode)) return -EOPNOTSUPP; switch (type) { case ACL_TYPE_ACCESS: name_index = OCFS2_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { umode_t mode = inode->i_mode; ret = posix_acl_equiv_mode(acl, &mode); if (ret < 0) return ret; if (ret == 0) acl = NULL; ret = ocfs2_acl_set_mode(inode, di_bh, handle, mode); if (ret) return ret; } break; case ACL_TYPE_DEFAULT: name_index = OCFS2_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ocfs2_acl_to_xattr(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } if (handle) ret = ocfs2_xattr_set_handle(handle, inode, di_bh, name_index, "", value, size, 0, meta_ac, data_ac); else ret = ocfs2_xattr_set(inode, name_index, "", value, size, 0); kfree(value); return ret; } CWE ID: CWE-285 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: htc_request_check_host_hdr(struct http *hp) { int u; int seen_host = 0; for (u = HTTP_HDR_FIRST; u < hp->nhd; u++) { if (hp->hd[u].b == NULL) continue; AN(hp->hd[u].b); AN(hp->hd[u].e); if (http_IsHdr(&hp->hd[u], H_Host)) { if (seen_host) { return (400); } seen_host = 1; } } return (0); } CWE ID: Target: 1 Example 2: Code: static int decode_renew(struct xdr_stream *xdr) { return decode_op_hdr(xdr, OP_RENEW); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int replace_map_fd_with_map_ptr(struct verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose("BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose("BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose("invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose("unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose("fd %d is not pointing to valid bpf_map\n", insn->imm); fdput(f); return PTR_ERR(map); } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* remember this map */ env->used_maps[env->used_map_cnt++] = map; /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ bpf_map_inc(map, false); fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) { opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */ OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256]; OPJ_UINT8 const* pLUT[3]; opj_image_t * image = NULL; FILE *IN; OPJ_BITMAPFILEHEADER File_h; OPJ_BITMAPINFOHEADER Info_h; OPJ_UINT32 i, palette_len, numcmpts = 1U; OPJ_BOOL l_result = OPJ_FALSE; OPJ_UINT8* pData = NULL; OPJ_UINT32 stride; pLUT[0] = lut_R; pLUT[1] = lut_G; pLUT[2] = lut_B; IN = fopen(filename, "rb"); if (!IN) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); return NULL; } if (!bmp_read_file_header(IN, &File_h)) { fclose(IN); return NULL; } if (!bmp_read_info_header(IN, &Info_h)) { fclose(IN); return NULL; } /* Load palette */ if (Info_h.biBitCount <= 8U) { memset(&lut_R[0], 0, sizeof(lut_R)); memset(&lut_G[0], 0, sizeof(lut_G)); memset(&lut_B[0], 0, sizeof(lut_B)); palette_len = Info_h.biClrUsed; if((palette_len == 0U) && (Info_h.biBitCount <= 8U)) { palette_len = (1U << Info_h.biBitCount); } if (palette_len > 256U) { palette_len = 256U; } if (palette_len > 0U) { OPJ_UINT8 has_color = 0U; for (i = 0U; i < palette_len; i++) { lut_B[i] = (OPJ_UINT8)getc(IN); lut_G[i] = (OPJ_UINT8)getc(IN); lut_R[i] = (OPJ_UINT8)getc(IN); (void)getc(IN); /* padding */ has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]); } if(has_color) { numcmpts = 3U; } } } else { numcmpts = 3U; if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) { numcmpts++; } } stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) * 4U; /* rows are aligned on 32bits */ if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */ stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U; } pData = (OPJ_UINT8 *) calloc(1, stride * Info_h.biHeight * sizeof(OPJ_UINT8)); if (pData == NULL) { fclose(IN); return NULL; } /* Place the cursor at the beginning of the image information */ fseek(IN, 0, SEEK_SET); fseek(IN, (long)File_h.bfOffBits, SEEK_SET); switch (Info_h.biCompression) { case 0: case 3: /* read raw data */ l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 1: /* read rle8 data */ l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 2: /* read rle4 data */ l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; default: fprintf(stderr, "Unsupported BMP compression\n"); l_result = OPJ_FALSE; break; } if (!l_result) { free(pData); fclose(IN); return NULL; } /* create the image */ memset(&cmptparm[0], 0, sizeof(cmptparm)); for(i = 0; i < 4U; i++) { cmptparm[i].prec = 8; cmptparm[i].bpp = 8; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy; cmptparm[i].w = Info_h.biWidth; cmptparm[i].h = Info_h.biHeight; } image = opj_image_create(numcmpts, &cmptparm[0], (numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB); if(!image) { fclose(IN); free(pData); return NULL; } if (numcmpts == 4U) { image->comps[3].alpha = 1; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32)parameters->subsampling_dx + 1U; image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32)parameters->subsampling_dy + 1U; /* Read the data */ if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */ bmp24toimage(pData, stride, image); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) { /* RGB 8bpp Indexed */ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/ bmp8toimage(pData, stride, image, pLUT); /* RLE 4 gets decoded as 8 bits data for now */ } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */ bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU, 0x00000000U); } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */ bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */ bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */ if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) { Info_h.biRedMask = 0xF800U; Info_h.biGreenMask = 0x07E0U; Info_h.biBlueMask = 0x001FU; } bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else { opj_image_destroy(image); image = NULL; fprintf(stderr, "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount); } free(pData); fclose(IN); return image; } CWE ID: CWE-190 Target: 1 Example 2: Code: OMX_ERRORTYPE omx_vdec::get_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_INOUT OMX_PTR configData) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Get Config in Invalid State"); return OMX_ErrorInvalidState; } switch ((unsigned long)configIndex) { case OMX_QcomIndexConfigInterlaced: { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_CONFIG_INTERLACETYPE); OMX_QCOM_CONFIG_INTERLACETYPE *configFmt = (OMX_QCOM_CONFIG_INTERLACETYPE *) configData; if (configFmt->nPortIndex == 1) { if (configFmt->nIndex == 0) { configFmt->eInterlaceType = OMX_QCOM_InterlaceFrameProgressive; } else if (configFmt->nIndex == 1) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst; } else if (configFmt->nIndex == 2) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst; } else { DEBUG_PRINT_ERROR("get_config: OMX_QcomIndexConfigInterlaced:" " NoMore Interlaced formats"); eRet = OMX_ErrorNoMore; } } else { DEBUG_PRINT_ERROR("get_config: Bad port index %d queried on only o/p port", (int)configFmt->nPortIndex); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexQueryNumberOfVideoDecInstance: { VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_QUERY_DECODER_INSTANCES); QOMX_VIDEO_QUERY_DECODER_INSTANCES *decoderinstances = (QOMX_VIDEO_QUERY_DECODER_INSTANCES*)configData; decoderinstances->nNumOfInstances = 16; /*TODO: How to handle this case */ break; } case OMX_QcomIndexConfigVideoFramePackingArrangement: { if (drv_ctx.decoder_format == VDEC_CODECTYPE_H264) { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_FRAME_PACK_ARRANGEMENT); OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; memcpy(configFmt, &m_frame_pack_arrangement, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); } else { DEBUG_PRINT_ERROR("get_config: Framepack data not supported for non H264 codecs"); } break; } case OMX_IndexConfigCommonOutputCrop: { VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_RECTTYPE); OMX_CONFIG_RECTTYPE *rect = (OMX_CONFIG_RECTTYPE *) configData; memcpy(rect, &rectangle, sizeof(OMX_CONFIG_RECTTYPE)); DEBUG_PRINT_HIGH("get_config: crop info: L: %u, T: %u, R: %u, B: %u", rectangle.nLeft, rectangle.nTop, rectangle.nWidth, rectangle.nHeight); break; } case OMX_QcomIndexConfigPerfLevel: { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL); struct v4l2_control control; OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting performance level: %d", errno); eRet = OMX_ErrorHardware; } if (eRet == OMX_ErrorNone) { switch (control.value) { case V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO: perf->ePerfLevel = OMX_QCOM_PerfLevelTurbo; break; default: DEBUG_PRINT_HIGH("Unknown perf level %d, reporting Nominal instead", control.value); /* Fall through */ case V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL: perf->ePerfLevel = OMX_QCOM_PerfLevelNominal; break; } } break; } default: { DEBUG_PRINT_ERROR("get_config: unknown param %d",configIndex); eRet = OMX_ErrorBadParameter; } } return eRet; } 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: int32_t DownmixLib_Create(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle) { int ret; int i; downmix_module_t *module; const effect_descriptor_t *desc; ALOGV("DownmixLib_Create()"); #ifdef DOWNMIX_TEST_CHANNEL_INDEX ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER); ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT); #endif if (pHandle == NULL || uuid == NULL) { return -EINVAL; } for (i = 0 ; i < kNbEffects ; i++) { desc = gDescriptors[i]; if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) { break; } } if (i == kNbEffects) { return -ENOENT; } module = malloc(sizeof(downmix_module_t)); module->itfe = &gDownmixInterface; module->context.state = DOWNMIX_STATE_UNINITIALIZED; ret = Downmix_Init(module); if (ret < 0) { ALOGW("DownmixLib_Create() init failed"); free(module); return ret; } *pHandle = (effect_handle_t) module; ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t)); 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: main(void) { unsigned int i; unsigned char buf[MAX_LENGTH]; unsigned long crc; unsigned char c; int inchar; /* Skip 8-byte signature */ for (i=8; i; i--) { c=GETBREAK; putchar(c); } if (inchar != EOF) for (;;) { /* Read the length */ unsigned long length; /* must be 32 bits! */ c=GETBREAK; buf[0] = c; length = c; length <<= 8; c=GETBREAK; buf[1] = c; length += c; length <<= 8; c=GETBREAK; buf[2] = c; length += c; length <<= 8; c=GETBREAK; buf[3] = c; length += c; /* Read the chunkname */ c=GETBREAK; buf[4] = c; c=GETBREAK; buf[5] = c; c=GETBREAK; buf[6] = c; c=GETBREAK; buf[7] = c; /* The iTXt chunk type expressed as integers is (105, 84, 88, 116) */ if (buf[4] == 105 && buf[5] == 84 && buf[6] == 88 && buf[7] == 116) { if (length >= MAX_LENGTH-12) break; /* To do: handle this more gracefully */ /* Initialize the CRC */ crc = crc32(0, Z_NULL, 0); /* Copy the data bytes */ for (i=8; i < length + 12; i++) { c=GETBREAK; buf[i] = c; } /* Calculate the CRC */ crc = crc32(crc, buf+4, (uInt)length+4); for (;;) { /* Check the CRC */ if (((crc >> 24) & 0xff) == buf[length+8] && ((crc >> 16) & 0xff) == buf[length+9] && ((crc >> 8) & 0xff) == buf[length+10] && ((crc ) & 0xff) == buf[length+11]) break; length++; if (length >= MAX_LENGTH-12) break; c=GETBREAK; buf[length+11]=c; /* Update the CRC */ crc = crc32(crc, buf+7+length, 1); } /* Update length bytes */ buf[0] = (unsigned char)((length << 24) & 0xff); buf[1] = (unsigned char)((length << 16) & 0xff); buf[2] = (unsigned char)((length << 8) & 0xff); buf[3] = (unsigned char)((length ) & 0xff); /* Write the fixed iTXt chunk (length, name, data, crc) */ for (i=0; i<length+12; i++) putchar(buf[i]); } else { /* Copy bytes that were already read (length and chunk name) */ for (i=0; i<8; i++) putchar(buf[i]); /* Copy data bytes and CRC */ for (i=8; i< length+12; i++) { c=GETBREAK; putchar(c); } if (inchar == EOF) { break; } /* The IEND chunk type expressed as integers is (73, 69, 78, 68) */ if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68) break; } if (inchar == EOF) break; if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68) break; } return 0; } CWE ID: Target: 1 Example 2: Code: cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;} CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int kvm_deassign_device(struct kvm *kvm, struct kvm_assigned_dev_kernel *assigned_dev) { struct iommu_domain *domain = kvm->arch.iommu_domain; struct pci_dev *pdev = NULL; /* check if iommu exists and in use */ if (!domain) return 0; pdev = assigned_dev->dev; if (pdev == NULL) return -ENODEV; iommu_detach_device(domain, &pdev->dev); pdev->dev_flags &= ~PCI_DEV_FLAGS_ASSIGNED; dev_info(&pdev->dev, "kvm deassign device\n"); return 0; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); perf_event_enable(event); return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: void InputHandler::paste() { executeTextEditCommand("Paste"); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool HTMLFormControlElement::willValidate() const { return ListedElement::WillValidate(); } 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: void read_boot(DOS_FS * fs) { struct boot_sector b; unsigned total_sectors; unsigned short logical_sector_size, sectors; unsigned fat_length; unsigned total_fat_entries; off_t data_size; fs_read(0, sizeof(b), &b); logical_sector_size = GET_UNALIGNED_W(b.sector_size); if (!logical_sector_size) die("Logical sector size is zero."); /* This was moved up because it's the first thing that will fail */ /* if the platform needs special handling of unaligned multibyte accesses */ /* but such handling isn't being provided. See GET_UNALIGNED_W() above. */ if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); fs->cluster_size = b.cluster_size * logical_sector_size; if (!fs->cluster_size) die("Cluster size is zero."); if (b.fats != 2 && b.fats != 1) die("Currently, only 1 or 2 FATs are supported, not %d.\n", b.fats); fs->nfats = b.fats; sectors = GET_UNALIGNED_W(b.sectors); total_sectors = sectors ? sectors : le32toh(b.total_sect); if (verbose) printf("Checking we can access the last sector of the filesystem\n"); /* Can't access last odd sector anyway, so round down */ fs_test((off_t)((total_sectors & ~1) - 1) * logical_sector_size, logical_sector_size); fat_length = le16toh(b.fat_length) ? le16toh(b.fat_length) : le32toh(b.fat32_length); fs->fat_start = (off_t)le16toh(b.reserved) * logical_sector_size; fs->root_start = ((off_t)le16toh(b.reserved) + b.fats * fat_length) * logical_sector_size; fs->root_entries = GET_UNALIGNED_W(b.dir_entries); fs->data_start = fs->root_start + ROUND_TO_MULTIPLE(fs->root_entries << MSDOS_DIR_BITS, logical_sector_size); data_size = (off_t)total_sectors * logical_sector_size - fs->data_start; fs->data_clusters = data_size / fs->cluster_size; fs->root_cluster = 0; /* indicates standard, pre-FAT32 root dir */ fs->fsinfo_start = 0; /* no FSINFO structure */ fs->free_clusters = -1; /* unknown */ if (!b.fat_length && b.fat32_length) { fs->fat_bits = 32; fs->root_cluster = le32toh(b.root_cluster); if (!fs->root_cluster && fs->root_entries) /* M$ hasn't specified this, but it looks reasonable: If * root_cluster is 0 but there is a separate root dir * (root_entries != 0), we handle the root dir the old way. Give a * warning, but convertig to a root dir in a cluster chain seems * to complex for now... */ printf("Warning: FAT32 root dir not in cluster chain! " "Compatibility mode...\n"); else if (!fs->root_cluster && !fs->root_entries) die("No root directory!"); else if (fs->root_cluster && fs->root_entries) printf("Warning: FAT32 root dir is in a cluster chain, but " "a separate root dir\n" " area is defined. Cannot fix this easily.\n"); if (fs->data_clusters < FAT16_THRESHOLD) printf("Warning: Filesystem is FAT32 according to fat_length " "and fat32_length fields,\n" " but has only %lu clusters, less than the required " "minimum of %d.\n" " This may lead to problems on some systems.\n", (unsigned long)fs->data_clusters, FAT16_THRESHOLD); check_fat_state_bit(fs, &b); fs->backupboot_start = le16toh(b.backup_boot) * logical_sector_size; check_backup_boot(fs, &b, logical_sector_size); read_fsinfo(fs, &b, logical_sector_size); } else if (!atari_format) { /* On real MS-DOS, a 16 bit FAT is used whenever there would be too * much clusers otherwise. */ fs->fat_bits = (fs->data_clusters >= FAT12_THRESHOLD) ? 16 : 12; if (fs->data_clusters >= FAT16_THRESHOLD) die("Too many clusters (%lu) for FAT16 filesystem.", fs->data_clusters); check_fat_state_bit(fs, &b); } else { /* On Atari, things are more difficult: GEMDOS always uses 12bit FATs * on floppies, and always 16 bit on harddisks. */ fs->fat_bits = 16; /* assume 16 bit FAT for now */ /* If more clusters than fat entries in 16-bit fat, we assume * it's a real MSDOS FS with 12-bit fat. */ if (fs->data_clusters + 2 > fat_length * logical_sector_size * 8 / 16 || /* if it has one of the usual floppy sizes -> 12bit FAT */ (total_sectors == 720 || total_sectors == 1440 || total_sectors == 2880)) fs->fat_bits = 12; } /* On FAT32, the high 4 bits of a FAT entry are reserved */ fs->eff_fat_bits = (fs->fat_bits == 32) ? 28 : fs->fat_bits; fs->fat_size = fat_length * logical_sector_size; fs->label = calloc(12, sizeof(uint8_t)); if (fs->fat_bits == 12 || fs->fat_bits == 16) { struct boot_sector_16 *b16 = (struct boot_sector_16 *)&b; if (b16->extended_sig == 0x29) memmove(fs->label, b16->label, 11); else fs->label = NULL; } else if (fs->fat_bits == 32) { if (b.extended_sig == 0x29) memmove(fs->label, &b.label, 11); else fs->label = NULL; } total_fat_entries = (uint64_t)fs->fat_size * 8 / fs->fat_bits; if (fs->data_clusters > total_fat_entries - 2) die("Filesystem has %u clusters but only space for %u FAT entries.", fs->data_clusters, total_fat_entries - 2); if (!fs->root_entries && !fs->root_cluster) die("Root directory has zero size."); if (fs->root_entries & (MSDOS_DPS - 1)) die("Root directory (%d entries) doesn't span an integral number of " "sectors.", fs->root_entries); if (logical_sector_size & (SECTOR_SIZE - 1)) die("Logical sector size (%d bytes) is not a multiple of the physical " "sector size.", logical_sector_size); #if 0 /* linux kernel doesn't check that either */ /* ++roman: On Atari, these two fields are often left uninitialized */ if (!atari_format && (!b.secs_track || !b.heads)) die("Invalid disk format in boot sector."); #endif if (verbose) dump_boot(fs, &b, logical_sector_size); } CWE ID: CWE-119 Target: 1 Example 2: Code: SWFOutput_writeGlyphShape(SWFOutput out, SWFShape shape) { unsigned char c; int styleDone = 0; int i; c = 1<<4; SWFOutput_writeUInt8(out, c); shape->nFills = 1; shape->nLines = 0; for ( i=0; i<shape->nRecords; ++i ) { if(!styleDone && shape->records[i].type == SHAPERECORD_STATECHANGE) { shape->records[i].record.stateChange->flags |= SWF_SHAPE_FILLSTYLE0FLAG; shape->records[i].record.stateChange->leftFill = 1; styleDone = 1; } if ( i < shape->nRecords-1 || shape->records[i].type != SHAPERECORD_STATECHANGE ) { SWFShape_writeShapeRecord(shape, shape->records[i], out); } } SWFOutput_writeBits(out, 0, 6); /* end tag */ SWFOutput_byteAlign(out); } 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 Browser::FindInPage(bool find_next, bool forward_direction) { ShowFindBar(); if (find_next) { string16 find_text; #if defined(OS_MACOSX) find_text = GetFindPboardText(); #endif GetSelectedTabContentsWrapper()-> GetFindManager()->StartFinding(find_text, forward_direction, false); // Not case sensitive. } } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int set_registers(rtl8150_t * dev, u16 indx, u16 size, void *data) { return usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0), RTL8150_REQ_SET_REGS, RTL8150_REQT_WRITE, indx, 0, data, size, 500); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int lxcfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { if (strcmp(path, "/") == 0) { if (filler(buf, "proc", NULL, 0) != 0 || filler(buf, "cgroup", NULL, 0) != 0) return -EINVAL; return 0; } if (strncmp(path, "/cgroup", 7) == 0) return cg_readdir(path, buf, filler, offset, fi); if (strcmp(path, "/proc") == 0) return proc_readdir(path, buf, filler, offset, fi); return -EINVAL; } 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 AppControllerImpl::GetApps( mojom::AppController::GetAppsCallback callback) { std::vector<chromeos::kiosk_next_home::mojom::AppPtr> app_list; app_service_proxy_->AppRegistryCache().ForEachApp( [this, &app_list](const apps::AppUpdate& update) { app_list.push_back(CreateAppPtr(update)); }); std::move(callback).Run(std::move(app_list)); } CWE ID: CWE-416 Output:
1