prompt
stringlengths
799
20.4k
output
int64
0
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int php_session_destroy(TSRMLS_D) /* {{{ */ { int retval = SUCCESS; if (PS(session_status) != php_session_active) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to destroy uninitialized session"); return FAILURE; } return FAILURE; } if (PS(mod)->s_destroy(&PS(mod_data), PS(id) TSRMLS_CC) == FAILURE) { retval = FAILURE; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Session object destruction failed"); } php_rinit_session_globals(TSRMLS_C); return retval; } /* }}} */ PHPAPI void php_add_session_var(char *name, size_t namelen TSRMLS_DC) /* {{{ */ { zval **sym_track = NULL; IF_SESSION_VARS() { zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void *) &sym_track); } else { return; } if (sym_track == NULL) { zval *empty_var; ALLOC_INIT_ZVAL(empty_var); ZEND_SET_SYMBOL_WITH_LENGTH(Z_ARRVAL_P(PS(http_session_vars)), name, namelen+1, empty_var, 1, 0); } } /* }}} */ PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */ { IF_SESSION_VARS() { zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars))); } } /* }}} */ PHPAPI int php_get_session_var(char *name, size_t namelen, zval ***state_var TSRMLS_DC) /* {{{ */ { int ret = FAILURE; IF_SESSION_VARS() { ret = zend_hash_find(Z_ARRVAL_P(PS(http_session_vars)), name, namelen + 1, (void **) state_var); } return ret; } /* }}} */ static void php_session_track_init(TSRMLS_D) /* {{{ */ { zval *session_vars = NULL; /* Unconditionally destroy existing array -- possible dirty data */ zend_delete_global_variable("_SESSION", sizeof("_SESSION")-1 TSRMLS_CC); if (PS(http_session_vars)) { zval_ptr_dtor(&PS(http_session_vars)); } MAKE_STD_ZVAL(session_vars); array_init(session_vars); PS(http_session_vars) = session_vars; ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), 2, 1); } /* }}} */ static char *php_session_encode(int *newlen TSRMLS_DC) /* {{{ */ { char *ret = NULL; IF_SESSION_VARS() { if (!PS(serializer)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object"); ret = NULL; } else if (PS(serializer)->encode(&ret, newlen TSRMLS_CC) == FAILURE) { ret = NULL; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot encode non-existent session"); } return ret; } /* }}} */ static void php_session_decode(const char *val, int vallen TSRMLS_DC) /* {{{ */ { if (!PS(serializer)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object"); return; } if (PS(serializer)->decode(val, vallen TSRMLS_CC) == FAILURE) { php_session_destroy(TSRMLS_C); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to decode session object. Session has been destroyed"); } } /* }}} */ /* * Note that we cannot use the BASE64 alphabet here, because * it contains "/" and "+": both are unacceptable for simple inclusion * into URLs. */ static char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-"; enum { CWE ID: CWE-264 Target: 1 Example 2: Code: t2p_mapproc(thandle_t handle, void **data, toff_t *offset) { (void) handle, (void) data, (void) offset; return -1; } 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 RunCurrentTasks() { size_t posted_tasks_size = runner_->GetPostedTasks().size(); for (size_t i = 0; i < posted_tasks_size; ++i) { runner_->RunNextTask(); } } 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: userauth_pubkey(struct ssh *ssh) { Authctxt *authctxt = ssh->authctxt; struct passwd *pw = authctxt->pw; struct sshbuf *b; struct sshkey *key = NULL; char *pkalg, *userstyle = NULL, *key_s = NULL, *ca_s = NULL; u_char *pkblob, *sig, have_sig; size_t blen, slen; int r, pktype; int authenticated = 0; struct sshauthopt *authopts = NULL; if (!authctxt->valid) { debug2("%s: disabled because of invalid user", __func__); return 0; } if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 || (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 || (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0) fatal("%s: parse request failed: %s", __func__, ssh_err(r)); pktype = sshkey_type_from_name(pkalg); if (pktype == KEY_UNSPEC) { /* this is perfectly legal */ verbose("%s: unsupported public key algorithm: %s", __func__, pkalg); goto done; } if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) { error("%s: could not parse key: %s", __func__, ssh_err(r)); goto done; } if (key == NULL) { error("%s: cannot decode key: %s", __func__, pkalg); goto done; } if (key->type != pktype) { error("%s: type mismatch for decoded key " "(received %d, expected %d)", __func__, key->type, pktype); goto done; } if (sshkey_type_plain(key->type) == KEY_RSA && (ssh->compat & SSH_BUG_RSASIGMD5) != 0) { logit("Refusing RSA key because client uses unsafe " "signature scheme"); goto done; } if (auth2_key_already_used(authctxt, key)) { logit("refusing previously-used %s key", sshkey_type(key)); goto done; } if (match_pattern_list(pkalg, options.pubkey_key_types, 0) != 1) { logit("%s: key type %s not in PubkeyAcceptedKeyTypes", __func__, sshkey_ssh_name(key)); goto done; } key_s = format_key(key); if (sshkey_is_cert(key)) ca_s = format_key(key->cert->signature_key); if (have_sig) { debug3("%s: have %s signature for %s%s%s", __func__, pkalg, key_s, ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s); if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 || (r = sshpkt_get_end(ssh)) != 0) fatal("%s: %s", __func__, ssh_err(r)); if ((b = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); if (ssh->compat & SSH_OLD_SESSIONID) { if ((r = sshbuf_put(b, session_id2, session_id2_len)) != 0) fatal("%s: sshbuf_put session id: %s", __func__, ssh_err(r)); } else { if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0) fatal("%s: sshbuf_put_string session id: %s", __func__, ssh_err(r)); } /* reconstruct packet */ xasprintf(&userstyle, "%s%s%s", authctxt->user, authctxt->style ? ":" : "", authctxt->style ? authctxt->style : ""); if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || (r = sshbuf_put_cstring(b, userstyle)) != 0 || (r = sshbuf_put_cstring(b, authctxt->service)) != 0 || (r = sshbuf_put_cstring(b, "publickey")) != 0 || (r = sshbuf_put_u8(b, have_sig)) != 0 || (r = sshbuf_put_cstring(b, pkalg) != 0) || (r = sshbuf_put_string(b, pkblob, blen)) != 0) fatal("%s: build packet failed: %s", __func__, ssh_err(r)); #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif /* test for correct signature */ authenticated = 0; if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) && PRIVSEP(sshkey_verify(key, sig, slen, sshbuf_ptr(b), sshbuf_len(b), (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL, ssh->compat)) == 0) { authenticated = 1; } sshbuf_free(b); free(sig); auth2_record_key(authctxt, authenticated, key); } else { debug("%s: test pkalg %s pkblob %s%s%s", __func__, pkalg, key_s, ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s); if ((r = sshpkt_get_end(ssh)) != 0) fatal("%s: %s", __func__, ssh_err(r)); /* XXX fake reply and always send PK_OK ? */ /* * XXX this allows testing whether a user is allowed * to login: if you happen to have a valid pubkey this * message is sent. the message is NEVER sent at all * if a user is not allowed to login. is this an * issue? -markus */ if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) { if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK)) != 0 || (r = sshpkt_put_cstring(ssh, pkalg)) != 0 || (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 || (r = sshpkt_send(ssh)) != 0 || (r = ssh_packet_write_wait(ssh)) != 0) fatal("%s: %s", __func__, ssh_err(r)); authctxt->postponed = 1; } } done: if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) { debug("%s: key options inconsistent with existing", __func__); authenticated = 0; } debug2("%s: authenticated %d pkalg %s", __func__, authenticated, pkalg); sshauthopt_free(authopts); sshkey_free(key); free(userstyle); free(pkalg); free(pkblob); free(key_s); free(ca_s); return authenticated; } CWE ID: CWE-200 Target: 1 Example 2: Code: pkinit_init_kdc_req_context(krb5_context context, pkinit_kdc_req_context *ctx) { krb5_error_code retval = ENOMEM; pkinit_kdc_req_context reqctx = NULL; reqctx = malloc(sizeof(*reqctx)); if (reqctx == NULL) return retval; memset(reqctx, 0, sizeof(*reqctx)); reqctx->magic = PKINIT_CTX_MAGIC; retval = pkinit_init_req_crypto(&reqctx->cryptoctx); if (retval) goto cleanup; reqctx->rcv_auth_pack = NULL; reqctx->rcv_auth_pack9 = NULL; pkiDebug("%s: returning reqctx at %p\n", __FUNCTION__, reqctx); *ctx = reqctx; retval = 0; cleanup: if (retval) pkinit_fini_kdc_req_context(context, reqctx); return retval; } 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: ChildProcessSecurityPolicyImpl::ChildProcessSecurityPolicyImpl() { RegisterWebSafeScheme(url::kHttpScheme); RegisterWebSafeScheme(url::kHttpsScheme); RegisterWebSafeScheme(url::kFtpScheme); RegisterWebSafeScheme(url::kDataScheme); RegisterWebSafeScheme("feed"); RegisterWebSafeScheme(url::kBlobScheme); RegisterWebSafeScheme(url::kFileSystemScheme); RegisterPseudoScheme(url::kAboutScheme); RegisterPseudoScheme(url::kJavaScriptScheme); RegisterPseudoScheme(kViewSourceScheme); } 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: RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() { WebContentsImpl* focused_web_contents = GetFocusedWebContents(); if (focused_web_contents->ShowingInterstitialPage()) { return static_cast<RenderFrameHostImpl*>( focused_web_contents->GetRenderManager() ->interstitial_page() ->GetMainFrame()) ->GetRenderWidgetHost(); } return focused_web_contents->GetMainFrame()->GetRenderWidgetHost(); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void renew_lease(const struct nfs_server *server, unsigned long timestamp) { struct nfs_client *clp = server->nfs_client; if (!nfs4_has_session(clp)) do_renew_lease(clp, timestamp); } 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 uwbd_start(struct uwb_rc *rc) { rc->uwbd.task = kthread_run(uwbd, rc, "uwbd"); if (rc->uwbd.task == NULL) printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); else rc->uwbd.pid = rc->uwbd.task->pid; } 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 mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt) { struct serial_icounter_struct icount; struct sb_uart_icount cnow; struct sb_uart_port *port = state->port; spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); icount.cts = cnow.cts; icount.dsr = cnow.dsr; icount.rng = cnow.rng; icount.dcd = cnow.dcd; icount.rx = cnow.rx; icount.tx = cnow.tx; icount.frame = cnow.frame; icount.overrun = cnow.overrun; icount.parity = cnow.parity; icount.brk = cnow.brk; icount.buf_overrun = cnow.buf_overrun; return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: int sm_looptest_fast(p_fm_config_conx_hdlt hdl, fm_mgr_type_t mgr, int argc, char *argv[]) { fm_mgr_config_errno_t res; fm_msg_ret_code_t ret_code; int plen=1; if (argc > 1) { printf("Error: only 1 argument expected\n"); return 0; } if (argc == 1) { plen = atol(argv[0]); } if((res = fm_mgr_simple_query(hdl, FM_ACT_GET, FM_DT_SM_LOOP_TEST_FAST, mgr, sizeof(plen), (void *)&plen, &ret_code)) != FM_CONF_OK) { fprintf(stderr, "sm_looptest_fast: Failed to retrieve data: \n" "\tError:(%d) %s \n\tRet code:(%d) %s\n", res, fm_mgr_get_error_str(res),ret_code, fm_mgr_get_resp_error_str(ret_code)); } else { printf("Successfully sent Loop Test Fast Mode %d control to local SM instance\n", plen); } 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: bool BaseAudioContext::WouldTaintOrigin(const KURL& url) const { if (url.ProtocolIsData()) { return false; } Document* document = GetDocument(); if (document && document->GetSecurityOrigin()) { return !document->GetSecurityOrigin()->CanRequest(url); } return true; } CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SendTabToSelfInfoBarDelegate::Create(const SendTabToSelfEntry* entry) { return base::WrapUnique(new SendTabToSelfInfoBarDelegate(entry)); } CWE ID: CWE-190 Target: 1 Example 2: Code: static int select_cur_seq_no(HLSContext *c, struct playlist *pls) { int seq_no; if (!pls->finished && !c->first_packet && av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls)) /* reload the playlist since it was suspended */ parse_playlist(c, pls->url, pls, NULL); /* If playback is already in progress (we are just selecting a new * playlist) and this is a complete file, find the matching segment * by counting durations. */ if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) { find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no); return seq_no; } if (!pls->finished) { if (!c->first_packet && /* we are doing a segment selection during playback */ c->cur_seq_no >= pls->start_seq_no && c->cur_seq_no < pls->start_seq_no + pls->n_segments) /* While spec 3.4.3 says that we cannot assume anything about the * content at the same sequence number on different playlists, * in practice this seems to work and doing it otherwise would * require us to download a segment to inspect its timestamps. */ return c->cur_seq_no; /* If this is a live stream, start live_start_index segments from the * start or end */ if (c->live_start_index < 0) return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0); else return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1); } /* Otherwise just start on the first segment. */ return pls->start_seq_no; } CWE ID: CWE-835 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb) { int len = skb->len; skb_queue_tail(&sk->sk_receive_queue, skb); sk->sk_data_ready(sk, len); return len; } CWE ID: CWE-287 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: std::unique_ptr<service_manager::Service> CreateMediaService() { return std::unique_ptr<service_manager::Service>( new ::media::MediaService(base::MakeUnique<CdmMojoMediaClient>())); } CWE ID: CWE-119 Target: 1 Example 2: Code: has_caps (void) { struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 }; struct __user_cap_data_struct data[2] = { { 0 } }; if (capget (&hdr, data) < 0) die_with_error ("capget failed"); return data[0].permitted != 0 || data[1].permitted != 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void show_stack(struct task_struct *tsk, unsigned long *sp) { dump_backtrace(NULL, tsk); barrier(); } 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: parse_file (FILE* input_file, char* directory, char *body_filename, char *body_pref, int flags) { uint32 d; uint16 key; Attr *attr = NULL; File *file = NULL; int rtf_size = 0, html_size = 0; MessageBody body; memset (&body, '\0', sizeof (MessageBody)); /* store the program options in our file global variables */ g_flags = flags; /* check that this is in fact a TNEF file */ d = geti32(input_file); if (d != TNEF_SIGNATURE) { fprintf (stdout, "Seems not to be a TNEF file\n"); return 1; } /* Get the key */ key = geti16(input_file); debug_print ("TNEF Key: %hx\n", key); /* The rest of the file is a series of 'messages' and 'attachments' */ while ( data_left( input_file ) ) { attr = read_object( input_file ); if ( attr == NULL ) break; /* This signals the beginning of a file */ if (attr->name == attATTACHRENDDATA) { if (file) { file_write (file, directory); file_free (file); } else { file = CHECKED_XCALLOC (File, 1); } } /* Add the data to our lists. */ switch (attr->lvl_type) { case LVL_MESSAGE: if (attr->name == attBODY) { body.text_body = get_text_data (attr); } else if (attr->name == attMAPIPROPS) { MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf); if (mapi_attrs) { int i; for (i = 0; mapi_attrs[i]; i++) { MAPI_Attr *a = mapi_attrs[i]; if (a->name == MAPI_BODY_HTML) { body.html_bodies = get_html_data (a); html_size = a->num_values; } else if (a->name == MAPI_RTF_COMPRESSED) { body.rtf_bodies = get_rtf_data (a); rtf_size = a->num_values; } } /* cannot save attributes to file, since they * are not attachment attributes */ /* file_add_mapi_attrs (file, mapi_attrs); */ mapi_attr_free_list (mapi_attrs); XFREE (mapi_attrs); } } break; case LVL_ATTACHMENT: file_add_attr (file, attr); break; default: fprintf (stderr, "Invalid lvl type on attribute: %d\n", attr->lvl_type); return 1; break; } attr_free (attr); XFREE (attr); } if (file) { file_write (file, directory); file_free (file); XFREE (file); } /* Write the message body */ if (flags & SAVEBODY) { int i = 0; int all_flag = 0; if (strcmp (body_pref, "all") == 0) { all_flag = 1; body_pref = "rht"; } for (; i < 3; i++) { File **files = get_body_files (body_filename, body_pref[i], &body); if (files) { int j = 0; for (; files[j]; j++) { file_write(files[j], directory); file_free (files[j]); XFREE(files[j]); } XFREE(files); if (!all_flag) break; } } } if (body.text_body) { free_bodies(body.text_body, 1); XFREE(body.text_body); } if (rtf_size > 0) { free_bodies(body.rtf_bodies, rtf_size); XFREE(body.rtf_bodies); } if (html_size > 0) { free_bodies(body.html_bodies, html_size); XFREE(body.html_bodies); } return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: static int nft_delset(struct nft_ctx *ctx, struct nft_set *set) { int err; err = nft_trans_set_add(ctx, NFT_MSG_DELSET, set); if (err < 0) return err; list_del_rcu(&set->list); ctx->table->use--; 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: path_poly(PG_FUNCTION_ARGS) { PATH *path = PG_GETARG_PATH_P(0); POLYGON *poly; int size; int i; /* This is not very consistent --- other similar cases return NULL ... */ if (!path->closed) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("open path cannot be converted to polygon"))); size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * path->npts; poly = (POLYGON *) palloc(size); SET_VARSIZE(poly, size); poly->npts = path->npts; for (i = 0; i < path->npts; i++) { poly->p[i].x = path->p[i].x; poly->p[i].y = path->p[i].y; } make_bound_box(poly); PG_RETURN_POLYGON_P(poly); } 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 TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; if (content::AreAllSitesIsolatedForTesting()) host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); if (content::AreAllSitesIsolatedForTesting()) EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph2); else EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool IsPinned(const ash::wm::WindowState* window_state) { return window_state->IsPinned() || window_state->IsTrustedPinned(); } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static PHP_GINIT_FUNCTION(libxml) { libxml_globals->stream_context = NULL; libxml_globals->error_buffer.c = NULL; libxml_globals->error_list = NULL; } 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 libxsmm_sparse_csc_reader( libxsmm_generated_code* io_generated_code, const char* i_csc_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csc_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_column_idx_id = NULL; unsigned int l_i = 0; l_csc_file_handle = fopen( i_csc_file_in, "r" ); if ( l_csc_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_INPUT ); return; } while (fgets(l_line, l_line_length, l_csc_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose( l_csc_file_handle ); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC data structure matching mtx file */ *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_column_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_column_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_column_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_column_idx, 0, sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_column_idx_id, 0, sizeof(unsigned int) * (*o_column_count)); /* init column idx */ for (l_i = 0; l_i <= *o_column_count; ++l_i) { (*o_column_idx)[l_i] = *o_element_count; } /* init */ (*o_column_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_DESC ); fclose( l_csc_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_ELEMS ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_row_idx)[l_i] = l_row; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_column_idx_id[l_column] = 1; (*o_column_idx)[l_column+1] = l_i; } } } /* close mtx file */ fclose( l_csc_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_LEN ); return; } if ( l_column_idx_id != NULL ) { /* let's handle empty columns */ for ( l_i = 0; l_i < (*o_column_count); l_i++) { if ( l_column_idx_id[l_i] == 0 ) { (*o_column_idx)[l_i+1] = (*o_column_idx)[l_i]; } } /* free helper data structure */ free( l_column_idx_id ); } } CWE ID: CWE-119 Target: 1 Example 2: Code: uint64_t streamDelConsumer(streamCG *cg, sds name) { streamConsumer *consumer = streamLookupConsumer(cg,name,0); if (consumer == NULL) return 0; uint64_t retval = raxSize(consumer->pel); /* Iterate all the consumer pending messages, deleting every corresponding * entry from the global entry. */ raxIterator ri; raxStart(&ri,consumer->pel); raxSeek(&ri,"^",NULL,0); while(raxNext(&ri)) { streamNACK *nack = ri.data; raxRemove(cg->pel,ri.key,ri.key_len,NULL); streamFreeNACK(nack); } raxStop(&ri); /* Deallocate the consumer. */ raxRemove(cg->consumers,(unsigned char*)name,sdslen(name),NULL); streamFreeConsumer(consumer); return retval; } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int BN_GF2m_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { int i; const BIGNUM *at, *bt; bn_check_top(a); bn_check_top(b); if (a->top < b->top) { at = b; bt = a; } else { at = a; bt = b; } if (bn_wexpand(r, at->top) == NULL) return 0; for (i = 0; i < bt->top; i++) { r->d[i] = at->d[i] ^ bt->d[i]; } for (; i < at->top; i++) { r->d[i] = at->d[i]; } r->top = at->top; bn_correct_top(r); return 1; } 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 ssize_t stellaris_enet_receive(NetClientState *nc, const uint8_t *buf, size_t size) { stellaris_enet_state *s = qemu_get_nic_opaque(nc); int n; uint8_t *p; uint32_t crc; if ((s->rctl & SE_RCTL_RXEN) == 0) return -1; if (s->np >= 31) { return 0; } DPRINTF("Received packet len=%zu\n", size); n = s->next_packet + s->np; if (n >= 31) n -= 31; s->np++; s->rx[n].len = size + 6; p = s->rx[n].data; *(p++) = (size + 6); memset(p, 0, (6 - size) & 3); } CWE ID: CWE-20 Target: 1 Example 2: Code: DragState& DragController::GetDragState() { if (!drag_state_) drag_state_ = new DragState; return *drag_state_; } 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 mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) { size_t len = 0; /* First step: count keys into table. No other way to do it with the * Lua API, we need to iterate a first time. Note that an alternative * would be to do a single run, and then hack the buffer to insert the * map opcodes for message pack. Too hackish for this lib. */ lua_pushnil(L); while(lua_next(L,-2)) { lua_pop(L,1); /* remove value, keep key for next iteration. */ len++; } /* Step two: actually encoding of the map. */ mp_encode_map(L,buf,len); lua_pushnil(L); while(lua_next(L,-2)) { /* Stack: ... key value */ lua_pushvalue(L,-2); /* Stack: ... key value key */ mp_encode_lua_type(L,buf,level+1); /* encode key */ mp_encode_lua_type(L,buf,level+1); /* encode val */ } } 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: TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 rowsperstrip; uint32 stripsperplane; uint32 stripinplane; uint16 plane; uint32 rows; tmsize_t stripsize; if (!TIFFCheckRead(tif,0)) return((tmsize_t)(-1)); if (strip>=td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata,module, "%lu: Strip out of range, max %lu",(unsigned long)strip, (unsigned long)td->td_nstrips); return((tmsize_t)(-1)); } /* * Calculate the strip size according to the number of * rows in the strip (check for truncated last strip on any * of the separations). */ rowsperstrip=td->td_rowsperstrip; if (rowsperstrip>td->td_imagelength) rowsperstrip=td->td_imagelength; stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip); stripinplane=(strip%stripsperplane); plane=(uint16)(strip/stripsperplane); rows=td->td_imagelength-stripinplane*rowsperstrip; if (rows>rowsperstrip) rows=rowsperstrip; stripsize=TIFFVStripSize(tif,rows); if (stripsize==0) return((tmsize_t)(-1)); /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE && size!=(tmsize_t)(-1) && size >= stripsize && !isMapped(tif) && ((tif->tif_flags&TIFF_NOREADRAW)==0) ) { if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(buf,stripsize); (*tif->tif_postdecode)(tif,buf,stripsize); return (stripsize); } if ((size!=(tmsize_t)(-1))&&(size<stripsize)) stripsize=size; if (!TIFFFillStrip(tif,strip)) return((tmsize_t)(-1)); if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0) return((tmsize_t)(-1)); (*tif->tif_postdecode)(tif,buf,stripsize); return(stripsize); } CWE ID: CWE-369 Target: 1 Example 2: Code: static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) { int len, at, newdep; newdep = 0; zpath[0] = 0; len = 0; at = 0; while ( zname[at] != 0 ) { if ( zname[at] == '/' || zname[at] == '\\' ) { len = at; newdep++; } at++; } strcpy( zpath, zname ); zpath[len] = 0; *depth = newdep; return len; } CWE ID: CWE-269 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: poppler_page_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { PopplerPage *page = POPPLER_PAGE (object); GooString label; switch (prop_id) { case PROP_LABEL: page->document->doc->getCatalog ()->indexToLabel (page->index, &label); g_value_take_string (value, _poppler_goo_string_to_utf8(&label)); break; } } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BrowserViewRenderer::ScrollTo(gfx::Vector2d scroll_offset) { gfx::Vector2d max_offset = max_scroll_offset(); gfx::Vector2dF scroll_offset_dip; if (max_offset.x()) { scroll_offset_dip.set_x((scroll_offset.x() * max_scroll_offset_dip_.x()) / max_offset.x()); } if (max_offset.y()) { scroll_offset_dip.set_y((scroll_offset.y() * max_scroll_offset_dip_.y()) / max_offset.y()); } DCHECK_LE(0.f, scroll_offset_dip.x()); DCHECK_LE(0.f, scroll_offset_dip.y()); DCHECK(scroll_offset_dip.x() < max_scroll_offset_dip_.x() || scroll_offset_dip.x() - max_scroll_offset_dip_.x() < kEpsilon) << scroll_offset_dip.x() << " " << max_scroll_offset_dip_.x(); DCHECK(scroll_offset_dip.y() < max_scroll_offset_dip_.y() || scroll_offset_dip.y() - max_scroll_offset_dip_.y() < kEpsilon) << scroll_offset_dip.y() << " " << max_scroll_offset_dip_.y(); if (scroll_offset_dip_ == scroll_offset_dip) return; scroll_offset_dip_ = scroll_offset_dip; TRACE_EVENT_INSTANT2("android_webview", "BrowserViewRenderer::ScrollTo", TRACE_EVENT_SCOPE_THREAD, "x", scroll_offset_dip.x(), "y", scroll_offset_dip.y()); if (compositor_) { compositor_->DidChangeRootLayerScrollOffset( gfx::ScrollOffset(scroll_offset_dip_)); } } CWE ID: CWE-399 Target: 1 Example 2: Code: void NavigationControllerImpl::SetPendingEntry( std::unique_ptr<NavigationEntryImpl> entry) { DiscardNonCommittedEntriesInternal(); pending_entry_ = entry.release(); DCHECK_EQ(-1, pending_entry_index_); NotificationService::current()->Notify( NOTIFICATION_NAV_ENTRY_PENDING, Source<NavigationController>(this), Details<NavigationEntry>(pending_entry_)); } 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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithSequenceArg(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); sequence<ScriptProfile>* sequenceArg(toNativeArray<ScriptProfile>(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->methodWithSequenceArg(sequenceArg); return JSValue::encode(jsUndefined()); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Cluster::HasBlockEntries( const Segment* pSegment, long long off, // relative to start of segment payload long long& pos, long& len) { assert(pSegment); assert(off >= 0); // relative to segment IMkvReader* const pReader = pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = pSegment->m_start + off; // absolute if ((total >= 0) && (pos >= total)) return 0; // we don't even have a complete cluster const long long segment_stop = (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; long long cluster_stop = -1; // interpreted later to mean "unknown size" { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id != 0x0F43B675) // weird: not cluster ID return -1; // generic error pos += len; // consume Cluster ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); if (size == 0) return 0; // cluster does not have entries pos += len; // consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) { cluster_stop = pos + size; assert(cluster_stop >= 0); if ((segment_stop >= 0) && (cluster_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (cluster_stop > total)) return 0; // cluster does not have any entries } } for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) return 0; // no entries detected if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id == 0x0F43B675) // Cluster ID return 0; // no entries found if (id == 0x0C53BB6B) // Cues ID return 0; // no entries found pos += len; // consume id field if ((cluster_stop >= 0) && (pos >= cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // underflow return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; // not supported inside cluster if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x20) // BlockGroup ID return 1; // have at least one entry if (id == 0x23) // SimpleBlock ID return 1; // have at least one entry pos += size; // consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } } CWE ID: CWE-20 Target: 1 Example 2: Code: static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct msr_data apic_base_msr; u64 cr0; vmx->rmode.vm86_active = 0; vmx->spec_ctrl = 0; vcpu->arch.microcode_version = 0x100000000ULL; vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val(); kvm_set_cr8(vcpu, 0); if (!init_event) { apic_base_msr.data = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE; if (kvm_vcpu_is_reset_bsp(vcpu)) apic_base_msr.data |= MSR_IA32_APICBASE_BSP; apic_base_msr.host_initiated = true; kvm_set_apic_base(vcpu, &apic_base_msr); } vmx_segment_cache_clear(vmx); seg_setup(VCPU_SREG_CS); vmcs_write16(GUEST_CS_SELECTOR, 0xf000); vmcs_writel(GUEST_CS_BASE, 0xffff0000ul); seg_setup(VCPU_SREG_DS); seg_setup(VCPU_SREG_ES); seg_setup(VCPU_SREG_FS); seg_setup(VCPU_SREG_GS); seg_setup(VCPU_SREG_SS); vmcs_write16(GUEST_TR_SELECTOR, 0); vmcs_writel(GUEST_TR_BASE, 0); vmcs_write32(GUEST_TR_LIMIT, 0xffff); vmcs_write32(GUEST_TR_AR_BYTES, 0x008b); vmcs_write16(GUEST_LDTR_SELECTOR, 0); vmcs_writel(GUEST_LDTR_BASE, 0); vmcs_write32(GUEST_LDTR_LIMIT, 0xffff); vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082); if (!init_event) { vmcs_write32(GUEST_SYSENTER_CS, 0); vmcs_writel(GUEST_SYSENTER_ESP, 0); vmcs_writel(GUEST_SYSENTER_EIP, 0); vmcs_write64(GUEST_IA32_DEBUGCTL, 0); } kvm_set_rflags(vcpu, X86_EFLAGS_FIXED); kvm_rip_write(vcpu, 0xfff0); vmcs_writel(GUEST_GDTR_BASE, 0); vmcs_write32(GUEST_GDTR_LIMIT, 0xffff); vmcs_writel(GUEST_IDTR_BASE, 0); vmcs_write32(GUEST_IDTR_LIMIT, 0xffff); vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE); vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0); vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0); if (kvm_mpx_supported()) vmcs_write64(GUEST_BNDCFGS, 0); setup_msrs(vmx); vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */ if (cpu_has_vmx_tpr_shadow() && !init_event) { vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0); if (cpu_need_tpr_shadow(vcpu)) vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, __pa(vcpu->arch.apic->regs)); vmcs_write32(TPR_THRESHOLD, 0); } kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu); if (vmx->vpid != 0) vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid); cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET; vmx->vcpu.arch.cr0 = cr0; vmx_set_cr0(vcpu, cr0); /* enter rmode */ vmx_set_cr4(vcpu, 0); vmx_set_efer(vcpu, 0); update_exception_bitmap(vcpu); vpid_sync_context(vmx->vpid); if (init_event) vmx_clear_hlt(vcpu); } 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 DevToolsUIBindings::IsValidRemoteFrontendURL(const GURL& url) { return ::SanitizeFrontendURL(url, url::kHttpsScheme, kRemoteFrontendDomain, url.path(), true) .spec() == url.spec(); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int mount_autodev(const char *name, const struct lxc_rootfs *rootfs, const char *lxcpath) { int ret; size_t clen; char *path; INFO("Mounting container /dev"); /* $(rootfs->mount) + "/dev/pts" + '\0' */ clen = (rootfs->path ? strlen(rootfs->mount) : 0) + 9; path = alloca(clen); ret = snprintf(path, clen, "%s/dev", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= clen) return -1; if (!dir_exists(path)) { WARN("No /dev in container."); WARN("Proceeding without autodev setup"); return 0; } if (mount("none", path, "tmpfs", 0, "size=100000,mode=755")) { SYSERROR("Failed mounting tmpfs onto %s\n", path); return false; } INFO("Mounted tmpfs onto %s", path); ret = snprintf(path, clen, "%s/dev/pts", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= clen) return -1; /* * If we are running on a devtmpfs mapping, dev/pts may already exist. * If not, then create it and exit if that fails... */ if (!dir_exists(path)) { ret = mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); if (ret) { SYSERROR("Failed to create /dev/pts in container"); return -1; } } INFO("Mounted container /dev"); return 0; } CWE ID: CWE-59 Target: 1 Example 2: Code: static int __init nfs_init_inodecache(void) { nfs_inode_cachep = kmem_cache_create("nfs_inode_cache", sizeof(struct nfs_inode), 0, (SLAB_RECLAIM_ACCOUNT| SLAB_MEM_SPREAD), init_once); if (nfs_inode_cachep == NULL) return -ENOMEM; return 0; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Compositor::CreateContextProvider( gpu::SurfaceHandle handle, gpu::ContextCreationAttribs attributes, gpu::SharedMemoryLimits shared_memory_limits, ContextProviderCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserMainLoop::GetInstance() ->gpu_channel_establish_factory() ->EstablishGpuChannel( base::BindOnce(&CreateContextProviderAfterGpuChannelEstablished, handle, attributes, shared_memory_limits, callback)); } 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 IDNToUnicodeOneComponent(const base::char16* comp, size_t comp_len, base::string16* out) { DCHECK(out); if (comp_len == 0) return false; static const base::char16 kIdnPrefix[] = {'x', 'n', '-', '-'}; if ((comp_len > arraysize(kIdnPrefix)) && !memcmp(comp, kIdnPrefix, sizeof(kIdnPrefix))) { UIDNA* uidna = g_uidna.Get().value; DCHECK(uidna != NULL); size_t original_length = out->length(); int32_t output_length = 64; UIDNAInfo info = UIDNA_INFO_INITIALIZER; UErrorCode status; do { out->resize(original_length + output_length); status = U_ZERO_ERROR; output_length = uidna_labelToUnicode( uidna, comp, static_cast<int32_t>(comp_len), &(*out)[original_length], output_length, &info, &status); } while ((status == U_BUFFER_OVERFLOW_ERROR && info.errors == 0)); if (U_SUCCESS(status) && info.errors == 0) { out->resize(original_length + output_length); if (IsIDNComponentSafe( base::StringPiece16(out->data() + original_length, base::checked_cast<size_t>(output_length)))) return true; } out->resize(original_length); } out->append(comp, comp_len); return false; } CWE ID: CWE-20 Target: 1 Example 2: Code: PHP_FUNCTION(pg_fetch_all_columns) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; zend_long colno=0; int pg_numrows, pg_row; size_t num_fields; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &result, &colno) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result); pgsql_result = pg_result->result; num_fields = PQnfields(pgsql_result); if (colno >= (zend_long)num_fields || colno < 0) { php_error_docref(NULL, E_WARNING, "Invalid column number '%pd'", colno); RETURN_FALSE; } array_init(return_value); if ((pg_numrows = PQntuples(pgsql_result)) <= 0) { return; } for (pg_row = 0; pg_row < pg_numrows; pg_row++) { if (PQgetisnull(pgsql_result, pg_row, (int)colno)) { add_next_index_null(return_value); } else { add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, (int)colno)); } } } 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: PHP_FUNCTION(stream_set_read_buffer) { zval *arg1; int ret; long arg2; size_t buff; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &arg2) == FAILURE) { RETURN_FALSE; } php_stream_from_zval(stream, &arg1); buff = arg2; /* if buff is 0 then set to non-buffered */ if (buff == 0) { ret = php_stream_set_option(stream, PHP_STREAM_OPTION_READ_BUFFER, PHP_STREAM_BUFFER_NONE, NULL); } else { ret = php_stream_set_option(stream, PHP_STREAM_OPTION_READ_BUFFER, PHP_STREAM_BUFFER_FULL, &buff); } RETURN_LONG(ret == 0 ? 0 : EOF); } 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: int PrintPreviewUI::GetAvailableDraftPageCount() { return print_preview_data_service()->GetAvailableDraftPageCount( preview_ui_addr_str_); } CWE ID: CWE-200 Target: 1 Example 2: Code: static void activityLoggingAccessForIsolatedWorldsPerWorldBindingsLongAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); V8PerContextData* contextData = V8PerContextData::from(info.GetIsolate()->GetCurrentContext()); if (contextData && contextData->activityLogger()) { v8::Handle<v8::Value> loggerArg[] = { jsValue }; contextData->activityLogger()->log("TestObjectPython.activityLoggingAccessForIsolatedWorldsPerWorldBindingsLongAttribute", 1, &loggerArg[0], "Setter"); } TestObjectPythonV8Internal::activityLoggingAccessForIsolatedWorldsPerWorldBindingsLongAttributeAttributeSetter(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void withScriptStateVoidMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectV8Internal::withScriptStateVoidMethod(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: GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox); if (e) { return e; } if (!((GF_DataInformationBox *)s)->dref) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n")); ((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); } return GF_OK; } CWE ID: CWE-400 Target: 1 Example 2: Code: UsbDevice::~UsbDevice() { } 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 ext4_set_aops(struct inode *inode) { if (ext4_should_order_data(inode) && test_opt(inode->i_sb, DELALLOC)) inode->i_mapping->a_ops = &ext4_da_aops; else if (ext4_should_order_data(inode)) inode->i_mapping->a_ops = &ext4_ordered_aops; else if (ext4_should_writeback_data(inode) && test_opt(inode->i_sb, DELALLOC)) inode->i_mapping->a_ops = &ext4_da_aops; else if (ext4_should_writeback_data(inode)) inode->i_mapping->a_ops = &ext4_writeback_aops; else inode->i_mapping->a_ops = &ext4_journalled_aops; } 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: cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { assert((size_t)CDF_SEC_SIZE(h) == len); return cdf_read(info, (off_t)CDF_SEC_POS(h, id), ((char *)buf) + offs, len); } CWE ID: CWE-119 Target: 1 Example 2: Code: const Tracks* Segment::GetTracks() const { return m_pTracks; } 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 RemoteFrame::Navigate(const FrameLoadRequest& passed_request) { FrameLoadRequest frame_request(passed_request); FrameLoader::SetReferrerForFrameRequest(frame_request); FrameLoader::UpgradeInsecureRequest(frame_request.GetResourceRequest(), frame_request.OriginDocument()); frame_request.GetResourceRequest().SetHasUserGesture( Frame::HasTransientUserActivation(this)); Client()->Navigate(frame_request.GetResourceRequest(), frame_request.ReplacesCurrentItem()); } 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 ssl3_send_alert(SSL *s, int level, int desc) { /* Map tls/ssl alert value to correct one */ desc = s->method->ssl3_enc->alert_value(desc); if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION) desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have * protocol_version alerts */ * protocol_version alerts */ if (desc < 0) return -1; /* If a fatal one, remove from cache */ if ((level == 2) && (s->session != NULL)) SSL_CTX_remove_session(s->session_ctx, s->session); s->s3->alert_dispatch = 1; s->s3->send_alert[0] = level; * else data is still being written out, we will get written some time in * the future */ return -1; } CWE ID: CWE-200 Target: 1 Example 2: Code: session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns) { const char *remote = ""; if (utmp_size > 0) remote = auth_get_canonical_hostname(ssh, use_dns); if (utmp_size == 0 || strlen(remote) > utmp_size) remote = ssh_remote_ipaddr(ssh); return remote; } 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 check_ctx_access(struct verifier_env *env, int off, int size, enum bpf_access_type t) { if (env->prog->aux->ops->is_valid_access && env->prog->aux->ops->is_valid_access(off, size, t)) return 0; verbose("invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } 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: status_t Parcel::readUtf8FromUtf16(std::string* str) const { size_t utf16Size = 0; const char16_t* src = readString16Inplace(&utf16Size); if (!src) { return UNEXPECTED_NULL; } if (utf16Size == 0u) { str->clear(); return NO_ERROR; } ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size); if (utf8Size < 0) { return BAD_VALUE; } str->resize(utf8Size + 1); utf16_to_utf8(src, utf16Size, &((*str)[0])); str->resize(utf8Size); return NO_ERROR; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int vmxnet3_mcast_list_pre_load(void *opaque) { VMXNET3State *s = opaque; s->mcast_list = g_malloc(s->mcast_list_buff_size); return 0; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void f2fs_put_super(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int i; f2fs_quota_off_umount(sb); /* prevent remaining shrinker jobs */ mutex_lock(&sbi->umount_mutex); /* * We don't need to do checkpoint when superblock is clean. * But, the previous checkpoint was not done by umount, it needs to do * clean checkpoint again. */ if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) || !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { struct cp_control cpc = { .reason = CP_UMOUNT, }; write_checkpoint(sbi, &cpc); } /* be sure to wait for any on-going discard commands */ f2fs_wait_discard_bios(sbi); if (f2fs_discard_en(sbi) && !sbi->discard_blks) { struct cp_control cpc = { .reason = CP_UMOUNT | CP_TRIMMED, }; write_checkpoint(sbi, &cpc); } /* write_checkpoint can update stat informaion */ f2fs_destroy_stats(sbi); /* * normally superblock is clean, so we need to release this. * In addition, EIO will skip do checkpoint, we need this as well. */ release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); mutex_unlock(&sbi->umount_mutex); /* our cp_error case, we can wait for any writeback page */ f2fs_flush_merged_writes(sbi); iput(sbi->node_inode); iput(sbi->meta_inode); /* destroy f2fs internal modules */ destroy_node_manager(sbi); destroy_segment_manager(sbi); kfree(sbi->ckpt); f2fs_unregister_sysfs(sbi); sb->s_fs_info = NULL; if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->raw_super); destroy_device_list(sbi); mempool_destroy(sbi->write_io_dummy); #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif destroy_percpu_info(sbi); for (i = 0; i < NR_PAGE_TYPE; i++) kfree(sbi->write_io[i]); kfree(sbi); } 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: w3m_exit(int i) { #ifdef USE_MIGEMO init_migemo(); /* close pipe to migemo */ #endif stopDownload(); deleteFiles(); #ifdef USE_SSL free_ssl_ctx(); #endif disconnectFTP(); #ifdef USE_NNTP disconnectNews(); #endif #ifdef __MINGW32_VERSION WSACleanup(); #endif exit(i); } CWE ID: CWE-59 Target: 1 Example 2: Code: static void OverloadedMethodD1Method(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "overloadedMethodD"); TestObject* impl = V8TestObject::ToImpl(info.Holder()); int32_t long_arg; long_arg = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), info[0], exception_state); if (exception_state.HadException()) return; impl->overloadedMethodD(long_arg); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GLES2Implementation::GetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glGetAttachedShaders(" << program << ", " << maxcount << ", " << static_cast<const void*>(count) << ", " << static_cast<const void*>(shaders) << ", "); if (maxcount < 0) { SetGLError(GL_INVALID_VALUE, "glGetAttachedShaders", "maxcount < 0"); return; } TRACE_EVENT0("gpu", "GLES2::GetAttachedShaders"); typedef cmds::GetAttachedShaders::Result Result; uint32_t checked_size = 0; if (!Result::ComputeSize(maxcount).AssignIfValid(&checked_size)) { SetGLError(GL_OUT_OF_MEMORY, "glGetAttachedShaders", "allocation too large"); return; } Result* result = static_cast<Result*>(transfer_buffer_->Alloc(checked_size)); if (!result) { return; } result->SetNumResults(0); helper_->GetAttachedShaders(program, transfer_buffer_->GetShmId(), transfer_buffer_->GetOffset(result), checked_size); int32_t token = helper_->InsertToken(); WaitForCmd(); if (count) { *count = result->GetNumResults(); } result->CopyResult(shaders); GPU_CLIENT_LOG_CODE_BLOCK({ for (int32_t i = 0; i < result->GetNumResults(); ++i) { GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]); } }); transfer_buffer_->FreePendingToken(result, token); CheckGLError(); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BOOL license_read_scope_list(wStream* s, SCOPE_LIST* scopeList) { UINT32 i; UINT32 scopeCount; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, scopeCount); /* ScopeCount (4 bytes) */ scopeList->count = scopeCount; scopeList->array = (LICENSE_BLOB*) malloc(sizeof(LICENSE_BLOB) * scopeCount); /* ScopeArray */ for (i = 0; i < scopeCount; i++) { scopeList->array[i].type = BB_SCOPE_BLOB; if (!license_read_binary_blob(s, &scopeList->array[i])) return FALSE; } return TRUE; } CWE ID: CWE-189 Target: 1 Example 2: Code: update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) { long delta = gcfs_rq->avg.util_avg - se->avg.util_avg; /* Nothing to update */ if (!delta) return; /* * The relation between sum and avg is: * * LOAD_AVG_MAX - 1024 + sa->period_contrib * * however, the PELT windows are not aligned between grq and gse. */ /* Set new sched_entity's utilization */ se->avg.util_avg = gcfs_rq->avg.util_avg; se->avg.util_sum = se->avg.util_avg * LOAD_AVG_MAX; /* Update parent cfs_rq utilization */ add_positive(&cfs_rq->avg.util_avg, delta); cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * LOAD_AVG_MAX; } CWE ID: CWE-400 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: process_db_args(krb5_context context, char **db_args, xargs_t *xargs, OPERATION optype) { int i=0; krb5_error_code st=0; char *arg=NULL, *arg_val=NULL; char **dptr=NULL; unsigned int arg_val_len=0; if (db_args) { for (i=0; db_args[i]; ++i) { arg = strtok_r(db_args[i], "=", &arg_val); if (strcmp(arg, TKTPOLICY_ARG) == 0) { dptr = &xargs->tktpolicydn; } else { if (strcmp(arg, USERDN_ARG) == 0) { if (optype == MODIFY_PRINCIPAL || xargs->dn != NULL || xargs->containerdn != NULL || xargs->linkdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->dn; } else if (strcmp(arg, CONTAINERDN_ARG) == 0) { if (optype == MODIFY_PRINCIPAL || xargs->dn != NULL || xargs->containerdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->containerdn; } else if (strcmp(arg, LINKDN_ARG) == 0) { if (xargs->dn != NULL || xargs->linkdn != NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option not supported"), arg); goto cleanup; } dptr = &xargs->linkdn; } else { st = EINVAL; k5_setmsg(context, st, _("unknown option: %s"), arg); goto cleanup; } xargs->dn_from_kbd = TRUE; if (arg_val == NULL || strlen(arg_val) == 0) { st = EINVAL; k5_setmsg(context, st, _("%s option value missing"), arg); goto cleanup; } } if (arg_val == NULL) { st = EINVAL; k5_setmsg(context, st, _("%s option value missing"), arg); goto cleanup; } arg_val_len = strlen(arg_val) + 1; if (strcmp(arg, TKTPOLICY_ARG) == 0) { if ((st = krb5_ldap_name_to_policydn (context, arg_val, dptr)) != 0) goto cleanup; } else { *dptr = k5memdup(arg_val, arg_val_len, &st); if (*dptr == NULL) goto cleanup; } } } cleanup: return st; } 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 megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) { PCIDevice *pci_dev = PCI_DEVICE(s); PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); struct mfi_ctrl_info info; size_t dcmd_size = sizeof(info); BusChild *kid; int num_pd_disks = 0; memset(&info, 0x0, dcmd_size); if (cmd->iov_size < dcmd_size) { trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, dcmd_size); return MFI_STAT_INVALID_PARAMETER; } info.pci.vendor = cpu_to_le16(pci_class->vendor_id); info.pci.device = cpu_to_le16(pci_class->device_id); info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); /* * For some reason the firmware supports * only up to 8 device ports. * Despite supporting a far larger number * of devices for the physical devices. * So just display the first 8 devices * in the device port list, independent * of how many logical devices are actually * present. */ info.host.type = MFI_INFO_HOST_PCIE; info.device.type = MFI_INFO_DEV_SAS3G; info.device.port_count = 8; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = SCSI_DEVICE(kid->child); uint16_t pd_id; if (num_pd_disks < 8) { pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); info.device.port_addr[num_pd_disks] = cpu_to_le64(megasas_get_sata_addr(pd_id)); } num_pd_disks++; } memcpy(info.product_name, base_class->product_name, 24); snprintf(info.serial_number, 32, "%s", s->hba_serial); snprintf(info.package_version, 0x60, "%s-QEMU", qemu_hw_version()); memcpy(info.image_component[0].name, "APP", 3); snprintf(info.image_component[0].version, 10, "%s-QEMU", base_class->product_version); memcpy(info.image_component[0].build_date, "Apr 1 2014", 11); memcpy(info.image_component[0].build_time, "12:34:56", 8); info.image_component_count = 1; if (pci_dev->has_rom) { uint8_t biosver[32]; uint8_t *ptr; ptr = memory_region_get_ram_ptr(&pci_dev->rom); memcpy(biosver, ptr + 0x41, 31); memcpy(info.image_component[1].name, "BIOS", 4); memcpy(info.image_component[1].version, biosver, strlen((const char *)biosver)); } info.current_fw_time = cpu_to_le32(megasas_fw_time()); info.max_arms = 32; info.max_spans = 8; info.max_arrays = MEGASAS_MAX_ARRAYS; info.max_lds = MFI_MAX_LD; info.max_cmds = cpu_to_le16(s->fw_cmds); info.max_sg_elements = cpu_to_le16(s->fw_sge); info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); if (!megasas_is_jbod(s)) info.lds_present = cpu_to_le16(num_pd_disks); info.pd_present = cpu_to_le16(num_pd_disks); info.pd_disks_present = cpu_to_le16(num_pd_disks); info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | MFI_INFO_HW_MEM | MFI_INFO_HW_FLASH); info.memory_size = cpu_to_le16(512); info.nvram_size = cpu_to_le16(32); info.flash_size = cpu_to_le16(16); info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0); info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE | MFI_INFO_AOPS_SELF_DIAGNOSTIC | MFI_INFO_AOPS_MIXED_ARRAY); info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY | MFI_INFO_LDOPS_ACCESS_POLICY | MFI_INFO_LDOPS_IO_POLICY | MFI_INFO_LDOPS_WRITE_POLICY | MFI_INFO_LDOPS_READ_POLICY); info.max_strips_per_io = cpu_to_le16(s->fw_sge); info.stripe_sz_ops.min = 3; info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1); info.properties.pred_fail_poll_interval = cpu_to_le16(300); info.properties.intr_throttle_cnt = cpu_to_le16(16); info.properties.intr_throttle_timeout = cpu_to_le16(50); info.properties.rebuild_rate = 30; info.properties.patrol_read_rate = 30; info.properties.bgi_rate = 30; info.properties.cc_rate = 30; info.properties.recon_rate = 30; info.properties.cache_flush_interval = 4; info.properties.spinup_drv_cnt = 2; info.properties.spinup_delay = 6; info.properties.ecc_bucket_size = 15; info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440); info.properties.expose_encl_devices = 1; info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD); info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE | MFI_INFO_PDOPS_FORCE_OFFLINE); info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS | MFI_INFO_PDMIX_SATA | MFI_INFO_PDMIX_LD); cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); return MFI_STAT_OK; } CWE ID: CWE-200 Target: 1 Example 2: Code: scoped_refptr<const Extension> CreateTestExtension( const std::string& id, bool has_active_tab_permission, bool has_tab_capture_permission) { ListBuilder permissions; if (has_active_tab_permission) permissions.Append("activeTab"); if (has_tab_capture_permission) permissions.Append("tabCapture"); return ExtensionBuilder() .SetManifest(DictionaryBuilder() .Set("name", "Extension with ID " + id) .Set("version", "1.0") .Set("manifest_version", 2) .Set("permissions", permissions.Build()) .Build()) .SetID(id) .Build(); } 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 DevToolsWindow::CreateDevToolsBrowser() { std::string wp_key = GetDevToolsWindowPlacementPrefKey(); PrefService* prefs = profile_->GetPrefs(); const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str()); if (!wp_pref || wp_pref->empty()) { DictionaryPrefUpdate update(prefs, wp_key.c_str()); DictionaryValue* defaults = update.Get(); defaults->SetInteger("left", 100); defaults->SetInteger("top", 100); defaults->SetInteger("right", 740); defaults->SetInteger("bottom", 740); defaults->SetBoolean("maximized", false); defaults->SetBoolean("always_on_top", false); } browser_ = new Browser(Browser::CreateParams::CreateForDevTools( profile_, chrome::GetHostDesktopTypeForNativeView( web_contents_->GetView()->GetNativeView()))); browser_->tab_strip_model()->AddWebContents( web_contents_, -1, content::PAGE_TRANSITION_AUTO_TOPLEVEL, TabStripModel::ADD_ACTIVE); GetRenderViewHost()->SyncRendererPrefs(); } 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 struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ __ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ if (np->opt != NULL) newnp->opt = ipv6_dup_options(newsk, np->opt); inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt != NULL) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } CWE ID: CWE-416 Target: 1 Example 2: Code: JNIEnv* getCallbackEnv() { return callbackEnv; } 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: OMX_ERRORTYPE SoftAAC2::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch ((int)index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.aac", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) { mIsADTS = false; } else if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4ADTS) { mIsADTS = true; } else { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAndroidAacPresentation: { const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *aacPresParams = (const OMX_AUDIO_PARAM_ANDROID_AACPRESENTATIONTYPE *)params; if (aacPresParams->nMaxOutputChannels >= 0) { int max; if (aacPresParams->nMaxOutputChannels >= 8) { max = 8; } else if (aacPresParams->nMaxOutputChannels >= 6) { max = 6; } else if (aacPresParams->nMaxOutputChannels >= 2) { max = 2; } else { max = aacPresParams->nMaxOutputChannels; } ALOGV("set nMaxOutputChannels=%d", max); aacDecoder_SetParam(mAACDecoder, AAC_PCM_MAX_OUTPUT_CHANNELS, max); } bool updateDrcWrapper = false; if (aacPresParams->nDrcBoost >= 0) { ALOGV("set nDrcBoost=%d", aacPresParams->nDrcBoost); mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_BOOST_FACTOR, aacPresParams->nDrcBoost); updateDrcWrapper = true; } if (aacPresParams->nDrcCut >= 0) { ALOGV("set nDrcCut=%d", aacPresParams->nDrcCut); mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_ATT_FACTOR, aacPresParams->nDrcCut); updateDrcWrapper = true; } if (aacPresParams->nHeavyCompression >= 0) { ALOGV("set nHeavyCompression=%d", aacPresParams->nHeavyCompression); mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_HEAVY, aacPresParams->nHeavyCompression); updateDrcWrapper = true; } if (aacPresParams->nTargetReferenceLevel >= 0) { ALOGV("set nTargetReferenceLevel=%d", aacPresParams->nTargetReferenceLevel); mDrcWrap.setParam(DRC_PRES_MODE_WRAP_DESIRED_TARGET, aacPresParams->nTargetReferenceLevel); updateDrcWrapper = true; } if (aacPresParams->nEncodedTargetLevel >= 0) { ALOGV("set nEncodedTargetLevel=%d", aacPresParams->nEncodedTargetLevel); mDrcWrap.setParam(DRC_PRES_MODE_WRAP_ENCODER_TARGET, aacPresParams->nEncodedTargetLevel); updateDrcWrapper = true; } if (aacPresParams->nPCMLimiterEnable >= 0) { aacDecoder_SetParam(mAACDecoder, AAC_PCM_LIMITER_ENABLE, (aacPresParams->nPCMLimiterEnable != 0)); } if (updateDrcWrapper) { mDrcWrap.update(); } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } 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: virtual void SetUp() { url_util::AddStandardScheme("tabcontentstest"); old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); RenderViewHostTestHarness::SetUp(); } CWE ID: CWE-264 Target: 1 Example 2: Code: static int l_publickey_canauth (lua_State *L) { return publickey_canauth(L, 0, 0); } CWE ID: CWE-415 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Ins_CLEAR( TT_ExecContext exc ) { exc->new_top = 0; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' }; midi * ret = NULL; if (!WM_Initialized) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0); return (NULL); } if (midibuffer == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0); return (NULL); } if (size > WM_MAXFILESIZE) { /* don't bother loading suspiciously long files */ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0); return (NULL); } if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) { ret = (void *) _WM_ParseNewHmp(midibuffer, size); } else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) { ret = (void *) _WM_ParseNewHmi(midibuffer, size); } else if (memcmp(midibuffer, mus_hdr, 4) == 0) { ret = (void *) _WM_ParseNewMus(midibuffer, size); } else if (memcmp(midibuffer, xmi_hdr, 4) == 0) { ret = (void *) _WM_ParseNewXmi(midibuffer, size); } else { ret = (void *) _WM_ParseNewMidi(midibuffer, size); } if (ret) { if (add_handle(ret) != 0) { WildMidi_Close(ret); ret = NULL; } } return (ret); } CWE ID: CWE-119 Target: 1 Example 2: Code: _archive_write_finish_entry(struct archive *_a) { struct archive_write *a = (struct archive_write *)_a; int ret = ARCHIVE_OK; archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA, "archive_write_finish_entry"); if (a->archive.state & ARCHIVE_STATE_DATA && a->format_finish_entry != NULL) ret = (a->format_finish_entry)(a); a->archive.state = ARCHIVE_STATE_HEADER; return (ret); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int send_solid_rect(VncState *vs) { size_t bytes; tight_pack24(vs, vs->tight.tight.buffer, 1, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->clientds.pf.bytes_per_pixel; } 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 HeapObjectHeader::zapMagic() { ASSERT(checkHeader()); m_magic = zappedMagic; } CWE ID: CWE-119 Target: 1 Example 2: Code: gx_ttfReader__default_get_metrics(const ttfReader *ttf, uint glyph_index, bool bVertical, short *sideBearing, unsigned short *nAdvance) { gx_ttfReader *self = (gx_ttfReader *)ttf; float sbw[4]; int sbw_offset = bVertical; int code; int factor = self->pfont->data.unitsPerEm; code = self->pfont->data.get_metrics(self->pfont, glyph_index, bVertical, sbw); if (code < 0) return code; /* Due to an obsolete convention, simple_glyph_metrics scales the metrics into 1x1 rectangle as Postscript like. In same time, the True Type interpreter needs the original design units. Undo the scaling here with accurate rounding. */ *sideBearing = (short)floor(sbw[0 + sbw_offset] * factor + 0.5); *nAdvance = (short)floor(sbw[2 + sbw_offset] * factor + 0.5); return 0; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: RGBA32 AXNodeObject::colorValue() const { if (!isHTMLInputElement(getNode()) || !isColorWell()) return AXObject::colorValue(); HTMLInputElement* input = toHTMLInputElement(getNode()); const AtomicString& type = input->getAttribute(typeAttr); if (!equalIgnoringCase(type, "color")) return AXObject::colorValue(); Color color; bool success = color.setFromString(input->value()); DCHECK(success); return color.rgb(); } CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Segment::DoLoadClusterUnknownSize( long long& pos, long& len) { assert(m_pos < 0); assert(m_pUnknownSize); #if 0 assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this const long long element_start = m_pUnknownSize->m_element_start; pos = -m_pos; assert(pos > element_start); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long element_size = -1; for (;;) //determine cluster size { if ((total >= 0) && (pos >= total)) { element_size = total - element_start; assert(element_size > 0); break; } if ((segment_stop >= 0) && (pos >= segment_stop)) { element_size = segment_stop - element_start; assert(element_size > 0); break; } if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) //error (or underflow) return static_cast<long>(id); if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster ID or Cues ID { element_size = pos - element_start; assert(element_size > 0); break; } #ifdef _DEBUG switch (id) { case 0x20: //BlockGroup case 0x23: //Simple Block case 0x67: //TimeCode case 0x2B: //PrevSize break; default: assert(false); break; } #endif pos += len; //consume ID (of sub-element) if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume size field of element if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not allowed for sub-elements if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird return E_FILE_FORMAT_INVALID; pos += size; //consume payload of sub-element assert((segment_stop < 0) || (pos <= segment_stop)); } //determine cluster size assert(element_size >= 0); m_pos = element_start + element_size; m_pUnknownSize = 0; return 2; //continue parsing #else const long status = m_pUnknownSize->Parse(pos, len); if (status < 0) //error or underflow return status; if (status == 0) //parsed a block return 2; //continue parsing assert(status > 0); //nothing left to parse of this cluster const long long start = m_pUnknownSize->m_element_start; const long long size = m_pUnknownSize->GetElementSize(); assert(size >= 0); pos = start + size; m_pos = pos; m_pUnknownSize = 0; return 2; //continue parsing #endif } CWE ID: CWE-119 Target: 1 Example 2: Code: sg_add_request(Sg_fd * sfp) { int k; unsigned long iflags; Sg_request *rp = sfp->req_arr; write_lock_irqsave(&sfp->rq_list_lock, iflags); if (!list_empty(&sfp->rq_list)) { if (!sfp->cmd_q) goto out_unlock; for (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) { if (!rp->parentfp) break; } if (k >= SG_MAX_QUEUE) goto out_unlock; } memset(rp, 0, sizeof (Sg_request)); rp->parentfp = sfp; rp->header.duration = jiffies_to_msecs(jiffies); list_add_tail(&rp->entry, &sfp->rq_list); write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return rp; out_unlock: write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return NULL; } 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 zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops) { while (elements-- > 0) { zval key, *data, d, *old_data; zend_ulong idx; ZVAL_UNDEF(&key); if (!php_var_unserialize_internal(&key, p, max, NULL, classes)) { zval_dtor(&key); return 0; } data = NULL; ZVAL_UNDEF(&d); if (!objprops) { if (Z_TYPE(key) == IS_LONG) { idx = Z_LVAL(key); numeric_key: if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) { var_push_dtor(var_hash, old_data); data = zend_hash_index_update(ht, idx, &d); } else { data = zend_hash_index_add_new(ht, idx, &d); } } else if (Z_TYPE(key) == IS_STRING) { if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) { goto numeric_key; } if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) { var_push_dtor(var_hash, old_data); data = zend_hash_update(ht, Z_STR(key), &d); } else { data = zend_hash_add_new(ht, Z_STR(key), &d); } } else { zval_dtor(&key); return 0; } } else { if (EXPECTED(Z_TYPE(key) == IS_STRING)) { string_key: if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) { if (Z_TYPE_P(old_data) == IS_INDIRECT) { old_data = Z_INDIRECT_P(old_data); } var_push_dtor(var_hash, old_data); data = zend_hash_update_ind(ht, Z_STR(key), &d); } else { data = zend_hash_add_new(ht, Z_STR(key), &d); } } else if (Z_TYPE(key) == IS_LONG) { /* object properties should include no integers */ convert_to_string(&key); goto string_key; } else { zval_dtor(&key); return 0; } } if (!php_var_unserialize_internal(data, p, max, var_hash, classes)) { zval_dtor(&key); return 0; } if (UNEXPECTED(Z_ISUNDEF_P(data))) { if (Z_TYPE(key) == IS_LONG) { zend_hash_index_del(ht, Z_LVAL(key)); } else { zend_hash_del_ind(ht, Z_STR(key)); } } else { var_push_dtor(var_hash, data); } zval_dtor(&key); if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } } 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: _warc_read(struct archive_read *a, const void **buf, size_t *bsz, int64_t *off) { struct warc_s *w = a->format->data; const char *rab; ssize_t nrd; if (w->cntoff >= w->cntlen) { eof: /* it's our lucky day, no work, we can leave early */ *buf = NULL; *bsz = 0U; *off = w->cntoff + 4U/*for \r\n\r\n separator*/; w->unconsumed = 0U; return (ARCHIVE_EOF); } rab = __archive_read_ahead(a, 1U, &nrd); if (nrd < 0) { *bsz = 0U; /* big catastrophe */ return (int)nrd; } else if (nrd == 0) { goto eof; } else if ((size_t)nrd > w->cntlen - w->cntoff) { /* clamp to content-length */ nrd = w->cntlen - w->cntoff; } *off = w->cntoff; *bsz = nrd; *buf = rab; w->cntoff += nrd; w->unconsumed = (size_t)nrd; return (ARCHIVE_OK); } CWE ID: CWE-415 Target: 1 Example 2: Code: CGLContextObj WebPluginAcceleratedSurfaceProxy::context() { return surface_ ? surface_->context() : NULL; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ pcap_close(fp); if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; } CWE ID: CWE-918 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 dcbnl_cee_fill(struct sk_buff *skb, struct net_device *netdev) { struct nlattr *cee, *app; struct dcb_app_type *itr; const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops; int dcbx, i, err = -EMSGSIZE; u8 value; if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name)) goto nla_put_failure; cee = nla_nest_start(skb, DCB_ATTR_CEE); if (!cee) goto nla_put_failure; /* local pg */ if (ops->getpgtccfgtx && ops->getpgbwgcfgtx) { err = dcbnl_cee_pg_fill(skb, netdev, 1); if (err) goto nla_put_failure; } if (ops->getpgtccfgrx && ops->getpgbwgcfgrx) { err = dcbnl_cee_pg_fill(skb, netdev, 0); if (err) goto nla_put_failure; } /* local pfc */ if (ops->getpfccfg) { struct nlattr *pfc_nest = nla_nest_start(skb, DCB_ATTR_CEE_PFC); if (!pfc_nest) goto nla_put_failure; for (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) { ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value); if (nla_put_u8(skb, i, value)) goto nla_put_failure; } nla_nest_end(skb, pfc_nest); } /* local app */ spin_lock(&dcb_lock); app = nla_nest_start(skb, DCB_ATTR_CEE_APP_TABLE); if (!app) goto dcb_unlock; list_for_each_entry(itr, &dcb_app_list, list) { if (itr->ifindex == netdev->ifindex) { struct nlattr *app_nest = nla_nest_start(skb, DCB_ATTR_APP); if (!app_nest) goto dcb_unlock; err = nla_put_u8(skb, DCB_APP_ATTR_IDTYPE, itr->app.selector); if (err) goto dcb_unlock; err = nla_put_u16(skb, DCB_APP_ATTR_ID, itr->app.protocol); if (err) goto dcb_unlock; err = nla_put_u8(skb, DCB_APP_ATTR_PRIORITY, itr->app.priority); if (err) goto dcb_unlock; nla_nest_end(skb, app_nest); } } nla_nest_end(skb, app); if (netdev->dcbnl_ops->getdcbx) dcbx = netdev->dcbnl_ops->getdcbx(netdev); else dcbx = -EOPNOTSUPP; spin_unlock(&dcb_lock); /* features flags */ if (ops->getfeatcfg) { struct nlattr *feat = nla_nest_start(skb, DCB_ATTR_CEE_FEAT); if (!feat) goto nla_put_failure; for (i = DCB_FEATCFG_ATTR_ALL + 1; i <= DCB_FEATCFG_ATTR_MAX; i++) if (!ops->getfeatcfg(netdev, i, &value) && nla_put_u8(skb, i, value)) goto nla_put_failure; nla_nest_end(skb, feat); } /* peer info if available */ if (ops->cee_peer_getpg) { struct cee_pg pg; err = ops->cee_peer_getpg(netdev, &pg); if (!err && nla_put(skb, DCB_ATTR_CEE_PEER_PG, sizeof(pg), &pg)) goto nla_put_failure; } if (ops->cee_peer_getpfc) { struct cee_pfc pfc; err = ops->cee_peer_getpfc(netdev, &pfc); if (!err && nla_put(skb, DCB_ATTR_CEE_PEER_PFC, sizeof(pfc), &pfc)) goto nla_put_failure; } if (ops->peer_getappinfo && ops->peer_getapptable) { err = dcbnl_build_peer_app(netdev, skb, DCB_ATTR_CEE_PEER_APP_TABLE, DCB_ATTR_CEE_PEER_APP_INFO, DCB_ATTR_CEE_PEER_APP); if (err) goto nla_put_failure; } nla_nest_end(skb, cee); /* DCBX state */ if (dcbx >= 0) { err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx); if (err) goto nla_put_failure; } return 0; dcb_unlock: spin_unlock(&dcb_lock); nla_put_failure: return err; } CWE ID: CWE-399 Target: 1 Example 2: Code: static void on_l2cap_data_ind(tBTA_JV *evt, uint32_t id) { l2cap_socket *sock; pthread_mutex_lock(&state_lock); sock = btsock_l2cap_find_by_id_l(id); if (sock) { if (sock->fixed_chan) { /* we do these differently */ tBTA_JV_LE_DATA_IND *p_le_data_ind = &evt->le_data_ind; BT_HDR *p_buf = p_le_data_ind->p_buf; uint8_t *data = (uint8_t*)(p_buf + 1) + p_buf->offset; if (packet_put_tail_l(sock, data, p_buf->len)) btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id); else {//connection must be dropped APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket - closing" " fixed channel"); BTA_JvL2capCloseLE(sock->handle); btsock_l2cap_free_l(sock); } } else { tBTA_JV_DATA_IND *p_data_ind = &evt->data_ind; UINT8 buffer[L2CAP_MAX_SDU_LENGTH]; UINT32 count; if (BTA_JvL2capReady(sock->handle, &count) == BTA_JV_SUCCESS) { if (BTA_JvL2capRead(sock->handle, sock->id, buffer, count) == BTA_JV_SUCCESS) { if (packet_put_tail_l(sock, buffer, count)) btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id); else {//connection must be dropped APPL_TRACE_DEBUG("on_l2cap_data_ind() unable to push data to socket" " - closing channel"); BTA_JvL2capClose(sock->handle); btsock_l2cap_free_l(sock); } } } } } pthread_mutex_unlock(&state_lock); } CWE ID: CWE-284 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool vhost_notify(struct vhost_dev *dev, struct vhost_virtqueue *vq) { __u16 old, new; __virtio16 event; bool v; /* Flush out used index updates. This is paired * with the barrier that the Guest executes when enabling * interrupts. */ smp_mb(); if (vhost_has_feature(vq, VIRTIO_F_NOTIFY_ON_EMPTY) && unlikely(vq->avail_idx == vq->last_avail_idx)) return true; if (!vhost_has_feature(vq, VIRTIO_RING_F_EVENT_IDX)) { __virtio16 flags; if (__get_user(flags, &vq->avail->flags)) { vq_err(vq, "Failed to get flags"); return true; } return !(flags & cpu_to_vhost16(vq, VRING_AVAIL_F_NO_INTERRUPT)); } old = vq->signalled_used; v = vq->signalled_used_valid; new = vq->signalled_used = vq->last_used_idx; vq->signalled_used_valid = true; if (unlikely(!v)) return true; if (__get_user(event, vhost_used_event(vq))) { vq_err(vq, "Failed to get used event idx"); return true; } return vring_need_event(vhost16_to_cpu(vq, event), new, old); } 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: bool mkvparser::Match( IMkvReader* pReader, long long& pos, unsigned long id_, unsigned char*& buf, size_t& buflen) { assert(pReader); assert(pos >= 0); long long total, available; long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; //consume id const long long size_ = ReadUInt(pReader, pos, len); assert(size_ >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; //consume length of size of payload assert((pos + size_) <= available); const long buflen_ = static_cast<long>(size_); buf = new (std::nothrow) unsigned char[buflen_]; assert(buf); //TODO status = pReader->Read(pos, buflen_, buf); assert(status == 0); //TODO buflen = buflen_; pos += size_; //consume size of payload return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: int32_t EqualizerGetBand(EffectContext *pContext __unused, uint32_t targetFreq){ int band = 0; if(targetFreq < bandFreqRange[0][0]){ return -EINVAL; }else if(targetFreq == bandFreqRange[0][0]){ return 0; } for(int i=0; i<FIVEBAND_NUMBANDS;i++){ if((targetFreq > bandFreqRange[i][0])&&(targetFreq <= bandFreqRange[i][1])){ band = i; } } return band; } 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 opl3_load_patch(int dev, int format, const char __user *addr, int offs, int count, int pmgr_flag) { struct sbi_instrument ins; if (count <sizeof(ins)) { printk(KERN_WARNING "FM Error: Patch record too short\n"); return -EINVAL; } /* * What the fuck is going on here? We leave junk in the beginning * of ins and then check the field pretty close to that beginning? */ if(copy_from_user(&((char *) &ins)[offs], addr + offs, sizeof(ins) - offs)) return -EFAULT; if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) { printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel); return -EINVAL; } ins.key = format; return store_instr(ins.channel, &ins); } 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 Initialize(ChannelLayout channel_layout, int bits_per_channel) { AudioParameters params( media::AudioParameters::AUDIO_PCM_LINEAR, channel_layout, kSamplesPerSecond, bits_per_channel, kRawDataSize); algorithm_.Initialize(1, params, base::Bind( &AudioRendererAlgorithmTest::EnqueueData, base::Unretained(this))); EnqueueData(); } CWE ID: CWE-119 Target: 1 Example 2: Code: poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms) { pool->blocks = NULL; pool->freeBlocks = NULL; pool->start = NULL; pool->ptr = NULL; pool->end = NULL; pool->mem = ms; } CWE ID: CWE-611 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void mark_object(struct object *obj, struct strbuf *path, const char *name, void *data) { update_progress(data); } 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: status_t OMXNodeInstance::storeMetaDataInBuffers_l( OMX_U32 portIndex, OMX_BOOL enable, MetadataBufferType *type) { if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { android_errorWriteLog(0x534e4554, "26324358"); if (type != NULL) { *type = kMetadataBufferTypeInvalid; } return BAD_VALUE; } OMX_INDEXTYPE index; OMX_STRING name = const_cast<OMX_STRING>( "OMX.google.android.index.storeMetaDataInBuffers"); OMX_STRING nativeBufferName = const_cast<OMX_STRING>( "OMX.google.android.index.storeANWBufferInMetadata"); MetadataBufferType negotiatedType; MetadataBufferType requestedType = type != NULL ? *type : kMetadataBufferTypeANWBuffer; StoreMetaDataInBuffersParams params; InitOMXParams(&params); params.nPortIndex = portIndex; params.bStoreMetaData = enable; OMX_ERRORTYPE err = requestedType == kMetadataBufferTypeANWBuffer ? OMX_GetExtensionIndex(mHandle, nativeBufferName, &index) : OMX_ErrorUnsupportedIndex; OMX_ERRORTYPE xerr = err; if (err == OMX_ErrorNone) { err = OMX_SetParameter(mHandle, index, &params); if (err == OMX_ErrorNone) { name = nativeBufferName; // set name for debugging negotiatedType = requestedType; } } if (err != OMX_ErrorNone) { err = OMX_GetExtensionIndex(mHandle, name, &index); xerr = err; if (err == OMX_ErrorNone) { negotiatedType = requestedType == kMetadataBufferTypeANWBuffer ? kMetadataBufferTypeGrallocSource : requestedType; err = OMX_SetParameter(mHandle, index, &params); } } if (err != OMX_ErrorNone) { if (err == OMX_ErrorUnsupportedIndex && portIndex == kPortIndexOutput) { CLOGW("component does not support metadata mode; using fallback"); } else if (xerr != OMX_ErrorNone) { CLOG_ERROR(getExtensionIndex, xerr, "%s", name); } else { CLOG_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d type=%d", name, index, portString(portIndex), portIndex, enable, negotiatedType); } negotiatedType = mMetadataType[portIndex]; } else { if (!enable) { negotiatedType = kMetadataBufferTypeInvalid; } mMetadataType[portIndex] = negotiatedType; } CLOG_CONFIG(storeMetaDataInBuffers, "%s:%u %srequested %s:%d negotiated %s:%d", portString(portIndex), portIndex, enable ? "" : "UN", asString(requestedType), requestedType, asString(negotiatedType), negotiatedType); if (type != NULL) { *type = negotiatedType; } return StatusFromOMXError(err); } CWE ID: CWE-200 Target: 1 Example 2: Code: void Document::postTask(const WebTraceLocation& location, PassOwnPtr<ExecutionContextTask> task) { m_taskRunner->postTask(location, task); } 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 si_swapinfo(struct sysinfo *val) { unsigned int type; unsigned long nr_to_be_unused = 0; spin_lock(&swap_lock); for (type = 0; type < nr_swapfiles; type++) { struct swap_info_struct *si = swap_info[type]; if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK)) nr_to_be_unused += si->inuse_pages; } val->freeswap = nr_swap_pages + nr_to_be_unused; val->totalswap = total_swap_pages + nr_to_be_unused; spin_unlock(&swap_lock); } 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: png_read_finish_row(png_structp png_ptr) { #ifdef PNG_READ_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif /* PNG_READ_INTERLACING_SUPPORTED */ png_debug(1, "in png_read_finish_row"); png_ptr->row_number++; if (png_ptr->row_number < png_ptr->num_rows) return; #ifdef PNG_READ_INTERLACING_SUPPORTED if (png_ptr->interlaced) { png_ptr->row_number = 0; png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1); do { png_ptr->pass++; if (png_ptr->pass >= 7) break; png_ptr->iwidth = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; if (!(png_ptr->transformations & PNG_INTERLACE)) { png_ptr->num_rows = (png_ptr->height + png_pass_yinc[png_ptr->pass] - 1 - png_pass_ystart[png_ptr->pass]) / png_pass_yinc[png_ptr->pass]; if (!(png_ptr->num_rows)) continue; } else /* if (png_ptr->transformations & PNG_INTERLACE) */ break; } while (png_ptr->iwidth == 0); if (png_ptr->pass < 7) return; } #endif /* PNG_READ_INTERLACING_SUPPORTED */ if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED)) { #ifdef PNG_USE_LOCAL_ARRAYS PNG_CONST PNG_IDAT; #endif char extra; int ret; png_ptr->zstream.next_out = (Byte *)&extra; png_ptr->zstream.avail_out = (uInt)1; for (;;) { if (!(png_ptr->zstream.avail_in)) { while (!png_ptr->idat_size) { png_byte chunk_length[4]; png_crc_finish(png_ptr, 0); png_read_data(png_ptr, chunk_length, 4); png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length); png_reset_crc(png_ptr); png_crc_read(png_ptr, png_ptr->chunk_name, 4); if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) png_error(png_ptr, "Not enough image data"); } png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size; png_ptr->zstream.next_in = png_ptr->zbuf; if (png_ptr->zbuf_size > png_ptr->idat_size) png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size; png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in); png_ptr->idat_size -= png_ptr->zstream.avail_in; } ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH); if (ret == Z_STREAM_END) { if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in || png_ptr->idat_size) png_warning(png_ptr, "Extra compressed data."); png_ptr->mode |= PNG_AFTER_IDAT; png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; break; } if (ret != Z_OK) png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg : "Decompression Error"); if (!(png_ptr->zstream.avail_out)) { png_warning(png_ptr, "Extra compressed data."); png_ptr->mode |= PNG_AFTER_IDAT; png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED; break; } } png_ptr->zstream.avail_out = 0; } if (png_ptr->idat_size || png_ptr->zstream.avail_in) png_warning(png_ptr, "Extra compression data."); inflateReset(&png_ptr->zstream); png_ptr->mode |= PNG_AFTER_IDAT; } CWE ID: CWE-119 Target: 1 Example 2: Code: XineramaPointInWindowIsVisible(WindowPtr pWin, int x, int y) { BoxRec box; int i, xoff, yoff; if (!pWin->realized) return FALSE; if (RegionContainsPoint(&pWin->borderClip, x, y, &box)) return TRUE; if (!XineramaSetWindowPntrs(inputInfo.pointer, pWin)) return FALSE; xoff = x + screenInfo.screens[0]->x; yoff = y + screenInfo.screens[0]->y; FOR_NSCREENS_FORWARD_SKIP(i) { pWin = inputInfo.pointer->spriteInfo->sprite->windows[i]; x = xoff - screenInfo.screens[i]->x; y = yoff - screenInfo.screens[i]->y; if (RegionContainsPoint(&pWin->borderClip, x, y, &box) && (!wInputShape(pWin) || RegionContainsPoint(wInputShape(pWin), x - pWin->drawable.x, y - pWin->drawable.y, &box))) return TRUE; } return FALSE; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GKI_delay(UINT32 timeout_ms) { struct timespec delay; delay.tv_sec = timeout_ms / 1000; delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000); int err; do { err = nanosleep(&delay, &delay); } while (err == -1 && errno == EINTR); } CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> supplementalMethod2Callback(const v8::Arguments& args) { INC_STATS("DOM.TestInterface.supplementalMethod2"); if (args.Length() < 2) return V8Proxy::throwNotEnoughArgumentsError(); TestInterface* imp = V8TestInterface::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0); ScriptExecutionContext* scriptContext = getScriptExecutionContext(); if (!scriptContext) return v8::Undefined(); RefPtr<TestObj> result = TestSupplemental::supplementalMethod2(imp, scriptContext, strArg, objArg, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release(), args.GetIsolate()); } fail: V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: HTMLFormControlElement::HTMLFormControlElement(const QualifiedName& tag_name, Document& document) : HTMLElement(tag_name, document), autofill_state_(WebAutofillState::kNotFilled), blocks_form_submission_(false) { SetHasCustomStyleCallbacks(); static unsigned next_free_unique_id = 0; unique_renderer_form_control_id_ = next_free_unique_id++; } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: TextTrack* TextTrackCue::track() const { return track_; } 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 mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( f_rng != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_sign_restartable( grp, r, s, d, buf, blen, f_rng, p_rng, NULL ) ); } CWE ID: CWE-200 Target: 1 Example 2: Code: bool AudioFlinger::EffectModule::isOffloaded() const { Mutex::Autolock _l(mLock); return mOffloaded; } 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: hcom_client_init ( OUT p_hsm_com_client_hdl_t *p_hdl, IN char *server_path, IN char *client_path, IN int max_data_len ) { hsm_com_client_hdl_t *hdl = NULL; hsm_com_errno_t res = HSM_COM_OK; if((strlen(server_path) > (HSM_COM_SVR_MAX_PATH - 1)) || (strlen(server_path) == 0)){ res = HSM_COM_PATH_ERR; goto cleanup; } if((strlen(client_path) > (HSM_COM_SVR_MAX_PATH - 1)) || (strlen(client_path) == 0)){ res = HSM_COM_PATH_ERR; goto cleanup; } if((hdl = calloc(1,sizeof(hsm_com_client_hdl_t))) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->scr.scratch = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->recv_buf = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } if((hdl->send_buf = malloc(max_data_len)) == NULL) { res = HSM_COM_NO_MEM; goto cleanup; } hdl->scr.scratch_fill = 0; hdl->scr.scratch_len = max_data_len; hdl->buf_len = max_data_len; hdl->trans_id = 1; strcpy(hdl->s_path,server_path); strcpy(hdl->c_path,client_path); hdl->client_state = HSM_COM_C_STATE_IN; *p_hdl = hdl; return res; cleanup: if(hdl) { if (hdl->scr.scratch) { free(hdl->scr.scratch); } if (hdl->recv_buf) { free(hdl->recv_buf); } free(hdl); } return res; } 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: v8::Handle<v8::Value> V8WebSocket::sendCallback(const v8::Arguments& args) { INC_STATS("DOM.WebSocket.send()"); if (!args.Length()) return V8Proxy::throwNotEnoughArgumentsError(); WebSocket* webSocket = V8WebSocket::toNative(args.Holder()); v8::Handle<v8::Value> message = args[0]; ExceptionCode ec = 0; bool result; if (V8ArrayBuffer::HasInstance(message)) { ArrayBuffer* arrayBuffer = V8ArrayBuffer::toNative(v8::Handle<v8::Object>::Cast(message)); ASSERT(arrayBuffer); result = webSocket->send(arrayBuffer, ec); } else if (V8Blob::HasInstance(message)) { Blob* blob = V8Blob::toNative(v8::Handle<v8::Object>::Cast(message)); ASSERT(blob); result = webSocket->send(blob, ec); } else { v8::TryCatch tryCatch; v8::Handle<v8::String> stringMessage = message->ToString(); if (tryCatch.HasCaught()) return throwError(tryCatch.Exception(), args.GetIsolate()); result = webSocket->send(toWebCoreString(stringMessage), ec); } if (ec) return throwError(ec, args.GetIsolate()); return v8Boolean(result); } CWE ID: Target: 1 Example 2: Code: static uint32_t GetEntryForIndexImpl(Isolate* isolate, JSObject* holder, FixedArrayBase* backing_store, uint32_t index, PropertyFilter filter) { uint32_t length = Subclass::GetMaxIndex(holder, backing_store); if (IsHoleyElementsKind(kind())) { return index < length && !BackingStore::cast(backing_store) ->is_the_hole(isolate, index) ? index : kMaxUInt32; } else { return index < length ? index : kMaxUInt32; } } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: v8::Handle<v8::Value> V8WebGLRenderingContext::getParameterCallback(const v8::Arguments& args) { INC_STATS("DOM.WebGLRenderingContext.getParameter()"); if (args.Length() != 1) return V8Proxy::throwNotEnoughArgumentsError(); ExceptionCode ec = 0; WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); unsigned pname = toInt32(args[0]); WebGLGetInfo info = context->getParameter(pname, ec); if (ec) { V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } return toV8Object(info, args.GetIsolate()); } 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 RunMemCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 5000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) { input_block[j] = rnd.Rand8() - rnd.Rand8(); input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255; } if (i == 0) for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = 255; if (i == 1) for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = -255; fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { EXPECT_EQ(output_block[j], output_ref_block[j]); EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j])) << "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE"; } } } CWE ID: CWE-119 Target: 1 Example 2: Code: void PermissionsData::ClearTabSpecificPermissions(int tab_id) const { base::AutoLock auto_lock(runtime_lock_); CHECK_GE(tab_id, 0); tab_specific_permissions_.erase(tab_id); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void rt_free(struct rtable *rt) { call_rcu(&rt->dst.rcu_head, dst_rcu_free); } CWE ID: CWE-17 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Factory(mojo::ScopedSharedBufferMapping mapping, std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm, const PlatformSensorProviderBase::CreateSensorCallback& callback, PlatformSensorProvider* provider) : fusion_algorithm_(std::move(fusion_algorithm)), result_callback_(std::move(callback)), mapping_(std::move(mapping)), provider_(provider) { const auto& types = fusion_algorithm_->source_types(); DCHECK(!types.empty()); DCHECK(std::adjacent_find(types.begin(), types.end()) == types.end()); DCHECK(result_callback_); DCHECK(mapping_); DCHECK(provider_); } CWE ID: CWE-732 Target: 1 Example 2: Code: dmxProcRenderFreeGlyphSet(ClientPtr client) { GlyphSetPtr glyphSet; REQUEST(xRenderFreeGlyphSetReq); REQUEST_SIZE_MATCH(xRenderFreeGlyphSetReq); dixLookupResourceByType((void **) &glyphSet, stuff->glyphset, GlyphSetType, client, DixDestroyAccess); if (glyphSet && glyphSet->refcnt == 1) { dmxGlyphPrivPtr glyphPriv = DMX_GET_GLYPH_PRIV(glyphSet); int i; for (i = 0; i < dmxNumScreens; i++) { DMXScreenInfo *dmxScreen = &dmxScreens[i]; if (dmxScreen->beDisplay) { if (dmxBEFreeGlyphSet(screenInfo.screens[i], glyphSet)) dmxSync(dmxScreen, FALSE); } } MAXSCREENSFREE(glyphPriv->glyphSets); free(glyphPriv); DMX_SET_GLYPH_PRIV(glyphSet, NULL); } return dmxSaveRenderVector[stuff->renderReqType] (client); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t 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; } if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*image->columns*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*image->columns*quantum_info->depth+7)/8)); } CWE ID: CWE-369 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ih264d_init_decoder(void * ps_dec_params) { dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params; dec_slice_params_t *ps_cur_slice; pocstruct_t *ps_prev_poc, *ps_cur_poc; /* Free any dynamic buffers that are allocated */ ih264d_free_dynamic_bufs(ps_dec); ps_cur_slice = ps_dec->ps_cur_slice; ps_dec->init_done = 0; ps_dec->u4_num_cores = 1; ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0; ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE; ps_dec->u4_app_disable_deblk_frm = 0; ps_dec->i4_degrade_type = 0; ps_dec->i4_degrade_pics = 0; ps_dec->i4_app_skip_mode = IVD_SKIP_NONE; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; memset(ps_dec->ps_pps, 0, ((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS)); memset(ps_dec->ps_sps, 0, ((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS)); /* Initialization of function pointers ih264d_deblock_picture function*/ ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff; ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff; ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec; ps_dec->u4_num_fld_in_frm = 0; ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec; /* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/ ps_dec->ps_sei->u1_is_valid = 0; /* decParams Initializations */ ps_dec->ps_cur_pps = NULL; ps_dec->ps_cur_sps = NULL; ps_dec->u1_init_dec_flag = 0; ps_dec->u1_first_slice_in_stream = 1; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_last_pic_not_decoded = 0; ps_dec->u4_app_disp_width = 0; ps_dec->i4_header_decoded = 0; ps_dec->u4_total_frames_decoded = 0; ps_dec->i4_error_code = 0; ps_dec->i4_content_type = -1; ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0; ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS; ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN; ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT; ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME; ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN; ps_dec->u1_pr_sl_type = 0xFF; ps_dec->u2_mbx = 0xffff; ps_dec->u2_mby = 0; ps_dec->u2_total_mbs_coded = 0; /* POC initializations */ ps_prev_poc = &ps_dec->s_prev_pic_poc; ps_cur_poc = &ps_dec->s_cur_pic_poc; ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0] = 0; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1] = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count = 0; ps_prev_poc->i4_bottom_field_order_count = ps_cur_poc->i4_bottom_field_order_count = 0; ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0; ps_cur_slice->u1_mmco_equalto5 = 0; ps_cur_slice->u2_frame_num = 0; ps_dec->i4_max_poc = 0; ps_dec->i4_prev_max_display_seq = 0; ps_dec->u1_recon_mb_grp = 4; /* Field PIC initializations */ ps_dec->u1_second_field = 0; ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; /* Set the cropping parameters as zero */ ps_dec->u2_crop_offset_y = 0; ps_dec->u2_crop_offset_uv = 0; /* The Initial Frame Rate Info is not Present */ ps_dec->i4_vui_frame_rate = -1; ps_dec->i4_pic_type = -1; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u1_res_changed = 0; ps_dec->u1_frame_decoded_flag = 0; /* Set the default frame seek mask mode */ ps_dec->u4_skip_frm_mask = SKIP_NONE; /********************************************************/ /* Initialize CAVLC residual decoding function pointers */ /********************************************************/ ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1; ps_dec->pf_cavlc_4x4res_block[1] = ih264d_cavlc_4x4res_block_totalcoeff_2to10; ps_dec->pf_cavlc_4x4res_block[2] = ih264d_cavlc_4x4res_block_totalcoeff_11to16; ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7; ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8; ps_dec->pf_cavlc_parse_8x8block[0] = ih264d_cavlc_parse_8x8block_none_available; ps_dec->pf_cavlc_parse_8x8block[1] = ih264d_cavlc_parse_8x8block_left_available; ps_dec->pf_cavlc_parse_8x8block[2] = ih264d_cavlc_parse_8x8block_top_available; ps_dec->pf_cavlc_parse_8x8block[3] = ih264d_cavlc_parse_8x8block_both_available; /***************************************************************************/ /* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */ /***************************************************************************/ ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice; ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice; ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice; ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice; ps_dec->pf_fill_bs_xtra_left_edge[0] = ih264d_fill_bs_xtra_left_edge_cur_frm; ps_dec->pf_fill_bs_xtra_left_edge[1] = ih264d_fill_bs_xtra_left_edge_cur_fld; /* Initialize Reference Pic Buffers */ ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr); ps_dec->u2_prv_frame_num = 0; ps_dec->u1_top_bottom_decoded = 0; ps_dec->u1_dangling_field = 0; ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table; ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0]; ps_dec->pi1_left_ref_idx_ctxt_inc = &ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0]; ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb; /* ! */ /* Initializing flush frame u4_flag */ ps_dec->u1_flushfrm = 0; { ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec; ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec; ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec; ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec; } memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t)); memset(ps_dec->u4_disp_buf_mapping, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); memset(ps_dec->u4_disp_buf_to_be_freed, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); ih264d_init_arch(ps_dec); ih264d_init_function_ptr(ps_dec); ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT; ps_dec->init_done = 1; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int crypto_init_blkcipher_ops_async(struct crypto_tfm *tfm) { struct ablkcipher_tfm *crt = &tfm->crt_ablkcipher; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; crt->setkey = async_setkey; crt->encrypt = async_encrypt; crt->decrypt = async_decrypt; if (!alg->ivsize) { crt->givencrypt = skcipher_null_givencrypt; crt->givdecrypt = skcipher_null_givdecrypt; } crt->base = __crypto_ablkcipher_cast(tfm); crt->ivsize = alg->ivsize; return 0; } CWE ID: CWE-310 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static size_t calculate_slab_order(struct kmem_cache *cachep, size_t size, unsigned long flags) { size_t left_over = 0; int gfporder; for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) { unsigned int num; size_t remainder; num = cache_estimate(gfporder, size, flags, &remainder); if (!num) continue; /* Can't handle number of objects more than SLAB_OBJ_MAX_NUM */ if (num > SLAB_OBJ_MAX_NUM) break; if (flags & CFLGS_OFF_SLAB) { struct kmem_cache *freelist_cache; size_t freelist_size; freelist_size = num * sizeof(freelist_idx_t); freelist_cache = kmalloc_slab(freelist_size, 0u); if (!freelist_cache) continue; /* * Needed to avoid possible looping condition * in cache_grow_begin() */ if (OFF_SLAB(freelist_cache)) continue; /* check if off slab has enough benefit */ if (freelist_cache->size > cachep->size / 2) continue; } /* Found something acceptable - save it away */ cachep->num = num; cachep->gfporder = gfporder; left_over = remainder; /* * A VFS-reclaimable slab tends to have most allocations * as GFP_NOFS and we really don't want to have to be allocating * higher-order pages when we are unable to shrink dcache. */ if (flags & SLAB_RECLAIM_ACCOUNT) break; /* * Large number of objects is good, but very large slabs are * currently bad for the gfp()s. */ if (gfporder >= slab_max_order) break; /* * Acceptable internal fragmentation? */ if (left_over * 8 <= (PAGE_SIZE << gfporder)) break; } return left_over; } 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: v8::Local<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* methodName, v8::Local<v8::Value> holder, int argc, v8::Local<v8::Value> argv[]) { v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> method; if (!classObject->Get(scriptState->context(), v8String(scriptState->isolate(), methodName)).ToLocal(&method) || !method->IsFunction()) { fprintf(stderr, "Private script error: Target DOM method was not found. (Class name = %s, Method name = %s)\n", className, methodName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(scriptState->isolate()); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(method), scriptState->getExecutionContext(), holder, argc, argv, scriptState->isolate()).ToLocal(&result)) { rethrowExceptionInPrivateScript(scriptState->isolate(), block, scriptStateInUserScript, ExceptionState::ExecutionContext, methodName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; } CWE ID: CWE-79 Target: 1 Example 2: Code: static int __dev_queue_xmit(struct sk_buff *skb, void *accel_priv) { struct net_device *dev = skb->dev; struct netdev_queue *txq; struct Qdisc *q; int rc = -ENOMEM; skb_reset_mac_header(skb); if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP)) __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED); /* Disable soft irqs for various locks below. Also * stops preemption for RCU. */ rcu_read_lock_bh(); skb_update_prio(skb); qdisc_pkt_len_init(skb); #ifdef CONFIG_NET_CLS_ACT skb->tc_at_ingress = 0; # ifdef CONFIG_NET_EGRESS if (static_key_false(&egress_needed)) { skb = sch_handle_egress(skb, &rc, dev); if (!skb) goto out; } # endif #endif /* If device/qdisc don't need skb->dst, release it right now while * its hot in this cpu cache. */ if (dev->priv_flags & IFF_XMIT_DST_RELEASE) skb_dst_drop(skb); else skb_dst_force(skb); txq = netdev_pick_tx(dev, skb, accel_priv); q = rcu_dereference_bh(txq->qdisc); trace_net_dev_queue(skb); if (q->enqueue) { rc = __dev_xmit_skb(skb, q, dev, txq); goto out; } /* The device has no queue. Common case for software devices: * loopback, all the sorts of tunnels... * Really, it is unlikely that netif_tx_lock protection is necessary * here. (f.e. loopback and IP tunnels are clean ignoring statistics * counters.) * However, it is possible, that they rely on protection * made by us here. * Check this and shot the lock. It is not prone from deadlocks. *Either shot noqueue qdisc, it is even simpler 8) */ if (dev->flags & IFF_UP) { int cpu = smp_processor_id(); /* ok because BHs are off */ if (txq->xmit_lock_owner != cpu) { if (unlikely(__this_cpu_read(xmit_recursion) > XMIT_RECURSION_LIMIT)) goto recursion_alert; skb = validate_xmit_skb(skb, dev); if (!skb) goto out; HARD_TX_LOCK(dev, txq, cpu); if (!netif_xmit_stopped(txq)) { __this_cpu_inc(xmit_recursion); skb = dev_hard_start_xmit(skb, dev, txq, &rc); __this_cpu_dec(xmit_recursion); if (dev_xmit_complete(rc)) { HARD_TX_UNLOCK(dev, txq); goto out; } } HARD_TX_UNLOCK(dev, txq); net_crit_ratelimited("Virtual device %s asks to queue packet!\n", dev->name); } else { /* Recursion is detected! It is possible, * unfortunately */ recursion_alert: net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n", dev->name); } } rc = -ENETDOWN; rcu_read_unlock_bh(); atomic_long_inc(&dev->tx_dropped); kfree_skb_list(skb); return rc; out: rcu_read_unlock_bh(); return rc; } 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: gp_bgra8(Pixel *p, png_const_voidp pb) { png_const_bytep pp = voidcast(png_const_bytep, pb); p->r = pp[2]; p->g = pp[1]; p->b = pp[0]; p->a = pp[3]; } 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: logger_get_mask_expanded (struct t_gui_buffer *buffer, const char *mask) { char *mask2, *mask_decoded, *mask_decoded2, *mask_decoded3, *mask_decoded4; char *mask_decoded5; const char *dir_separator; int length; time_t seconds; struct tm *date_tmp; mask2 = NULL; mask_decoded = NULL; mask_decoded2 = NULL; mask_decoded3 = NULL; mask_decoded4 = NULL; mask_decoded5 = NULL; dir_separator = weechat_info_get ("dir_separator", ""); if (!dir_separator) return NULL; /* * we first replace directory separator (commonly '/') by \01 because * buffer mask can contain this char, and will be replaced by replacement * char ('_' by default) */ mask2 = weechat_string_replace (mask, dir_separator, "\01"); if (!mask2) goto end; mask_decoded = weechat_buffer_string_replace_local_var (buffer, mask2); if (!mask_decoded) goto end; mask_decoded2 = weechat_string_replace (mask_decoded, dir_separator, weechat_config_string (logger_config_file_replacement_char)); if (!mask_decoded2) goto end; #ifdef __CYGWIN__ mask_decoded3 = weechat_string_replace (mask_decoded2, "\\", weechat_config_string (logger_config_file_replacement_char)); #else mask_decoded3 = strdup (mask_decoded2); #endif /* __CYGWIN__ */ if (!mask_decoded3) goto end; /* restore directory separator */ mask_decoded4 = weechat_string_replace (mask_decoded3, "\01", dir_separator); if (!mask_decoded4) goto end; /* replace date/time specifiers in mask */ length = strlen (mask_decoded4) + 256 + 1; mask_decoded5 = malloc (length); if (!mask_decoded5) goto end; seconds = time (NULL); date_tmp = localtime (&seconds); mask_decoded5[0] = '\0'; strftime (mask_decoded5, length - 1, mask_decoded4, date_tmp); /* convert to lower case? */ if (weechat_config_boolean (logger_config_file_name_lower_case)) weechat_string_tolower (mask_decoded5); if (weechat_logger_plugin->debug) { weechat_printf_date_tags (NULL, 0, "no_log", "%s: buffer = \"%s\", mask = \"%s\", " "decoded mask = \"%s\"", LOGGER_PLUGIN_NAME, weechat_buffer_get_string (buffer, "name"), mask, mask_decoded5); } end: if (mask2) free (mask2); if (mask_decoded) free (mask_decoded); if (mask_decoded2) free (mask_decoded2); if (mask_decoded3) free (mask_decoded3); if (mask_decoded4) free (mask_decoded4); return mask_decoded5; } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params& params) { MaybeHandleDebugURL(params.url); if (!render_view_->webview()) return; render_view_->OnNavigate(params); bool is_reload = RenderViewImpl::IsReload(params); WebURLRequest::CachePolicy cache_policy = WebURLRequest::UseProtocolCachePolicy; if (render_view_->IsBackForwardToStaleEntry(params, is_reload)) return; if (render_view_->is_swapped_out_) { render_view_->webview()->setVisibilityState( render_view_->visibilityState(), false); is_reload = false; cache_policy = WebURLRequest::ReloadIgnoringCacheData; RenderThreadImpl::NotifyTimezoneChange(); render_view_->SetSwappedOut(false); is_swapped_out_ = false; } if (params.should_clear_history_list) { CHECK_EQ(params.pending_history_list_offset, -1); CHECK_EQ(params.current_history_list_offset, -1); CHECK_EQ(params.current_history_list_length, 0); } render_view_->history_list_offset_ = params.current_history_list_offset; render_view_->history_list_length_ = params.current_history_list_length; if (render_view_->history_list_length_ >= 0) { render_view_->history_page_ids_.resize( render_view_->history_list_length_, -1); } if (params.pending_history_list_offset >= 0 && params.pending_history_list_offset < render_view_->history_list_length_) { render_view_->history_page_ids_[params.pending_history_list_offset] = params.page_id; } GetContentClient()->SetActiveURL(params.url); WebFrame* frame = frame_; if (!params.frame_to_navigate.empty()) { frame = render_view_->webview()->findFrameByName( WebString::fromUTF8(params.frame_to_navigate)); CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate; } if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) { is_reload = false; cache_policy = WebURLRequest::ReloadIgnoringCacheData; } render_view_->pending_navigation_params_.reset( new FrameMsg_Navigate_Params(params)); if (is_reload) { bool reload_original_url = (params.navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL); bool ignore_cache = (params.navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE); if (reload_original_url) frame->reloadWithOverrideURL(params.url, true); else frame->reload(ignore_cache); } else if (params.page_state.IsValid()) { DCHECK_NE(params.page_id, -1); scoped_ptr<HistoryEntry> entry = PageStateToHistoryEntry(params.page_state); if (entry) { CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL)); render_view_->history_controller()->GoToEntry(entry.Pass(), cache_policy); } } else if (!params.base_url_for_data_url.is_empty()) { std::string mime_type, charset, data; if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) { frame->loadData( WebData(data.c_str(), data.length()), WebString::fromUTF8(mime_type), WebString::fromUTF8(charset), params.base_url_for_data_url, params.history_url_for_data_url, false); } else { CHECK(false) << "Invalid URL passed: " << params.url.possibly_invalid_spec(); } } else { WebURLRequest request(params.url); CHECK_EQ(params.page_id, -1); if (frame->isViewSourceModeEnabled()) request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad); if (params.referrer.url.is_valid()) { WebString referrer = WebSecurityPolicy::generateReferrerHeader( params.referrer.policy, params.url, WebString::fromUTF8(params.referrer.url.spec())); if (!referrer.isEmpty()) request.setHTTPReferrer(referrer, params.referrer.policy); } if (!params.extra_headers.empty()) { for (net::HttpUtil::HeadersIterator i(params.extra_headers.begin(), params.extra_headers.end(), "\n"); i.GetNext(); ) { request.addHTTPHeaderField(WebString::fromUTF8(i.name()), WebString::fromUTF8(i.values())); } } if (params.is_post) { request.setHTTPMethod(WebString::fromUTF8("POST")); WebHTTPBody http_body; http_body.initialize(); const char* data = NULL; if (params.browser_initiated_post_data.size()) { data = reinterpret_cast<const char*>( &params.browser_initiated_post_data.front()); } http_body.appendData( WebData(data, params.browser_initiated_post_data.size())); request.setHTTPBody(http_body); } frame->loadRequest(request); if (!params.browser_navigation_start.is_null() && frame->provisionalDataSource()) { base::TimeTicks navigation_start = std::min( base::TimeTicks::Now(), params.browser_navigation_start); double navigation_start_seconds = (navigation_start - base::TimeTicks()).InSecondsF(); frame->provisionalDataSource()->setNavigationStartTime( navigation_start_seconds); } } render_view_->pending_navigation_params_.reset(); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const { return x >= frameLeft && x <= frameRight && y >= frameTop && y <= frameBottom; } 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 inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn, struct nlattr *rp) { struct xfrm_replay_state_esn *up; if (!replay_esn || !rp) return 0; up = nla_data(rp); if (xfrm_replay_state_esn_len(replay_esn) != xfrm_replay_state_esn_len(up)) return -EINVAL; return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: void smp_send_pair_rsp(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { SMP_TRACE_DEBUG("%s", __func__); p_cb->local_i_key &= p_cb->peer_i_key; p_cb->local_r_key &= p_cb->peer_r_key; if (smp_send_cmd(SMP_OPCODE_PAIRING_RSP, p_cb)) { if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) smp_use_oob_private_key(p_cb, NULL); else smp_decide_association_model(p_cb, NULL); } } 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 RenderWidgetHostViewGuest::UpdateFrameInfo( const gfx::Vector2d& scroll_offset, float page_scale_factor, float min_page_scale_factor, float max_page_scale_factor, const gfx::Size& content_size) { NOTIMPLEMENTED(); } 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: dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags); if (offset == 0) break; } } return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: static unsigned int calculate_ticks_for_ns(const unsigned int ref_clk_hz, const unsigned int ns_val) { unsigned int ticks; ticks = ref_clk_hz / 1000; /* kHz */ ticks = DIV_ROUND_UP(ticks * ns_val, 1000000); return ticks; } 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 __always_inline int __linearize(struct x86_emulate_ctxt *ctxt, struct segmented_address addr, unsigned *max_size, unsigned size, bool write, bool fetch, enum x86emul_mode mode, ulong *linear) { struct desc_struct desc; bool usable; ulong la; u32 lim; u16 sel; la = seg_base(ctxt, addr.seg) + addr.ea; *max_size = 0; switch (mode) { case X86EMUL_MODE_PROT64: if (is_noncanonical_address(la)) goto bad; *max_size = min_t(u64, ~0u, (1ull << 48) - la); if (size > *max_size) goto bad; break; default: usable = ctxt->ops->get_segment(ctxt, &sel, &desc, NULL, addr.seg); if (!usable) goto bad; /* code segment in protected mode or read-only data segment */ if ((((ctxt->mode != X86EMUL_MODE_REAL) && (desc.type & 8)) || !(desc.type & 2)) && write) goto bad; /* unreadable code segment */ if (!fetch && (desc.type & 8) && !(desc.type & 2)) goto bad; lim = desc_limit_scaled(&desc); if (!(desc.type & 8) && (desc.type & 4)) { /* expand-down segment */ if (addr.ea <= lim) goto bad; lim = desc.d ? 0xffffffff : 0xffff; } if (addr.ea > lim) goto bad; *max_size = min_t(u64, ~0u, (u64)lim + 1 - addr.ea); if (size > *max_size) goto bad; la &= (u32)-1; break; } if (insn_aligned(ctxt, size) && ((la & (size - 1)) != 0)) return emulate_gp(ctxt, 0); *linear = la; return X86EMUL_CONTINUE; bad: if (addr.seg == VCPU_SREG_SS) return emulate_ss(ctxt, 0); else return emulate_gp(ctxt, 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: void LauncherView::OnBoundsChanged(const gfx::Rect& previous_bounds) { LayoutToIdealBounds(); FOR_EACH_OBSERVER(LauncherIconObserver, observers_, OnLauncherIconPositionsChanged()); } CWE ID: CWE-119 Target: 1 Example 2: Code: virtual bool OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(SnifferObserver, message) IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingError, OnError) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } 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: HeadlessPrintManager::GetPrintParamsFromSettings( const HeadlessPrintSettings& settings) { printing::PrintSettings print_settings; print_settings.set_dpi(printing::kPointsPerInch); print_settings.set_should_print_backgrounds( settings.should_print_backgrounds); print_settings.set_scale_factor(settings.scale); print_settings.SetOrientation(settings.landscape); print_settings.set_display_header_footer(settings.display_header_footer); if (print_settings.display_header_footer()) { url::Replacements<char> url_sanitizer; url_sanitizer.ClearUsername(); url_sanitizer.ClearPassword(); std::string url = printing_rfh_->GetLastCommittedURL() .ReplaceComponents(url_sanitizer) .spec(); print_settings.set_url(base::UTF8ToUTF16(url)); } print_settings.set_margin_type(printing::CUSTOM_MARGINS); print_settings.SetCustomMargins(settings.margins_in_points); gfx::Rect printable_area_device_units(settings.paper_size_in_points); print_settings.SetPrinterPrintableArea(settings.paper_size_in_points, printable_area_device_units, true); auto print_params = std::make_unique<PrintMsg_PrintPages_Params>(); printing::RenderParamsFromPrintSettings(print_settings, &print_params->params); print_params->params.document_cookie = printing::PrintSettings::NewCookie(); return print_params; } 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: test_size(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, int bdlo, int PNG_CONST bdhi) { /* Run the tests on each combination. * * NOTE: on my 32 bit x86 each of the following blocks takes * a total of 3.5 seconds if done across every combo of bit depth * width and height. This is a waste of time in practice, hence the * hinc and winc stuff: */ static PNG_CONST png_byte hinc[] = {1, 3, 11, 1, 5}; static PNG_CONST png_byte winc[] = {1, 9, 5, 7, 1}; for (; bdlo <= bdhi; ++bdlo) { png_uint_32 h, w; for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo]) { /* First test all the 'size' images against the sequential * reader using libpng to deinterlace (where required.) This * validates the write side of libpng. There are four possibilities * to validate. */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # ifdef PNG_WRITE_INTERLACING_SUPPORTED standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # endif /* Now validate the interlaced read side - do_interlace true, * in the progressive case this does actually make a difference * to the code used in the non-interlaced case too. */ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # ifdef PNG_WRITE_INTERLACING_SUPPORTED standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; # endif } } return 1; /* keep going */ } CWE ID: Target: 1 Example 2: Code: static zend_always_inline int zend_mm_bitset_is_set(zend_mm_bitset *bitset, int bit) { return (bitset[bit / ZEND_MM_BITSET_LEN] & (Z_L(1) << (bit & (ZEND_MM_BITSET_LEN-1)))) != 0; } 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 CL_CheckAutoUpdate( void ) { int validServerNum = 0; int i = 0, rnd = 0; netadr_t temp; char *servername; if ( !cl_autoupdate->integer ) { return; } if ( autoupdateChecked ) { return; } srand( Com_Milliseconds() ); for ( i = 0; i < MAX_AUTOUPDATE_SERVERS; i++ ) { if ( NET_StringToAdr( cls.autoupdateServerNames[i], &temp, NA_UNSPEC ) ) { validServerNum++; } } if ( validServerNum > 1 ) { rnd = rand() % validServerNum; } else { rnd = 0; } servername = cls.autoupdateServerNames[rnd]; Com_DPrintf( "Resolving AutoUpdate Server... " ); if ( !NET_StringToAdr( servername, &cls.autoupdateServer, NA_UNSPEC ) ) { Com_DPrintf( "Couldn't resolve first address, trying default..." ); if ( !NET_StringToAdr( cls.autoupdateServerNames[0], &cls.autoupdateServer, NA_UNSPEC ) ) { Com_DPrintf( "Failed to resolve any Auto-update servers.\n" ); autoupdateChecked = qtrue; return; } } cls.autoupdateServer.port = BigShort( PORT_SERVER ); Com_DPrintf( "%i.%i.%i.%i:%i\n", cls.autoupdateServer.ip[0], cls.autoupdateServer.ip[1], cls.autoupdateServer.ip[2], cls.autoupdateServer.ip[3], BigShort( cls.autoupdateServer.port ) ); NET_OutOfBandPrint( NS_CLIENT, cls.autoupdateServer, "getUpdateInfo \"%s\" \"%s\"-\"%s\"\n", Q3_VERSION, OS_STRING, ARCH_STRING ); CL_RequestMotd(); autoupdateChecked = qtrue; } CWE ID: CWE-269 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EncodedJSValue JSC_HOST_CALL jsTestActiveDOMObjectPrototypeFunctionPostMessage(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestActiveDOMObject::s_info)) return throwVMTypeError(exec); JSTestActiveDOMObject* castedThis = jsCast<JSTestActiveDOMObject*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestActiveDOMObject::s_info); TestActiveDOMObject* impl = static_cast<TestActiveDOMObject*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); const String& message(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->postMessage(message); return JSValue::encode(jsUndefined()); } CWE ID: CWE-20 Target: 1 Example 2: Code: bashline_set_event_hook () { rl_signal_event_hook = bash_event_hook; } 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 RenderLayerCompositor::frameViewDidScroll() { FrameView* frameView = m_renderView->frameView(); IntPoint scrollPosition = frameView->scrollPosition(); if (!m_scrollLayer) return; bool scrollingCoordinatorHandlesOffset = false; if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) { if (Settings* settings = m_renderView->document().settings()) { if (isMainFrame() || settings->compositedScrollingForFramesEnabled()) scrollingCoordinatorHandlesOffset = scrollingCoordinator->scrollableAreaScrollLayerDidChange(frameView); } } if (scrollingCoordinatorHandlesOffset) m_scrollLayer->setPosition(-frameView->minimumScrollPosition()); else m_scrollLayer->setPosition(-scrollPosition); blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground", ScrolledMainFrameBucket, AcceleratedFixedRootBackgroundHistogramMax); if (!m_renderView->rootBackgroundIsEntirelyFixed()) return; blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground", !!fixedRootBackgroundLayer() ? ScrolledMainFrameWithAcceleratedFixedRootBackground : ScrolledMainFrameWithUnacceleratedFixedRootBackground, AcceleratedFixedRootBackgroundHistogramMax); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LocalFileSystem::deleteFileSystem(ExecutionContext* context, FileSystemType type, PassOwnPtr<AsyncFileSystemCallbacks> callbacks) { RefPtrWillBeRawPtr<ExecutionContext> contextPtr(context); ASSERT(context); ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument()); RefPtr<CallbackWrapper> wrapper = adoptRef(new CallbackWrapper(callbacks)); requestFileSystemAccessInternal(context, bind(&LocalFileSystem::deleteFileSystemInternal, this, contextPtr, type, wrapper), bind(&LocalFileSystem::fileSystemNotAllowedInternal, this, contextPtr, wrapper)); } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root, struct inode *inode, struct btrfs_dio_private *dip, struct bio *bio, u64 file_offset) { struct btrfs_io_bio *io_bio = btrfs_io_bio(bio); struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio); int ret; /* * We load all the csum data we need when we submit * the first bio to reduce the csum tree search and * contention. */ if (dip->logical_offset == file_offset) { ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio, file_offset); if (ret) return ret; } if (bio == dip->orig_bio) return 0; file_offset -= dip->logical_offset; file_offset >>= inode->i_sb->s_blocksize_bits; io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset); return 0; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: write_header( FT_Error error_code ) { FT_Face face; const char* basename; const char* format; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) Fatal( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%s')", basename ); break; default: sprintf( status.header_buffer, "File `%s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = (const char *)status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); format = "at %g points, first glyph index = %d"; snprintf( status.header_buffer, 256, format, status.ptsize/64., status.Num ); if ( FT_HAS_GLYPH_NAMES( face ) ) { char* p; int format_len, gindex, size; size = strlen( status.header_buffer ); p = status.header_buffer + size; size = 256 - size; format = ", name = "; format_len = strlen( format ); if ( size >= format_len + 2 ) { gindex = status.Num; strcpy( p, format ); if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) ) *p = '\0'; } } status.header = (const char *)status.header_buffer; grWriteCellString( display->bitmap, 0, HEADER_HEIGHT, status.header_buffer, display->fore_color ); grRefreshSurface( display->surface ); } 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: GahpServer::Reaper(Service *,int pid,int status) { /* This should be much better.... for now, if our Gahp Server goes away for any reason, we EXCEPT. */ GahpServer *dead_server = NULL; GahpServer *next_server = NULL; GahpServersById.startIterations(); while ( GahpServersById.iterate( next_server ) != 0 ) { if ( pid == next_server->m_gahp_pid ) { dead_server = next_server; break; } } std::string buf; sprintf( buf, "Gahp Server (pid=%d) ", pid ); if( WIFSIGNALED(status) ) { sprintf_cat( buf, "died due to %s", daemonCore->GetExceptionString(status) ); } else { sprintf_cat( buf, "exited with status %d", WEXITSTATUS(status) ); } if ( dead_server ) { sprintf_cat( buf, " unexpectedly" ); EXCEPT( buf.c_str() ); } else { sprintf_cat( buf, "\n" ); dprintf( D_ALWAYS, buf.c_str() ); } } CWE ID: CWE-134 Target: 1 Example 2: Code: void BluetoothOptionsHandler::EnableChangeCallback( const ListValue* args) { bool bluetooth_enabled; args->GetBoolean(0, &bluetooth_enabled); base::FundamentalValue checked(bluetooth_enabled); web_ui_->CallJavascriptFunction( "options.SystemOptions.setBluetoothCheckboxState", checked); } 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 BrowserNonClientFrameViewAura::ResetWindowControls() { maximize_button_->SetState(views::CustomButton::BS_NORMAL); } 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 inline struct keydata *get_keyptr(void) { struct keydata *keyptr = &ip_keydata[ip_cnt & 1]; smp_rmb(); return keyptr; } CWE ID: Target: 1 Example 2: Code: static int _ffs_func_bind(struct usb_configuration *c, struct usb_function *f) { struct ffs_function *func = ffs_func_from_usb(f); struct ffs_data *ffs = func->ffs; const int full = !!func->ffs->fs_descs_count; const int high = gadget_is_dualspeed(func->gadget) && func->ffs->hs_descs_count; const int super = gadget_is_superspeed(func->gadget) && func->ffs->ss_descs_count; int fs_len, hs_len, ss_len, ret, i; /* Make it a single chunk, less management later on */ vla_group(d); vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count); vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs, full ? ffs->fs_descs_count + 1 : 0); vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs, high ? ffs->hs_descs_count + 1 : 0); vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs, super ? ffs->ss_descs_count + 1 : 0); vla_item_with_sz(d, short, inums, ffs->interfaces_count); vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table, c->cdev->use_os_string ? ffs->interfaces_count : 0); vla_item_with_sz(d, char[16], ext_compat, c->cdev->use_os_string ? ffs->interfaces_count : 0); vla_item_with_sz(d, struct usb_os_desc, os_desc, c->cdev->use_os_string ? ffs->interfaces_count : 0); vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop, ffs->ms_os_descs_ext_prop_count); vla_item_with_sz(d, char, ext_prop_name, ffs->ms_os_descs_ext_prop_name_len); vla_item_with_sz(d, char, ext_prop_data, ffs->ms_os_descs_ext_prop_data_len); vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length); char *vlabuf; ENTER(); /* Has descriptors only for speeds gadget does not support */ if (unlikely(!(full | high | super))) return -ENOTSUPP; /* Allocate a single chunk, less management later on */ vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL); if (unlikely(!vlabuf)) return -ENOMEM; ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop); ffs->ms_os_descs_ext_prop_name_avail = vla_ptr(vlabuf, d, ext_prop_name); ffs->ms_os_descs_ext_prop_data_avail = vla_ptr(vlabuf, d, ext_prop_data); /* Copy descriptors */ memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs, ffs->raw_descs_length); memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz); for (ret = ffs->eps_count; ret; --ret) { struct ffs_ep *ptr; ptr = vla_ptr(vlabuf, d, eps); ptr[ret].num = -1; } /* Save pointers * d_eps == vlabuf, func->eps used to kfree vlabuf later */ func->eps = vla_ptr(vlabuf, d, eps); func->interfaces_nums = vla_ptr(vlabuf, d, inums); /* * Go through all the endpoint descriptors and allocate * endpoints first, so that later we can rewrite the endpoint * numbers without worrying that it may be described later on. */ if (likely(full)) { func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs); fs_len = ffs_do_descs(ffs->fs_descs_count, vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz, __ffs_func_bind_do_descs, func); if (unlikely(fs_len < 0)) { ret = fs_len; goto error; } } else { fs_len = 0; } if (likely(high)) { func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs); hs_len = ffs_do_descs(ffs->hs_descs_count, vla_ptr(vlabuf, d, raw_descs) + fs_len, d_raw_descs__sz - fs_len, __ffs_func_bind_do_descs, func); if (unlikely(hs_len < 0)) { ret = hs_len; goto error; } } else { hs_len = 0; } if (likely(super)) { func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs); ss_len = ffs_do_descs(ffs->ss_descs_count, vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len, d_raw_descs__sz - fs_len - hs_len, __ffs_func_bind_do_descs, func); if (unlikely(ss_len < 0)) { ret = ss_len; goto error; } } else { ss_len = 0; } /* * Now handle interface numbers allocation and interface and * endpoint numbers rewriting. We can do that in one go * now. */ ret = ffs_do_descs(ffs->fs_descs_count + (high ? ffs->hs_descs_count : 0) + (super ? ffs->ss_descs_count : 0), vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz, __ffs_func_bind_do_nums, func); if (unlikely(ret < 0)) goto error; func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table); if (c->cdev->use_os_string) for (i = 0; i < ffs->interfaces_count; ++i) { struct usb_os_desc *desc; desc = func->function.os_desc_table[i].os_desc = vla_ptr(vlabuf, d, os_desc) + i * sizeof(struct usb_os_desc); desc->ext_compat_id = vla_ptr(vlabuf, d, ext_compat) + i * 16; INIT_LIST_HEAD(&desc->ext_prop); } ret = ffs_do_os_descs(ffs->ms_os_descs_count, vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len + ss_len, d_raw_descs__sz - fs_len - hs_len - ss_len, __ffs_func_bind_do_os_desc, func); if (unlikely(ret < 0)) goto error; func->function.os_desc_n = c->cdev->use_os_string ? ffs->interfaces_count : 0; /* And we're done */ ffs_event_add(ffs, FUNCTIONFS_BIND); return 0; error: /* XXX Do we need to release all claimed endpoints here? */ return ret; } 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: FileMetricsProviderTest() : create_large_files_(GetParam()), task_runner_(new base::TestSimpleTaskRunner()), thread_task_runner_handle_(task_runner_), statistics_recorder_( base::StatisticsRecorder::CreateTemporaryForTesting()), prefs_(new TestingPrefServiceSimple) { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName); FileMetricsProvider::SetTaskRunnerForTesting(task_runner_); base::GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); } 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: DailyDataSavingUpdate( const char* pref_original, const char* pref_received, PrefService* pref_service) : pref_original_(pref_original), pref_received_(pref_received), original_update_(pref_service, pref_original_), received_update_(pref_service, pref_received_) { } CWE ID: CWE-416 Target: 1 Example 2: Code: ip_vs_zero_stats(struct ip_vs_stats *stats) { spin_lock_bh(&stats->lock); /* get current counters as zero point, rates are zeroed */ #define IP_VS_ZERO_STATS_COUNTER(c) stats->ustats0.c = stats->ustats.c IP_VS_ZERO_STATS_COUNTER(conns); IP_VS_ZERO_STATS_COUNTER(inpkts); IP_VS_ZERO_STATS_COUNTER(outpkts); IP_VS_ZERO_STATS_COUNTER(inbytes); IP_VS_ZERO_STATS_COUNTER(outbytes); ip_vs_zero_estimator(stats); spin_unlock_bh(&stats->lock); } 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 pvc_create(struct net *net, struct socket *sock, int protocol, int kern) { if (net != &init_net) return -EAFNOSUPPORT; sock->ops = &pvc_proto_ops; return vcc_create(net, sock, protocol, PF_ATMPVC); } 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 GLES2DecoderImpl::SimulateAttrib0( GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; const VertexAttribManager::VertexAttribInfo* info = vertex_attrib_manager_->GetVertexAttribInfo(0); bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL; if (info->enabled() && attrib_0_used) { return true; } typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4; GLuint num_vertices = max_vertex_accessed + 1; GLuint size_needed = 0; if (num_vertices == 0 || !SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)), &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0"); return false; } CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_); if (static_cast<GLsizei>(size_needed) > attrib_0_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0"); return false; } attrib_0_buffer_matches_value_ = false; } if (attrib_0_used && (!attrib_0_buffer_matches_value_ || (info->value().v[0] != attrib_0_value_.v[0] || info->value().v[1] != attrib_0_value_.v[1] || info->value().v[2] != attrib_0_value_.v[2] || info->value().v[3] != attrib_0_value_.v[3]))) { std::vector<Vec4> temp(num_vertices, info->value()); glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]); attrib_0_buffer_matches_value_ = true; attrib_0_value_ = info->value(); attrib_0_size_ = size_needed; } glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); if (info->divisor()) glVertexAttribDivisorANGLE(0, 0); *simulated = true; return true; } CWE ID: Target: 1 Example 2: Code: bool MediaPlayerService::Client::shouldDropMetadata(media::Metadata::Type code) const { Mutex::Autolock lock(mLock); if (findMetadata(mMetadataDrop, code)) { return true; } if (mMetadataAllow.isEmpty() || findMetadata(mMetadataAllow, code)) { return false; } else { return true; } } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: __u32 cookie_v6_init_sequence(const struct sk_buff *skb, __u16 *mssp) { const struct ipv6hdr *iph = ipv6_hdr(skb); const struct tcphdr *th = tcp_hdr(skb); return __cookie_v6_init_sequence(iph, th, mssp); } 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: IW_IMPL(int) iw_get_i32le(const iw_byte *b) { return (iw_int32)(iw_uint32)(b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24)); } CWE ID: CWE-682 Target: 1 Example 2: Code: static void pdf_run_Do_image(fz_context *ctx, pdf_processor *proc, const char *name, fz_image *image) { pdf_run_processor *pr = (pdf_run_processor *)proc; pdf_show_image(ctx, pr, image); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PeopleHandler::OnAccountUpdated(const AccountInfo& info) { FireWebUIListener("stored-accounts-updated", *GetStoredAccountsList()); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Warning: invalid .Xauthority file\n"); return 0; } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), 0600); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); return 1; // file copied } return 0; } CWE ID: CWE-269 Target: 1 Example 2: Code: static void blendXor(SplashColorPtr src, SplashColorPtr dest, SplashColorPtr blend, SplashColorMode cm) { int i; for (i = 0; i < splashColorModeNComps[cm]; ++i) { blend[i] = src[i] ^ dest[i]; } } 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: status_t MPEG4Extractor::parse3GPPMetaData(off64_t offset, size_t size, int depth) { if (size < 4 || size == SIZE_MAX) { return ERROR_MALFORMED; } uint8_t *buffer = new (std::nothrow) uint8_t[size + 1]; if (buffer == NULL) { return ERROR_MALFORMED; } if (mDataSource->readAt( offset, buffer, size) != (ssize_t)size) { delete[] buffer; buffer = NULL; return ERROR_IO; } uint32_t metadataKey = 0; switch (mPath[depth]) { case FOURCC('t', 'i', 't', 'l'): { metadataKey = kKeyTitle; break; } case FOURCC('p', 'e', 'r', 'f'): { metadataKey = kKeyArtist; break; } case FOURCC('a', 'u', 't', 'h'): { metadataKey = kKeyWriter; break; } case FOURCC('g', 'n', 'r', 'e'): { metadataKey = kKeyGenre; break; } case FOURCC('a', 'l', 'b', 'm'): { if (buffer[size - 1] != '\0') { char tmp[4]; sprintf(tmp, "%u", buffer[size - 1]); mFileMetaData->setCString(kKeyCDTrackNumber, tmp); } metadataKey = kKeyAlbum; break; } case FOURCC('y', 'r', 'r', 'c'): { char tmp[5]; uint16_t year = U16_AT(&buffer[4]); if (year < 10000) { sprintf(tmp, "%u", year); mFileMetaData->setCString(kKeyYear, tmp); } break; } default: break; } if (metadataKey > 0) { bool isUTF8 = true; // Common case char16_t *framedata = NULL; int len16 = 0; // Number of UTF-16 characters if (size - 6 >= 4) { len16 = ((size - 6) / 2) - 1; // don't include 0x0000 terminator framedata = (char16_t *)(buffer + 6); if (0xfffe == *framedata) { for (int i = 0; i < len16; i++) { framedata[i] = bswap_16(framedata[i]); } } if (0xfeff == *framedata) { framedata++; len16--; isUTF8 = false; } } if (isUTF8) { buffer[size] = 0; mFileMetaData->setCString(metadataKey, (const char *)buffer + 6); } else { String8 tmpUTF8str(framedata, len16); mFileMetaData->setCString(metadataKey, tmpUTF8str.string()); } } delete[] buffer; buffer = NULL; return OK; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void TabletModeWindowState::LeaveTabletMode(wm::WindowState* window_state) { EnterAnimationType animation_type = window_state->IsSnapped() || IsTopWindow(window_state->window()) ? DEFAULT : IMMEDIATE; if (old_state_->GetType() == window_state->GetStateType() && !window_state->IsNormalStateType()) { animation_type = IMMEDIATE; } old_state_->set_enter_animation_type(animation_type); std::unique_ptr<wm::WindowState::State> our_reference = window_state->SetStateObject(std::move(old_state_)); } CWE ID: CWE-362 Target: 1 Example 2: Code: bool DocumentLoader::ShouldContinueForResponse() const { if (substitute_data_.IsValid()) return true; int status_code = response_.HttpStatusCode(); if (status_code == 204 || status_code == 205) { return false; } if (IsContentDispositionAttachment( response_.HttpHeaderField(HTTPNames::Content_Disposition))) { return false; } if (!CanShowMIMEType(response_.MimeType(), frame_)) return false; return true; } 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: bool Textfield::ChangeTextDirectionAndLayoutAlignment( base::i18n::TextDirection direction) { const gfx::DirectionalityMode mode = direction == base::i18n::RIGHT_TO_LEFT ? gfx::DIRECTIONALITY_FORCE_RTL : gfx::DIRECTIONALITY_FORCE_LTR; if (mode == GetRenderText()->directionality_mode()) GetRenderText()->SetDirectionalityMode(gfx::DIRECTIONALITY_FROM_TEXT); else GetRenderText()->SetDirectionalityMode(mode); SchedulePaint(); 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: void RunInvAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, in, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, coeff, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); in[j] = src[j] - dst[j]; } fwd_txfm_ref(in, coeff, pitch_, tx_type_); REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; EXPECT_GE(1u, error) << "Error: 16x16 IDCT has error " << error << " at index " << j; } } } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderViewImpl::ApplyWebPreferencesInternal( const WebPreferences& prefs, blink::WebView* web_view, CompositorDependencies* compositor_deps) { ApplyWebPreferences(prefs, web_view); } 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: MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *name,ExceptionInfo *exception) { char filename[MagickPathExtent]; Image *clip_mask; const char *value; DrawInfo *clone_info; MagickStatusType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); (void) FormatLocaleString(filename,MagickPathExtent,"%s",name); value=GetImageArtifact(image,filename); if (value == (const char *) NULL) return(MagickFalse); clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (clip_mask == (Image *) NULL) return(MagickFalse); (void) QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(Quantum) TransparentAlpha; (void) SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", draw_info->clip_mask); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,value); (void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); clone_info->clip_mask=(char *) NULL; status=NegateImage(clip_mask,MagickFalse,exception); (void) SetImageMask(image,ReadPixelMask,clip_mask,exception); clip_mask=DestroyImage(clip_mask); status&=DrawImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(status != 0 ? MagickTrue : MagickFalse); } 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 vpx_codec_err_t vp8_decode(vpx_codec_alg_priv_t *ctx, const uint8_t *data, unsigned int data_sz, void *user_priv, long deadline) { vpx_codec_err_t res = VPX_CODEC_OK; unsigned int resolution_change = 0; unsigned int w, h; if (!ctx->fragments.enabled && (data == NULL && data_sz == 0)) { return 0; } /* Update the input fragment data */ if(update_fragments(ctx, data, data_sz, &res) <= 0) return res; /* Determine the stream parameters. Note that we rely on peek_si to * validate that we have a buffer that does not wrap around the top * of the heap. */ w = ctx->si.w; h = ctx->si.h; res = vp8_peek_si_internal(ctx->fragments.ptrs[0], ctx->fragments.sizes[0], &ctx->si, ctx->decrypt_cb, ctx->decrypt_state); if((res == VPX_CODEC_UNSUP_BITSTREAM) && !ctx->si.is_kf) { /* the peek function returns an error for non keyframes, however for * this case, it is not an error */ res = VPX_CODEC_OK; } if(!ctx->decoder_init && !ctx->si.is_kf) res = VPX_CODEC_UNSUP_BITSTREAM; if ((ctx->si.h != h) || (ctx->si.w != w)) resolution_change = 1; /* Initialize the decoder instance on the first frame*/ if (!res && !ctx->decoder_init) { VP8D_CONFIG oxcf; oxcf.Width = ctx->si.w; oxcf.Height = ctx->si.h; oxcf.Version = 9; oxcf.postprocess = 0; oxcf.max_threads = ctx->cfg.threads; oxcf.error_concealment = (ctx->base.init_flags & VPX_CODEC_USE_ERROR_CONCEALMENT); /* If postprocessing was enabled by the application and a * configuration has not been provided, default it. */ if (!ctx->postproc_cfg_set && (ctx->base.init_flags & VPX_CODEC_USE_POSTPROC)) { ctx->postproc_cfg.post_proc_flag = VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE; ctx->postproc_cfg.deblocking_level = 4; ctx->postproc_cfg.noise_level = 0; } res = vp8_create_decoder_instances(&ctx->yv12_frame_buffers, &oxcf); ctx->decoder_init = 1; } /* Set these even if already initialized. The caller may have changed the * decrypt config between frames. */ if (ctx->decoder_init) { ctx->yv12_frame_buffers.pbi[0]->decrypt_cb = ctx->decrypt_cb; ctx->yv12_frame_buffers.pbi[0]->decrypt_state = ctx->decrypt_state; } if (!res) { VP8D_COMP *pbi = ctx->yv12_frame_buffers.pbi[0]; if (resolution_change) { VP8_COMMON *const pc = & pbi->common; MACROBLOCKD *const xd = & pbi->mb; #if CONFIG_MULTITHREAD int i; #endif pc->Width = ctx->si.w; pc->Height = ctx->si.h; { int prev_mb_rows = pc->mb_rows; if (setjmp(pbi->common.error.jmp)) { pbi->common.error.setjmp = 0; vp8_clear_system_state(); /* same return value as used in vp8dx_receive_compressed_data */ return -1; } pbi->common.error.setjmp = 1; if (pc->Width <= 0) { pc->Width = w; vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME, "Invalid frame width"); } if (pc->Height <= 0) { pc->Height = h; vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME, "Invalid frame height"); } if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height)) vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, "Failed to allocate frame buffers"); xd->pre = pc->yv12_fb[pc->lst_fb_idx]; xd->dst = pc->yv12_fb[pc->new_fb_idx]; #if CONFIG_MULTITHREAD for (i = 0; i < pbi->allocated_decoding_thread_count; i++) { pbi->mb_row_di[i].mbd.dst = pc->yv12_fb[pc->new_fb_idx]; vp8_build_block_doffsets(&pbi->mb_row_di[i].mbd); } #endif vp8_build_block_doffsets(&pbi->mb); /* allocate memory for last frame MODE_INFO array */ #if CONFIG_ERROR_CONCEALMENT if (pbi->ec_enabled) { /* old prev_mip was released by vp8_de_alloc_frame_buffers() * called in vp8_alloc_frame_buffers() */ pc->prev_mip = vpx_calloc( (pc->mb_cols + 1) * (pc->mb_rows + 1), sizeof(MODE_INFO)); if (!pc->prev_mip) { vp8_de_alloc_frame_buffers(pc); vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, "Failed to allocate" "last frame MODE_INFO array"); } pc->prev_mi = pc->prev_mip + pc->mode_info_stride + 1; if (vp8_alloc_overlap_lists(pbi)) vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, "Failed to allocate overlap lists " "for error concealment"); } #endif #if CONFIG_MULTITHREAD if (pbi->b_multithreaded_rd) vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows); #else (void)prev_mb_rows; #endif } pbi->common.error.setjmp = 0; /* required to get past the first get_free_fb() call */ pbi->common.fb_idx_ref_cnt[0] = 0; } /* update the pbi fragment data */ pbi->fragments = ctx->fragments; ctx->user_priv = user_priv; if (vp8dx_receive_compressed_data(pbi, data_sz, data, deadline)) { res = update_error_state(ctx, &pbi->common.error); } /* get ready for the next series of fragments */ ctx->fragments.count = 0; } return res; } CWE ID: CWE-20 Target: 1 Example 2: Code: static inline int NonASCIISequenceLength(uint8_t first_byte) { static const uint8_t kLengths[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; return kLengths[first_byte]; } 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 vpx_image_t *img_alloc_helper(vpx_image_t *img, vpx_img_fmt_t fmt, unsigned int d_w, unsigned int d_h, unsigned int buf_align, unsigned int stride_align, unsigned char *img_data) { unsigned int h, w, s, xcs, ycs, bps; unsigned int stride_in_bytes; int align; /* Treat align==0 like align==1 */ if (!buf_align) buf_align = 1; /* Validate alignment (must be power of 2) */ if (buf_align & (buf_align - 1)) goto fail; /* Treat align==0 like align==1 */ if (!stride_align) stride_align = 1; /* Validate alignment (must be power of 2) */ if (stride_align & (stride_align - 1)) goto fail; /* Get sample size for this format */ switch (fmt) { case VPX_IMG_FMT_RGB32: case VPX_IMG_FMT_RGB32_LE: case VPX_IMG_FMT_ARGB: case VPX_IMG_FMT_ARGB_LE: bps = 32; break; case VPX_IMG_FMT_RGB24: case VPX_IMG_FMT_BGR24: bps = 24; break; case VPX_IMG_FMT_RGB565: case VPX_IMG_FMT_RGB565_LE: case VPX_IMG_FMT_RGB555: case VPX_IMG_FMT_RGB555_LE: case VPX_IMG_FMT_UYVY: case VPX_IMG_FMT_YUY2: case VPX_IMG_FMT_YVYU: bps = 16; break; case VPX_IMG_FMT_I420: case VPX_IMG_FMT_YV12: case VPX_IMG_FMT_VPXI420: case VPX_IMG_FMT_VPXYV12: bps = 12; break; case VPX_IMG_FMT_I422: case VPX_IMG_FMT_I440: bps = 16; break; case VPX_IMG_FMT_I444: bps = 24; break; case VPX_IMG_FMT_I42016: bps = 24; break; case VPX_IMG_FMT_I42216: case VPX_IMG_FMT_I44016: bps = 32; break; case VPX_IMG_FMT_I44416: bps = 48; break; default: bps = 16; break; } /* Get chroma shift values for this format */ switch (fmt) { case VPX_IMG_FMT_I420: case VPX_IMG_FMT_YV12: case VPX_IMG_FMT_VPXI420: case VPX_IMG_FMT_VPXYV12: case VPX_IMG_FMT_I422: case VPX_IMG_FMT_I42016: case VPX_IMG_FMT_I42216: xcs = 1; break; default: xcs = 0; break; } switch (fmt) { case VPX_IMG_FMT_I420: case VPX_IMG_FMT_I440: case VPX_IMG_FMT_YV12: case VPX_IMG_FMT_VPXI420: case VPX_IMG_FMT_VPXYV12: case VPX_IMG_FMT_I42016: case VPX_IMG_FMT_I44016: ycs = 1; break; default: ycs = 0; break; } /* Calculate storage sizes given the chroma subsampling */ align = (1 << xcs) - 1; w = (d_w + align) & ~align; align = (1 << ycs) - 1; h = (d_h + align) & ~align; s = (fmt & VPX_IMG_FMT_PLANAR) ? w : bps * w / 8; s = (s + stride_align - 1) & ~(stride_align - 1); stride_in_bytes = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? s * 2 : s; /* Allocate the new image */ if (!img) { img = (vpx_image_t *)calloc(1, sizeof(vpx_image_t)); if (!img) goto fail; img->self_allocd = 1; } else { memset(img, 0, sizeof(vpx_image_t)); } img->img_data = img_data; if (!img_data) { const uint64_t alloc_size = (fmt & VPX_IMG_FMT_PLANAR) ? (uint64_t)h * s * bps / 8 : (uint64_t)h * s; if (alloc_size != (size_t)alloc_size) goto fail; img->img_data = (uint8_t *)vpx_memalign(buf_align, (size_t)alloc_size); img->img_data_owner = 1; } if (!img->img_data) goto fail; img->fmt = fmt; img->bit_depth = (fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? 16 : 8; img->w = w; img->h = h; img->x_chroma_shift = xcs; img->y_chroma_shift = ycs; img->bps = bps; /* Calculate strides */ img->stride[VPX_PLANE_Y] = img->stride[VPX_PLANE_ALPHA] = stride_in_bytes; img->stride[VPX_PLANE_U] = img->stride[VPX_PLANE_V] = stride_in_bytes >> xcs; /* Default viewport to entire image */ if (!vpx_img_set_rect(img, 0, 0, d_w, d_h)) return img; fail: vpx_img_free(img); return NULL; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xfs_setattr_nonsize( struct xfs_inode *ip, struct iattr *iattr, int flags) { xfs_mount_t *mp = ip->i_mount; struct inode *inode = VFS_I(ip); int mask = iattr->ia_valid; xfs_trans_t *tp; int error; kuid_t uid = GLOBAL_ROOT_UID, iuid = GLOBAL_ROOT_UID; kgid_t gid = GLOBAL_ROOT_GID, igid = GLOBAL_ROOT_GID; struct xfs_dquot *udqp = NULL, *gdqp = NULL; struct xfs_dquot *olddquot1 = NULL, *olddquot2 = NULL; ASSERT((mask & ATTR_SIZE) == 0); /* * If disk quotas is on, we make sure that the dquots do exist on disk, * before we start any other transactions. Trying to do this later * is messy. We don't care to take a readlock to look at the ids * in inode here, because we can't hold it across the trans_reserve. * If the IDs do change before we take the ilock, we're covered * because the i_*dquot fields will get updated anyway. */ if (XFS_IS_QUOTA_ON(mp) && (mask & (ATTR_UID|ATTR_GID))) { uint qflags = 0; if ((mask & ATTR_UID) && XFS_IS_UQUOTA_ON(mp)) { uid = iattr->ia_uid; qflags |= XFS_QMOPT_UQUOTA; } else { uid = inode->i_uid; } if ((mask & ATTR_GID) && XFS_IS_GQUOTA_ON(mp)) { gid = iattr->ia_gid; qflags |= XFS_QMOPT_GQUOTA; } else { gid = inode->i_gid; } /* * We take a reference when we initialize udqp and gdqp, * so it is important that we never blindly double trip on * the same variable. See xfs_create() for an example. */ ASSERT(udqp == NULL); ASSERT(gdqp == NULL); error = xfs_qm_vop_dqalloc(ip, xfs_kuid_to_uid(uid), xfs_kgid_to_gid(gid), xfs_get_projid(ip), qflags, &udqp, &gdqp, NULL); if (error) return error; } error = xfs_trans_alloc(mp, &M_RES(mp)->tr_ichange, 0, 0, 0, &tp); if (error) goto out_dqrele; xfs_ilock(ip, XFS_ILOCK_EXCL); xfs_trans_ijoin(tp, ip, 0); /* * Change file ownership. Must be the owner or privileged. */ if (mask & (ATTR_UID|ATTR_GID)) { /* * These IDs could have changed since we last looked at them. * But, we're assured that if the ownership did change * while we didn't have the inode locked, inode's dquot(s) * would have changed also. */ iuid = inode->i_uid; igid = inode->i_gid; gid = (mask & ATTR_GID) ? iattr->ia_gid : igid; uid = (mask & ATTR_UID) ? iattr->ia_uid : iuid; /* * Do a quota reservation only if uid/gid is actually * going to change. */ if (XFS_IS_QUOTA_RUNNING(mp) && ((XFS_IS_UQUOTA_ON(mp) && !uid_eq(iuid, uid)) || (XFS_IS_GQUOTA_ON(mp) && !gid_eq(igid, gid)))) { ASSERT(tp); error = xfs_qm_vop_chown_reserve(tp, ip, udqp, gdqp, NULL, capable(CAP_FOWNER) ? XFS_QMOPT_FORCE_RES : 0); if (error) /* out of quota */ goto out_cancel; } } /* * Change file ownership. Must be the owner or privileged. */ if (mask & (ATTR_UID|ATTR_GID)) { /* * CAP_FSETID overrides the following restrictions: * * The set-user-ID and set-group-ID bits of a file will be * cleared upon successful return from chown() */ if ((inode->i_mode & (S_ISUID|S_ISGID)) && !capable(CAP_FSETID)) inode->i_mode &= ~(S_ISUID|S_ISGID); /* * Change the ownerships and register quota modifications * in the transaction. */ if (!uid_eq(iuid, uid)) { if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_UQUOTA_ON(mp)) { ASSERT(mask & ATTR_UID); ASSERT(udqp); olddquot1 = xfs_qm_vop_chown(tp, ip, &ip->i_udquot, udqp); } ip->i_d.di_uid = xfs_kuid_to_uid(uid); inode->i_uid = uid; } if (!gid_eq(igid, gid)) { if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_GQUOTA_ON(mp)) { ASSERT(xfs_sb_version_has_pquotino(&mp->m_sb) || !XFS_IS_PQUOTA_ON(mp)); ASSERT(mask & ATTR_GID); ASSERT(gdqp); olddquot2 = xfs_qm_vop_chown(tp, ip, &ip->i_gdquot, gdqp); } ip->i_d.di_gid = xfs_kgid_to_gid(gid); inode->i_gid = gid; } } if (mask & ATTR_MODE) xfs_setattr_mode(ip, iattr); if (mask & (ATTR_ATIME|ATTR_CTIME|ATTR_MTIME)) xfs_setattr_time(ip, iattr); xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); XFS_STATS_INC(mp, xs_ig_attrchg); if (mp->m_flags & XFS_MOUNT_WSYNC) xfs_trans_set_sync(tp); error = xfs_trans_commit(tp); xfs_iunlock(ip, XFS_ILOCK_EXCL); /* * Release any dquot(s) the inode had kept before chown. */ xfs_qm_dqrele(olddquot1); xfs_qm_dqrele(olddquot2); xfs_qm_dqrele(udqp); xfs_qm_dqrele(gdqp); if (error) return error; /* * XXX(hch): Updating the ACL entries is not atomic vs the i_mode * update. We could avoid this with linked transactions * and passing down the transaction pointer all the way * to attr_set. No previous user of the generic * Posix ACL code seems to care about this issue either. */ if ((mask & ATTR_MODE) && !(flags & XFS_ATTR_NOACL)) { error = posix_acl_chmod(inode, inode->i_mode); if (error) return error; } return 0; out_cancel: xfs_trans_cancel(tp); out_dqrele: xfs_qm_dqrele(udqp); xfs_qm_dqrele(gdqp); return error; } CWE ID: CWE-399 Target: 1 Example 2: Code: static int create_pin_file(const sc_path_t *inpath, int chv, const char *key_id) { char prompt[40], *pin, *puk; char buf[30], *p = buf; sc_path_t file_id, path; sc_file_t *file; size_t len; int r; file_id = *inpath; if (file_id.len < 2) return -1; if (chv == 1) sc_format_path("I0000", &file_id); else if (chv == 2) sc_format_path("I0100", &file_id); else return -1; r = sc_select_file(card, inpath, NULL); if (r) return -1; r = sc_select_file(card, &file_id, NULL); if (r == 0) return 0; sprintf(prompt, "Please enter CHV%d%s: ", chv, key_id); pin = getpin(prompt); if (pin == NULL) return -1; sprintf(prompt, "Please enter PUK for CHV%d%s: ", chv, key_id); puk = getpin(prompt); if (puk == NULL) { free(pin); return -1; } memset(p, 0xFF, 3); p += 3; memcpy(p, pin, 8); p += 8; *p++ = opt_pin_attempts; *p++ = opt_pin_attempts; memcpy(p, puk, 8); p += 8; *p++ = opt_puk_attempts; *p++ = opt_puk_attempts; len = p - buf; free(pin); free(puk); file = sc_file_new(); file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = SC_FILE_EF_TRANSPARENT; sc_file_add_acl_entry(file, SC_AC_OP_READ, SC_AC_NEVER, SC_AC_KEY_REF_NONE); if (inpath->len == 2 && inpath->value[0] == 0x3F && inpath->value[1] == 0x00) sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_AUT, 1); else sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, SC_AC_CHV, 2); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_AUT, 1); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_AUT, 1); file->size = len; file->id = (file_id.value[0] << 8) | file_id.value[1]; r = sc_create_file(card, file); sc_file_free(file); if (r) { fprintf(stderr, "PIN file creation failed: %s\n", sc_strerror(r)); return r; } path = *inpath; sc_append_path(&path, &file_id); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select created PIN file: %s\n", sc_strerror(r)); return r; } r = sc_update_binary(card, 0, (const u8 *) buf, len, 0); if (r < 0) { fprintf(stderr, "Unable to update created PIN file: %s\n", sc_strerror(r)); return r; } return 0; } CWE ID: CWE-415 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: token_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save) { os_ptr op = osp; int code; ref token; /* Note that gs_scan_token may change osp! */ pop(1); /* remove the file or scanner state */ again: gs_scanner_error_object(i_ctx_p, pstate, &i_ctx_p->error_object); break; case scan_BOS: code = 0; case 0: /* read a token */ push(2); ref_assign(op - 1, &token); make_true(op); break; case scan_EOF: /* no tokens */ push(1); make_false(op); code = 0; break; case scan_Refill: /* need more data */ code = gs_scan_handle_refill(i_ctx_p, pstate, save, ztoken_continue); switch (code) { case 0: /* state is not copied to the heap */ goto again; case o_push_estack: return code; } break; /* error */ } 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: size_t mptsas_config_ioc_0(MPTSASState *s, uint8_t **data, int address) { PCIDeviceClass *pcic = PCI_DEVICE_GET_CLASS(s); return MPTSAS_CONFIG_PACK(0, MPI_CONFIG_PAGETYPE_IOC, 0x01, "*l*lwwb*b*b*blww", pcic->vendor_id, pcic->device_id, pcic->revision, pcic->subsystem_vendor_id, pcic->subsystem_id); } CWE ID: CWE-20 Target: 1 Example 2: Code: std::unique_ptr<TracedValue> InspectorCompileScriptEvent::Data( const String& url, const TextPosition& text_position) { return FillLocation(url, text_position); } 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: gre_sre_print(netdissect_options *ndo, uint16_t af, uint8_t sreoff, uint8_t srelen, const u_char *bp, u_int len) { int ret; switch (af) { case GRESRE_IP: ND_PRINT((ndo, ", (rtaf=ip")); ret = gre_sre_ip_print(ndo, sreoff, srelen, bp, len); ND_PRINT((ndo, ")")); break; case GRESRE_ASN: ND_PRINT((ndo, ", (rtaf=asn")); ret = gre_sre_asn_print(ndo, sreoff, srelen, bp, len); ND_PRINT((ndo, ")")); break; default: ND_PRINT((ndo, ", (rtaf=0x%x)", af)); ret = 1; } return (ret); } 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 SetupConnectedStreams() { CallbackRunLoop run_loop(runner()); ASSERT_TRUE(client_peer_->quic_transport()->IsEncryptionEstablished()); ASSERT_TRUE(server_peer_->quic_transport()->IsEncryptionEstablished()); client_peer_->CreateStreamWithDelegate(); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); base::RepeatingCallback<void()> callback = run_loop.CreateCallback(); QuicPeerForTest* server_peer_ptr = server_peer_.get(); MockP2PQuicStreamDelegate* stream_delegate = new MockP2PQuicStreamDelegate(); P2PQuicStream* server_stream; EXPECT_CALL(*server_peer_->quic_transport_delegate(), OnStream(_)) .WillOnce(Invoke([&callback, &server_stream, &stream_delegate](P2PQuicStream* stream) { stream->SetDelegate(stream_delegate); server_stream = stream; callback.Run(); })); client_peer_->stream()->WriteOrBufferData(kTriggerRemoteStreamPhrase, /*fin=*/false, nullptr); run_loop.RunUntilCallbacksFired(); server_peer_ptr->SetStreamAndDelegate( static_cast<P2PQuicStreamImpl*>(server_stream), std::unique_ptr<MockP2PQuicStreamDelegate>(stream_delegate)); ASSERT_TRUE(client_peer_->stream()); ASSERT_TRUE(client_peer_->stream_delegate()); } CWE ID: CWE-284 Target: 1 Example 2: Code: static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c, uint8_t *properties) { int compno, ret; if (bytestream2_get_bytes_left(&s->g) < 2) return AVERROR_INVALIDDATA; compno = bytestream2_get_byteu(&s->g); if (compno >= s->ncomponents) { av_log(s->avctx, AV_LOG_ERROR, "Invalid compno %d. There are %d components in the image.\n", compno, s->ncomponents); return AVERROR_INVALIDDATA; } c += compno; c->csty = bytestream2_get_byteu(&s->g); if ((ret = get_cox(s, c)) < 0) return ret; properties[compno] |= HAD_COC; 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: my_object_class_init (MyObjectClass *mobject_class) { GObjectClass *gobject_class = G_OBJECT_CLASS (mobject_class); gobject_class->finalize = my_object_finalize; gobject_class->set_property = my_object_set_property; gobject_class->get_property = my_object_get_property; g_object_class_install_property (gobject_class, PROP_THIS_IS_A_STRING, g_param_spec_string ("this_is_a_string", _("Sample string"), _("Example of a string property"), "default value", G_PARAM_READWRITE)); signals[FROBNICATE] = g_signal_new ("frobnicate", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); signals[SIG0] = g_signal_new ("sig0", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, my_object_marshal_VOID__STRING_INT_STRING, G_TYPE_NONE, 3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING); signals[SIG1] = g_signal_new ("sig1", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, my_object_marshal_VOID__STRING_BOXED, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_VALUE); signals[SIG2] = g_signal_new ("sig2", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, DBUS_TYPE_G_STRING_STRING_HASHTABLE); } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int svc_rdma_handle_bc_reply(struct rpc_xprt *xprt, struct rpcrdma_msg *rmsgp, struct xdr_buf *rcvbuf) { struct rpcrdma_xprt *r_xprt = rpcx_to_rdmax(xprt); struct kvec *dst, *src = &rcvbuf->head[0]; struct rpc_rqst *req; unsigned long cwnd; u32 credits; size_t len; __be32 xid; __be32 *p; int ret; p = (__be32 *)src->iov_base; len = src->iov_len; xid = rmsgp->rm_xid; #ifdef SVCRDMA_BACKCHANNEL_DEBUG pr_info("%s: xid=%08x, length=%zu\n", __func__, be32_to_cpu(xid), len); pr_info("%s: RPC/RDMA: %*ph\n", __func__, (int)RPCRDMA_HDRLEN_MIN, rmsgp); pr_info("%s: RPC: %*ph\n", __func__, (int)len, p); #endif ret = -EAGAIN; if (src->iov_len < 24) goto out_shortreply; spin_lock_bh(&xprt->transport_lock); req = xprt_lookup_rqst(xprt, xid); if (!req) goto out_notfound; dst = &req->rq_private_buf.head[0]; memcpy(&req->rq_private_buf, &req->rq_rcv_buf, sizeof(struct xdr_buf)); if (dst->iov_len < len) goto out_unlock; memcpy(dst->iov_base, p, len); credits = be32_to_cpu(rmsgp->rm_credit); if (credits == 0) credits = 1; /* don't deadlock */ else if (credits > r_xprt->rx_buf.rb_bc_max_requests) credits = r_xprt->rx_buf.rb_bc_max_requests; cwnd = xprt->cwnd; xprt->cwnd = credits << RPC_CWNDSHIFT; if (xprt->cwnd > cwnd) xprt_release_rqst_cong(req->rq_task); ret = 0; xprt_complete_rqst(req->rq_task, rcvbuf->len); rcvbuf->len = 0; out_unlock: spin_unlock_bh(&xprt->transport_lock); out: return ret; out_shortreply: dprintk("svcrdma: short bc reply: xprt=%p, len=%zu\n", xprt, src->iov_len); goto out; out_notfound: dprintk("svcrdma: unrecognized bc reply: xprt=%p, xid=%08x\n", xprt, be32_to_cpu(xid)); goto out_unlock; } CWE ID: CWE-404 Target: 1 Example 2: Code: static long do_sys_ftruncate(unsigned int fd, loff_t length, int small) { struct inode *inode; struct dentry *dentry; struct fd f; int error; error = -EINVAL; if (length < 0) goto out; error = -EBADF; f = fdget(fd); if (!f.file) goto out; /* explicitly opened as large or we are on 64-bit box */ if (f.file->f_flags & O_LARGEFILE) small = 0; dentry = f.file->f_path.dentry; inode = dentry->d_inode; error = -EINVAL; if (!S_ISREG(inode->i_mode) || !(f.file->f_mode & FMODE_WRITE)) goto out_putf; error = -EINVAL; /* Cannot ftruncate over 2^31 bytes without large file support */ if (small && length > MAX_NON_LFS) goto out_putf; error = -EPERM; if (IS_APPEND(inode)) goto out_putf; sb_start_write(inode->i_sb); error = locks_verify_truncate(inode, f.file, length); if (!error) error = security_path_truncate(&f.file->f_path); if (!error) error = do_truncate(dentry, length, ATTR_MTIME|ATTR_CTIME, f.file); sb_end_write(inode->i_sb); out_putf: fdput(f); out: return error; } 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: static void free_mnt_ns(struct mnt_namespace *ns) { ns_free_inum(&ns->ns); put_user_ns(ns->user_ns); kfree(ns); } 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: hstore_slice_to_hstore(PG_FUNCTION_ARGS) { HStore *hs = PG_GETARG_HS(0); HEntry *entries = ARRPTR(hs); char *ptr = STRPTR(hs); ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(1); HStore *out; int nkeys; Pairs *key_pairs = hstoreArrayToPairs(key_array, &nkeys); Pairs *out_pairs; int bufsiz; int lastidx = 0; int i; int out_count = 0; if (nkeys == 0) { out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); } out_pairs = palloc(sizeof(Pairs) * nkeys); bufsiz = 0; /* * we exploit the fact that the pairs list is already sorted into strictly * increasing order to narrow the hstoreFindKey search; each search can * start one entry past the previous "found" entry, or at the lower bound * of the last search. */ for (i = 0; i < nkeys; ++i) { int idx = hstoreFindKey(hs, &lastidx, key_pairs[i].key, key_pairs[i].keylen); if (idx >= 0) { out_pairs[out_count].key = key_pairs[i].key; bufsiz += (out_pairs[out_count].keylen = key_pairs[i].keylen); out_pairs[out_count].val = HS_VAL(entries, ptr, idx); bufsiz += (out_pairs[out_count].vallen = HS_VALLEN(entries, idx)); out_pairs[out_count].isnull = HS_VALISNULL(entries, idx); out_pairs[out_count].needfree = false; ++out_count; } } /* * we don't use uniquePairs here because we know that the pairs list is * already sorted and uniq'ed. */ out = hstorePairs(out_pairs, out_count, bufsiz); PG_RETURN_POINTER(out); } CWE ID: CWE-189 Target: 1 Example 2: Code: bool GLES2DecoderImpl::GenRenderbuffersHelper( GLsizei n, const GLuint* client_ids) { for (GLsizei ii = 0; ii < n; ++ii) { if (GetRenderbuffer(client_ids[ii])) { return false; } } scoped_ptr<GLuint[]> service_ids(new GLuint[n]); glGenRenderbuffersEXT(n, service_ids.get()); for (GLsizei ii = 0; ii < n; ++ii) { CreateRenderbuffer(client_ids[ii], service_ids[ii]); } return true; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void virtio_queue_notify_vq(VirtQueue *vq) { if (vq->vring.desc) { VirtIODevice *vdev = vq->vdev; trace_virtio_queue_notify(vdev, vq - vdev->vq, vq); vq->handle_output(vdev, vq); } } 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 ASessionDescription::getFormatType( size_t index, unsigned long *PT, AString *desc, AString *params) const { AString format; getFormat(index, &format); const char *lastSpacePos = strrchr(format.c_str(), ' '); CHECK(lastSpacePos != NULL); char *end; unsigned long x = strtoul(lastSpacePos + 1, &end, 10); CHECK_GT(end, lastSpacePos + 1); CHECK_EQ(*end, '\0'); *PT = x; char key[20]; sprintf(key, "a=rtpmap:%lu", x); CHECK(findAttribute(index, key, desc)); sprintf(key, "a=fmtp:%lu", x); if (!findAttribute(index, key, params)) { params->clear(); } } CWE ID: CWE-284 Target: 1 Example 2: Code: static int jsR_delproperty(js_State *J, js_Object *obj, const char *name) { js_Property *ref; int k; if (obj->type == JS_CARRAY) { if (!strcmp(name, "length")) goto dontconf; } else if (obj->type == JS_CSTRING) { if (!strcmp(name, "length")) goto dontconf; if (js_isarrayindex(J, name, &k)) if (js_runeat(J, obj->u.s.string, k)) goto dontconf; } else if (obj->type == JS_CREGEXP) { if (!strcmp(name, "source")) goto dontconf; if (!strcmp(name, "global")) goto dontconf; if (!strcmp(name, "ignoreCase")) goto dontconf; if (!strcmp(name, "multiline")) goto dontconf; if (!strcmp(name, "lastIndex")) goto dontconf; } else if (obj->type == JS_CUSERDATA) { if (obj->u.user.delete && obj->u.user.delete(J, obj->u.user.data, name)) return 1; } ref = jsV_getownproperty(J, obj, name); if (ref) { if (ref->atts & JS_DONTCONF) goto dontconf; jsV_delproperty(J, obj, name); } return 1; dontconf: if (J->strict) js_typeerror(J, "'%s' is non-configurable", name); 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: const char* Chapters::Display::GetLanguage() const { return m_language; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool Segment::DoneParsing() const { if (m_size < 0) { long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) //error return true; //must assume done if (total < 0) return false; //assume live stream return (m_pos >= total); } const long long stop = m_start + m_size; return (m_pos >= stop); } CWE ID: CWE-119 Target: 1 Example 2: Code: int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len) { if (s->version >= TLS1_VERSION) { OPENSSL_free(s->tlsext_session_ticket); s->tlsext_session_ticket = NULL; s->tlsext_session_ticket = OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len); if (!s->tlsext_session_ticket) { SSLerr(SSL_F_SSL_SET_SESSION_TICKET_EXT, ERR_R_MALLOC_FAILURE); return 0; } if (ext_data) { s->tlsext_session_ticket->length = ext_len; s->tlsext_session_ticket->data = s->tlsext_session_ticket + 1; memcpy(s->tlsext_session_ticket->data, ext_data, ext_len); } else { s->tlsext_session_ticket->length = 0; s->tlsext_session_ticket->data = NULL; } 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: void PrerenderTestURL( const std::string& html_file, const std::deque<FinalStatus>& expected_final_status_queue, int total_navigations) { ASSERT_TRUE(test_server()->Start()); PrerenderTestURLImpl(test_server()->GetURL(html_file), expected_final_status_queue, total_navigations); } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void APIPermissionInfo::RegisterAllPermissions( PermissionsInfo* info) { struct PermissionRegistration { APIPermission::ID id; const char* name; int flags; int l10n_message_id; PermissionMessage::ID message_id; APIPermissionConstructor constructor; } PermissionsToRegister[] = { { APIPermission::kBackground, "background" }, { APIPermission::kClipboardRead, "clipboardRead", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_CLIPBOARD, PermissionMessage::kClipboard }, { APIPermission::kClipboardWrite, "clipboardWrite" }, { APIPermission::kDeclarativeWebRequest, "declarativeWebRequest" }, { APIPermission::kDownloads, "downloads", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_DOWNLOADS, PermissionMessage::kDownloads }, { APIPermission::kExperimental, "experimental", kFlagCannotBeOptional }, { APIPermission::kGeolocation, "geolocation", kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION, PermissionMessage::kGeolocation }, { APIPermission::kNotification, "notifications" }, { APIPermission::kUnlimitedStorage, "unlimitedStorage", kFlagCannotBeOptional }, { APIPermission::kAppNotifications, "appNotifications" }, { APIPermission::kActiveTab, "activeTab" }, { APIPermission::kAlarms, "alarms" }, { APIPermission::kBookmark, "bookmarks", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BOOKMARKS, PermissionMessage::kBookmarks }, { APIPermission::kBrowsingData, "browsingData" }, { APIPermission::kContentSettings, "contentSettings", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS, PermissionMessage::kContentSettings }, { APIPermission::kContextMenus, "contextMenus" }, { APIPermission::kCookie, "cookies" }, { APIPermission::kFileBrowserHandler, "fileBrowserHandler", kFlagCannotBeOptional }, { APIPermission::kFontSettings, "fontSettings", kFlagCannotBeOptional }, { APIPermission::kHistory, "history", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY, PermissionMessage::kBrowsingHistory }, { APIPermission::kIdle, "idle" }, { APIPermission::kInput, "input", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_INPUT, PermissionMessage::kInput }, { APIPermission::kManagement, "management", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_MANAGEMENT, PermissionMessage::kManagement }, { APIPermission::kPrivacy, "privacy", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_PRIVACY, PermissionMessage::kPrivacy }, { APIPermission::kStorage, "storage" }, { APIPermission::kSyncFileSystem, "syncFileSystem" }, { APIPermission::kTab, "tabs", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs }, { APIPermission::kTopSites, "topSites", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY, PermissionMessage::kBrowsingHistory }, { APIPermission::kTts, "tts", 0, kFlagCannotBeOptional }, { APIPermission::kTtsEngine, "ttsEngine", kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_TTS_ENGINE, PermissionMessage::kTtsEngine }, { APIPermission::kWebNavigation, "webNavigation", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs }, { APIPermission::kWebRequest, "webRequest" }, { APIPermission::kWebRequestBlocking, "webRequestBlocking" }, { APIPermission::kWebView, "webview", kFlagCannotBeOptional }, { APIPermission::kBookmarkManagerPrivate, "bookmarkManagerPrivate", kFlagCannotBeOptional }, { APIPermission::kChromeosInfoPrivate, "chromeosInfoPrivate", kFlagCannotBeOptional }, { APIPermission::kFileBrowserHandlerInternal, "fileBrowserHandlerInternal", kFlagCannotBeOptional }, { APIPermission::kFileBrowserPrivate, "fileBrowserPrivate", kFlagCannotBeOptional }, { APIPermission::kManagedModePrivate, "managedModePrivate", kFlagCannotBeOptional }, { APIPermission::kMediaPlayerPrivate, "mediaPlayerPrivate", kFlagCannotBeOptional }, { APIPermission::kMetricsPrivate, "metricsPrivate", kFlagCannotBeOptional }, { APIPermission::kSystemPrivate, "systemPrivate", kFlagCannotBeOptional }, { APIPermission::kCloudPrintPrivate, "cloudPrintPrivate", kFlagCannotBeOptional }, { APIPermission::kInputMethodPrivate, "inputMethodPrivate", kFlagCannotBeOptional }, { APIPermission::kEchoPrivate, "echoPrivate", kFlagCannotBeOptional }, { APIPermission::kRtcPrivate, "rtcPrivate", kFlagCannotBeOptional }, { APIPermission::kTerminalPrivate, "terminalPrivate", kFlagCannotBeOptional }, { APIPermission::kWallpaperPrivate, "wallpaperPrivate", kFlagCannotBeOptional }, { APIPermission::kWebRequestInternal, "webRequestInternal" }, { APIPermission::kWebSocketProxyPrivate, "webSocketProxyPrivate", kFlagCannotBeOptional }, { APIPermission::kWebstorePrivate, "webstorePrivate", kFlagCannotBeOptional }, { APIPermission::kMediaGalleriesPrivate, "mediaGalleriesPrivate", kFlagCannotBeOptional }, { APIPermission::kDebugger, "debugger", kFlagImpliesFullURLAccess | kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_DEBUGGER, PermissionMessage::kDebugger }, { APIPermission::kDevtools, "devtools", kFlagImpliesFullURLAccess | kFlagCannotBeOptional }, { APIPermission::kPageCapture, "pageCapture", kFlagImpliesFullURLAccess }, { APIPermission::kTabCapture, "tabCapture", kFlagImpliesFullURLAccess }, { APIPermission::kPlugin, "plugin", kFlagImpliesFullURLAccess | kFlagImpliesFullAccess | kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS, PermissionMessage::kFullAccess }, { APIPermission::kProxy, "proxy", kFlagImpliesFullURLAccess | kFlagCannotBeOptional }, { APIPermission::kSerial, "serial", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_SERIAL, PermissionMessage::kSerial }, { APIPermission::kSocket, "socket", kFlagCannotBeOptional, 0, PermissionMessage::kNone, &::CreateAPIPermission<SocketPermission> }, { APIPermission::kAppCurrentWindowInternal, "app.currentWindowInternal" }, { APIPermission::kAppRuntime, "app.runtime" }, { APIPermission::kAppWindow, "app.window" }, { APIPermission::kAudioCapture, "audioCapture", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_AUDIO_CAPTURE, PermissionMessage::kAudioCapture }, { APIPermission::kVideoCapture, "videoCapture", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_VIDEO_CAPTURE, PermissionMessage::kVideoCapture }, { APIPermission::kFileSystem, "fileSystem" }, { APIPermission::kFileSystemWrite, "fileSystem.write", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_FILE_SYSTEM_WRITE, PermissionMessage::kFileSystemWrite }, { APIPermission::kMediaGalleries, "mediaGalleries" }, { APIPermission::kMediaGalleriesRead, "mediaGalleries.read" }, { APIPermission::kMediaGalleriesAllAutoDetected, "mediaGalleries.allAutoDetected", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES, PermissionMessage::kMediaGalleriesAllGalleries }, { APIPermission::kPushMessaging, "pushMessaging", kFlagCannotBeOptional }, { APIPermission::kBluetooth, "bluetooth", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BLUETOOTH, PermissionMessage::kBluetooth }, { APIPermission::kBluetoothDevice, "bluetoothDevice", kFlagNone, 0, PermissionMessage::kNone, &::CreateAPIPermission<BluetoothDevicePermission> }, { APIPermission::kUsb, "usb", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_USB, PermissionMessage::kUsb }, { APIPermission::kSystemIndicator, "systemIndicator", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_SYSTEM_INDICATOR, PermissionMessage::kSystemIndicator }, { APIPermission::kPointerLock, "pointerLock" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(PermissionsToRegister); ++i) { const PermissionRegistration& pr = PermissionsToRegister[i]; info->RegisterPermission( pr.id, pr.name, pr.l10n_message_id, pr.message_id ? pr.message_id : PermissionMessage::kNone, pr.flags, pr.constructor); } info->RegisterAlias("unlimitedStorage", kOldUnlimitedStoragePermission); info->RegisterAlias("tabs", kWindowsPermission); } CWE ID: CWE-119 Target: 1 Example 2: Code: RenderFrameCreatedObserver(Shell* shell) : WebContentsObserver(shell->web_contents()), last_rfh_(NULL) { } 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 Document::DispatchBeforeUnloadEvent(ChromeClient& chrome_client, bool is_reload, bool& did_allow_navigation) { if (!dom_window_) return true; if (!body()) return true; if (ProcessingBeforeUnload()) return false; BeforeUnloadEvent* before_unload_event = BeforeUnloadEvent::Create(); before_unload_event->initEvent(EventTypeNames::beforeunload, false, true); load_event_progress_ = kBeforeUnloadEventInProgress; const TimeTicks beforeunload_event_start = CurrentTimeTicks(); dom_window_->DispatchEvent(before_unload_event, this); const TimeTicks beforeunload_event_end = CurrentTimeTicks(); load_event_progress_ = kBeforeUnloadEventCompleted; DEFINE_STATIC_LOCAL( CustomCountHistogram, beforeunload_histogram, ("DocumentEventTiming.BeforeUnloadDuration", 0, 10000000, 50)); beforeunload_histogram.Count( (beforeunload_event_end - beforeunload_event_start).InMicroseconds()); if (!before_unload_event->defaultPrevented()) DefaultEventHandler(before_unload_event); enum BeforeUnloadDialogHistogramEnum { kNoDialogNoText, kNoDialogNoUserGesture, kNoDialogMultipleConfirmationForNavigation, kShowDialog, kDialogEnumMax }; DEFINE_STATIC_LOCAL(EnumerationHistogram, beforeunload_dialog_histogram, ("Document.BeforeUnloadDialog", kDialogEnumMax)); if (before_unload_event->returnValue().IsNull()) { beforeunload_dialog_histogram.Count(kNoDialogNoText); } if (!GetFrame() || before_unload_event->returnValue().IsNull()) return true; if (!GetFrame()->HasBeenActivated()) { beforeunload_dialog_histogram.Count(kNoDialogNoUserGesture); AddConsoleMessage(ConsoleMessage::Create( kInterventionMessageSource, kErrorMessageLevel, "Blocked attempt to show a 'beforeunload' confirmation panel for a " "frame that never had a user gesture since its load. " "https://www.chromestatus.com/feature/5082396709879808")); return true; } if (did_allow_navigation) { beforeunload_dialog_histogram.Count( kNoDialogMultipleConfirmationForNavigation); AddConsoleMessage(ConsoleMessage::Create( kInterventionMessageSource, kErrorMessageLevel, "Blocked attempt to show multiple 'beforeunload' confirmation panels " "for a single navigation.")); return true; } String text = before_unload_event->returnValue(); beforeunload_dialog_histogram.Count( BeforeUnloadDialogHistogramEnum::kShowDialog); if (chrome_client.OpenBeforeUnloadConfirmPanel(text, frame_, is_reload)) { did_allow_navigation = true; return true; } return false; } CWE ID: CWE-285 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; unsigned char* cp = (unsigned char*) cp0; assert((cc%stride)==0); if (cc > stride) { /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; cc -= 3; cp += 3; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cc -= 3; cp += 3; } } else if (stride == 4) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; unsigned int ca = cp[3]; cc -= 4; cp += 4; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cp[3] = (unsigned char) ((ca += cp[3]) & 0xff); cc -= 4; cp += 4; } } else { cc -= stride; do { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + *cp) & 0xff); cp++) cc -= stride; } while (cc>0); } } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void __drop_largest_extent(struct inode *inode, pgoff_t fofs, unsigned int len) { struct extent_info *largest = &F2FS_I(inode)->extent_tree->largest; if (fofs < largest->fofs + largest->len && fofs + len > largest->fofs) { largest->len = 0; f2fs_mark_inode_dirty_sync(inode, true); } } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: std::string ExtensionTtsController::GetMatchingExtensionId( Utterance* utterance) { ExtensionService* service = utterance->profile()->GetExtensionService(); DCHECK(service); ExtensionEventRouter* event_router = utterance->profile()->GetExtensionEventRouter(); DCHECK(event_router); const ExtensionList* extensions = service->extensions(); ExtensionList::const_iterator iter; for (iter = extensions->begin(); iter != extensions->end(); ++iter) { const Extension* extension = *iter; if (!event_router->ExtensionHasEventListener( extension->id(), events::kOnSpeak) || !event_router->ExtensionHasEventListener( extension->id(), events::kOnStop)) { continue; } const std::vector<Extension::TtsVoice>& tts_voices = extension->tts_voices(); for (size_t i = 0; i < tts_voices.size(); ++i) { const Extension::TtsVoice& voice = tts_voices[i]; if (!voice.voice_name.empty() && !utterance->voice_name().empty() && voice.voice_name != utterance->voice_name()) { continue; } if (!voice.locale.empty() && !utterance->locale().empty() && voice.locale != utterance->locale()) { continue; } if (!voice.gender.empty() && !utterance->gender().empty() && voice.gender != utterance->gender()) { continue; } return extension->id(); } } return std::string(); } 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 SeekHead::ParseEntry( IMkvReader* pReader, long long start, long long size_, Entry* pEntry) { if (size_ <= 0) return false; long long pos = start; const long long stop = start + size_; long len; const long long seekIdId = ReadUInt(pReader, pos, len); if (seekIdId != 0x13AB) //SeekID ID return false; if ((pos + len) > stop) return false; pos += len; //consume SeekID id const long long seekIdSize = ReadUInt(pReader, pos, len); if (seekIdSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; //consume size of field if ((pos + seekIdSize) > stop) return false; pEntry->id = ReadUInt(pReader, pos, len); //payload if (pEntry->id <= 0) return false; if (len != seekIdSize) return false; pos += seekIdSize; //consume SeekID payload const long long seekPosId = ReadUInt(pReader, pos, len); if (seekPosId != 0x13AC) //SeekPos ID return false; if ((pos + len) > stop) return false; pos += len; //consume id const long long seekPosSize = ReadUInt(pReader, pos, len); if (seekPosSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; //consume size if ((pos + seekPosSize) > stop) return false; pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); if (pEntry->pos < 0) return false; pos += seekPosSize; //consume payload if (pos != stop) return false; return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->alpha_trait=BlendPixelTrait; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register Quantum *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long Track::GetNext(const BlockEntry* pCurrEntry, const BlockEntry*& pNextEntry) const { assert(pCurrEntry); assert(!pCurrEntry->EOS()); //? const Block* const pCurrBlock = pCurrEntry->GetBlock(); assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number); if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number) return -1; const Cluster* pCluster = pCurrEntry->GetCluster(); assert(pCluster); assert(!pCluster->EOS()); long status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; for (int i = 0;;) { while (pNextEntry) { const Block* const pNextBlock = pNextEntry->GetBlock(); assert(pNextBlock); if (pNextBlock->GetTrackNumber() == m_info.number) return 0; pCurrEntry = pNextEntry; status = pCluster->GetNext(pCurrEntry, pNextEntry); if (status < 0) // error return status; } pCluster = m_pSegment->GetNext(pCluster); if (pCluster == NULL) { pNextEntry = GetEOS(); return 1; } if (pCluster->EOS()) { #if 0 if (m_pSegment->Unparsed() <= 0) //all clusters have been loaded { pNextEntry = GetEOS(); return 1; } #else if (m_pSegment->DoneParsing()) { pNextEntry = GetEOS(); return 1; } #endif pNextEntry = NULL; return E_BUFFER_NOT_FULL; } status = pCluster->GetFirst(pNextEntry); if (status < 0) // error return status; if (pNextEntry == NULL) // empty cluster continue; ++i; if (i >= 100) break; } pNextEntry = GetEOS(); // so we can return a non-NULL value return 1; } 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 LocalFrameClientImpl::NavigateBackForward(int offset) const { WebViewImpl* webview = web_frame_->ViewImpl(); if (!webview->Client()) return false; DCHECK(offset); if (offset > webview->Client()->HistoryForwardListCount()) return false; if (offset < -webview->Client()->HistoryBackListCount()) return false; webview->Client()->NavigateBackForwardSoon(offset); return true; } CWE ID: CWE-254 Target: 1 Example 2: Code: static TT_F26Dot6 Round_To_Double_Grid( EXEC_OPS TT_F26Dot6 distance, TT_F26Dot6 compensation ) { TT_F26Dot6 val; (void)exc; if ( distance >= 0 ) { val = (distance + compensation + 16) & (-32); if ( val < 0 ) val = 0; } else { val = -( (compensation - distance + 16) & (-32) ); if ( val > 0 ) val = 0; } return val; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int blobReadWrite( sqlite3_blob *pBlob, void *z, int n, int iOffset, int (*xCall)(BtCursor*, u32, u32, void*) ){ int rc; Incrblob *p = (Incrblob *)pBlob; Vdbe *v; sqlite3 *db; if( p==0 ) return SQLITE_MISUSE_BKPT; db = p->db; sqlite3_mutex_enter(db->mutex); v = (Vdbe*)p->pStmt; if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){ /* Request is out of range. Return a transient error. */ rc = SQLITE_ERROR; }else if( v==0 ){ /* If there is no statement handle, then the blob-handle has ** already been invalidated. Return SQLITE_ABORT in this case. */ rc = SQLITE_ABORT; }else{ /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is ** returned, clean-up the statement handle. */ assert( db == v->db ); sqlite3BtreeEnterCursor(p->pCsr); #ifdef SQLITE_ENABLE_PREUPDATE_HOOK if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){ /* If a pre-update hook is registered and this is a write cursor, ** invoke it here. ** ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this ** operation should really be an SQLITE_UPDATE. This is probably ** incorrect, but is convenient because at this point the new.* values ** are not easily obtainable. And for the sessions module, an ** SQLITE_UPDATE where the PK columns do not change is handled in the ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually ** slightly more efficient). Since you cannot write to a PK column ** using the incremental-blob API, this works. For the sessions module ** anyhow. */ sqlite3_int64 iKey; iKey = sqlite3BtreeIntegerKey(p->pCsr); sqlite3VdbePreUpdateHook( v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1 ); } #endif rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); sqlite3BtreeLeaveCursor(p->pCsr); if( rc==SQLITE_ABORT ){ sqlite3VdbeFinalize(v); p->pStmt = 0; }else{ v->rc = rc; } } sqlite3Error(db, rc); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WebGL2RenderingContextBase::texSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, MaybeShared<DOMArrayBufferView> pixels, GLuint src_offset) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage3D", "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } TexImageHelperDOMArrayBufferView( kTexSubImage3D, target, level, 0, width, height, depth, 0, format, type, xoffset, yoffset, zoffset, pixels.View(), kNullNotReachable, src_offset); } CWE ID: CWE-125 Target: 1 Example 2: Code: static int hls_close(AVFormatContext *s) { HLSContext *c = s->priv_data; free_playlist_list(c); free_variant_list(c); free_rendition_list(c); av_dict_free(&c->avio_opts); return 0; } CWE ID: CWE-835 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void EnsureInitializeForAndroidLayoutTests() { CHECK(CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)); JNIEnv* env = base::android::AttachCurrentThread(); content::NestedMessagePumpAndroid::RegisterJni(env); content::RegisterNativesImpl(env); bool success = base::MessageLoop::InitMessagePumpForUIFactory( &CreateMessagePumpForUI); CHECK(success) << "Unable to initialize the message pump for Android."; base::FilePath files_dir(GetTestFilesDirectory(env)); base::FilePath stdout_fifo(files_dir.Append(FILE_PATH_LITERAL("test.fifo"))); EnsureCreateFIFO(stdout_fifo); base::FilePath stderr_fifo( files_dir.Append(FILE_PATH_LITERAL("stderr.fifo"))); EnsureCreateFIFO(stderr_fifo); base::FilePath stdin_fifo(files_dir.Append(FILE_PATH_LITERAL("stdin.fifo"))); EnsureCreateFIFO(stdin_fifo); success = base::android::RedirectStream(stdout, stdout_fifo, "w") && base::android::RedirectStream(stdin, stdin_fifo, "r") && base::android::RedirectStream(stderr, stderr_fifo, "w"); CHECK(success) << "Unable to initialize the Android FIFOs."; } 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 void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); if (chown(dest, getuid(), getgid()) < 0) errExit("chown"); if (chmod(dest, S_IRUSR | S_IWUSR) < 0) errExit("chmod"); unlink(src); } CWE ID: CWE-269 Target: 1 Example 2: Code: static TEE_Result get_pbkdf2_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, size_t *derived_key_len, size_t *iteration_count) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 }; uint8_t found = 0; *salt = NULL; *salt_len = *derived_key_len = *iteration_count = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_PBKDF2_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_PBKDF2_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_PBKDF2_ITERATION_COUNT: if (!(found & COUNT)) { *iteration_count = params[n].content.value.a; found |= COUNT; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int init_admin_reserve(void) { unsigned long free_kbytes; free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10); sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13); 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: void WorkerProcessLauncherTest::SetUp() { task_runner_ = new AutoThreadTaskRunner( message_loop_.message_loop_proxy(), base::Bind(&WorkerProcessLauncherTest::QuitMainMessageLoop, base::Unretained(this))); exit_code_ = STILL_ACTIVE; launcher_delegate_.reset(new MockProcessLauncherDelegate()); EXPECT_CALL(*launcher_delegate_, Send(_)) .Times(AnyNumber()) .WillRepeatedly(Return(false)); EXPECT_CALL(*launcher_delegate_, GetExitCode()) .Times(AnyNumber()) .WillRepeatedly(ReturnPointee(&exit_code_)); EXPECT_CALL(*launcher_delegate_, KillProcess(_)) .Times(AnyNumber()) .WillRepeatedly(Invoke(this, &WorkerProcessLauncherTest::KillProcess)); EXPECT_CALL(ipc_delegate_, OnMessageReceived(_)) .Times(AnyNumber()) .WillRepeatedly(Return(false)); } CWE ID: CWE-399 Target: 1 Example 2: Code: lzss_size(struct lzss *lzss) { return lzss->mask + 1; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void shrink_dentry_list(struct list_head *list) { struct dentry *dentry, *parent; while (!list_empty(list)) { struct inode *inode; dentry = list_entry(list->prev, struct dentry, d_lru); spin_lock(&dentry->d_lock); parent = lock_parent(dentry); /* * The dispose list is isolated and dentries are not accounted * to the LRU here, so we can simply remove it from the list * here regardless of whether it is referenced or not. */ d_shrink_del(dentry); /* * We found an inuse dentry which was not removed from * the LRU because of laziness during lookup. Do not free it. */ if (dentry->d_lockref.count > 0) { spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); continue; } if (unlikely(dentry->d_flags & DCACHE_DENTRY_KILLED)) { bool can_free = dentry->d_flags & DCACHE_MAY_FREE; spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); if (can_free) dentry_free(dentry); continue; } inode = dentry->d_inode; if (inode && unlikely(!spin_trylock(&inode->i_lock))) { d_shrink_add(dentry, list); spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); continue; } __dentry_kill(dentry); /* * We need to prune ancestors too. This is necessary to prevent * quadratic behavior of shrink_dcache_parent(), but is also * expected to be beneficial in reducing dentry cache * fragmentation. */ dentry = parent; while (dentry && !lockref_put_or_lock(&dentry->d_lockref)) { parent = lock_parent(dentry); if (dentry->d_lockref.count != 1) { dentry->d_lockref.count--; spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); break; } inode = dentry->d_inode; /* can't be NULL */ if (unlikely(!spin_trylock(&inode->i_lock))) { spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); cpu_relax(); continue; } __dentry_kill(dentry); dentry = parent; } } } 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: static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos, unsigned int *pv) { unsigned int field_type; unsigned int value_count; field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian); value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian); if(value_count!=1) return 0; if(field_type==3) { // SHORT (uint16) *pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian); return 1; } else if(field_type==4) { // LONG (uint32) *pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian); return 1; } return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: bool CWebServer::FindAdminUser() { for (const auto & itt : m_users) { if (itt.userrights == URIGHTS_ADMIN) return true; } return false; } CWE ID: CWE-89 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void VideoCaptureImpl::OnBufferCreated(int32_t buffer_id, mojo::ScopedSharedBufferHandle handle) { DVLOG(1) << __func__ << " buffer_id: " << buffer_id; DCHECK(io_thread_checker_.CalledOnValidThread()); DCHECK(handle.is_valid()); base::SharedMemoryHandle memory_handle; size_t memory_size = 0; bool read_only_flag = false; const MojoResult result = mojo::UnwrapSharedMemoryHandle( std::move(handle), &memory_handle, &memory_size, &read_only_flag); DCHECK_EQ(MOJO_RESULT_OK, result); DCHECK_GT(memory_size, 0u); std::unique_ptr<base::SharedMemory> shm( new base::SharedMemory(memory_handle, true /* read_only */)); if (!shm->Map(memory_size)) { DLOG(ERROR) << "OnBufferCreated: Map failed."; return; } const bool inserted = client_buffers_ .insert(std::make_pair(buffer_id, new ClientBuffer(std::move(shm), memory_size))) .second; DCHECK(inserted); } 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 SeekHead::GetVoidElementCount() const { return m_void_element_count; } CWE ID: CWE-119 Target: 1 Example 2: Code: static struct inode *mqueue_alloc_inode(struct super_block *sb) { struct mqueue_inode_info *ei; ei = kmem_cache_alloc(mqueue_inode_cachep, GFP_KERNEL); if (!ei) return NULL; return &ei->vfs_inode; } 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: get_entry(const void *base, unsigned int offset) { return (struct ipt_entry *)(base + offset); } 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: WebView* RenderViewImpl::createView( WebFrame* creator, const WebURLRequest& request, const WebWindowFeatures& features, const WebString& frame_name, WebNavigationPolicy policy) { if (shared_popup_counter_->data > kMaximumNumberOfUnacknowledgedPopups) return NULL; ViewHostMsg_CreateWindow_Params params; params.opener_id = routing_id_; params.user_gesture = creator->isProcessingUserGesture(); params.window_container_type = WindowFeaturesToContainerType(features); params.session_storage_namespace_id = session_storage_namespace_id_; params.frame_name = frame_name; params.opener_frame_id = creator->identifier(); params.opener_url = creator->document().url(); params.opener_security_origin = creator->document().securityOrigin().toString().utf8(); params.opener_suppressed = creator->willSuppressOpenerInNewFrame(); params.disposition = NavigationPolicyToDisposition(policy); if (!request.isNull()) params.target_url = request.url(); int32 routing_id = MSG_ROUTING_NONE; int32 surface_id = 0; int64 cloned_session_storage_namespace_id; RenderThread::Get()->Send( new ViewHostMsg_CreateWindow(params, &routing_id, &surface_id, &cloned_session_storage_namespace_id)); if (routing_id == MSG_ROUTING_NONE) return NULL; creator->consumeUserGesture(); RenderViewImpl* view = RenderViewImpl::Create( routing_id_, renderer_preferences_, webkit_preferences_, shared_popup_counter_, routing_id, surface_id, cloned_session_storage_namespace_id, frame_name, true, false, 1, screen_info_, accessibility_mode_); view->opened_by_user_gesture_ = params.user_gesture; view->opener_suppressed_ = params.opener_suppressed; view->alternate_error_page_url_ = alternate_error_page_url_; return view->webview(); } CWE ID: Target: 1 Example 2: Code: void DataUseUserData::AttachToFetcher(net::URLFetcher* fetcher, ServiceName service_name) { fetcher->SetURLRequestUserData(kUserDataKey, base::Bind(&Create, service_name)); } 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: EXPORTED int mboxlist_delete(const char *name) { return mboxlist_update_entry(name, NULL, NULL); } 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: int HttpProxyClientSocket::DoReadHeadersComplete(int result) { if (result < 0) return result; if (response_.headers->GetParsedHttpVersion() < HttpVersion(1, 0)) return ERR_TUNNEL_CONNECTION_FAILED; net_log_.AddEvent( NetLog::TYPE_HTTP_TRANSACTION_READ_TUNNEL_RESPONSE_HEADERS, base::Bind(&HttpResponseHeaders::NetLogCallback, response_.headers)); if (proxy_delegate_) { proxy_delegate_->OnTunnelHeadersReceived( HostPortPair::FromURL(request_.url), proxy_server_, *response_.headers); } switch (response_.headers->response_code()) { case 200: // OK if (http_stream_parser_->IsMoreDataBuffered()) return ERR_TUNNEL_CONNECTION_FAILED; next_state_ = STATE_DONE; return OK; case 302: // Found / Moved Temporarily if (is_https_proxy_ && SanitizeProxyRedirect(&response_, request_.url)) { bool is_connection_reused = http_stream_parser_->IsConnectionReused(); redirect_has_load_timing_info_ = transport_->GetLoadTimingInfo( is_connection_reused, &redirect_load_timing_info_); transport_.reset(); http_stream_parser_.reset(); return ERR_HTTPS_PROXY_TUNNEL_RESPONSE; } LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; case 407: // Proxy Authentication Required return HandleProxyAuthChallenge(auth_.get(), &response_, net_log_); default: LogBlockedTunnelResponse(); return ERR_TUNNEL_CONNECTION_FAILED; } } CWE ID: CWE-19 Target: 1 Example 2: Code: int _yr_emit_inst_arg_int16( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, int16_t argument, uint8_t** instruction_addr, int16_t** argument_addr, size_t* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(int16_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(int16_t); return ERROR_SUCCESS; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GLES2DecoderImpl::~GLES2DecoderImpl() { } 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: size_t calculate_camera_metadata_entry_data_size(uint8_t type, size_t data_count) { if (type >= NUM_TYPES) return 0; size_t data_bytes = data_count * camera_metadata_type_size[type]; return data_bytes <= 4 ? 0 : ALIGN_TO(data_bytes, DATA_ALIGNMENT); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0) { struct vcpu_vmx *vmx = to_vmx(vcpu); unsigned long hw_cr0; hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK); if (enable_unrestricted_guest) hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST; else { hw_cr0 |= KVM_VM_CR0_ALWAYS_ON; if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE)) enter_pmode(vcpu); if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE)) enter_rmode(vcpu); } #ifdef CONFIG_X86_64 if (vcpu->arch.efer & EFER_LME) { if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) enter_lmode(vcpu); if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) exit_lmode(vcpu); } #endif if (enable_ept && !enable_unrestricted_guest) ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu); vmcs_writel(CR0_READ_SHADOW, cr0); vmcs_writel(GUEST_CR0, hw_cr0); vcpu->arch.cr0 = cr0; /* depends on vcpu->arch.cr0 to be set to a new value */ vmx->emulation_required = emulation_required(vcpu); } 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 WebSocketJob::OnSentData(SocketStream* socket, int amount_sent) { DCHECK_NE(INITIALIZED, state_); if (state_ == CLOSED) return; if (state_ == CONNECTING) { OnSentHandshakeRequest(socket, amount_sent); return; } if (delegate_) { DCHECK(state_ == OPEN || state_ == CLOSING); DCHECK_GT(amount_sent, 0); DCHECK(current_buffer_); current_buffer_->DidConsume(amount_sent); if (current_buffer_->BytesRemaining() > 0) return; amount_sent = send_frame_handler_->GetOriginalBufferSize(); DCHECK_GT(amount_sent, 0); current_buffer_ = NULL; send_frame_handler_->ReleaseCurrentBuffer(); delegate_->OnSentData(socket, amount_sent); MessageLoopForIO::current()->PostTask( FROM_HERE, NewRunnableMethod(this, &WebSocketJob::SendPending)); } } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void fanout_release(struct sock *sk) { struct packet_sock *po = pkt_sk(sk); struct packet_fanout *f; f = po->fanout; if (!f) return; mutex_lock(&fanout_mutex); po->fanout = NULL; if (atomic_dec_and_test(&f->sk_ref)) { list_del(&f->list); dev_remove_pack(&f->prot_hook); fanout_release_data(f); kfree(f); } mutex_unlock(&fanout_mutex); if (po->rollover) kfree_rcu(po->rollover, rcu); } CWE ID: CWE-416 Target: 1 Example 2: Code: static void do_fault_around(struct vm_area_struct *vma, unsigned long address, pte_t *pte, pgoff_t pgoff, unsigned int flags) { unsigned long start_addr, nr_pages, mask; pgoff_t max_pgoff; struct vm_fault vmf; int off; nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT; mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK; start_addr = max(address & mask, vma->vm_start); off = ((address - start_addr) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1); pte -= off; pgoff -= off; /* * max_pgoff is either end of page table or end of vma * or fault_around_pages() from pgoff, depending what is nearest. */ max_pgoff = pgoff - ((start_addr >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) + PTRS_PER_PTE - 1; max_pgoff = min3(max_pgoff, vma_pages(vma) + vma->vm_pgoff - 1, pgoff + nr_pages - 1); /* Check if it makes any sense to call ->map_pages */ while (!pte_none(*pte)) { if (++pgoff > max_pgoff) return; start_addr += PAGE_SIZE; if (start_addr >= vma->vm_end) return; pte++; } vmf.virtual_address = (void __user *) start_addr; vmf.pte = pte; vmf.pgoff = pgoff; vmf.max_pgoff = max_pgoff; vmf.flags = flags; vma->vm_ops->map_pages(vma, &vmf); } 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: dissect_ac_if_input_terminal(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_, proto_tree *tree, usb_conv_info_t *usb_conv_info _U_) { gint offset_start; offset_start = offset; proto_tree_add_item(tree, hf_ac_if_input_terminalid, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset += 1; proto_tree_add_item(tree, hf_ac_if_input_terminaltype, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_ac_if_input_assocterminal, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset += 1; proto_tree_add_item(tree, hf_ac_if_input_nrchannels, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset += 1; proto_tree_add_item(tree, hf_ac_if_input_channelconfig, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(tree, hf_ac_if_input_channelnames, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset += 1; proto_tree_add_item(tree, hf_ac_if_input_terminal, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset += 1; return offset-offset_start; } 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: PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings( const DictionaryValue& job_settings, const PageRanges& ranges) { #if defined(OS_CHROMEOS) bool landscape = false; if (!job_settings.GetBoolean(kSettingLandscape, &landscape)) return OnError(); settings_.SetOrientation(landscape); settings_.ranges = ranges; return OK; #else DCHECK(!in_print_job_); if (!print_dialog_->UpdateSettings(job_settings, ranges)) return OnError(); return OK; #endif } CWE ID: CWE-399 Target: 1 Example 2: Code: static void perf_event_free_bpf_prog(struct perf_event *event) { struct bpf_prog *prog; perf_event_free_bpf_handler(event); if (!event->tp_event) return; prog = event->tp_event->prog; if (prog) { event->tp_event->prog = NULL; bpf_prog_put(prog); } } 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 unix_notinflight(struct file *fp) { struct sock *s = unix_get_socket(fp); if (s) { struct unix_sock *u = unix_sk(s); spin_lock(&unix_gc_lock); BUG_ON(list_empty(&u->link)); if (atomic_long_dec_and_test(&u->inflight)) list_del_init(&u->link); unix_tot_inflight--; spin_unlock(&unix_gc_lock); } } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int nfc_llcp_send_cc(struct nfc_llcp_sock *sock) { struct nfc_llcp_local *local; struct sk_buff *skb; u8 *miux_tlv = NULL, miux_tlv_length; u8 *rw_tlv = NULL, rw_tlv_length, rw; int err; u16 size = 0; __be16 miux; pr_debug("Sending CC\n"); local = sock->local; if (local == NULL) return -ENODEV; /* If the socket parameters are not set, use the local ones */ miux = be16_to_cpu(sock->miux) > LLCP_MAX_MIUX ? local->miux : sock->miux; rw = sock->rw > LLCP_MAX_RW ? local->rw : sock->rw; miux_tlv = nfc_llcp_build_tlv(LLCP_TLV_MIUX, (u8 *)&miux, 0, &miux_tlv_length); size += miux_tlv_length; rw_tlv = nfc_llcp_build_tlv(LLCP_TLV_RW, &rw, 0, &rw_tlv_length); size += rw_tlv_length; skb = llcp_allocate_pdu(sock, LLCP_PDU_CC, size); if (skb == NULL) { err = -ENOMEM; goto error_tlv; } llcp_add_tlv(skb, miux_tlv, miux_tlv_length); llcp_add_tlv(skb, rw_tlv, rw_tlv_length); skb_queue_tail(&local->tx_queue, skb); err = 0; error_tlv: if (err) pr_err("error %d\n", err); kfree(miux_tlv); kfree(rw_tlv); return err; } CWE ID: CWE-476 Target: 1 Example 2: Code: void local_flush_tlb_one(unsigned long asid, unsigned long page) { unsigned long long match, pteh=0, lpage; unsigned long tlb; /* * Sign-extend based on neff. */ lpage = neff_sign_extend(page); match = (asid << PTEH_ASID_SHIFT) | PTEH_VALID; match |= lpage; for_each_itlb_entry(tlb) { asm volatile ("getcfg %1, 0, %0" : "=r" (pteh) : "r" (tlb) ); if (pteh == match) { __flush_tlb_slot(tlb); break; } } for_each_dtlb_entry(tlb) { asm volatile ("getcfg %1, 0, %0" : "=r" (pteh) : "r" (tlb) ); if (pteh == match) { __flush_tlb_slot(tlb); 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 void key_search_validate(struct extent_buffer *b, struct btrfs_key *key, int level) { #ifdef CONFIG_BTRFS_ASSERT struct btrfs_disk_key disk_key; btrfs_cpu_key_to_disk(&disk_key, key); if (level == 0) ASSERT(!memcmp_extent_buffer(b, &disk_key, offsetof(struct btrfs_leaf, items[0].key), sizeof(disk_key))); else ASSERT(!memcmp_extent_buffer(b, &disk_key, offsetof(struct btrfs_node, ptrs[0].key), sizeof(disk_key))); #endif } CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace) { if (paintingDisabled()) return; notImplemented(); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void addEventListenerMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "addEventListener", "TestObjectPython", info.Holder(), info.GetIsolate()); EventTarget* impl = V8TestObjectPython::toNative(info.Holder()); if (DOMWindow* window = impl->toDOMWindow()) { if (!BindingSecurity::shouldAllowAccessToFrame(info.GetIsolate(), window->frame(), exceptionState)) { exceptionState.throwIfNeeded(); return; } if (!window->document()) return; } RefPtr<EventListener> listener = V8EventListenerList::getEventListener(info[1], false, ListenerFindOrCreate); if (listener) { V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<WithNullCheck>, eventName, info[0]); impl->addEventListener(eventName, listener, info[2]->BooleanValue()); if (!impl->toNode()) addHiddenValueToArray(info.Holder(), info[1], V8TestObjectPython::eventListenerCacheIndex, info.GetIsolate()); } } 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: Tracks::~Tracks() { Track** i = m_trackEntries; Track** const j = m_trackEntriesEnd; while (i != j) { Track* const pTrack = *i++; delete pTrack; } delete[] m_trackEntries; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int hfsplus_rename_cat(u32 cnid, struct inode *src_dir, struct qstr *src_name, struct inode *dst_dir, struct qstr *dst_name) { struct super_block *sb = src_dir->i_sb; struct hfs_find_data src_fd, dst_fd; hfsplus_cat_entry entry; int entry_size, type; int err; dprint(DBG_CAT_MOD, "rename_cat: %u - %lu,%s - %lu,%s\n", cnid, src_dir->i_ino, src_name->name, dst_dir->i_ino, dst_name->name); err = hfs_find_init(HFSPLUS_SB(sb)->cat_tree, &src_fd); if (err) return err; dst_fd = src_fd; /* find the old dir entry and read the data */ hfsplus_cat_build_key(sb, src_fd.search_key, src_dir->i_ino, src_name); err = hfs_brec_find(&src_fd); if (err) goto out; hfs_bnode_read(src_fd.bnode, &entry, src_fd.entryoffset, src_fd.entrylength); /* create new dir entry with the data from the old entry */ hfsplus_cat_build_key(sb, dst_fd.search_key, dst_dir->i_ino, dst_name); err = hfs_brec_find(&dst_fd); if (err != -ENOENT) { if (!err) err = -EEXIST; goto out; } err = hfs_brec_insert(&dst_fd, &entry, src_fd.entrylength); if (err) goto out; dst_dir->i_size++; dst_dir->i_mtime = dst_dir->i_ctime = CURRENT_TIME_SEC; /* finally remove the old entry */ hfsplus_cat_build_key(sb, src_fd.search_key, src_dir->i_ino, src_name); err = hfs_brec_find(&src_fd); if (err) goto out; err = hfs_brec_remove(&src_fd); if (err) goto out; src_dir->i_size--; src_dir->i_mtime = src_dir->i_ctime = CURRENT_TIME_SEC; /* remove old thread entry */ hfsplus_cat_build_key(sb, src_fd.search_key, cnid, NULL); err = hfs_brec_find(&src_fd); if (err) goto out; type = hfs_bnode_read_u16(src_fd.bnode, src_fd.entryoffset); err = hfs_brec_remove(&src_fd); if (err) goto out; /* create new thread entry */ hfsplus_cat_build_key(sb, dst_fd.search_key, cnid, NULL); entry_size = hfsplus_fill_cat_thread(sb, &entry, type, dst_dir->i_ino, dst_name); err = hfs_brec_find(&dst_fd); if (err != -ENOENT) { if (!err) err = -EEXIST; goto out; } err = hfs_brec_insert(&dst_fd, &entry, entry_size); hfsplus_mark_inode_dirty(dst_dir, HFSPLUS_I_CAT_DIRTY); hfsplus_mark_inode_dirty(src_dir, HFSPLUS_I_CAT_DIRTY); out: hfs_bnode_put(dst_fd.bnode); hfs_find_exit(&src_fd); return err; } CWE ID: CWE-264 Target: 1 Example 2: Code: DevToolsAgentHost::List GetBrowserAgentHosts() { DevToolsAgentHost::List result; for (const auto& id_host : g_devtools_instances.Get()) { if (id_host.second->GetType() == DevToolsAgentHost::kTypeBrowser) result.push_back(id_host.second); } return result; } 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: cf2_hint_isLocked( const CF2_Hint hint ) { return (FT_Bool)( ( hint->flags & CF2_Locked ) != 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: PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encoderow != NULL); /* XXX horizontal differencing alters user's data XXX */ (*sp->encodepfunc)(tif, bp, cc); return (*sp->encoderow)(tif, bp, cc, s); } CWE ID: CWE-119 Target: 1 Example 2: Code: int cap_file_mmap(struct file *file, unsigned long reqprot, unsigned long prot, unsigned long flags, unsigned long addr, unsigned long addr_only) { int ret = 0; if (addr < dac_mmap_min_addr) { ret = cap_capable(current_cred(), &init_user_ns, CAP_SYS_RAWIO, SECURITY_CAP_AUDIT); /* set PF_SUPERPRIV if it turns out we allow the low mmap */ if (ret == 0) current->flags |= PF_SUPERPRIV; } return ret; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: read_png(FILE *fp) { png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0); png_infop info_ptr = NULL; png_bytep row = NULL, display = NULL; if (png_ptr == NULL) return 0; if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); if (row != NULL) free(row); if (display != NULL) free(display); return 0; } png_init_io(png_ptr, fp); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0); png_read_info(png_ptr, info_ptr); { png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); row = malloc(rowbytes); display = malloc(rowbytes); if (row == NULL || display == NULL) png_error(png_ptr, "OOM allocating row buffers"); { png_uint_32 height = png_get_image_height(png_ptr, info_ptr); int passes = png_set_interlace_handling(png_ptr); int pass; png_start_read_image(png_ptr); for (pass = 0; pass < passes; ++pass) { png_uint_32 y = height; /* NOTE: this trashes the row each time; interlace handling won't * work, but this avoids memory thrashing for speed testing. */ while (y-- > 0) png_read_row(png_ptr, row, display); } } } /* Make sure to read to the end of the file: */ png_read_end(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); free(row); free(display); return 1; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int CIFSFindNext(const int xid, struct cifs_tcon *tcon, __u16 searchHandle, struct cifs_search_info *psrch_inf) { TRANSACTION2_FNEXT_REQ *pSMB = NULL; TRANSACTION2_FNEXT_RSP *pSMBr = NULL; T2_FNEXT_RSP_PARMS *parms; char *response_data; int rc = 0; int bytes_returned, name_len; __u16 params, byte_count; cFYI(1, "In FindNext"); if (psrch_inf->endOfSearch) return -ENOENT; rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB, (void **) &pSMBr); if (rc) return rc; params = 14; /* includes 2 bytes of null string, converted to LE below*/ byte_count = 0; pSMB->TotalDataCount = 0; /* no EAs */ pSMB->MaxParameterCount = cpu_to_le16(8); pSMB->MaxDataCount = cpu_to_le16((tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE) & 0xFFFFFF00); pSMB->MaxSetupCount = 0; pSMB->Reserved = 0; pSMB->Flags = 0; pSMB->Timeout = 0; pSMB->Reserved2 = 0; pSMB->ParameterOffset = cpu_to_le16( offsetof(struct smb_com_transaction2_fnext_req,SearchHandle) - 4); pSMB->DataCount = 0; pSMB->DataOffset = 0; pSMB->SetupCount = 1; pSMB->Reserved3 = 0; pSMB->SubCommand = cpu_to_le16(TRANS2_FIND_NEXT); pSMB->SearchHandle = searchHandle; /* always kept as le */ pSMB->SearchCount = cpu_to_le16(CIFSMaxBufSize / sizeof(FILE_UNIX_INFO)); pSMB->InformationLevel = cpu_to_le16(psrch_inf->info_level); pSMB->ResumeKey = psrch_inf->resume_key; pSMB->SearchFlags = cpu_to_le16(CIFS_SEARCH_CLOSE_AT_END | CIFS_SEARCH_RETURN_RESUME); name_len = psrch_inf->resume_name_len; params += name_len; if (name_len < PATH_MAX) { memcpy(pSMB->ResumeFileName, psrch_inf->presume_name, name_len); byte_count += name_len; /* 14 byte parm len above enough for 2 byte null terminator */ pSMB->ResumeFileName[name_len] = 0; pSMB->ResumeFileName[name_len+1] = 0; } else { rc = -EINVAL; goto FNext2_err_exit; } byte_count = params + 1 /* pad */ ; pSMB->TotalParameterCount = cpu_to_le16(params); pSMB->ParameterCount = pSMB->TotalParameterCount; inc_rfc1001_len(pSMB, byte_count); pSMB->ByteCount = cpu_to_le16(byte_count); rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB, (struct smb_hdr *) pSMBr, &bytes_returned, 0); cifs_stats_inc(&tcon->num_fnext); if (rc) { if (rc == -EBADF) { psrch_inf->endOfSearch = true; cifs_buf_release(pSMB); rc = 0; /* search probably was closed at end of search*/ } else cFYI(1, "FindNext returned = %d", rc); } else { /* decode response */ rc = validate_t2((struct smb_t2_rsp *)pSMBr); if (rc == 0) { unsigned int lnoff; /* BB fixme add lock for file (srch_info) struct here */ if (pSMBr->hdr.Flags2 & SMBFLG2_UNICODE) psrch_inf->unicode = true; else psrch_inf->unicode = false; response_data = (char *) &pSMBr->hdr.Protocol + le16_to_cpu(pSMBr->t2.ParameterOffset); parms = (T2_FNEXT_RSP_PARMS *)response_data; response_data = (char *)&pSMBr->hdr.Protocol + le16_to_cpu(pSMBr->t2.DataOffset); if (psrch_inf->smallBuf) cifs_small_buf_release( psrch_inf->ntwrk_buf_start); else cifs_buf_release(psrch_inf->ntwrk_buf_start); psrch_inf->srch_entries_start = response_data; psrch_inf->ntwrk_buf_start = (char *)pSMB; psrch_inf->smallBuf = 0; if (parms->EndofSearch) psrch_inf->endOfSearch = true; else psrch_inf->endOfSearch = false; psrch_inf->entries_in_buffer = le16_to_cpu(parms->SearchCount); psrch_inf->index_of_last_entry += psrch_inf->entries_in_buffer; lnoff = le16_to_cpu(parms->LastNameOffset); if (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE < lnoff) { cERROR(1, "ignoring corrupt resume name"); psrch_inf->last_entry = NULL; return rc; } else psrch_inf->last_entry = psrch_inf->srch_entries_start + lnoff; /* cFYI(1, "fnxt2 entries in buf %d index_of_last %d", psrch_inf->entries_in_buffer, psrch_inf->index_of_last_entry); */ /* BB fixme add unlock here */ } } /* BB On error, should we leave previous search buf (and count and last entry fields) intact or free the previous one? */ /* Note: On -EAGAIN error only caller can retry on handle based calls since file handle passed in no longer valid */ FNext2_err_exit: if (rc != 0) cifs_buf_release(pSMB); return rc; } CWE ID: CWE-189 Target: 1 Example 2: Code: static u64 ept_rsvd_mask(u64 spte, int level) { int i; u64 mask = 0; for (i = 51; i > boot_cpu_data.x86_phys_bits; i--) mask |= (1ULL << i); if (level > 2) /* bits 7:3 reserved */ mask |= 0xf8; else if (level == 2) { if (spte & (1ULL << 7)) /* 2MB ref, bits 20:12 reserved */ mask |= 0x1ff000; else /* bits 6:3 reserved */ mask |= 0x78; } return mask; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int BrowserWindowGtk::GetXPositionOfLocationIcon(GtkWidget* relative_to) { GtkWidget* location_icon = toolbar_->GetLocationBarView()-> location_icon_widget(); GtkAllocation location_icon_allocation; gtk_widget_get_allocation(location_icon, &location_icon_allocation); int x = 0; gtk_widget_translate_coordinates( location_icon, relative_to, (location_icon_allocation.width + 1) / 2, 0, &x, NULL); if (!gtk_widget_get_has_window(relative_to)) { GtkAllocation allocation; gtk_widget_get_allocation(relative_to, &allocation); x += allocation.x; } return x; } 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: int test_mod_exp(BIO *bp, BN_CTX *ctx) { BIGNUM *a, *b, *c, *d, *e; int i; a = BN_new(); b = BN_new(); c = BN_new(); d = BN_new(); e = BN_new(); BN_one(a); BN_one(b); BN_zero(c); if (BN_mod_exp(d, a, b, c, ctx)) { fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n"); return 0; } BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */ for (i = 0; i < num2; i++) { BN_bntest_rand(a, 20 + i * 5, 0, 0); BN_bntest_rand(b, 2 + i, 0, 0); if (!BN_mod_exp(d, a, b, c, ctx)) return (0); if (bp != NULL) { if (!results) { BN_print(bp, a); BIO_puts(bp, " ^ "); BN_print(bp, b); BIO_puts(bp, " % "); BN_print(bp, c); BIO_puts(bp, " - "); } BN_print(bp, d); BIO_puts(bp, "\n"); } BN_exp(e, a, b, ctx); BN_sub(e, e, d); BN_div(a, b, e, c, ctx); if (!BN_is_zero(b)) { fprintf(stderr, "Modulo exponentiation test failed!\n"); return 0; } } BN_free(a); BN_free(b); BN_free(c); BN_zero(c); if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) { fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus " "succeeded\n"); return 0; } BN_set_word(c, 16); if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) { fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus " "succeeded\n"); return 0; } BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */ for (i = 0; i < num2; i++) { BN_bntest_rand(a, 20 + i * 5, 0, 0); BN_bntest_rand(b, 2 + i, 0, 0); if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) return (00); if (bp != NULL) { if (!results) { BN_print(bp, a); BIO_puts(bp, " ^ "); BN_print(bp, b); BIO_puts(bp, " % "); BN_print(bp, c); BIO_puts(bp, " - "); } BN_print(bp, d); BIO_puts(bp, "\n"); } BN_exp(e, a, b, ctx); BN_sub(e, e, d); BN_div(a, b, e, c, ctx); if (!BN_is_zero(b)) { fprintf(stderr, "Modulo exponentiation test failed!\n"); return 0; } } BN_free(a); BN_free(b); BN_free(c); BN_free(d); BN_free(e); return (1); } CWE ID: CWE-200 Target: 1 Example 2: Code: static void read_exception(struct pstore *ps, uint32_t index, struct core_exception *result) { struct disk_exception *de = get_exception(ps, index); /* copy it */ result->old_chunk = le64_to_cpu(de->old_chunk); result->new_chunk = le64_to_cpu(de->new_chunk); } 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 ValidateRenderFrameId(int render_process_id, int render_frame_id, const base::Callback<void(bool)>& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); const bool frame_exists = !!RenderFrameHost::FromID(render_process_id, render_frame_id); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(callback, frame_exists)); } 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: TabStyle::TabColors GM2TabStyle::CalculateColors() const { const ui::ThemeProvider* theme_provider = tab_->GetThemeProvider(); constexpr float kMinimumActiveContrastRatio = 6.05f; constexpr float kMinimumInactiveContrastRatio = 4.61f; constexpr float kMinimumHoveredContrastRatio = 5.02f; constexpr float kMinimumPressedContrastRatio = 4.41f; float expected_opacity = 0.0f; if (tab_->IsActive()) { expected_opacity = 1.0f; } else if (tab_->IsSelected()) { expected_opacity = kSelectedTabOpacity; } else if (tab_->mouse_hovered()) { expected_opacity = GetHoverOpacity(); } const SkColor bg_color = color_utils::AlphaBlend( tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE), tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE), expected_opacity); SkColor title_color = tab_->controller()->GetTabForegroundColor( expected_opacity > 0.5f ? TAB_ACTIVE : TAB_INACTIVE, bg_color); title_color = color_utils::GetColorWithMinimumContrast(title_color, bg_color); const SkColor base_hovered_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_HOVER); const SkColor base_pressed_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_PRESSED); const auto get_color_for_contrast_ratio = [](SkColor fg_color, SkColor bg_color, float contrast_ratio) { const SkAlpha blend_alpha = color_utils::GetBlendValueWithMinimumContrast( bg_color, fg_color, bg_color, contrast_ratio); return color_utils::AlphaBlend(fg_color, bg_color, blend_alpha); }; const SkColor generated_icon_color = get_color_for_contrast_ratio( title_color, bg_color, tab_->IsActive() ? kMinimumActiveContrastRatio : kMinimumInactiveContrastRatio); const SkColor generated_hovered_color = get_color_for_contrast_ratio( base_hovered_color, bg_color, kMinimumHoveredContrastRatio); const SkColor generated_pressed_color = get_color_for_contrast_ratio( base_pressed_color, bg_color, kMinimumPressedContrastRatio); const SkColor generated_hovered_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_hovered_color); const SkColor generated_pressed_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_pressed_color); return {bg_color, title_color, generated_icon_color, generated_hovered_icon_color, generated_pressed_icon_color, generated_hovered_color, generated_pressed_color}; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int slab_unmergeable(struct kmem_cache *s) { if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE)) return 1; if (s->ctor) return 1; /* * We may have set a slab to be unmergeable during bootstrap. */ if (s->refcount < 0) return 1; 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: static void shm_close(struct vm_area_struct *vma) { struct file * file = vma->vm_file; struct shm_file_data *sfd = shm_file_data(file); struct shmid_kernel *shp; struct ipc_namespace *ns = sfd->ns; down_write(&shm_ids(ns).rwsem); /* remove from the list of attaches of the shm segment */ shp = shm_lock(ns, sfd->id); BUG_ON(IS_ERR(shp)); shp->shm_lprid = task_tgid_vnr(current); shp->shm_dtim = get_seconds(); shp->shm_nattch--; if (shm_may_destroy(ns, shp)) shm_destroy(ns, shp); else shm_unlock(shp); up_write(&shm_ids(ns).rwsem); } 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: PHP_FUNCTION(mcrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; unsigned char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mcrypt_generic(pm->td, data_s, data_size); data_s[data_size] = '\0'; RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); } CWE ID: CWE-190 Target: 1 Example 2: Code: static int dib7070_tuner_reset(struct dvb_frontend *fe, int onoff) { struct dvb_usb_adapter *adap = fe->dvb->priv; struct dib0700_adapter_state *state = adap->priv; return state->dib7000p_ops.set_gpio(fe, 8, 0, !onoff); } 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: DialogOverlayString::DialogOverlayString() {} 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 GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased) { if (paintingDisabled()) return; if (numPoints <= 1) return; } CWE ID: CWE-399 Target: 1 Example 2: Code: void fuse_put_request(struct fuse_conn *fc, struct fuse_req *req) { if (atomic_dec_and_test(&req->count)) { if (req->waiting) atomic_dec(&fc->num_waiting); if (req->stolen_file) put_reserved_req(fc, req); else fuse_request_free(req); } } 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: X11SurfaceFactory::GetAllowedGLImplementations() { std::vector<gl::GLImplementation> impls; impls.push_back(gl::kGLImplementationEGLGLES2); impls.push_back(gl::kGLImplementationDesktopGL); impls.push_back(gl::kGLImplementationOSMesaGL); return impls; } 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: read_one_file(Image *image) { if (!(image->opts & READ_FILE) || (image->opts & USE_STDIO)) { /* memory or stdio. */ FILE *f = fopen(image->file_name, "rb"); if (f != NULL) { if (image->opts & READ_FILE) image->input_file = f; else /* memory */ { if (fseek(f, 0, SEEK_END) == 0) { long int cb = ftell(f); if (cb > 0 && (unsigned long int)cb < (size_t)~(size_t)0) { png_bytep b = voidcast(png_bytep, malloc((size_t)cb)); if (b != NULL) { rewind(f); if (fread(b, (size_t)cb, 1, f) == 1) { fclose(f); image->input_memory_size = cb; image->input_memory = b; } else { free(b); return logclose(image, f, image->file_name, ": read failed: "); } } else return logclose(image, f, image->file_name, ": out of memory: "); } else if (cb == 0) return logclose(image, f, image->file_name, ": zero length: "); else return logclose(image, f, image->file_name, ": tell failed: "); } else return logclose(image, f, image->file_name, ": seek failed: "); } } else return logerror(image, image->file_name, ": open failed: ", strerror(errno)); } return read_file(image, FORMAT_NO_CHANGE, NULL); } CWE ID: Target: 1 Example 2: Code: static int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb, struct tipc_sock *tsk) { int err; void *hdr; struct nlattr *attrs; struct net *net = sock_net(skb->sk); struct tipc_net *tn = net_generic(net, tipc_net_id); hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, &tipc_genl_family, NLM_F_MULTI, TIPC_NL_SOCK_GET); if (!hdr) goto msg_cancel; attrs = nla_nest_start(skb, TIPC_NLA_SOCK); if (!attrs) goto genlmsg_cancel; if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->portid)) goto attr_msg_cancel; if (nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tn->own_addr)) goto attr_msg_cancel; if (tsk->connected) { err = __tipc_nl_add_sk_con(skb, tsk); if (err) goto attr_msg_cancel; } else if (!list_empty(&tsk->publications)) { if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL)) goto attr_msg_cancel; } nla_nest_end(skb, attrs); genlmsg_end(skb, hdr); return 0; attr_msg_cancel: nla_nest_cancel(skb, attrs); genlmsg_cancel: genlmsg_cancel(skb, hdr); msg_cancel: return -EMSGSIZE; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewImpl::DidInitiatePaint() { pepper_helper_->ViewInitiatedPaint(); } 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: load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, char immediate_load) { static const int intoffset[] = { 0, 4, 2, 1 }; static const int intjump[] = { 8, 8, 4, 2 }; int rc; DATA32 *ptr; GifFileType *gif; GifRowType *rows; GifRecordType rec; ColorMapObject *cmap; int i, j, done, bg, r, g, b, w = 0, h = 0; float per = 0.0, per_inc; int last_per = 0, last_y = 0; int transp; int fd; done = 0; rows = NULL; transp = -1; /* if immediate_load is 1, then dont delay image laoding as below, or */ /* already data in this image - dont load it again */ if (im->data) return 0; fd = open(im->real_file, O_RDONLY); if (fd < 0) return 0; #if GIFLIB_MAJOR >= 5 gif = DGifOpenFileHandle(fd, NULL); #else gif = DGifOpenFileHandle(fd); #endif if (!gif) { close(fd); return 0; } rc = 0; /* Failure */ do { if (DGifGetRecordType(gif, &rec) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) { if (DGifGetImageDesc(gif) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; break; } w = gif->Image.Width; h = gif->Image.Height; if (!IMAGE_DIMENSIONS_OK(w, h)) goto quit2; rows = calloc(h, sizeof(GifRowType *)); if (!rows) goto quit2; for (i = 0; i < h; i++) { rows[i] = calloc(w, sizeof(GifPixelType)); if (!rows[i]) goto quit; } if (gif->Image.Interlace) { for (i = 0; i < 4; i++) { for (j = intoffset[i]; j < h; j += intjump[i]) { DGifGetLine(gif, rows[j], w); } } } else { for (i = 0; i < h; i++) { DGifGetLine(gif, rows[i], w); } } done = 1; } else if (rec == EXTENSION_RECORD_TYPE) { int ext_code; GifByteType *ext; ext = NULL; DGifGetExtension(gif, &ext_code, &ext); while (ext) { if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) { transp = (int)ext[4]; } ext = NULL; DGifGetExtensionNext(gif, &ext); } } } while (rec != TERMINATE_RECORD_TYPE); if (transp >= 0) { SET_FLAG(im->flags, F_HAS_ALPHA); } else { UNSET_FLAG(im->flags, F_HAS_ALPHA); } if (!rows) { goto quit2; } /* set the format string member to the lower-case full extension */ /* name for the format - so example names would be: */ /* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */ im->w = w; im->h = h; if (!im->format) im->format = strdup("gif"); if (im->loader || immediate_load || progress) { bg = gif->SBackGroundColor; cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap); im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h); if (!im->data) goto quit; { r = cmap->Colors[bg].Red; g = cmap->Colors[bg].Green; b = cmap->Colors[bg].Blue; *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; { for (j = 0; j < w; j++) { if (rows[i][j] == transp) { r = cmap->Colors[bg].Red; g = cmap->Colors[bg].Green; b = cmap->Colors[bg].Blue; *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; } per += per_inc; if (progress && (((int)per) != last_per) && (((int)per) % progress_granularity == 0)) { rc = 2; goto quit; } last_y = i; } } } finish: if (progress) progress(im, 100, 0, last_y, w, h); } rc = 1; /* Success */ quit: for (i = 0; i < h; i++) free(rows[i]); free(rows); quit2: #if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1) DGifCloseFile(gif, NULL); #else DGifCloseFile(gif); #endif return rc; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool WebViewTest::TapElement(WebInputEvent::Type type, Element* element) { if (!element || !element->GetLayoutObject()) return false; DCHECK(web_view_helper_.GetWebView()); element->scrollIntoViewIfNeeded(); IntPoint center = web_view_helper_.GetWebView() ->MainFrameImpl() ->GetFrameView() ->ContentsToScreen( element->GetLayoutObject()->AbsoluteBoundingBoxRect()) .Center(); WebGestureEvent event(type, WebInputEvent::kNoModifiers, WebInputEvent::kTimeStampForTesting); event.source_device = kWebGestureDeviceTouchscreen; event.x = center.X(); event.y = center.Y(); web_view_helper_.GetWebView()->HandleInputEvent( WebCoalescedInputEvent(event)); RunPendingTasks(); return true; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void v9fs_walk(void *opaque) { int name_idx; V9fsFidState *newfidp = NULL; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames); if (err < 0) { pdu_complete(pdu, err); return ; } V9fsFidState *newfidp = NULL; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames); if (err < 0) { for (i = 0; i < nwnames; i++) { err = pdu_unmarshal(pdu, offset, "s", &wnames[i]); if (err < 0) { goto out_nofid; } if (name_is_illegal(wnames[i].data)) { err = -ENOENT; goto out_nofid; } offset += err; } } else if (nwnames > P9_MAXWELEM) { err = -EINVAL; goto out_nofid; } fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -ENOENT; goto out_nofid; } v9fs_path_init(&dpath); v9fs_path_init(&path); /* * Both dpath and path initially poin to fidp. * Needed to handle request with nwnames == 0 */ v9fs_path_copy(&dpath, &fidp->path); err = -ENOENT; goto out_nofid; } CWE ID: CWE-22 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool PasswordAutofillAgent::TryToShowTouchToFill( const WebFormControlElement& control_element) { const WebInputElement* element = ToWebInputElement(&control_element); if (!element || (!base::Contains(web_input_to_password_info_, *element) && !base::Contains(password_to_username_, *element))) { return false; } if (was_touch_to_fill_ui_shown_) return false; was_touch_to_fill_ui_shown_ = true; GetPasswordManagerDriver()->ShowTouchToFill(); return true; } CWE ID: CWE-125 Target: 1 Example 2: Code: int kvm_ioapic_set_irq(struct kvm_ioapic *ioapic, int irq, int irq_source_id, int level) { u32 old_irr; u32 mask = 1 << irq; union kvm_ioapic_redirect_entry entry; int ret, irq_level; BUG_ON(irq < 0 || irq >= IOAPIC_NUM_PINS); spin_lock(&ioapic->lock); old_irr = ioapic->irr; irq_level = __kvm_irq_line_state(&ioapic->irq_states[irq], irq_source_id, level); entry = ioapic->redirtbl[irq]; irq_level ^= entry.fields.polarity; if (!irq_level) { ioapic->irr &= ~mask; ret = 1; } else { int edge = (entry.fields.trig_mode == IOAPIC_EDGE_TRIG); ioapic->irr |= mask; if ((edge && old_irr != ioapic->irr) || (!edge && !entry.fields.remote_irr)) ret = ioapic_service(ioapic, irq); else ret = 0; /* report coalesced interrupt */ } trace_kvm_ioapic_set_irq(entry.bits, irq, ret == 0); spin_unlock(&ioapic->lock); return ret; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void aesni_gcm_enc_avx2(void *ctx, u8 *out, const u8 *in, unsigned long plaintext_len, u8 *iv, u8 *hash_subkey, const u8 *aad, unsigned long aad_len, u8 *auth_tag, unsigned long auth_tag_len) { if (plaintext_len < AVX_GEN2_OPTSIZE) { aesni_gcm_enc(ctx, out, in, plaintext_len, iv, hash_subkey, aad, aad_len, auth_tag, auth_tag_len); } else if (plaintext_len < AVX_GEN4_OPTSIZE) { aesni_gcm_precomp_avx_gen2(ctx, hash_subkey); aesni_gcm_enc_avx_gen2(ctx, out, in, plaintext_len, iv, aad, aad_len, auth_tag, auth_tag_len); } else { aesni_gcm_precomp_avx_gen4(ctx, hash_subkey); aesni_gcm_enc_avx_gen4(ctx, out, in, plaintext_len, iv, aad, aad_len, auth_tag, auth_tag_len); } } 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: const char* WinPKIErrorString(void) { static char error_string[64]; DWORD error_code = GetLastError(); if ((error_code >> 16) != 0x8009) return WindowsErrorString(); switch (error_code) { case NTE_BAD_UID: return "Bad UID."; case CRYPT_E_MSG_ERROR: return "An error occurred while performing an operation on a cryptographic message."; case CRYPT_E_UNKNOWN_ALGO: return "Unknown cryptographic algorithm."; case CRYPT_E_INVALID_MSG_TYPE: return "Invalid cryptographic message type."; case CRYPT_E_HASH_VALUE: return "The hash value is not correct"; case CRYPT_E_ISSUER_SERIALNUMBER: return "Invalid issuer and/or serial number."; case CRYPT_E_BAD_LEN: return "The length specified for the output data was insufficient."; case CRYPT_E_BAD_ENCODE: return "An error occurred during encode or decode operation."; case CRYPT_E_FILE_ERROR: return "An error occurred while reading or writing to a file."; case CRYPT_E_NOT_FOUND: return "Cannot find object or property."; case CRYPT_E_EXISTS: return "The object or property already exists."; case CRYPT_E_NO_PROVIDER: return "No provider was specified for the store or object."; case CRYPT_E_DELETED_PREV: return "The previous certificate or CRL context was deleted."; case CRYPT_E_NO_MATCH: return "Cannot find the requested object."; case CRYPT_E_UNEXPECTED_MSG_TYPE: case CRYPT_E_NO_KEY_PROPERTY: case CRYPT_E_NO_DECRYPT_CERT: return "Private key or certificate issue"; case CRYPT_E_BAD_MSG: return "Not a cryptographic message."; case CRYPT_E_NO_SIGNER: return "The signed cryptographic message does not have a signer for the specified signer index."; case CRYPT_E_REVOKED: return "The certificate is revoked."; case CRYPT_E_NO_REVOCATION_DLL: case CRYPT_E_NO_REVOCATION_CHECK: case CRYPT_E_REVOCATION_OFFLINE: case CRYPT_E_NOT_IN_REVOCATION_DATABASE: return "Cannot check certificate revocation."; case CRYPT_E_INVALID_NUMERIC_STRING: case CRYPT_E_INVALID_PRINTABLE_STRING: case CRYPT_E_INVALID_IA5_STRING: case CRYPT_E_INVALID_X500_STRING: case CRYPT_E_NOT_CHAR_STRING: return "Invalid string."; case CRYPT_E_SECURITY_SETTINGS: return "The cryptographic operation failed due to a local security option setting."; case CRYPT_E_NO_VERIFY_USAGE_CHECK: case CRYPT_E_VERIFY_USAGE_OFFLINE: return "Cannot complete usage check."; case CRYPT_E_NO_TRUSTED_SIGNER: return "None of the signers of the cryptographic message or certificate trust list is trusted."; default: static_sprintf(error_string, "Unknown PKI error 0x%08lX", error_code); return error_string; } } CWE ID: CWE-494 Target: 1 Example 2: Code: static void mptsas_free_request(MPTSASRequest *req) { MPTSASState *s = req->dev; if (req->sreq != NULL) { req->sreq->hba_private = NULL; scsi_req_unref(req->sreq); req->sreq = NULL; QTAILQ_REMOVE(&s->pending, req, next); } qemu_sglist_destroy(&req->qsg); g_free(req); } 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: archive_acl_add_entry(struct archive_acl *acl, int type, int permset, int tag, int id, const char *name) { struct archive_acl_entry *ap; if (acl_special(acl, type, permset, tag) == 0) return ARCHIVE_OK; ap = acl_new_entry(acl, type, permset, tag, id); if (ap == NULL) { /* XXX Error XXX */ return ARCHIVE_FAILED; } if (name != NULL && *name != '\0') archive_mstring_copy_mbs(&ap->name, name); else archive_mstring_clean(&ap->name); return ARCHIVE_OK; } 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: TransformPaintPropertyNode* TransformPaintPropertyNode::Root() { DEFINE_STATIC_REF( TransformPaintPropertyNode, root, base::AdoptRef(new TransformPaintPropertyNode( nullptr, State{TransformationMatrix(), FloatPoint3D(), false, BackfaceVisibility::kVisible, 0, CompositingReason::kNone, CompositorElementId(), ScrollPaintPropertyNode::Root()}))); return root; } CWE ID: Target: 1 Example 2: Code: static void pcd_release(struct cdrom_device_info *cdi) { } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Browser::ShowSingletonTabRespectRef(const GURL& url) { browser::NavigateParams params(GetSingletonTabNavigateParams(url)); params.ref_behavior = browser::NavigateParams::RESPECT_REF; browser::Navigate(&params); } 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: const Block::Frame& Block::GetFrame(int idx) const { assert(idx >= 0); assert(idx < m_frame_count); const Frame& f = m_frames[idx]; assert(f.pos > 0); assert(f.len > 0); return f; } CWE ID: CWE-119 Target: 1 Example 2: Code: int jbd2_journal_dirty_metadata(handle_t *handle, struct buffer_head *bh) { transaction_t *transaction = handle->h_transaction; journal_t *journal = transaction->t_journal; struct journal_head *jh = bh2jh(bh); int ret = 0; jbd_debug(5, "journal_head %p\n", jh); JBUFFER_TRACE(jh, "entry"); if (is_handle_aborted(handle)) goto out; if (!buffer_jbd(bh)) { ret = -EUCLEAN; goto out; } jbd_lock_bh_state(bh); if (jh->b_modified == 0) { /* * This buffer's got modified and becoming part * of the transaction. This needs to be done * once a transaction -bzzz */ jh->b_modified = 1; J_ASSERT_JH(jh, handle->h_buffer_credits > 0); handle->h_buffer_credits--; } /* * fastpath, to avoid expensive locking. If this buffer is already * on the running transaction's metadata list there is nothing to do. * Nobody can take it off again because there is a handle open. * I _think_ we're OK here with SMP barriers - a mistaken decision will * result in this test being false, so we go in and take the locks. */ if (jh->b_transaction == transaction && jh->b_jlist == BJ_Metadata) { JBUFFER_TRACE(jh, "fastpath"); if (unlikely(jh->b_transaction != journal->j_running_transaction)) { printk(KERN_EMERG "JBD: %s: " "jh->b_transaction (%llu, %p, %u) != " "journal->j_running_transaction (%p, %u)", journal->j_devname, (unsigned long long) bh->b_blocknr, jh->b_transaction, jh->b_transaction ? jh->b_transaction->t_tid : 0, journal->j_running_transaction, journal->j_running_transaction ? journal->j_running_transaction->t_tid : 0); ret = -EINVAL; } goto out_unlock_bh; } set_buffer_jbddirty(bh); /* * Metadata already on the current transaction list doesn't * need to be filed. Metadata on another transaction's list must * be committing, and will be refiled once the commit completes: * leave it alone for now. */ if (jh->b_transaction != transaction) { JBUFFER_TRACE(jh, "already on other transaction"); if (unlikely(jh->b_transaction != journal->j_committing_transaction)) { printk(KERN_EMERG "JBD: %s: " "jh->b_transaction (%llu, %p, %u) != " "journal->j_committing_transaction (%p, %u)", journal->j_devname, (unsigned long long) bh->b_blocknr, jh->b_transaction, jh->b_transaction ? jh->b_transaction->t_tid : 0, journal->j_committing_transaction, journal->j_committing_transaction ? journal->j_committing_transaction->t_tid : 0); ret = -EINVAL; } if (unlikely(jh->b_next_transaction != transaction)) { printk(KERN_EMERG "JBD: %s: " "jh->b_next_transaction (%llu, %p, %u) != " "transaction (%p, %u)", journal->j_devname, (unsigned long long) bh->b_blocknr, jh->b_next_transaction, jh->b_next_transaction ? jh->b_next_transaction->t_tid : 0, transaction, transaction->t_tid); ret = -EINVAL; } /* And this case is illegal: we can't reuse another * transaction's data buffer, ever. */ goto out_unlock_bh; } /* That test should have eliminated the following case: */ J_ASSERT_JH(jh, jh->b_frozen_data == NULL); JBUFFER_TRACE(jh, "file as BJ_Metadata"); spin_lock(&journal->j_list_lock); __jbd2_journal_file_buffer(jh, handle->h_transaction, BJ_Metadata); spin_unlock(&journal->j_list_lock); out_unlock_bh: jbd_unlock_bh_state(bh); out: JBUFFER_TRACE(jh, "exit"); WARN_ON(ret); /* All errors are bugs, so dump the stack */ return ret; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int huft_build(const unsigned *b, const unsigned n, const unsigned s, const unsigned short *d, const unsigned char *e, huft_t **t, unsigned *m) { unsigned a; /* counter for codes of length k */ unsigned c[BMAX + 1]; /* bit length count table */ unsigned eob_len; /* length of end-of-block code (value 256) */ unsigned f; /* i repeats in table every f entries */ int g; /* maximum code length */ int htl; /* table level */ unsigned i; /* counter, current code */ unsigned j; /* counter */ int k; /* number of bits in current code */ unsigned *p; /* pointer into c[], b[], or v[] */ huft_t *q; /* points to current table */ huft_t r; /* table entry for structure assignment */ huft_t *u[BMAX]; /* table stack */ unsigned v[N_MAX]; /* values in order of bit length */ int ws[BMAX + 1]; /* bits decoded stack */ int w; /* bits decoded */ unsigned x[BMAX + 1]; /* bit offsets, then code stack */ int y; /* number of dummy codes added */ unsigned z; /* number of entries in current table */ /* Length of EOB code, if any */ eob_len = n > 256 ? b[256] : BMAX; *t = NULL; /* Generate counts for each bit length */ memset(c, 0, sizeof(c)); p = (unsigned *) b; /* cast allows us to reuse p for pointing to b */ i = n; do { c[*p]++; /* assume all entries <= BMAX */ } while (--i); if (c[0] == n) { /* null input - all zero length codes */ *m = 0; return 2; } /* Find minimum and maximum length, bound *m by those */ for (j = 1; (j <= BMAX) && (c[j] == 0); j++) continue; k = j; /* minimum code length */ for (i = BMAX; (c[i] == 0) && i; i--) continue; g = i; /* maximum code length */ *m = (*m < j) ? j : ((*m > i) ? i : *m); /* Adjust last length count to fill out codes, if needed */ for (y = 1 << j; j < i; j++, y <<= 1) { y -= c[j]; if (y < 0) return 2; /* bad input: more codes than bits */ } y -= c[i]; if (y < 0) return 2; c[i] += y; /* Generate starting offsets into the value table for each length */ x[1] = j = 0; p = c + 1; xp = x + 2; while (--i) { /* note that i == g from above */ j += *p++; *xp++ = j; } } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int br_multicast_add_group(struct net_bridge *br, struct net_bridge_port *port, struct br_ip *group) { struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; unsigned long now = jiffies; int err; spin_lock(&br->multicast_lock); if (!netif_running(br->dev) || (port && port->state == BR_STATE_DISABLED)) goto out; mp = br_multicast_new_group(br, port, group); err = PTR_ERR(mp); if (IS_ERR(mp)) goto err; if (!port) { hlist_add_head(&mp->mglist, &br->mglist); mod_timer(&mp->timer, now + br->multicast_membership_interval); goto out; } for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (p->port == port) goto found; if ((unsigned long)p->port < (unsigned long)port) break; } p = kzalloc(sizeof(*p), GFP_ATOMIC); err = -ENOMEM; if (unlikely(!p)) goto err; p->addr = *group; p->port = port; p->next = *pp; hlist_add_head(&p->mglist, &port->mglist); setup_timer(&p->timer, br_multicast_port_group_expired, (unsigned long)p); setup_timer(&p->query_timer, br_multicast_port_group_query_expired, (unsigned long)p); rcu_assign_pointer(*pp, p); found: mod_timer(&p->timer, now + br->multicast_membership_interval); out: err = 0; err: spin_unlock(&br->multicast_lock); return err; } CWE ID: CWE-399 Target: 1 Example 2: Code: svcxdr_tmpalloc(struct nfsd4_compoundargs *argp, u32 len) { struct svcxdr_tmpbuf *tb; tb = kmalloc(sizeof(*tb) + len, GFP_KERNEL); if (!tb) return NULL; tb->next = argp->to_free; argp->to_free = tb; return tb->buf; } CWE ID: CWE-404 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: string16 ConfirmEmailDialogDelegate::GetLinkText() const { return l10n_util::GetStringUTF16(IDS_LEARN_MORE); } CWE ID: CWE-287 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: std::unique_ptr<HttpResponse> HandleFileRequest( const base::FilePath& server_root, const HttpRequest& request) { base::ScopedAllowBlockingForTesting allow_blocking; GURL request_url = request.GetURL(); std::string relative_path(request_url.path()); std::string post_prefix("/post/"); if (base::StartsWith(relative_path, post_prefix, base::CompareCase::SENSITIVE)) { if (request.method != METHOD_POST) return nullptr; relative_path = relative_path.substr(post_prefix.size() - 1); } RequestQuery query = ParseQuery(request_url); std::unique_ptr<BasicHttpResponse> failed_response(new BasicHttpResponse); failed_response->set_code(HTTP_NOT_FOUND); if (query.find("expected_body") != query.end()) { if (request.content.find(query["expected_body"].front()) == std::string::npos) { return std::move(failed_response); } } if (query.find("expected_headers") != query.end()) { for (const auto& header : query["expected_headers"]) { if (header.find(":") == std::string::npos) return std::move(failed_response); std::string key = header.substr(0, header.find(":")); std::string value = header.substr(header.find(":") + 1); if (request.headers.find(key) == request.headers.end() || request.headers.at(key) != value) { return std::move(failed_response); } } } DCHECK(base::StartsWith(relative_path, "/", base::CompareCase::SENSITIVE)); std::string request_path = relative_path.substr(1); base::FilePath file_path(server_root.AppendASCII(request_path)); std::string file_contents; if (!base::ReadFileToString(file_path, &file_contents)) { file_path = file_path.AppendASCII("index.html"); if (!base::ReadFileToString(file_path, &file_contents)) return nullptr; } if (request.method == METHOD_HEAD) file_contents = ""; if (query.find("replace_text") != query.end()) { for (const auto& replacement : query["replace_text"]) { if (replacement.find(":") == std::string::npos) return std::move(failed_response); std::string find; std::string with; base::Base64Decode(replacement.substr(0, replacement.find(":")), &find); base::Base64Decode(replacement.substr(replacement.find(":") + 1), &with); base::ReplaceSubstringsAfterOffset(&file_contents, 0, find, with); } } base::FilePath::StringPieceType mock_headers_extension; #if defined(OS_WIN) base::string16 temp = base::ASCIIToUTF16(kMockHttpHeadersExtension); mock_headers_extension = temp; #else mock_headers_extension = kMockHttpHeadersExtension; #endif base::FilePath headers_path(file_path.AddExtension(mock_headers_extension)); if (base::PathExists(headers_path)) { std::string headers_contents; if (!base::ReadFileToString(headers_path, &headers_contents)) return nullptr; return std::make_unique<RawHttpResponse>(headers_contents, file_contents); } std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_OK); if (request.headers.find("Range") != request.headers.end()) { std::vector<HttpByteRange> ranges; if (HttpUtil::ParseRangeHeader(request.headers.at("Range"), &ranges) && ranges.size() == 1) { ranges[0].ComputeBounds(file_contents.size()); size_t start = ranges[0].first_byte_position(); size_t end = ranges[0].last_byte_position(); http_response->set_code(HTTP_PARTIAL_CONTENT); http_response->AddCustomHeader( "Content-Range", base::StringPrintf("bytes %" PRIuS "-%" PRIuS "/%" PRIuS, start, end, file_contents.size())); file_contents = file_contents.substr(start, end - start + 1); } } http_response->set_content_type(GetContentType(file_path)); http_response->AddCustomHeader("Accept-Ranges", "bytes"); http_response->AddCustomHeader("ETag", "'" + file_path.MaybeAsASCII() + "'"); http_response->set_content(file_contents); return std::move(http_response); } CWE ID: Target: 1 Example 2: Code: void ExtensionAppItem::UpdatePositionFromExtensionOrdering() { const syncer::StringOrdinal& page = GetAppSorting(profile_)->GetPageOrdinal(extension_id_); const syncer::StringOrdinal& launch = GetAppSorting(profile_)->GetAppLaunchOrdinal(extension_id_); set_position(syncer::StringOrdinal( page.ToInternalValue() + launch.ToInternalValue())); } 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 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->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-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 rt_fill_info(struct net *net, __be32 dst, __be32 src, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq, int event, int nowait, unsigned int flags) { struct rtable *rt = skb_rtable(skb); struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); if (nlh == NULL) return -EMSGSIZE; r = nlmsg_data(nlh); r->rtm_family = AF_INET; r->rtm_dst_len = 32; r->rtm_src_len = 0; r->rtm_tos = fl4->flowi4_tos; r->rtm_table = RT_TABLE_MAIN; if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN)) goto nla_put_failure; r->rtm_type = rt->rt_type; r->rtm_scope = RT_SCOPE_UNIVERSE; r->rtm_protocol = RTPROT_UNSPEC; r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; if (rt->rt_flags & RTCF_NOTIFY) r->rtm_flags |= RTM_F_NOTIFY; if (nla_put_be32(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_be32(skb, RTA_SRC, src)) goto nla_put_failure; } if (rt->dst.dev && nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) goto nla_put_failure; #ifdef CONFIG_IP_ROUTE_CLASSID if (rt->dst.tclassid && nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) goto nla_put_failure; #endif if (!rt_is_input_route(rt) && fl4->saddr != src) { if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway)) goto nla_put_failure; expires = rt->dst.expires; if (expires) { unsigned long now = jiffies; if (time_before(now, expires)) expires -= now; else expires = 0; } memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); if (rt->rt_pmtu && expires) metrics[RTAX_MTU - 1] = rt->rt_pmtu; if (rtnetlink_put_metrics(skb, metrics) < 0) goto nla_put_failure; if (fl4->flowi4_mark && nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) goto nla_put_failure; error = rt->dst.error; if (rt_is_input_route(rt)) { #ifdef CONFIG_IP_MROUTE if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { int err = ipmr_get_route(net, skb, fl4->saddr, fl4->daddr, r, nowait); if (err <= 0) { if (!nowait) { if (err == 0) return 0; goto nla_put_failure; } else { if (err == -EMSGSIZE) goto nla_put_failure; error = err; } } } else #endif if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } CWE ID: CWE-17 Target: 1 Example 2: Code: void Layer::SetScrollOffsetFromImplSide(const gfx::Vector2d& scroll_offset) { DCHECK(IsPropertyChangeAllowed()); DCHECK(layer_tree_host_ && layer_tree_host_->CommitRequested()); if (scroll_offset_ == scroll_offset) return; scroll_offset_ = scroll_offset; SetNeedsPushProperties(); if (!did_scroll_callback_.is_null()) did_scroll_callback_.Run(); } 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 MagickBooleanType TIFFWritePhotoshopLayers(Image* image, const ImageInfo *image_info,EndianType endian,ExceptionInfo *exception) { BlobInfo *blob; CustomStreamInfo *custom_stream; Image *base_image, *next; ImageInfo *clone_info; MagickBooleanType status; PhotoshopProfile profile; PSDInfo info; StringInfo *layers; base_image=CloneImage(image,0,0,MagickFalse,exception); if (base_image == (Image *) NULL) return(MagickTrue); clone_info=CloneImageInfo(image_info); if (clone_info == (ImageInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); profile.offset=0; profile.quantum=MagickMinBlobExtent; layers=AcquireStringInfo(profile.quantum); if (layers == (StringInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } profile.data=layers; profile.extent=layers->length; custom_stream=TIFFAcquireCustomStreamForWriting(&profile,exception); if (custom_stream == (CustomStreamInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } blob=CloneBlobInfo((BlobInfo *) NULL); if (blob == (BlobInfo *) NULL) { clone_info=DestroyImageInfo(clone_info); layers=DestroyStringInfo(layers); custom_stream=DestroyCustomStreamInfo(custom_stream); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } DestroyBlob(base_image); base_image->blob=blob; next=base_image; while (next != (Image *) NULL) next=SyncNextImageInList(next); AttachCustomStream(base_image->blob,custom_stream); InitPSDInfo(image,&info); base_image->endian=endian; WriteBlobString(base_image,"Adobe Photoshop Document Data Block"); WriteBlobByte(base_image,0); WriteBlobString(base_image,base_image->endian == LSBEndian ? "MIB8ryaL" : "8BIMLayr"); status=WritePSDLayers(base_image,clone_info,&info,exception); if (status != MagickFalse) { SetStringInfoLength(layers,(size_t) profile.offset); status=SetImageProfile(image,"tiff:37724",layers,exception); } next=base_image; while (next != (Image *) NULL) { CloseBlob(next); next=next->next; } layers=DestroyStringInfo(layers); clone_info=DestroyImageInfo(clone_info); custom_stream=DestroyCustomStreamInfo(custom_stream); return(status); } CWE ID: CWE-772 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int fib6_add(struct fib6_node *root, struct rt6_info *rt, struct nl_info *info) { struct fib6_node *fn, *pn = NULL; int err = -ENOMEM; int allow_create = 1; int replace_required = 0; if (info->nlh) { if (!(info->nlh->nlmsg_flags & NLM_F_CREATE)) allow_create = 0; if (info->nlh->nlmsg_flags & NLM_F_REPLACE) replace_required = 1; } if (!allow_create && !replace_required) pr_warn("RTM_NEWROUTE with no NLM_F_CREATE or NLM_F_REPLACE\n"); fn = fib6_add_1(root, &rt->rt6i_dst.addr, rt->rt6i_dst.plen, offsetof(struct rt6_info, rt6i_dst), allow_create, replace_required); if (IS_ERR(fn)) { err = PTR_ERR(fn); goto out; } pn = fn; #ifdef CONFIG_IPV6_SUBTREES if (rt->rt6i_src.plen) { struct fib6_node *sn; if (!fn->subtree) { struct fib6_node *sfn; /* * Create subtree. * * fn[main tree] * | * sfn[subtree root] * \ * sn[new leaf node] */ /* Create subtree root node */ sfn = node_alloc(); if (!sfn) goto st_failure; sfn->leaf = info->nl_net->ipv6.ip6_null_entry; atomic_inc(&info->nl_net->ipv6.ip6_null_entry->rt6i_ref); sfn->fn_flags = RTN_ROOT; sfn->fn_sernum = fib6_new_sernum(); /* Now add the first leaf node to new subtree */ sn = fib6_add_1(sfn, &rt->rt6i_src.addr, rt->rt6i_src.plen, offsetof(struct rt6_info, rt6i_src), allow_create, replace_required); if (IS_ERR(sn)) { /* If it is failed, discard just allocated root, and then (in st_failure) stale node in main tree. */ node_free(sfn); err = PTR_ERR(sn); goto st_failure; } /* Now link new subtree to main tree */ sfn->parent = fn; fn->subtree = sfn; } else { sn = fib6_add_1(fn->subtree, &rt->rt6i_src.addr, rt->rt6i_src.plen, offsetof(struct rt6_info, rt6i_src), allow_create, replace_required); if (IS_ERR(sn)) { err = PTR_ERR(sn); goto st_failure; } } if (!fn->leaf) { fn->leaf = rt; atomic_inc(&rt->rt6i_ref); } fn = sn; } #endif err = fib6_add_rt2node(fn, rt, info); if (!err) { fib6_start_gc(info->nl_net, rt); if (!(rt->rt6i_flags & RTF_CACHE)) fib6_prune_clones(info->nl_net, pn, rt); } out: if (err) { #ifdef CONFIG_IPV6_SUBTREES /* * If fib6_add_1 has cleared the old leaf pointer in the * super-tree leaf node we have to find a new one for it. */ if (pn != fn && pn->leaf == rt) { pn->leaf = NULL; atomic_dec(&rt->rt6i_ref); } if (pn != fn && !pn->leaf && !(pn->fn_flags & RTN_RTINFO)) { pn->leaf = fib6_find_prefix(info->nl_net, pn); #if RT6_DEBUG >= 2 if (!pn->leaf) { WARN_ON(pn->leaf == NULL); pn->leaf = info->nl_net->ipv6.ip6_null_entry; } #endif atomic_inc(&pn->leaf->rt6i_ref); } #endif dst_free(&rt->dst); } return err; #ifdef CONFIG_IPV6_SUBTREES /* Subtree creation failed, probably main tree node is orphan. If it is, shoot it. */ st_failure: if (fn && !(fn->fn_flags & (RTN_RTINFO|RTN_ROOT))) fib6_repair_tree(info->nl_net, fn); dst_free(&rt->dst); return err; #endif } CWE ID: CWE-264 Target: 1 Example 2: Code: static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Document::processHttpEquiv(const String& equiv, const String& content) { ASSERT(!equiv.isNull() && !content.isNull()); Frame* frame = this->frame(); if (equalIgnoringCase(equiv, "default-style")) { m_styleSheetCollection->setSelectedStylesheetSetName(content); m_styleSheetCollection->setPreferredStylesheetSetName(content); styleResolverChanged(DeferRecalcStyle); } else if (equalIgnoringCase(equiv, "refresh")) { double delay; String url; if (frame && parseHTTPRefresh(content, true, delay, url)) { if (url.isEmpty()) url = m_url.string(); else url = completeURL(url).string(); frame->navigationScheduler()->scheduleRedirect(delay, url); } } else if (equalIgnoringCase(equiv, "set-cookie")) { if (isHTMLDocument()) { toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION); } } else if (equalIgnoringCase(equiv, "content-language")) setContentLanguage(content); else if (equalIgnoringCase(equiv, "x-dns-prefetch-control")) parseDNSPrefetchControlHeader(content); else if (equalIgnoringCase(equiv, "x-frame-options")) { if (frame) { FrameLoader* frameLoader = frame->loader(); unsigned long requestIdentifier = 0; if (frameLoader->activeDocumentLoader() && frameLoader->activeDocumentLoader()->mainResourceLoader()) requestIdentifier = frameLoader->activeDocumentLoader()->mainResourceLoader()->identifier(); if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) { String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'."; frameLoader->stopAllLoaders(); frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), "data:text/html,<p></p>", String()); addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier); } } } else if (equalIgnoringCase(equiv, "content-security-policy")) contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce); else if (equalIgnoringCase(equiv, "content-security-policy-report-only")) contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report); else if (equalIgnoringCase(equiv, "x-webkit-csp")) contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce); else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only")) contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport); } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void P2PQuicStreamImpl::OnStreamReset(const quic::QuicRstStreamFrame& frame) { quic::QuicStream::OnStreamReset(frame); delegate_->OnRemoteReset(); } CWE ID: CWE-284 Target: 1 Example 2: Code: WebPluginContainerImpl* LocalFrameClientImpl::CreatePlugin( HTMLPlugInElement& element, const KURL& url, const Vector<String>& param_names, const Vector<String>& param_values, const String& mime_type, bool load_manually) { if (!web_frame_->Client()) return nullptr; WebPluginParams params; params.url = url; params.mime_type = mime_type; params.attribute_names = param_names; params.attribute_values = param_values; params.load_manually = load_manually; WebPlugin* web_plugin = web_frame_->Client()->CreatePlugin(params); if (!web_plugin) return nullptr; WebPluginContainerImpl* container = WebPluginContainerImpl::Create(element, web_plugin); if (!web_plugin->Initialize(container)) return nullptr; if (!element.GetLayoutObject()) return nullptr; return container; } 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: ReadableStream::ReadableStream(UnderlyingSource* source) : m_source(source) , m_isStarted(false) , m_isDraining(false) , m_isPulling(false) , m_isDisturbed(false) , m_state(Readable) { } 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 unix_inflight(struct file *fp) { struct sock *s = unix_get_socket(fp); spin_lock(&unix_gc_lock); if (s) { struct unix_sock *u = unix_sk(s); if (atomic_long_inc_return(&u->inflight) == 1) { BUG_ON(!list_empty(&u->link)); list_add_tail(&u->link, &gc_inflight_list); } else { BUG_ON(list_empty(&u->link)); } unix_tot_inflight++; } fp->f_cred->user->unix_inflight++; spin_unlock(&unix_gc_lock); } CWE ID: CWE-399 Target: 1 Example 2: Code: static int alloc_med_class_bfreg(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi) { int minidx = first_med_bfreg(dev, bfregi); int i; if (minidx < 0) return minidx; for (i = minidx; i < first_hi_bfreg(dev, bfregi); i++) { if (bfregi->count[i] < bfregi->count[minidx]) minidx = i; if (!bfregi->count[minidx]) break; } bfregi->count[minidx]++; return minidx; } 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 rose_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name; size_t copied; unsigned char *asmptr; struct sk_buff *skb; int n, er, qbit; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) return er; qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT; skb_pull(skb, ROSE_MIN_LEN); if (rose->qbitincl) { asmptr = skb_push(skb, 1); *asmptr = qbit; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (srose != NULL) { memset(srose, 0, msg->msg_namelen); srose->srose_family = AF_ROSE; srose->srose_addr = rose->dest_addr; srose->srose_call = rose->dest_call; srose->srose_ndigis = rose->dest_ndigis; if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name; for (n = 0 ; n < rose->dest_ndigis ; n++) full_srose->srose_digis[n] = rose->dest_digis[n]; msg->msg_namelen = sizeof(struct full_sockaddr_rose); } else { if (rose->dest_ndigis >= 1) { srose->srose_ndigis = 1; srose->srose_digi = rose->dest_digis[0]; } msg->msg_namelen = sizeof(struct sockaddr_rose); } } skb_free_datagram(sk, skb); return copied; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info) { struct iphdr *iph; int room; struct icmp_bxm icmp_param; struct rtable *rt = skb_rtable(skb_in); struct ipcm_cookie ipc; __be32 saddr; u8 tos; struct net *net; struct sock *sk; if (!rt) goto out; net = dev_net(rt->dst.dev); /* * Find the original header. It is expected to be valid, of course. * Check this, icmp_send is called from the most obscure devices * sometimes. */ iph = ip_hdr(skb_in); if ((u8 *)iph < skb_in->head || (skb_in->network_header + sizeof(*iph)) > skb_in->tail) goto out; /* * No replies to physical multicast/broadcast */ if (skb_in->pkt_type != PACKET_HOST) goto out; /* * Now check at the protocol level */ if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) goto out; /* * Only reply to fragment 0. We byte re-order the constant * mask for efficiency. */ if (iph->frag_off & htons(IP_OFFSET)) goto out; /* * If we send an ICMP error to an ICMP error a mess would result.. */ if (icmp_pointers[type].error) { /* * We are an error, check if we are replying to an * ICMP error */ if (iph->protocol == IPPROTO_ICMP) { u8 _inner_type, *itp; itp = skb_header_pointer(skb_in, skb_network_header(skb_in) + (iph->ihl << 2) + offsetof(struct icmphdr, type) - skb_in->data, sizeof(_inner_type), &_inner_type); if (itp == NULL) goto out; /* * Assume any unknown ICMP type is an error. This * isn't specified by the RFC, but think about it.. */ if (*itp > NR_ICMP_TYPES || icmp_pointers[*itp].error) goto out; } } sk = icmp_xmit_lock(net); if (sk == NULL) return; /* * Construct source address and options. */ saddr = iph->daddr; if (!(rt->rt_flags & RTCF_LOCAL)) { struct net_device *dev = NULL; rcu_read_lock(); if (rt_is_input_route(rt) && net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr) dev = dev_get_by_index_rcu(net, rt->rt_iif); if (dev) saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK); else saddr = 0; rcu_read_unlock(); } tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) | IPTOS_PREC_INTERNETCONTROL) : iph->tos; if (ip_options_echo(&icmp_param.replyopts, skb_in)) goto out_unlock; /* * Prepare data for ICMP header. */ icmp_param.data.icmph.type = type; icmp_param.data.icmph.code = code; icmp_param.data.icmph.un.gateway = info; icmp_param.data.icmph.checksum = 0; icmp_param.skb = skb_in; icmp_param.offset = skb_network_offset(skb_in); inet_sk(sk)->tos = tos; ipc.addr = iph->saddr; ipc.opt = &icmp_param.replyopts; ipc.tx_flags = 0; rt = icmp_route_lookup(net, skb_in, iph, saddr, tos, type, code, &icmp_param); if (IS_ERR(rt)) goto out_unlock; if (!icmpv4_xrlim_allow(net, rt, type, code)) goto ende; /* RFC says return as much as we can without exceeding 576 bytes. */ room = dst_mtu(&rt->dst); if (room > 576) room = 576; room -= sizeof(struct iphdr) + icmp_param.replyopts.optlen; room -= sizeof(struct icmphdr); icmp_param.data_len = skb_in->len - icmp_param.offset; if (icmp_param.data_len > room) icmp_param.data_len = room; icmp_param.head_len = sizeof(struct icmphdr); icmp_push_reply(&icmp_param, &ipc, &rt); ende: ip_rt_put(rt); out_unlock: icmp_xmit_unlock(sk); out:; } CWE ID: CWE-362 Target: 1 Example 2: Code: do_ip6t_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IP6T_SO_SET_REPLACE: ret = do_replace(sock_net(sk), user, len); break; case IP6T_SO_SET_ADD_COUNTERS: ret = do_add_counters(sock_net(sk), user, len, 0); break; default: duprintf("do_ip6t_set_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void NetworkHandler::GetCookies(Maybe<Array<String>> protocol_urls, std::unique_ptr<GetCookiesCallback> callback) { if (!host_) { callback->sendFailure(Response::InternalError()); return; } std::vector<GURL> urls = ComputeCookieURLs(host_, protocol_urls); scoped_refptr<CookieRetriever> retriever = new CookieRetriever(std::move(callback)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &CookieRetriever::RetrieveCookiesOnIO, retriever, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), urls)); } CWE ID: CWE-20 Output:
1