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 kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; void *shared_kaddr; s64 kernel_ns, max_kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info *guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __get_cpu_var(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->time_page) return 0; /* * Time as measured by the TSC may go backwards when resetting the base * tsc_timestamp. The reason for this is that the TSC resolution is * higher than the resolution of the other clock scales. Thus, many * possible measurments of the TSC correspond to one measurement of any * other clock, and so a spread of values is possible. This is not a * problem for the computation of the nanosecond clock; with TSC rates * around 1GHZ, there can only be a few cycles which correspond to one * nanosecond value, and any path through this code will inevitably * take longer than that. However, with the kernel_ns value itself, * the precision may be much lower, down to HZ granularity. If the * first sampling of TSC against kernel_ns ends in the low part of the * range, and the second in the high end of the range, we can get: * * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new * * As the sampling errors potentially range in the thousands of cycles, * it is possible such a time value has already been observed by the * guest. To protect against this, we must compute the system time as * observed by the guest and ensure the new system time is greater. */ max_kernel_ns = 0; if (vcpu->hv_clock.tsc_timestamp) { max_kernel_ns = vcpu->last_guest_tsc - vcpu->hv_clock.tsc_timestamp; max_kernel_ns = pvclock_scale_delta(max_kernel_ns, vcpu->hv_clock.tsc_to_system_mul, vcpu->hv_clock.tsc_shift); max_kernel_ns += vcpu->last_kernel_ns; } if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* with a master <monotonic time, tsc value> tuple, * pvclock clock reads always increase at the (scaled) rate * of guest TSC - no need to deal with sampling errors. */ if (!use_master_clock) { if (max_kernel_ns > kernel_ns) kernel_ns = max_kernel_ns; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_kernel_ns = kernel_ns; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; shared_kaddr = kmap_atomic(vcpu->time_page); guest_hv_clock = shared_kaddr + vcpu->time_offset; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); kunmap_atomic(shared_kaddr); mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT); return 0; } CWE ID: CWE-399 Target: 1 Example 2: Code: bool CanonicalizePathURL(const base::char16* spec, int spec_len, const Parsed& parsed, CanonOutput* output, Parsed* new_parsed) { return DoCanonicalizePathURL<base::char16, base::char16>( URLComponentSource<base::char16>(spec), parsed, output, new_parsed); } 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 SelectionEditor::MarkCacheDirty() { if (!cached_visible_selection_in_dom_tree_is_dirty_) { cached_visible_selection_in_dom_tree_ = VisibleSelection(); cached_visible_selection_in_dom_tree_is_dirty_ = true; } if (!cached_visible_selection_in_flat_tree_is_dirty_) { cached_visible_selection_in_flat_tree_ = VisibleSelectionInFlatTree(); cached_visible_selection_in_flat_tree_is_dirty_ = true; } } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(locale_filter_matches) { char* lang_tag = NULL; int lang_tag_len = 0; const char* loc_range = NULL; int loc_range_len = 0; int result = 0; char* token = 0; char* chrcheck = NULL; char* can_lang_tag = NULL; char* can_loc_range = NULL; char* cur_lang_tag = NULL; char* cur_loc_range = NULL; zend_bool boolCanonical = 0; UErrorCode status = U_ZERO_ERROR; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "ss|b", &lang_tag, &lang_tag_len , &loc_range , &loc_range_len , &boolCanonical) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_filter_matches: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } if( strcmp(loc_range,"*")==0){ RETURN_TRUE; } if( boolCanonical ){ /* canonicalize loc_range */ can_loc_range=get_icu_value_internal( loc_range , LOC_CANONICALIZE_TAG , &result , 0); if( result ==0) { intl_error_set( NULL, status, "locale_filter_matches : unable to canonicalize loc_range" , 0 TSRMLS_CC ); RETURN_FALSE; } /* canonicalize lang_tag */ can_lang_tag = get_icu_value_internal( lang_tag , LOC_CANONICALIZE_TAG , &result , 0); if( result ==0) { intl_error_set( NULL, status, "locale_filter_matches : unable to canonicalize lang_tag" , 0 TSRMLS_CC ); RETURN_FALSE; } /* Convert to lower case for case-insensitive comparison */ cur_lang_tag = ecalloc( 1, strlen(can_lang_tag) + 1); /* Convert to lower case for case-insensitive comparison */ result = strToMatch( can_lang_tag , cur_lang_tag); if( result == 0) { efree( cur_lang_tag ); efree( can_lang_tag ); RETURN_FALSE; } cur_loc_range = ecalloc( 1, strlen(can_loc_range) + 1); result = strToMatch( can_loc_range , cur_loc_range ); if( result == 0) { efree( cur_lang_tag ); efree( can_lang_tag ); efree( cur_loc_range ); efree( can_loc_range ); RETURN_FALSE; } /* check if prefix */ token = strstr( cur_lang_tag , cur_loc_range ); if( token && (token==cur_lang_tag) ){ /* check if the char. after match is SEPARATOR */ chrcheck = token + (strlen(cur_loc_range)); if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){ if( cur_lang_tag){ efree( cur_lang_tag ); } if( cur_loc_range){ efree( cur_loc_range ); } if( can_lang_tag){ efree( can_lang_tag ); } if( can_loc_range){ efree( can_loc_range ); } RETURN_TRUE; } } /* No prefix as loc_range */ if( cur_lang_tag){ efree( cur_lang_tag ); } if( cur_loc_range){ efree( cur_loc_range ); } if( can_lang_tag){ efree( can_lang_tag ); } if( can_loc_range){ efree( can_loc_range ); } RETURN_FALSE; } /* end of if isCanonical */ else{ /* Convert to lower case for case-insensitive comparison */ cur_lang_tag = ecalloc( 1, strlen(lang_tag ) + 1); result = strToMatch( lang_tag , cur_lang_tag); if( result == 0) { efree( cur_lang_tag ); RETURN_FALSE; } cur_loc_range = ecalloc( 1, strlen(loc_range ) + 1); result = strToMatch( loc_range , cur_loc_range ); if( result == 0) { efree( cur_lang_tag ); efree( cur_loc_range ); RETURN_FALSE; } /* check if prefix */ token = strstr( cur_lang_tag , cur_loc_range ); if( token && (token==cur_lang_tag) ){ /* check if the char. after match is SEPARATOR */ chrcheck = token + (strlen(cur_loc_range)); if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){ if( cur_lang_tag){ efree( cur_lang_tag ); } if( cur_loc_range){ efree( cur_loc_range ); } RETURN_TRUE; } } /* No prefix as loc_range */ if( cur_lang_tag){ efree( cur_lang_tag ); } if( cur_loc_range){ efree( cur_loc_range ); } RETURN_FALSE; } } CWE ID: CWE-125 Target: 1 Example 2: Code: static int xt_get_next_timeout(GSource *source) { static int has_compatible_appcontext = -1; if (has_compatible_appcontext < 0) { if ((has_compatible_appcontext = xt_has_compatible_appcontext()) == 0) npw_printf("WARNING: xt_get_next_timeout() is not optimizable\n"); } int timeout = XT_DEFAULT_TIMEOUT; if (has_compatible_appcontext) { int input_timeout, timer_timeout; /* Check there is any input source to process */ if (get_appcontext_input_count() > 0) input_timeout = XT_DEFAULT_TIMEOUT; else input_timeout = -1; /* Check there is any timer to process */ if (x_app_context->timerQueue == NULL) timer_timeout = -1; else { /* Determine delay to next timeout. Zero means timeout already expired */ struct timeval *next = &x_app_context->timerQueue->te_timer_value; GTimeVal now; int64_t diff; g_source_get_current_time(source, &now); if ((diff = (int64_t)next->tv_sec - (int64_t)now.tv_sec) < 0) timer_timeout = 0; else if ((diff = diff*1000 + ((int64_t)next->tv_usec - (int64_t)now.tv_usec)/1000) <= 0) timer_timeout = 0; else timer_timeout = diff; } if (input_timeout < 0) timeout = timer_timeout; else if (timer_timeout < 0) timeout = input_timeout; else timeout = MIN(input_timeout, timer_timeout); } return timeout; } 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: jiffies_to_timespec(const unsigned long jiffies, struct timespec *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &value->tv_nsec); } 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: ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { ActionReply reply; reply.addData("mh_mountpoint", args["mh_mountpoint"]); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); command << args["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << args["mh_command"].toString(); command << args["mh_options"].toStringList(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool user_kill = false; QStringList command; #if defined(Q_OS_LINUX) command << args["mh_command"].toString(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); command << args["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << args["mh_command"].toString(); command << args["mh_options"].toStringList(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); { } if (HelperSupport::isStopped()) { proc.kill(); user_kill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!user_kill) { reply.setErrorCode(ActionReply::HelperError); reply.setErrorDescription(i18n("The mount process crashed.")); return reply; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData("mh_error_message", stdErr.trimmed()); } } CWE ID: CWE-20 Target: 1 Example 2: Code: xmlParseURI(const char *str) { xmlURIPtr uri; int ret; if (str == NULL) return(NULL); uri = xmlCreateURI(); if (uri != NULL) { ret = xmlParse3986URIReference(uri, str); if (ret) { xmlFreeURI(uri); return(NULL); } } return(uri); } 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: spnego_gss_unwrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t output_message_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_unwrap(minor_status, context_handle, input_message_buffer, output_message_buffer, conf_state, qop_state); return (ret); } CWE ID: CWE-18 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SocketStream::DoLoop(int result) { if (!context_.get()) next_state_ = STATE_CLOSE; if (next_state_ == STATE_NONE) return; do { State state = next_state_; next_state_ = STATE_NONE; switch (state) { case STATE_BEFORE_CONNECT: DCHECK_EQ(OK, result); result = DoBeforeConnect(); break; case STATE_BEFORE_CONNECT_COMPLETE: result = DoBeforeConnectComplete(result); break; case STATE_RESOLVE_PROXY: DCHECK_EQ(OK, result); result = DoResolveProxy(); break; case STATE_RESOLVE_PROXY_COMPLETE: result = DoResolveProxyComplete(result); break; case STATE_RESOLVE_HOST: DCHECK_EQ(OK, result); result = DoResolveHost(); break; case STATE_RESOLVE_HOST_COMPLETE: result = DoResolveHostComplete(result); break; case STATE_RESOLVE_PROTOCOL: result = DoResolveProtocol(result); break; case STATE_RESOLVE_PROTOCOL_COMPLETE: result = DoResolveProtocolComplete(result); break; case STATE_TCP_CONNECT: result = DoTcpConnect(result); break; case STATE_TCP_CONNECT_COMPLETE: result = DoTcpConnectComplete(result); break; case STATE_GENERATE_PROXY_AUTH_TOKEN: result = DoGenerateProxyAuthToken(); break; case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE: result = DoGenerateProxyAuthTokenComplete(result); break; case STATE_WRITE_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoWriteTunnelHeaders(); break; case STATE_WRITE_TUNNEL_HEADERS_COMPLETE: result = DoWriteTunnelHeadersComplete(result); break; case STATE_READ_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoReadTunnelHeaders(); break; case STATE_READ_TUNNEL_HEADERS_COMPLETE: result = DoReadTunnelHeadersComplete(result); break; case STATE_SOCKS_CONNECT: DCHECK_EQ(OK, result); result = DoSOCKSConnect(); break; case STATE_SOCKS_CONNECT_COMPLETE: result = DoSOCKSConnectComplete(result); break; case STATE_SECURE_PROXY_CONNECT: DCHECK_EQ(OK, result); result = DoSecureProxyConnect(); break; case STATE_SECURE_PROXY_CONNECT_COMPLETE: result = DoSecureProxyConnectComplete(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR: result = DoSecureProxyHandleCertError(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE: result = DoSecureProxyHandleCertErrorComplete(result); break; case STATE_SSL_CONNECT: DCHECK_EQ(OK, result); result = DoSSLConnect(); break; case STATE_SSL_CONNECT_COMPLETE: result = DoSSLConnectComplete(result); break; case STATE_SSL_HANDLE_CERT_ERROR: result = DoSSLHandleCertError(result); break; case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE: result = DoSSLHandleCertErrorComplete(result); break; case STATE_READ_WRITE: result = DoReadWrite(result); break; case STATE_AUTH_REQUIRED: Finish(result); return; case STATE_CLOSE: DCHECK_LE(result, OK); Finish(result); return; default: NOTREACHED() << "bad state " << state; Finish(result); return; } if (state == STATE_RESOLVE_PROTOCOL && result == ERR_PROTOCOL_SWITCHED) continue; if (state != STATE_READ_WRITE && result < ERR_IO_PENDING) { net_log_.EndEventWithNetErrorCode( NetLog::TYPE_SOCKET_STREAM_CONNECT, result); } } while (result != ERR_IO_PENDING); } CWE ID: CWE-399 Target: 1 Example 2: Code: PluginDelegate::PlatformImage2D* ImageDataNaClBackend::PlatformImage() const { return NULL; } 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 inline void mcryptd_check_internal(struct rtattr **tb, u32 *type, u32 *mask) { struct crypto_attr_type *algt; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return; if ((algt->type & CRYPTO_ALG_INTERNAL)) *type |= CRYPTO_ALG_INTERNAL; if ((algt->mask & CRYPTO_ALG_INTERNAL)) *mask |= CRYPTO_ALG_INTERNAL; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) { exit_code_ = exit_code; BOOL result = SetEvent(process_exit_event_); EXPECT_TRUE(result); } CWE ID: CWE-399 Target: 1 Example 2: Code: _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = (uint8_t *)(void *)&sv; uint8_t *d = (uint8_t *)(void *)&rv; d[0] = s[1]; d[1] = s[0]; return rv; } 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 MemStream::reset() { bufPtr = buf + start; } 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: fgetwln(FILE *stream, size_t *lenp) { struct filewbuf *fb; wint_t wc; size_t wused = 0; /* Try to diminish the possibility of several fgetwln() calls being * used on different streams, by using a pool of buffers per file. */ fb = &fb_pool[fb_pool_cur]; if (fb->fp != stream && fb->fp != NULL) { fb_pool_cur++; fb_pool_cur %= FILEWBUF_POOL_ITEMS; fb = &fb_pool[fb_pool_cur]; } fb->fp = stream; while ((wc = fgetwc(stream)) != WEOF) { if (!fb->len || wused > fb->len) { wchar_t *wp; if (fb->len) fb->len *= 2; else fb->len = FILEWBUF_INIT_LEN; wp = reallocarray(fb->wbuf, fb->len, sizeof(wchar_t)); if (wp == NULL) { wused = 0; break; } fb->wbuf = wp; } fb->wbuf[wused++] = wc; if (wc == L'\n') break; } *lenp = wused; return wused ? fb->wbuf : NULL; } CWE ID: CWE-119 Target: 1 Example 2: Code: int32 WebContentsImpl::GetMaxPageIDForSiteInstance( SiteInstance* site_instance) { if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end()) max_page_ids_[site_instance->GetId()] = -1; return max_page_ids_[site_instance->GetId()]; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int jas_iccputsint(jas_stream_t *out, int n, longlong val) { ulonglong tmp; tmp = (val < 0) ? (abort(), 0) : val; return jas_iccputuint(out, n, tmp); } 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: DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : AbstractMetadataProvider(e), m_validate(XMLHelper::getAttrBool(e, false, validate)), m_id(XMLHelper::getAttrString(e, "Dynamic", id)), m_lock(RWLock::create()), m_refreshDelayFactor(0.75), m_minCacheDuration(XMLHelper::getAttrInt(e, 600, minCacheDuration)), m_maxCacheDuration(XMLHelper::getAttrInt(e, 28800, maxCacheDuration)), m_shutdown(false), m_cleanupInterval(XMLHelper::getAttrInt(e, 1800, cleanupInterval)), m_cleanupTimeout(XMLHelper::getAttrInt(e, 1800, cleanupTimeout)), m_cleanup_wait(nullptr), m_cleanup_thread(nullptr) { if (m_minCacheDuration > m_maxCacheDuration) { Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error( "minCacheDuration setting exceeds maxCacheDuration setting, lowering to match it" ); m_minCacheDuration = m_maxCacheDuration; } const XMLCh* delay = e ? e->getAttributeNS(nullptr, refreshDelayFactor) : nullptr; if (delay && *delay) { auto_ptr_char temp(delay); m_refreshDelayFactor = atof(temp.get()); if (m_refreshDelayFactor <= 0.0 || m_refreshDelayFactor >= 1.0) { Category::getInstance(SAML_LOGCAT ".MetadataProvider.Dynamic").error( "invalid refreshDelayFactor setting, using default" ); m_refreshDelayFactor = 0.75; } } if (m_cleanupInterval > 0) { if (m_cleanupTimeout < 0) m_cleanupTimeout = 0; m_cleanup_wait = CondWait::create(); m_cleanup_thread = Thread::create(&cleanup_fn, this); } } CWE ID: CWE-347 Target: 1 Example 2: Code: nfsd4_link(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_link *link) { __be32 status = nfserr_nofilehandle; if (!cstate->save_fh.fh_dentry) return status; status = nfsd_link(rqstp, &cstate->current_fh, link->li_name, link->li_namelen, &cstate->save_fh); if (!status) set_change_info(&link->li_cinfo, &cstate->current_fh); return status; } 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: __xmlStructuredError(void) { if (IS_MAIN_THREAD) return (&xmlStructuredError); else return (&xmlGetGlobalState()->xmlStructuredError); } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int evm_update_evmxattr(struct dentry *dentry, const char *xattr_name, const char *xattr_value, size_t xattr_value_len) { struct inode *inode = dentry->d_inode; struct evm_ima_xattr_data xattr_data; int rc = 0; rc = evm_calc_hmac(dentry, xattr_name, xattr_value, xattr_value_len, xattr_data.digest); if (rc == 0) { xattr_data.type = EVM_XATTR_HMAC; rc = __vfs_setxattr_noperm(dentry, XATTR_NAME_EVM, &xattr_data, sizeof(xattr_data), 0); } else if (rc == -ENODATA) rc = inode->i_op->removexattr(dentry, XATTR_NAME_EVM); return rc; } CWE ID: Target: 1 Example 2: Code: bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) { Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput]; for (size_t i = 0; i < buffers->size(); ++i) { if ((*buffers)[i].mBuffer == buffer) { return drainInputBuffer(&buffers->editItemAt(i)); } } CHECK(!"should not be here."); return false; } 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: int append_camera_metadata(camera_metadata_t *dst, const camera_metadata_t *src) { if (dst == NULL || src == NULL ) return ERROR; if (dst->entry_capacity < src->entry_count + dst->entry_count) return ERROR; if (dst->data_capacity < src->data_count + dst->data_count) return ERROR; memcpy(get_entries(dst) + dst->entry_count, get_entries(src), sizeof(camera_metadata_buffer_entry_t[src->entry_count])); memcpy(get_data(dst) + dst->data_count, get_data(src), sizeof(uint8_t[src->data_count])); if (dst->data_count != 0) { camera_metadata_buffer_entry_t *entry = get_entries(dst) + dst->entry_count; for (size_t i = 0; i < src->entry_count; i++, entry++) { if ( calculate_camera_metadata_entry_data_size(entry->type, entry->count) > 0 ) { entry->data.offset += dst->data_count; } } } if (dst->entry_count == 0) { dst->flags |= src->flags & FLAG_SORTED; } else if (src->entry_count != 0) { dst->flags &= ~FLAG_SORTED; } else { } dst->entry_count += src->entry_count; dst->data_count += src->data_count; assert(validate_camera_metadata_structure(dst, NULL) == OK); return OK; } 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: IW_IMPL(unsigned int) iw_get_ui32be(const iw_byte *b) { return (b[0]<<24) | (b[1]<<16) | (b[2]<<8) | b[3]; } CWE ID: CWE-682 Target: 1 Example 2: Code: leap_month( u_long sec /* current NTP second */ ) { int leap; int32 year, month; u_int32 ndays; ntpcal_split tmp; vint64 tvl; /* --*-- expand time and split to days */ tvl = ntpcal_ntp_to_ntp(sec, NULL); tmp = ntpcal_daysplit(&tvl); /* --*-- split to years and days in year */ tmp = ntpcal_split_eradays(tmp.hi + DAY_NTP_STARTS - 1, &leap); year = tmp.hi; /* --*-- split days of year to month */ tmp = ntpcal_split_yeardays(tmp.lo, leap); month = tmp.hi; /* --*-- get nominal start of next month */ ndays = ntpcal_edate_to_eradays(year, month+1, 0) + 1 - DAY_NTP_STARTS; return (u_int32)(ndays*SECSPERDAY - sec); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(call_user_func_array) { zval *params, *retval_ptr = NULL; zend_fcall_info fci; zend_fcall_info_cache fci_cache; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "fa/", &fci, &fci_cache, &params) == FAILURE) { return; } zend_fcall_info_args(&fci, params TSRMLS_CC); fci.retval_ptr_ptr = &retval_ptr; if (zend_call_function(&fci, &fci_cache TSRMLS_CC) == SUCCESS && fci.retval_ptr_ptr && *fci.retval_ptr_ptr) { COPY_PZVAL_TO_ZVAL(*return_value, *fci.retval_ptr_ptr); } zend_fcall_info_args_clear(&fci, 1); } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void qrio_prstcfg(u8 bit, u8 mode) { u32 prstcfg; u8 i; void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE; prstcfg = in_be32(qrio_base + PRSTCFG_OFF); for (i = 0; i < 2; i++) { if (mode & (1<<i)) set_bit(2*bit+i, &prstcfg); else clear_bit(2*bit+i, &prstcfg); } out_be32(qrio_base + PRSTCFG_OFF, prstcfg); } CWE ID: CWE-787 Target: 1 Example 2: Code: bool GLES2DecoderImpl::GenVertexArraysOESHelper( GLsizei n, const GLuint* client_ids) { for (GLsizei ii = 0; ii < n; ++ii) { if (GetVertexAttribManager(client_ids[ii])) { return false; } } if (!features().native_vertex_array_object) { for (GLsizei ii = 0; ii < n; ++ii) { CreateVertexAttribManager(client_ids[ii], 0, true); } } else { scoped_ptr<GLuint[]> service_ids(new GLuint[n]); glGenVertexArraysOES(n, service_ids.get()); for (GLsizei ii = 0; ii < n; ++ii) { CreateVertexAttribManager(client_ids[ii], service_ids[ii], true); } } 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: ChromeDownloadManagerDelegate::GetDownloadProtectionService() { #if defined(FULL_SAFE_BROWSING) SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service(); if (sb_service && sb_service->download_protection_service() && profile_->GetPrefs()->GetBoolean(prefs::kSafeBrowsingEnabled)) { return sb_service->download_protection_service(); } #endif return NULL; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_set_filter(png_structp png_ptr, int method, int filters) { png_debug(1, "in png_set_filter"); if (png_ptr == NULL) return; #ifdef PNG_MNG_FEATURES_SUPPORTED if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && (method == PNG_INTRAPIXEL_DIFFERENCING)) method = PNG_FILTER_TYPE_BASE; #endif if (method == PNG_FILTER_TYPE_BASE) { switch (filters & (PNG_ALL_FILTERS | 0x07)) { #ifdef PNG_WRITE_FILTER_SUPPORTED case 5: case 6: case 7: png_warning(png_ptr, "Unknown row filter for method 0"); #endif /* PNG_WRITE_FILTER_SUPPORTED */ case PNG_FILTER_VALUE_NONE: png_ptr->do_filter = PNG_FILTER_NONE; break; #ifdef PNG_WRITE_FILTER_SUPPORTED case PNG_FILTER_VALUE_SUB: png_ptr->do_filter = PNG_FILTER_SUB; break; case PNG_FILTER_VALUE_UP: png_ptr->do_filter = PNG_FILTER_UP; break; case PNG_FILTER_VALUE_AVG: png_ptr->do_filter = PNG_FILTER_AVG; break; case PNG_FILTER_VALUE_PAETH: png_ptr->do_filter = PNG_FILTER_PAETH; break; default: png_ptr->do_filter = (png_byte)filters; break; #else default: png_warning(png_ptr, "Unknown row filter for method 0"); #endif /* PNG_WRITE_FILTER_SUPPORTED */ } /* If we have allocated the row_buf, this means we have already started * with the image and we should have allocated all of the filter buffers * that have been selected. If prev_row isn't already allocated, then * it is too late to start using the filters that need it, since we * will be missing the data in the previous row. If an application * wants to start and stop using particular filters during compression, * it should start out with all of the filters, and then add and * remove them after the start of compression. */ if (png_ptr->row_buf != NULL) { #ifdef PNG_WRITE_FILTER_SUPPORTED if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL) { png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, (png_ptr->rowbytes + 1)); png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB; } if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL) { if (png_ptr->prev_row == NULL) { png_warning(png_ptr, "Can't add Up filter after starting"); png_ptr->do_filter &= ~PNG_FILTER_UP; } else { png_ptr->up_row = (png_bytep)png_malloc(png_ptr, (png_ptr->rowbytes + 1)); png_ptr->up_row[0] = PNG_FILTER_VALUE_UP; } } if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL) { if (png_ptr->prev_row == NULL) { png_warning(png_ptr, "Can't add Average filter after starting"); png_ptr->do_filter &= ~PNG_FILTER_AVG; } else { png_ptr->avg_row = (png_bytep)png_malloc(png_ptr, (png_ptr->rowbytes + 1)); png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG; } } if ((png_ptr->do_filter & PNG_FILTER_PAETH) && png_ptr->paeth_row == NULL) { if (png_ptr->prev_row == NULL) { png_warning(png_ptr, "Can't add Paeth filter after starting"); png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH); } else { png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr, (png_ptr->rowbytes + 1)); png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH; } } if (png_ptr->do_filter == PNG_NO_FILTERS) #endif /* PNG_WRITE_FILTER_SUPPORTED */ png_ptr->do_filter = PNG_FILTER_NONE; } } else png_error(png_ptr, "Unknown custom filter method"); } CWE ID: CWE-119 Target: 1 Example 2: Code: void RootWindow::SetHostBounds(const gfx::Rect& bounds_in_pixel) { DispatchHeldMouseMove(); host_->SetBounds(bounds_in_pixel); last_mouse_location_ = ui::ConvertPointToDIP(layer(), host_->QueryMouseLocation()); synthesize_mouse_move_ = false; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size) { int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems; int sg_tablesize = sfp->parentdp->sg_tablesize; int blk_size = buff_size, order; gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN; struct sg_device *sdp = sfp->parentdp; if (blk_size < 0) return -EFAULT; if (0 == blk_size) ++blk_size; /* don't know why */ /* round request up to next highest SG_SECTOR_SZ byte boundary */ blk_size = ALIGN(blk_size, SG_SECTOR_SZ); SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: buff_size=%d, blk_size=%d\n", buff_size, blk_size)); /* N.B. ret_sz carried into this block ... */ mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize); if (mx_sc_elems < 0) return mx_sc_elems; /* most likely -ENOMEM */ num = scatter_elem_sz; if (unlikely(num != scatter_elem_sz_prev)) { if (num < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = PAGE_SIZE; } else scatter_elem_sz_prev = num; } if (sdp->device->host->unchecked_isa_dma) gfp_mask |= GFP_DMA; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) gfp_mask |= __GFP_ZERO; order = get_order(num); retry: ret_sz = 1 << (PAGE_SHIFT + order); for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems; k++, rem_sz -= ret_sz) { num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz; schp->pages[k] = alloc_pages(gfp_mask, order); if (!schp->pages[k]) goto out; if (num == scatter_elem_sz_prev) { if (unlikely(ret_sz > scatter_elem_sz_prev)) { scatter_elem_sz = ret_sz; scatter_elem_sz_prev = ret_sz; } } SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n", k, num, ret_sz)); } /* end of for loop */ schp->page_order = order; schp->k_use_sg = k; SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp, "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n", k, rem_sz)); schp->bufflen = blk_size; if (rem_sz > 0) /* must have failed */ return -ENOMEM; return 0; out: for (i = 0; i < k; i++) __free_pages(schp->pages[i], order); if (--order >= 0) goto retry; return -ENOMEM; } 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 bump_cpu_timer(struct k_itimer *timer, u64 now) { int i; u64 delta, incr; if (timer->it.cpu.incr == 0) return; if (now < timer->it.cpu.expires) return; incr = timer->it.cpu.incr; delta = now + incr - timer->it.cpu.expires; /* Don't use (incr*2 < delta), incr*2 might overflow. */ for (i = 0; incr < delta - incr; i++) incr = incr << 1; for (; i >= 0; incr >>= 1, i--) { if (delta < incr) continue; timer->it.cpu.expires += incr; timer->it_overrun += 1 << i; delta -= incr; } } CWE ID: CWE-190 Target: 1 Example 2: Code: void RenderMenuList::setText(const String& s) { if (s.isEmpty()) { if (!m_buttonText || !m_buttonText->isBR()) { if (m_buttonText) m_buttonText->destroy(); m_buttonText = new (renderArena()) RenderBR(document()); m_buttonText->setStyle(style()); addChild(m_buttonText); } } else { if (m_buttonText && !m_buttonText->isBR()) m_buttonText->setText(s.impl(), true); else { if (m_buttonText) m_buttonText->destroy(); m_buttonText = new (renderArena()) RenderText(document(), s.impl()); m_buttonText->setStyle(style()); addChild(m_buttonText); } adjustInnerStyle(); } } 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: DefragVlanQinQTest(void) { Packet *p1 = NULL, *p2 = NULL, *r = NULL; int ret = 0; DefragInit(); p1 = BuildTestPacket(1, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(1, 1, 0, 'B', 8); if (p2 == NULL) goto end; /* With no VLAN IDs set, packets should re-assemble. */ if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) == NULL) goto end; SCFree(r); /* With mismatched VLANs, packets should not re-assemble. */ p1->vlan_id[0] = 1; p2->vlan_id[0] = 1; p1->vlan_id[1] = 1; p2->vlan_id[1] = 2; if ((r = Defrag(NULL, NULL, p1, NULL)) != NULL) goto end; if ((r = Defrag(NULL, NULL, p2, NULL)) != NULL) goto end; /* Pass. */ ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); DefragDestroy(); return ret; } CWE ID: CWE-358 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int kvm_iommu_unmap_memslots(struct kvm *kvm) { int idx; struct kvm_memslots *slots; struct kvm_memory_slot *memslot; idx = srcu_read_lock(&kvm->srcu); slots = kvm_memslots(kvm); kvm_for_each_memslot(memslot, slots) kvm_iommu_put_pages(kvm, memslot->base_gfn, memslot->npages); srcu_read_unlock(&kvm->srcu, idx); return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: int FileStream::Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback) { if (!IsOpen()) return ERR_UNEXPECTED; DCHECK_GT(buf_len, 0); return context_->Read(buf, buf_len, callback); } CWE ID: CWE-311 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void close_all_sockets(atransport* t) { asocket* s; /* this is a little gross, but since s->close() *will* modify ** the list out from under you, your options are limited. */ adb_mutex_lock(&socket_list_lock); restart: for (s = local_socket_list.next; s != &local_socket_list; s = s->next) { if (s->transport == t || (s->peer && s->peer->transport == t)) { local_socket_close_locked(s); goto restart; } } adb_mutex_unlock(&socket_list_lock); } 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 int open_url(AVFormatContext *s, AVIOContext **pb, const char *url, AVDictionary *opts, AVDictionary *opts2, int *is_http) { HLSContext *c = s->priv_data; AVDictionary *tmp = NULL; const char *proto_name = NULL; int ret; av_dict_copy(&tmp, opts, 0); av_dict_copy(&tmp, opts2, 0); if (av_strstart(url, "crypto", NULL)) { if (url[6] == '+' || url[6] == ':') proto_name = avio_find_protocol_name(url + 7); } if (!proto_name) proto_name = avio_find_protocol_name(url); if (!proto_name) return AVERROR_INVALIDDATA; if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL)) return AVERROR_INVALIDDATA; if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':') ; else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':') ; else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5)) return AVERROR_INVALIDDATA; ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp); if (ret >= 0) { char *new_cookies = NULL; if (!(s->flags & AVFMT_FLAG_CUSTOM_IO)) av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies); if (new_cookies) { av_free(c->cookies); c->cookies = new_cookies; } av_dict_set(&opts, "cookies", c->cookies, 0); } av_dict_free(&tmp); if (is_http) *is_http = av_strstart(proto_name, "http", NULL); return ret; } CWE ID: CWE-200 Target: 1 Example 2: Code: void AudioFlinger::EffectChain::process_l() { sp<ThreadBase> thread = mThread.promote(); if (thread == 0) { ALOGW("process_l(): cannot promote mixer thread"); return; } bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) || (mSessionId == AUDIO_SESSION_OUTPUT_STAGE); bool doProcess = (thread->type() != ThreadBase::OFFLOAD); if (!isGlobalSession) { bool tracksOnSession = (trackCnt() != 0); if (!tracksOnSession && mTailBufferCount == 0) { doProcess = false; } if (activeTrackCnt() == 0) { if (tracksOnSession || mTailBufferCount > 0) { clearInputBuffer_l(thread); if (mTailBufferCount > 0) { mTailBufferCount--; } } } } size_t size = mEffects.size(); if (doProcess) { for (size_t i = 0; i < size; i++) { mEffects[i]->process(); } } for (size_t i = 0; i < size; i++) { mEffects[i]->updateState(); } } 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 IssueOnQuery(int query_id) { const FormData form; FormFieldData field; field.is_focusable = true; field.should_autocomplete = true; external_delegate_->OnQuery(query_id, form, field, gfx::RectF()); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline int ldsem_cmpxchg(long *old, long new, struct ld_semaphore *sem) { long tmp = *old; *old = atomic_long_cmpxchg(&sem->count, *old, new); return *old == tmp; } CWE ID: CWE-362 Target: 1 Example 2: Code: asocket* find_local_socket(unsigned local_id, unsigned peer_id) { asocket* s; asocket* result = NULL; std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); for (s = local_socket_list.next; s != &local_socket_list; s = s->next) { if (s->id != local_id) { continue; } if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) { result = s; } break; } return result; } 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: bool WebGLRenderingContextBase::ValidateHTMLVideoElement( SecurityOrigin* security_origin, const char* function_name, HTMLVideoElement* video, ExceptionState& exception_state) { if (!video || !video->videoWidth() || !video->videoHeight()) { SynthesizeGLError(GL_INVALID_VALUE, function_name, "no video"); return false; } if (WouldTaintOrigin(video, security_origin)) { exception_state.ThrowSecurityError( "The video element contains cross-origin data, and may not be loaded."); return false; } return true; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: upnp_redirect(const char * rhost, unsigned short eport, const char * iaddr, unsigned short iport, const char * protocol, const char * desc, unsigned int leaseduration) { int proto, r; char iaddr_old[32]; char rhost_old[32]; unsigned short iport_old; struct in_addr address; unsigned int timestamp; proto = proto_atoi(protocol); if(inet_aton(iaddr, &address) <= 0) { syslog(LOG_ERR, "inet_aton(%s) FAILED", iaddr); return -1; } if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm, eport, address, iport)) { syslog(LOG_INFO, "redirection permission check failed for " "%hu->%s:%hu %s", eport, iaddr, iport, protocol); return -3; } /* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001) * - 2.2.20.PortMappingDescription : * Overwriting Previous / Existing Port Mappings: * If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient * are exactly the same as an existing mapping, the existing mapping values * for InternalPort, PortMappingDescription, PortMappingEnabled and * PortMappingLeaseDuration are overwritten. * Rejecting a New Port Mapping: * In cases where the RemoteHost, ExternalPort and PortMappingProtocol * are the same as an existing mapping, but the InternalClient is * different, the action is rejected with an appropriate error. * Add or Reject New Port Mapping behavior based on vendor implementation: * In cases where the ExternalPort, PortMappingProtocol and InternalClient * are the same, but RemoteHost is different, the vendor can choose to * support both mappings simultaneously, or reject the second mapping * with an appropriate error. * * - 2.4.16.AddPortMapping * This action creates a new port mapping or overwrites an existing * mapping with the same internal client. If the ExternalPort and * PortMappingProtocol pair is already mapped to another internal client, * an error is returned. * * IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010) * Protocol ExternalPort RemoteHost InternalClient Result * = = ≠ ≠ Failure * = = ≠ = Failure or success * (vendor specific) * = = = ≠ Failure * = = = = Success (overwrite) */ rhost_old[0] = '\0'; r = get_redirect_rule(ext_if_name, eport, proto, iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0, rhost_old, sizeof(rhost_old), &timestamp, 0, 0); if(r == 0) { if(strcmp(iaddr, iaddr_old)==0 && ((rhost == NULL && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, "*") == 0) && rhost_old[0]=='\0') || (rhost && (strcmp(rhost, rhost_old) == 0)))) { syslog(LOG_INFO, "updating existing port mapping %hu %s (rhost '%s') => %s:%hu", eport, protocol, rhost_old, iaddr_old, iport_old); timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; if(iport != iport_old) { r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp); } else { r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp); } #ifdef ENABLE_LEASEFILE if(r == 0) { lease_file_remove(eport, proto); lease_file_add(eport, iaddr, iport, proto, desc, timestamp); } #endif /* ENABLE_LEASEFILE */ return r; } else { syslog(LOG_INFO, "port %hu %s (rhost '%s') already redirected to %s:%hu", eport, protocol, rhost_old, iaddr_old, iport_old); return -2; } #ifdef CHECK_PORTINUSE } else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) { syslog(LOG_INFO, "port %hu protocol %s already in use", eport, protocol); return -4; #endif /* CHECK_PORTINUSE */ } else { timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0; syslog(LOG_INFO, "redirecting port %hu to %s:%hu protocol %s for: %s", eport, iaddr, iport, protocol, desc); return upnp_redirect_internal(rhost, eport, iaddr, iport, proto, desc, timestamp); } } CWE ID: CWE-476 Target: 1 Example 2: Code: _XcursorFindImageToc (XcursorFileHeader *fileHeader, XcursorDim size, int count) { unsigned int toc; XcursorDim thisSize; if (!fileHeader) return 0; for (toc = 0; toc < fileHeader->ntoc; toc++) { if (fileHeader->tocs[toc].type != XCURSOR_IMAGE_TYPE) continue; thisSize = fileHeader->tocs[toc].subtype; if (thisSize != size) continue; if (!count) break; count--; } if (toc == fileHeader->ntoc) return -1; return toc; } 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: QuotaThreadTask::~QuotaThreadTask() { } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FaviconWebUIHandler::OnFaviconDataAvailable( FaviconService::Handle request_handle, history::FaviconData favicon) { FaviconService* favicon_service = web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS); int id = consumer_.GetClientData(favicon_service, request_handle); if (favicon.is_valid()) { FundamentalValue id_value(id); color_utils::GridSampler sampler; SkColor color = color_utils::CalculateKMeanColorOfPNG(favicon.image_data, 100, 665, sampler); std::string css_color = base::StringPrintf("rgb(%d, %d, %d)", SkColorGetR(color), SkColorGetG(color), SkColorGetB(color)); StringValue color_value(css_color); web_ui_->CallJavascriptFunction("ntp4.setFaviconDominantColor", id_value, color_value); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int nfs4_verify_fore_channel_attrs(struct nfs41_create_session_args *args, struct nfs4_session *session) { struct nfs4_channel_attrs *sent = &args->fc_attrs; struct nfs4_channel_attrs *rcvd = &session->fc_attrs; if (rcvd->max_resp_sz > sent->max_resp_sz) return -EINVAL; /* * Our requested max_ops is the minimum we need; we're not * prepared to break up compounds into smaller pieces than that. * So, no point even trying to continue if the server won't * cooperate: */ if (rcvd->max_ops < sent->max_ops) return -EINVAL; if (rcvd->max_reqs == 0) return -EINVAL; if (rcvd->max_reqs > NFS4_MAX_SLOT_TABLE) rcvd->max_reqs = NFS4_MAX_SLOT_TABLE; 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: ExtensionTtsController* ExtensionTtsController::GetInstance() { return Singleton<ExtensionTtsController>::get(); } 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: SchedulerObject::hold(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Hold: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!holdJob(id.cluster, id.proc, reason.c_str(), true, // Always perform this action within a transaction true, // Always notify the shadow of the hold false, // Do not email the user about this action false, // Do not email admin about this action false // This is not a system related (internal) hold )) { text = "Failed to hold job"; return false; } return true; } CWE ID: CWE-20 Target: 1 Example 2: Code: int native_handle_delete(native_handle_t* h) { if (h) { if (h->version != sizeof(native_handle_t)) return -EINVAL; free(h); } return 0; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FileSystemOperation::DidFileExists( const StatusCallback& callback, base::PlatformFileError rv, const base::PlatformFileInfo& file_info, const FilePath& unused) { if (rv == base::PLATFORM_FILE_OK && file_info.is_directory) rv = base::PLATFORM_FILE_ERROR_NOT_A_FILE; callback.Run(rv); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int hwahc_security_create(struct hwahc *hwahc) { int result; struct wusbhc *wusbhc = &hwahc->wusbhc; struct usb_device *usb_dev = hwahc->wa.usb_dev; struct device *dev = &usb_dev->dev; struct usb_security_descriptor *secd; struct usb_encryption_descriptor *etd; void *itr, *top; size_t itr_size, needed, bytes; u8 index; char buf[64]; /* Find the host's security descriptors in the config descr bundle */ index = (usb_dev->actconfig - usb_dev->config) / sizeof(usb_dev->config[0]); itr = usb_dev->rawdescriptors[index]; itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength); top = itr + itr_size; result = __usb_get_extra_descriptor(usb_dev->rawdescriptors[index], le16_to_cpu(usb_dev->actconfig->desc.wTotalLength), USB_DT_SECURITY, (void **) &secd); if (result == -1) { dev_warn(dev, "BUG? WUSB host has no security descriptors\n"); return 0; } needed = sizeof(*secd); if (top - (void *)secd < needed) { dev_err(dev, "BUG? Not enough data to process security " "descriptor header (%zu bytes left vs %zu needed)\n", top - (void *) secd, needed); return 0; } needed = le16_to_cpu(secd->wTotalLength); if (top - (void *)secd < needed) { dev_err(dev, "BUG? Not enough data to process security " "descriptors (%zu bytes left vs %zu needed)\n", top - (void *) secd, needed); return 0; } /* Walk over the sec descriptors and store CCM1's on wusbhc */ itr = (void *) secd + sizeof(*secd); top = (void *) secd + le16_to_cpu(secd->wTotalLength); index = 0; bytes = 0; while (itr < top) { etd = itr; if (top - itr < sizeof(*etd)) { dev_err(dev, "BUG: bad host security descriptor; " "not enough data (%zu vs %zu left)\n", top - itr, sizeof(*etd)); break; } if (etd->bLength < sizeof(*etd)) { dev_err(dev, "BUG: bad host encryption descriptor; " "descriptor is too short " "(%zu vs %zu needed)\n", (size_t)etd->bLength, sizeof(*etd)); break; } itr += etd->bLength; bytes += snprintf(buf + bytes, sizeof(buf) - bytes, "%s (0x%02x) ", wusb_et_name(etd->bEncryptionType), etd->bEncryptionValue); wusbhc->ccm1_etd = etd; } dev_info(dev, "supported encryption types: %s\n", buf); if (wusbhc->ccm1_etd == NULL) { dev_err(dev, "E: host doesn't support CCM-1 crypto\n"); return 0; } /* Pretty print what we support */ return 0; } CWE ID: CWE-400 Target: 1 Example 2: Code: void EnterpriseEnrollmentScreen::OnClientLoginSuccess( const ClientLoginResult& result) { auth_fetcher_->StartIssueAuthToken( result.sid, result.lsid, GaiaConstants::kDeviceManagementService); } 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: tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h) { uint32_t *buf32; uint32_t pix32; int shift[3]; int *prev; int here[3], upper[3], left[3], upperleft[3]; int prediction; int x, y, c; buf32 = (uint32_t *)buf; memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int)); if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) == (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) { shift[0] = vs->clientds.pf.rshift; shift[1] = vs->clientds.pf.gshift; shift[2] = vs->clientds.pf.bshift; } else { shift[0] = 24 - vs->clientds.pf.rshift; shift[1] = 24 - vs->clientds.pf.gshift; shift[2] = 24 - vs->clientds.pf.bshift; } for (y = 0; y < h; y++) { for (c = 0; c < 3; c++) { upper[c] = 0; here[c] = 0; } prev = (int *)vs->tight.gradient.buffer; for (x = 0; x < w; x++) { pix32 = *buf32++; for (c = 0; c < 3; c++) { upperleft[c] = upper[c]; left[c] = here[c]; upper[c] = *prev; here[c] = (int)(pix32 >> shift[c] & 0xFF); *prev++ = here[c]; prediction = left[c] + upper[c] - upperleft[c]; if (prediction < 0) { prediction = 0; } else if (prediction > 0xFF) { prediction = 0xFF; } *buf++ = (char)(here[c] - prediction); } } } } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int PDFiumEngine::GetMostVisiblePage() { if (in_flight_visible_page_) return *in_flight_visible_page_; CalculateVisiblePages(); return most_visible_page_; } CWE ID: CWE-416 Target: 1 Example 2: Code: void iscsi_set_connection_parameters( struct iscsi_conn_ops *ops, struct iscsi_param_list *param_list) { char *tmpptr; struct iscsi_param *param; pr_debug("---------------------------------------------------" "---------------\n"); list_for_each_entry(param, &param_list->param_list, p_list) { /* * Special case to set MAXXMITDATASEGMENTLENGTH from the * target requested MaxRecvDataSegmentLength, even though * this key is not sent over the wire. */ if (!strcmp(param->name, MAXXMITDATASEGMENTLENGTH)) { if (param_list->iser == true) continue; ops->MaxXmitDataSegmentLength = simple_strtoul(param->value, &tmpptr, 0); pr_debug("MaxXmitDataSegmentLength: %s\n", param->value); } if (!IS_PSTATE_ACCEPTOR(param) && !IS_PSTATE_PROPOSER(param)) continue; if (!strcmp(param->name, AUTHMETHOD)) { pr_debug("AuthMethod: %s\n", param->value); } else if (!strcmp(param->name, HEADERDIGEST)) { ops->HeaderDigest = !strcmp(param->value, CRC32C); pr_debug("HeaderDigest: %s\n", param->value); } else if (!strcmp(param->name, DATADIGEST)) { ops->DataDigest = !strcmp(param->value, CRC32C); pr_debug("DataDigest: %s\n", param->value); } else if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH)) { /* * At this point iscsi_check_acceptor_state() will have * set ops->MaxRecvDataSegmentLength from the original * initiator provided value. */ pr_debug("MaxRecvDataSegmentLength: %u\n", ops->MaxRecvDataSegmentLength); } else if (!strcmp(param->name, OFMARKER)) { ops->OFMarker = !strcmp(param->value, YES); pr_debug("OFMarker: %s\n", param->value); } else if (!strcmp(param->name, IFMARKER)) { ops->IFMarker = !strcmp(param->value, YES); pr_debug("IFMarker: %s\n", param->value); } else if (!strcmp(param->name, OFMARKINT)) { ops->OFMarkInt = simple_strtoul(param->value, &tmpptr, 0); pr_debug("OFMarkInt: %s\n", param->value); } else if (!strcmp(param->name, IFMARKINT)) { ops->IFMarkInt = simple_strtoul(param->value, &tmpptr, 0); pr_debug("IFMarkInt: %s\n", param->value); } else if (!strcmp(param->name, INITIATORRECVDATASEGMENTLENGTH)) { ops->InitiatorRecvDataSegmentLength = simple_strtoul(param->value, &tmpptr, 0); pr_debug("InitiatorRecvDataSegmentLength: %s\n", param->value); ops->MaxRecvDataSegmentLength = ops->InitiatorRecvDataSegmentLength; pr_debug("Set MRDSL from InitiatorRecvDataSegmentLength\n"); } else if (!strcmp(param->name, TARGETRECVDATASEGMENTLENGTH)) { ops->TargetRecvDataSegmentLength = simple_strtoul(param->value, &tmpptr, 0); pr_debug("TargetRecvDataSegmentLength: %s\n", param->value); ops->MaxXmitDataSegmentLength = ops->TargetRecvDataSegmentLength; pr_debug("Set MXDSL from TargetRecvDataSegmentLength\n"); } } pr_debug("----------------------------------------------------" "--------------\n"); } 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 ScrollAnchor::NotifyBeforeLayout() { if (queued_) { scroll_anchor_disabling_style_changed_ |= ComputeScrollAnchorDisablingStyleChanged(); return; } DCHECK(scroller_); ScrollOffset scroll_offset = scroller_->GetScrollOffset(); float block_direction_scroll_offset = ScrollerLayoutBox(scroller_)->IsHorizontalWritingMode() ? scroll_offset.Height() : scroll_offset.Width(); if (block_direction_scroll_offset == 0) { ClearSelf(); return; } if (!anchor_object_) { FindAnchor(); if (!anchor_object_) return; } scroll_anchor_disabling_style_changed_ = ComputeScrollAnchorDisablingStyleChanged(); LocalFrameView* frame_view = ScrollerLayoutBox(scroller_)->GetFrameView(); auto* root_frame_viewport = DynamicTo<RootFrameViewport>(scroller_.Get()); ScrollableArea* owning_scroller = root_frame_viewport ? &root_frame_viewport->LayoutViewport() : scroller_.Get(); frame_view->EnqueueScrollAnchoringAdjustment(owning_scroller); queued_ = 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: image_transform_png_set_expand_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit * depth is at least 8 already. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } CWE ID: Target: 1 Example 2: Code: CrossThreadPersistentRegion& ProcessHeap::GetCrossThreadWeakPersistentRegion() { DEFINE_THREAD_SAFE_STATIC_LOCAL(CrossThreadPersistentRegion, persistent_region, ()); return persistent_region; } 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 RenderFrameHostImpl::AccessibilityFatalError() { browser_accessibility_manager_.reset(nullptr); if (accessibility_reset_token_) return; accessibility_reset_count_++; if (accessibility_reset_count_ >= kMaxAccessibilityResets) { Send(new AccessibilityMsg_FatalError(routing_id_)); } else { accessibility_reset_token_ = g_next_accessibility_reset_token++; Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_)); } } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_, long long size_) { const long long stop = start_ + size_; long long pos = start_; m_track = -1; m_pos = -1; m_block = 1; // default while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; // consume Size field assert((pos + size) <= stop); if (id == 0x77) // CueTrack ID m_track = UnserializeUInt(pReader, pos, size); else if (id == 0x71) // CueClusterPos ID m_pos = UnserializeUInt(pReader, pos, size); else if (id == 0x1378) // CueBlockNumber m_block = UnserializeUInt(pReader, pos, size); pos += size; // consume payload assert(pos <= stop); } assert(m_pos >= 0); assert(m_track > 0); } CWE ID: CWE-20 Target: 1 Example 2: Code: void hns_ppe_uninit_ex(struct ppe_common_cb *ppe_common) { u32 i; for (i = 0; i < ppe_common->ppe_num; i++) { if (ppe_common->dsaf_dev->mac_cb[i]) hns_ppe_uninit_hw(&ppe_common->ppe_cb[i]); memset(&ppe_common->ppe_cb[i], 0, sizeof(struct hns_ppe_cb)); } } 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 crypto_pcomp_init(struct crypto_tfm *tfm, u32 type, u32 mask) { return 0; } CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void btsnoop_write(const void *data, size_t length) { if (logfile_fd != INVALID_FD) write(logfile_fd, data, length); btsnoop_net_write(data, length); } CWE ID: CWE-284 Target: 1 Example 2: Code: _pure_ static const char *timer_sub_state_to_string(Unit *u) { assert(u); return timer_state_to_string(TIMER(u)->state); } 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: pdf_drop_xobject_imp(fz_context *ctx, fz_storable *xobj_) { pdf_xobject *xobj = (pdf_xobject *)xobj_; pdf_drop_obj(ctx, xobj->obj); fz_free(ctx, xobj); } 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 HTMLFormElement::scheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->method() == FormSubmission::PostMethod || submission->method() == FormSubmission::GetMethod); DCHECK(submission->data()); DCHECK(submission->form()); if (submission->action().isEmpty()) return; if (document().isSandboxed(SandboxForms)) { document().addConsoleMessage(ConsoleMessage::create( SecurityMessageSource, ErrorMessageLevel, "Blocked form submission to '" + submission->action().elidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (protocolIsJavaScript(submission->action())) { if (!document().contentSecurityPolicy()->allowFormAction( submission->action())) return; document().frame()->script().executeScriptIfJavaScriptURL( submission->action(), this); return; } Frame* targetFrame = document().frame()->findFrameForNavigation( submission->target(), *document().frame()); if (!targetFrame) { if (!LocalDOMWindow::allowPopUp(*document().frame()) && !UserGestureIndicator::utilizeUserGesture()) return; targetFrame = document().frame(); } else { submission->clearTarget(); } if (!targetFrame->host()) return; UseCounter::count(document(), UseCounter::FormsSubmitted); if (MixedContentChecker::isMixedFormAction(document().frame(), submission->action())) UseCounter::count(document().frame(), UseCounter::MixedContentFormsSubmitted); if (targetFrame->isLocalFrame()) { toLocalFrame(targetFrame) ->navigationScheduler() .scheduleFormSubmission(&document(), submission); } else { FrameLoadRequest frameLoadRequest = submission->createFrameLoadRequest(&document()); toRemoteFrame(targetFrame)->navigate(frameLoadRequest); } } CWE ID: CWE-19 Target: 1 Example 2: Code: static inline unsigned long hash(dev_t dev) { return MAJOR(dev)+MINOR(dev); } 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: InputMethodDescriptors* ChromeOSGetSupportedInputMethodDescriptors() { InputMethodDescriptors* input_methods = new InputMethodDescriptors; for (size_t i = 0; i < arraysize(chromeos::kIBusEngines); ++i) { if (InputMethodIdIsWhitelisted(chromeos::kIBusEngines[i].name)) { input_methods->push_back(chromeos::CreateInputMethodDescriptor( chromeos::kIBusEngines[i].name, chromeos::kIBusEngines[i].longname, chromeos::kIBusEngines[i].layout, chromeos::kIBusEngines[i].language)); } } return input_methods; } 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: pam_sm_close_session (pam_handle_t *pamh, int flags UNUSED, int argc, const char **argv) { void *cookiefile; int i, debug = 0; const char* user; struct passwd *tpwd = NULL; uid_t unlinkuid, fsuid; if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) pam_syslog(pamh, LOG_ERR, "error determining target user's name"); else { tpwd = pam_modutil_getpwnam(pamh, user); if (!tpwd) pam_syslog(pamh, LOG_ERR, "error determining target user's UID"); else unlinkuid = tpwd->pw_uid; } /* Parse arguments. We don't understand many, so no sense in breaking * this into a separate function. */ for (i = 0; i < argc; i++) { if (strcmp(argv[i], "debug") == 0) { debug = 1; continue; } if (strncmp(argv[i], "xauthpath=", 10) == 0) { continue; } if (strncmp(argv[i], "systemuser=", 11) == 0) { continue; } if (strncmp(argv[i], "targetuser=", 11) == 0) { continue; } pam_syslog(pamh, LOG_WARNING, "unrecognized option `%s'", argv[i]); } /* Try to retrieve the name of a file we created when the session was * opened. */ if (pam_get_data(pamh, DATANAME, (const void**) &cookiefile) == PAM_SUCCESS) { /* We'll only try to remove the file once. */ if (strlen((char*)cookiefile) > 0) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "removing `%s'", (char*)cookiefile); } /* NFS with root_squash requires non-root user */ if (tpwd) fsuid = setfsuid(unlinkuid); unlink((char*)cookiefile); if (tpwd) setfsuid(fsuid); *((char*)cookiefile) = '\0'; } } return PAM_SUCCESS; } CWE ID: Target: 1 Example 2: Code: void WebBluetoothServiceImpl::GattServicesDiscovered( device::BluetoothAdapter* adapter, device::BluetoothDevice* device) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DVLOG(1) << "Services discovered for device: " << device->GetAddress(); if (device_chooser_controller_.get()) { device_chooser_controller_->AddFilteredDevice(*device); } RunPendingPrimaryServicesRequests(device); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool BluetoothDeviceChromeOS::ExpectingPinCode() const { return !pincode_callback_.is_null(); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void ieee80211_if_setup(struct net_device *dev) { ether_setup(dev); dev->netdev_ops = &ieee80211_dataif_ops; dev->destructor = free_netdev; } CWE ID: CWE-264 Target: 1 Example 2: Code: static inline int ip_frag_too_far(struct ipq *qp) { struct inet_peer *peer = qp->peer; unsigned int max = sysctl_ipfrag_max_dist; unsigned int start, end; int rc; if (!peer || !max) return 0; start = qp->rid; end = atomic_inc_return(&peer->rid); qp->rid = end; rc = qp->q.fragments && (end - start) > max; if (rc) { struct net *net; net = container_of(qp->q.net, struct net, ipv4.frags); IP_INC_STATS_BH(net, IPSTATS_MIB_REASMFAILS); } return rc; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct dentry *sockfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo(fs_type, "socket:", &sockfs_ops, &sockfs_dentry_operations, SOCKFS_MAGIC); } 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: int VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVARefFramesFromDPB( const H264DPB& dpb, VAPictureH264* va_pics, int num_pics) { H264Picture::Vector::const_reverse_iterator rit; int i; for (rit = dpb.rbegin(), i = 0; rit != dpb.rend() && i < num_pics; ++rit) { if ((*rit)->ref) FillVAPicture(&va_pics[i++], *rit); } return i; } CWE ID: CWE-362 Target: 1 Example 2: Code: int snd_timer_global_free(struct snd_timer *timer) { return snd_timer_free(timer); } 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: int test_gf2m_mod_mul(BIO *bp,BN_CTX *ctx) { BIGNUM *a,*b[2],*c,*d,*e,*f,*g,*h; int i, j, ret = 0; int p0[] = {163,7,6,3,0,-1}; int p1[] = {193,15,0,-1}; a=BN_new(); b[0]=BN_new(); b[1]=BN_new(); c=BN_new(); d=BN_new(); e=BN_new(); f=BN_new(); g=BN_new(); h=BN_new(); BN_GF2m_arr2poly(p0, b[0]); BN_GF2m_arr2poly(p1, b[1]); for (i=0; i<num0; i++) { BN_bntest_rand(a, 1024, 0, 0); BN_bntest_rand(c, 1024, 0, 0); BN_bntest_rand(d, 1024, 0, 0); for (j=0; j < 2; j++) { BN_GF2m_mod_mul(e, a, c, b[j], ctx); #if 0 /* make test uses ouput in bc but bc can't handle GF(2^m) arithmetic */ if (bp != NULL) { if (!results) { BN_print(bp,a); BIO_puts(bp," * "); BN_print(bp,c); BIO_puts(bp," % "); BN_print(bp,b[j]); BIO_puts(bp," - "); BN_print(bp,e); BIO_puts(bp,"\n"); } } #endif BN_GF2m_add(f, a, d); BN_GF2m_mod_mul(g, f, c, b[j], ctx); BN_GF2m_mod_mul(h, d, c, b[j], ctx); BN_GF2m_add(f, e, g); BN_GF2m_add(f, f, h); /* Test that (a+d)*c = a*c + d*c. */ if(!BN_is_zero(f)) { fprintf(stderr,"GF(2^m) modular multiplication test failed!\n"); goto err; } } } ret = 1; err: BN_free(a); BN_free(b[0]); BN_free(b[1]); BN_free(c); BN_free(d); BN_free(e); BN_free(f); BN_free(g); BN_free(h); return ret; } CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void fe_netjoin_deinit(void) { while (joinservers != NULL) netjoin_server_remove(joinservers->data); if (join_tag != -1) { g_source_remove(join_tag); signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting); } signal_remove("setup changed", (SIGNAL_FUNC) read_settings); signal_remove("message quit", (SIGNAL_FUNC) msg_quit); signal_remove("message join", (SIGNAL_FUNC) msg_join); signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode); } CWE ID: CWE-416 Target: 1 Example 2: Code: network_resolve (const char *hostname, char *ip, int *version) { char ipbuffer[NI_MAXHOST]; struct addrinfo *res; if (version != NULL) *version = 0; res = NULL; if (getaddrinfo (hostname, NULL, NULL, &res) != 0) return 0; if (!res) return 0; if (getnameinfo (res->ai_addr, res->ai_addrlen, ipbuffer, sizeof(ipbuffer), NULL, 0, NI_NUMERICHOST) != 0) { freeaddrinfo (res); return 0; } if ((res->ai_family == AF_INET) && (version != NULL)) *version = 4; if ((res->ai_family == AF_INET6) && (version != NULL)) *version = 6; strcpy (ip, ipbuffer); freeaddrinfo (res); /* resolution ok */ return 1; } 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 cJSON *create_reference( cJSON *item ) { cJSON *ref; if ( ! ( ref = cJSON_New_Item() ) ) return 0; memcpy( ref, item, sizeof(cJSON) ); ref->string = 0; ref->type |= cJSON_IsReference; ref->next = ref->prev = 0; return ref; } 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 coroutine_fn v9fs_write(void *opaque) { ssize_t err; int32_t fid; uint64_t off; uint32_t count; int32_t len = 0; int32_t total = 0; size_t offset = 7; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; QEMUIOVector qiov_full; QEMUIOVector qiov; err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count); if (err < 0) { pdu_complete(pdu, err); return; } offset += err; v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true); trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -EINVAL; goto out_nofid; } if (fidp->fid_type == P9_FID_FILE) { if (fidp->fs.fd == -1) { err = -EINVAL; goto out; } } else if (fidp->fid_type == P9_FID_XATTR) { /* * setxattr operation */ err = v9fs_xattr_write(s, pdu, fidp, off, count, qiov_full.iov, qiov_full.niov); goto out; } else { err = -EINVAL; goto out; } qemu_iovec_init(&qiov, qiov_full.niov); do { qemu_iovec_reset(&qiov); qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total); if (0) { print_sg(qiov.iov, qiov.niov); } /* Loop in case of EINTR */ do { len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off); if (len >= 0) { off += len; total += len; } } while (len == -EINTR && !pdu->cancelled); if (len < 0) { /* IO error return the error */ err = len; goto out_qiov; } } while (total < count && len > 0); offset = 7; err = pdu_marshal(pdu, offset, "d", total); if (err < 0) { goto out; } err += offset; trace_v9fs_write_return(pdu->tag, pdu->id, total, err); out_qiov: qemu_iovec_destroy(&qiov); out: put_fid(pdu, fidp); out_nofid: qemu_iovec_destroy(&qiov_full); pdu_complete(pdu, err); } CWE ID: CWE-399 Target: 1 Example 2: Code: void *netdev_alloc_frag(unsigned int fragsz) { return __netdev_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD); } 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: zset_outputintent(i_ctx_t * i_ctx_p) { os_ptr op = osp; int code = 0; gx_device *dev = gs_currentdevice(igs); cmm_dev_profile_t *dev_profile; stream * s = 0L; ref * pnval; ref * pstrmval; int ncomps, dev_comps; cmm_profile_t *picc_profile; int expected = 0; gs_color_space_index index; gsicc_manager_t *icc_manager = igs->icc_manager; cmm_profile_t *source_profile = NULL; check_type(*op, t_dictionary); check_dict_read(*op); if_debug0m(gs_debug_flag_icc, imemory, "[icc] Using OutputIntent\n"); /* Get the device structure */ code = dev_proc(dev, get_profile)(dev, &dev_profile); if (code < 0) return code; if (dev_profile == NULL) { code = gsicc_init_device_profile_struct(dev, NULL, 0); if (code < 0) return code; code = dev_proc(dev, get_profile)(dev, &dev_profile); if (code < 0) return code; } if (dev_profile->oi_profile != NULL) { return 0; /* Allow only one setting of this object */ } code = dict_find_string(op, "N", &pnval); if (code < 0) return code; if (code == 0) return_error(gs_error_undefined); ncomps = pnval->value.intval; /* verify the DataSource entry. Creat profile from stream */ check_read_file(i_ctx_p, s, pstrmval); picc_profile = gsicc_profile_new(s, gs_gstate_memory(igs), NULL, 0); if (picc_profile == NULL) return gs_throw(gs_error_VMerror, "Creation of ICC profile failed"); picc_profile->num_comps = ncomps; picc_profile->profile_handle = gsicc_get_profile_handle_buffer(picc_profile->buffer, picc_profile->buffer_size, gs_gstate_memory(igs)); if (picc_profile->profile_handle == NULL) { rc_decrement(picc_profile,"zset_outputintent"); return -1; } picc_profile->data_cs = gscms_get_profile_data_space(picc_profile->profile_handle, picc_profile->memory); switch (picc_profile->data_cs) { case gsCIEXYZ: case gsCIELAB: case gsRGB: expected = 3; source_profile = icc_manager->default_rgb; break; case gsGRAY: expected = 1; source_profile = icc_manager->default_gray; break; case gsCMYK: expected = 4; source_profile = icc_manager->default_cmyk; break; case gsNCHANNEL: expected = 0; break; case gsNAMED: case gsUNDEFINED: break; } if (expected && ncomps != expected) { rc_decrement(picc_profile,"zset_outputintent"); return_error(gs_error_rangecheck); } gsicc_init_hash_cs(picc_profile, igs); /* All is well with the profile. Lets set the stuff that needs to be set */ dev_profile->oi_profile = picc_profile; picc_profile->name = (char *) gs_alloc_bytes(picc_profile->memory, MAX_DEFAULT_ICC_LENGTH, "zset_outputintent"); strncpy(picc_profile->name, OI_PROFILE, strlen(OI_PROFILE)); picc_profile->name[strlen(OI_PROFILE)] = 0; picc_profile->name_length = strlen(OI_PROFILE); /* Set the range of the profile */ gsicc_set_icc_range(&picc_profile); /* If the output device has a different number of componenets, then we are going to set the output intent as the proofing profile, unless the proofing profile has already been set. If the device has the same number of components (and color model) then as the profile we will use this as the output profile, unless someone has explicitly set the output profile. Finally, we will use the output intent profile for the default profile of the proper Device profile in the icc manager, again, unless someone has explicitly set this default profile. */ dev_comps = dev_profile->device_profile[0]->num_comps; index = gsicc_get_default_type(dev_profile->device_profile[0]); if (ncomps == dev_comps && index < gs_color_space_index_DevicePixel) { /* The OI profile is the same type as the profile for the device and a "default" profile for the device was not externally set. So we go ahead and use the OI profile as the device profile. Care needs to be taken here to keep from screwing up any device parameters. We will use a keyword of OIProfile for the user/device parameter to indicate its usage. Also, note conflicts if one is setting object dependent color management */ rc_assign(dev_profile->device_profile[0], picc_profile, "zset_outputintent"); if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used for device profile\n"); } else { if (dev_profile->proof_profile == NULL) { /* This means that we should use the OI profile as the proofing profile. Note that if someone already has specified a proofing profile it is unclear what they are trying to do with the output intent. In this case, we will use it just for the source data below */ dev_profile->proof_profile = picc_profile; rc_increment(picc_profile); if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used for proof profile\n"); } } /* Now the source colors. See which source color space needs to use the output intent ICC profile */ index = gsicc_get_default_type(source_profile); if (index < gs_color_space_index_DevicePixel) { /* source_profile is currently the default. Set it to the OI profile */ switch (picc_profile->data_cs) { case gsGRAY: if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used source Gray\n"); rc_assign(icc_manager->default_gray, picc_profile, "zset_outputintent"); break; case gsRGB: if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used source RGB\n"); rc_assign(icc_manager->default_rgb, picc_profile, "zset_outputintent"); break; case gsCMYK: if_debug0m(gs_debug_flag_icc, imemory, "[icc] OutputIntent used source CMYK\n"); rc_assign(icc_manager->default_cmyk, picc_profile, "zset_outputintent"); break; default: break; } } /* Remove the output intent dict from the stack */ pop(1); return code; } CWE ID: CWE-704 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { SEPARATE_ZVAL(var2); convert_to_double(*var2); matrix[i][j] = (float)Z_DVAL_PP(var2); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } } CWE ID: CWE-189 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoDiscardFramebufferEXT(GLenum target, GLsizei numAttachments, const GLenum* attachments) { Framebuffer* framebuffer = GetFramebufferInfoForTarget(GL_FRAMEBUFFER); for (GLsizei i = 0; i < numAttachments; ++i) { if ((framebuffer && !validators_->attachment.IsValid(attachments[i])) || (!framebuffer && !validators_->backbuffer_attachment.IsValid(attachments[i]))) { LOCAL_SET_GL_ERROR_INVALID_ENUM( "glDiscardFramebufferEXT", attachments[i], "attachments"); return; } } for (GLsizei i = 0; i < numAttachments; ++i) { if (framebuffer) { framebuffer->MarkAttachmentAsCleared(renderbuffer_manager(), texture_manager(), attachments[i], false); } else { switch (attachments[i]) { case GL_COLOR_EXT: backbuffer_needs_clear_bits_ |= GL_COLOR_BUFFER_BIT; break; case GL_DEPTH_EXT: backbuffer_needs_clear_bits_ |= GL_DEPTH_BUFFER_BIT; case GL_STENCIL_EXT: backbuffer_needs_clear_bits_ |= GL_STENCIL_BUFFER_BIT; break; default: NOTREACHED(); break; } } } scoped_ptr<GLenum[]> translated_attachments(new GLenum[numAttachments]); for (GLsizei i = 0; i < numAttachments; ++i) { GLenum attachment = attachments[i]; if (!framebuffer && GetBackbufferServiceId()) { switch (attachment) { case GL_COLOR_EXT: attachment = GL_COLOR_ATTACHMENT0; break; case GL_DEPTH_EXT: attachment = GL_DEPTH_ATTACHMENT; break; case GL_STENCIL_EXT: attachment = GL_STENCIL_ATTACHMENT; break; default: NOTREACHED(); return; } } translated_attachments[i] = attachment; } glDiscardFramebufferEXT(target, numAttachments, translated_attachments.get()); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int dev_get_valid_name(struct net *net, struct net_device *dev, const char *name) { BUG_ON(!net); if (!dev_valid_name(name)) return -EINVAL; if (strchr(name, '%')) return dev_alloc_name_ns(net, dev, name); else if (__dev_get_by_name(net, name)) return -EEXIST; else if (dev->name != name) strlcpy(dev->name, name, IFNAMSIZ); return 0; } 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: int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } CWE ID: CWE-476 Target: 1 Example 2: Code: static int decode_setclientid(struct xdr_stream *xdr, struct nfs4_setclientid_res *res) { __be32 *p; uint32_t opnum; int32_t nfserr; p = xdr_inline_decode(xdr, 8); if (unlikely(!p)) goto out_overflow; opnum = be32_to_cpup(p++); if (opnum != OP_SETCLIENTID) { dprintk("nfs: decode_setclientid: Server returned operation" " %d\n", opnum); return -EIO; } nfserr = be32_to_cpup(p); if (nfserr == NFS_OK) { p = xdr_inline_decode(xdr, 8 + NFS4_VERIFIER_SIZE); if (unlikely(!p)) goto out_overflow; p = xdr_decode_hyper(p, &res->clientid); memcpy(res->confirm.data, p, NFS4_VERIFIER_SIZE); } else if (nfserr == NFSERR_CLID_INUSE) { uint32_t len; /* skip netid string */ p = xdr_inline_decode(xdr, 4); if (unlikely(!p)) goto out_overflow; len = be32_to_cpup(p); p = xdr_inline_decode(xdr, len); if (unlikely(!p)) goto out_overflow; /* skip uaddr string */ p = xdr_inline_decode(xdr, 4); if (unlikely(!p)) goto out_overflow; len = be32_to_cpup(p); p = xdr_inline_decode(xdr, len); if (unlikely(!p)) goto out_overflow; return -NFSERR_CLID_INUSE; } else return nfs4_stat_to_errno(nfserr); return 0; out_overflow: print_overflow_msg(__func__, xdr); return -EIO; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameHostImpl::ExecuteJavaScript( const base::string16& javascript, const JavaScriptResultCallback& callback) { CHECK(CanExecuteJavaScript()); int key = g_next_javascript_callback_id++; Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_, javascript, key, true)); javascript_callbacks_.emplace(key, callback); } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; while (i < *striplength) { tsize_t datalen; uint16 ri; uint16 v_samp; uint16 h_samp; int j; int ncomp; /* marker header: one or more FFs */ if (strip[i] != 0xff) return(0); i++; while (i < *striplength && strip[i] == 0xff) i++; if (i >= *striplength) return(0); /* SOI is the only pre-SOS marker without a length word */ if (strip[i] == 0xd8) datalen = 0; else { if ((*striplength - i) <= 2) return(0); datalen = (strip[i+1] << 8) | strip[i+2]; if (datalen < 2 || datalen >= (*striplength - i)) return(0); } switch( strip[i] ){ case 0xd8: /* SOI - start of image */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); *bufferoffset+=2; break; case 0xc0: /* SOF0 */ case 0xc1: /* SOF1 */ case 0xc3: /* SOF3 */ case 0xc9: /* SOF9 */ case 0xca: /* SOF10 */ if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); ncomp = buffer[*bufferoffset+9]; if (ncomp < 1 || ncomp > 4) return(0); v_samp=1; h_samp=1; for(j=0;j<ncomp;j++){ uint16 samp = buffer[*bufferoffset+11+(3*j)]; if( (samp>>4) > h_samp) h_samp = (samp>>4); if( (samp & 0x0f) > v_samp) v_samp = (samp & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=datalen+2; /* insert a DRI marker */ buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } break; case 0xc4: /* DHT */ case 0xdb: /* DQT */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; break; case 0xda: /* SOS */ if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); *bufferoffset+=datalen+2; } else { buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); } i += datalen + 1; /* copy remainder of strip */ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i); *bufferoffset+= *striplength - i; return(1); default: /* ignore any other marker */ break; } i += datalen + 1; } /* failed to find SOS marker */ return(0); } CWE ID: CWE-787 Target: 1 Example 2: Code: const AutocompleteInput ZeroSuggestProvider::GetInput(bool is_keyword) const { return AutocompleteInput(base::string16(), base::string16::npos, std::string(), GURL(current_query_), current_title_, current_page_classification_, true, false, false, true, false, client()->GetSchemeClassifier()); } 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: e1000e_set_ctrlext(E1000ECore *core, int index, uint32_t val) { trace_e1000e_link_set_ext_params(!!(val & E1000_CTRL_EXT_ASDCHK), !!(val & E1000_CTRL_EXT_SPD_BYPS)); /* Zero self-clearing bits */ val &= ~(E1000_CTRL_EXT_ASDCHK | E1000_CTRL_EXT_EE_RST); core->mac[CTRL_EXT] = val; } CWE ID: CWE-835 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: my_object_throw_error (MyObject *obj, GError **error) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "%s", "this method always loses"); return FALSE; } CWE ID: CWE-264 Target: 1 Example 2: Code: bool TextureManager::TextureInfo::SetParameter( const FeatureInfo* feature_info, GLenum pname, GLint param) { DCHECK(feature_info); if (target_ == GL_TEXTURE_EXTERNAL_OES || target_ == GL_TEXTURE_RECTANGLE_ARB) { if (pname == GL_TEXTURE_MIN_FILTER && (param != GL_NEAREST && param != GL_LINEAR)) return false; if ((pname == GL_TEXTURE_WRAP_S || pname == GL_TEXTURE_WRAP_T) && param != GL_CLAMP_TO_EDGE) return false; } switch (pname) { case GL_TEXTURE_MIN_FILTER: if (!feature_info->validators()->texture_min_filter_mode.IsValid(param)) { return false; } min_filter_ = param; break; case GL_TEXTURE_MAG_FILTER: if (!feature_info->validators()->texture_mag_filter_mode.IsValid(param)) { return false; } mag_filter_ = param; break; case GL_TEXTURE_WRAP_S: if (!feature_info->validators()->texture_wrap_mode.IsValid(param)) { return false; } wrap_s_ = param; break; case GL_TEXTURE_WRAP_T: if (!feature_info->validators()->texture_wrap_mode.IsValid(param)) { return false; } wrap_t_ = param; break; case GL_TEXTURE_MAX_ANISOTROPY_EXT: break; case GL_TEXTURE_USAGE_ANGLE: if (!feature_info->validators()->texture_usage.IsValid(param)) { return false; } usage_ = param; break; default: NOTREACHED(); return false; } Update(feature_info); UpdateCleared(); return true; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void btrfs_extend_item(struct btrfs_root *root, struct btrfs_path *path, u32 data_size) { int slot; struct extent_buffer *leaf; struct btrfs_item *item; u32 nritems; unsigned int data_end; unsigned int old_data; unsigned int old_size; int i; struct btrfs_map_token token; btrfs_init_map_token(&token); leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); data_end = leaf_data_end(root, leaf); if (btrfs_leaf_free_space(root, leaf) < data_size) { btrfs_print_leaf(root, leaf); BUG(); } slot = path->slots[0]; old_data = btrfs_item_end_nr(leaf, slot); BUG_ON(slot < 0); if (slot >= nritems) { btrfs_print_leaf(root, leaf); btrfs_crit(root->fs_info, "slot %d too large, nritems %d", slot, nritems); BUG_ON(1); } /* * item0..itemN ... dataN.offset..dataN.size .. data0.size */ /* first correct the data pointers */ for (i = slot; i < nritems; i++) { u32 ioff; item = btrfs_item_nr(i); ioff = btrfs_token_item_offset(leaf, item, &token); btrfs_set_token_item_offset(leaf, item, ioff - data_size, &token); } /* shift the data */ memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) + data_end - data_size, btrfs_leaf_data(leaf) + data_end, old_data - data_end); data_end = old_data; old_size = btrfs_item_size_nr(leaf, slot); item = btrfs_item_nr(slot); btrfs_set_item_size(leaf, item, old_size + data_size); btrfs_mark_buffer_dirty(leaf); if (btrfs_leaf_free_space(root, leaf) < 0) { btrfs_print_leaf(root, leaf); BUG(); } } 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: bool WebPageSerializer::serialize(WebFrame* frame, bool recursive, WebPageSerializerClient* client, const WebVector<WebURL>& links, const WebVector<WebString>& localPaths, const WebString& localDirectoryName) { ASSERT(frame); ASSERT(client); ASSERT(links.size() == localPaths.size()); LinkLocalPathMap m_localLinks; for (size_t i = 0; i < links.size(); i++) { KURL url = links[i]; ASSERT(!m_localLinks.contains(url.string())); m_localLinks.set(url.string(), localPaths[i]); } Vector<SerializedResource> resources; PageSerializer serializer(&resources, &m_localLinks, localDirectoryName); serializer.serialize(toWebViewImpl(frame->view())->page()); for (Vector<SerializedResource>::const_iterator iter = resources.begin(); iter != resources.end(); ++iter) { client->didSerializeDataForFrame(iter->url, WebCString(iter->data->data(), iter->data->size()), WebPageSerializerClient::CurrentFrameIsFinished); } client->didSerializeDataForFrame(KURL(), WebCString("", 0), WebPageSerializerClient::AllFramesAreFinished); return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool Document::isAnimatingFullScreen() const { return m_isAnimatingFullScreen; } 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: AuthenticatorTransportSelectorSheetModel::GetStepIllustration( ImageColorScheme color_scheme) const { return color_scheme == ImageColorScheme::kDark ? kWebauthnWelcomeDarkIcon : kWebauthnWelcomeIcon; } 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 PrintViewManagerBase::OnDidPrintPage( const PrintHostMsg_DidPrintPage_Params& params) { if (!OpportunisticallyCreatePrintJob(params.document_cookie)) return; PrintedDocument* document = print_job_->document(); if (!document || params.document_cookie != document->cookie()) { return; } #if defined(OS_MACOSX) const bool metafile_must_be_valid = true; #else const bool metafile_must_be_valid = expecting_first_page_; expecting_first_page_ = false; #endif std::unique_ptr<base::SharedMemory> shared_buf; if (metafile_must_be_valid) { if (!base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { NOTREACHED() << "invalid memory handle"; web_contents()->Stop(); return; } shared_buf = base::MakeUnique<base::SharedMemory>(params.metafile_data_handle, true); if (!shared_buf->Map(params.data_size)) { NOTREACHED() << "couldn't map"; web_contents()->Stop(); return; } } else { if (base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { NOTREACHED() << "unexpected valid memory handle"; web_contents()->Stop(); base::SharedMemory::CloseHandle(params.metafile_data_handle); return; } } std::unique_ptr<PdfMetafileSkia> metafile( new PdfMetafileSkia(SkiaDocumentType::PDF)); if (metafile_must_be_valid) { if (!metafile->InitFromData(shared_buf->memory(), params.data_size)) { NOTREACHED() << "Invalid metafile header"; web_contents()->Stop(); return; } } #if defined(OS_WIN) print_job_->AppendPrintedPage(params.page_number); if (metafile_must_be_valid) { scoped_refptr<base::RefCountedBytes> bytes = new base::RefCountedBytes( reinterpret_cast<const unsigned char*>(shared_buf->memory()), params.data_size); document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf")); const auto& settings = document->settings(); if (settings.printer_is_textonly()) { print_job_->StartPdfToTextConversion(bytes, params.page_size); } else if ((settings.printer_is_ps2() || settings.printer_is_ps3()) && !base::FeatureList::IsEnabled( features::kDisablePostScriptPrinting)) { print_job_->StartPdfToPostScriptConversion(bytes, params.content_area, params.physical_offsets, settings.printer_is_ps2()); } else { bool print_text_with_gdi = settings.print_text_with_gdi() && !settings.printer_is_xps() && base::FeatureList::IsEnabled( features::kGdiTextPrinting); print_job_->StartPdfToEmfConversion( bytes, params.page_size, params.content_area, print_text_with_gdi); } } #else document->SetPage(params.page_number, std::move(metafile), #if defined(OS_WIN) 0.0f /* dummy shrink_factor */, #endif params.page_size, params.content_area); ShouldQuitFromInnerMessageLoop(); #endif } CWE ID: CWE-254 Target: 1 Example 2: Code: static void voidMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::voidMethodMethod(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: RenderFrameHostManager::DetermineSiteInstanceForURL( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* current_instance, SiteInstance* dest_instance, ui::PageTransition transition, bool dest_is_restore, bool dest_is_view_source_mode, bool force_browsing_instance_swap, bool was_server_redirect) { SiteInstanceImpl* current_instance_impl = static_cast<SiteInstanceImpl*>(current_instance); NavigationControllerImpl& controller = delegate_->GetControllerForRenderManager(); BrowserContext* browser_context = controller.GetBrowserContext(); if (dest_instance) { if (force_browsing_instance_swap) { CHECK(!dest_instance->IsRelatedSiteInstance( render_frame_host_->GetSiteInstance())); } return SiteInstanceDescriptor(dest_instance); } if (force_browsing_instance_swap) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kProcessPerSite) && ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) { return SiteInstanceDescriptor(current_instance_impl); } if (SiteIsolationPolicy::AreCrossProcessFramesPossible() && !frame_tree_node_->IsMainFrame()) { SiteInstance* parent_site_instance = frame_tree_node_->parent()->current_frame_host()->GetSiteInstance(); if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) && dest_url.SchemeIs(kChromeUIScheme)) { return SiteInstanceDescriptor(parent_site_instance); } } if (!current_instance_impl->HasSite()) { bool use_process_per_site = RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) && RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url); if (current_instance_impl->HasRelatedSiteInstance(dest_url) || use_process_per_site) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } if (current_instance_impl->HasWrongProcessForURL(dest_url)) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); if (dest_is_view_source_mode) return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL( browser_context, dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } if (dest_is_restore && GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) { current_instance_impl->SetSite(dest_url); } return SiteInstanceDescriptor(current_instance_impl); } NavigationEntry* current_entry = controller.GetLastCommittedEntry(); if (interstitial_page_) { current_entry = controller.GetEntryAtOffset(-1); } if (current_entry && current_entry->IsViewSourceMode() != dest_is_view_source_mode && !IsRendererDebugURL(dest_url)) { return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::UNRELATED); } GURL about_blank(url::kAboutBlankURL); GURL about_srcdoc(content::kAboutSrcDocURL); bool dest_is_data_or_about = dest_url == about_srcdoc || dest_url == about_blank || dest_url.scheme() == url::kDataScheme; if (source_instance && dest_is_data_or_about && !was_server_redirect) return SiteInstanceDescriptor(source_instance); if (IsCurrentlySameSite(render_frame_host_.get(), dest_url)) return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) { if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* main_frame = frame_tree_node_->frame_tree()->root()->current_frame_host(); if (IsCurrentlySameSite(main_frame, dest_url)) return SiteInstanceDescriptor(main_frame->GetSiteInstance()); } if (frame_tree_node_->opener()) { RenderFrameHostImpl* opener_frame = frame_tree_node_->opener()->current_frame_host(); if (IsCurrentlySameSite(opener_frame, dest_url)) return SiteInstanceDescriptor(opener_frame->GetSiteInstance()); } } if (!frame_tree_node_->IsMainFrame() && SiteIsolationPolicy::IsTopDocumentIsolationEnabled() && !SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url)) { if (GetContentClient() ->browser() ->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation( dest_url, current_instance)) { return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance()); } return SiteInstanceDescriptor( browser_context, dest_url, SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME); } if (!frame_tree_node_->IsMainFrame()) { RenderFrameHostImpl* parent = frame_tree_node_->parent()->current_frame_host(); bool dest_url_requires_dedicated_process = SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context, dest_url); if (!parent->GetSiteInstance()->RequiresDedicatedProcess() && !dest_url_requires_dedicated_process) { return SiteInstanceDescriptor(parent->GetSiteInstance()); } } return SiteInstanceDescriptor(browser_context, dest_url, SiteInstanceRelation::RELATED); } 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: Segment::Segment(IMkvReader* pReader, long long elem_start, long long start, long long size) : m_pReader(pReader), m_element_start(elem_start), m_start(start), m_size(size), m_pos(start), m_pUnknownSize(0), m_pSeekHead(NULL), m_pInfo(NULL), m_pTracks(NULL), m_pCues(NULL), m_pChapters(NULL), m_clusters(NULL), m_clusterCount(0), m_clusterPreloadCount(0), m_clusterSize(0) {} CWE ID: CWE-20 Target: 1 Example 2: Code: static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu) { if (skb->len <= mtu) return false; /* ipv6 conntrack defrag sets max_frag_size + ignore_df */ if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu) return true; if (skb->ignore_df) return false; if (skb_is_gso(skb) && skb_gso_network_seglen(skb) <= mtu) return false; return true; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool lockdep_rtnl_is_held(void) { return lockdep_is_held(&rtnl_mutex); } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); get_block_t *get_block; /* * Fallback to buffered I/O if we see an inode without * extents. */ if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) return 0; /* Fallback to buffered I/O if we do not support append dio. */ if (iocb->ki_pos + iter->count > i_size_read(inode) && !ocfs2_supports_append_dio(osb)) return 0; if (iov_iter_rw(iter) == READ) get_block = ocfs2_get_block; else get_block = ocfs2_dio_get_block; return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter, get_block, ocfs2_dio_end_io, NULL, 0); } CWE ID: CWE-362 Target: 1 Example 2: Code: bool readDOMFileSystem(v8::Handle<v8::Value>* value) { uint32_t type; String name; String url; if (!doReadUint32(&type)) return false; if (!readWebCoreString(&name)) return false; if (!readWebCoreString(&url)) return false; DOMFileSystem* fs = DOMFileSystem::create(m_scriptState->executionContext(), name, static_cast<blink::FileSystemType>(type), KURL(ParsedURLString, url)); *value = toV8(fs, m_scriptState->context()->Global(), isolate()); 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: ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_) { PCNetState *s = qemu_get_nic_opaque(nc); int is_padr = 0, is_bcast = 0, is_ladr = 0; uint8_t buf1[60]; int remaining; int crc_err = 0; int size = size_; if (CSR_DRX(s) || CSR_STOP(s) || CSR_SPND(s) || !size || (CSR_LOOP(s) && !s->looptest)) { return -1; } #ifdef PCNET_DEBUG printf("pcnet_receive size=%d\n", size); #endif /* if too small buffer, then expand it */ if (size < MIN_BUF_SIZE) { memcpy(buf1, buf, size); memset(buf1 + size, 0, MIN_BUF_SIZE - size); buf = buf1; size = MIN_BUF_SIZE; } if (CSR_PROM(s) || (is_padr=padr_match(s, buf, size)) || (is_bcast=padr_bcast(s, buf, size)) || (is_ladr=ladr_match(s, buf, size))) { pcnet_rdte_poll(s); if (!(CSR_CRST(s) & 0x8000) && s->rdra) { struct pcnet_RMD rmd; int rcvrc = CSR_RCVRC(s)-1,i; hwaddr nrda; for (i = CSR_RCVRL(s)-1; i > 0; i--, rcvrc--) { if (rcvrc <= 1) rcvrc = CSR_RCVRL(s); nrda = s->rdra + (CSR_RCVRL(s) - rcvrc) * (BCR_SWSTYLE(s) ? 16 : 8 ); RMDLOAD(&rmd, nrda); if (GET_FIELD(rmd.status, RMDS, OWN)) { #ifdef PCNET_DEBUG_RMD printf("pcnet - scan buffer: RCVRC=%d PREV_RCVRC=%d\n", rcvrc, CSR_RCVRC(s)); #endif CSR_RCVRC(s) = rcvrc; pcnet_rdte_poll(s); break; } } } if (!(CSR_CRST(s) & 0x8000)) { #ifdef PCNET_DEBUG_RMD printf("pcnet - no buffer: RCVRC=%d\n", CSR_RCVRC(s)); #endif s->csr[0] |= 0x1000; /* Set MISS flag */ CSR_MISSC(s)++; } else { uint8_t *src = s->buffer; hwaddr crda = CSR_CRDA(s); struct pcnet_RMD rmd; int pktcount = 0; if (!s->looptest) { memcpy(src, buf, size); /* no need to compute the CRC */ src[size] = 0; uint32_t fcs = ~0; uint8_t *p = src; while (p != &src[size]) CRC(fcs, *p++); *(uint32_t *)p = htonl(fcs); size += 4; } else { uint32_t fcs = ~0; uint8_t *p = src; while (p != &src[size]) CRC(fcs, *p++); crc_err = (*(uint32_t *)p != htonl(fcs)); } #ifdef PCNET_DEBUG_MATCH PRINT_PKTHDR(buf); #endif RMDLOAD(&rmd, PHYSADDR(s,crda)); /*if (!CSR_LAPPEN(s))*/ SET_FIELD(&rmd.status, RMDS, STP, 1); #define PCNET_RECV_STORE() do { \ int count = MIN(4096 - GET_FIELD(rmd.buf_length, RMDL, BCNT),remaining); \ hwaddr rbadr = PHYSADDR(s, rmd.rbadr); \ s->phys_mem_write(s->dma_opaque, rbadr, src, count, CSR_BSWP(s)); \ src += count; remaining -= count; \ SET_FIELD(&rmd.status, RMDS, OWN, 0); \ RMDSTORE(&rmd, PHYSADDR(s,crda)); \ pktcount++; \ } while (0) remaining = size; PCNET_RECV_STORE(); if ((remaining > 0) && CSR_NRDA(s)) { hwaddr nrda = CSR_NRDA(s); #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif RMDLOAD(&rmd, PHYSADDR(s,nrda)); if (GET_FIELD(rmd.status, RMDS, OWN)) { crda = nrda; PCNET_RECV_STORE(); #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif if ((remaining > 0) && (nrda=CSR_NNRD(s))) { RMDLOAD(&rmd, PHYSADDR(s,nrda)); if (GET_FIELD(rmd.status, RMDS, OWN)) { crda = nrda; PCNET_RECV_STORE(); } } } } #undef PCNET_RECV_STORE RMDLOAD(&rmd, PHYSADDR(s,crda)); if (remaining == 0) { SET_FIELD(&rmd.msg_length, RMDM, MCNT, size); SET_FIELD(&rmd.status, RMDS, ENP, 1); SET_FIELD(&rmd.status, RMDS, PAM, !CSR_PROM(s) && is_padr); SET_FIELD(&rmd.status, RMDS, LFAM, !CSR_PROM(s) && is_ladr); SET_FIELD(&rmd.status, RMDS, BAM, !CSR_PROM(s) && is_bcast); if (crc_err) { SET_FIELD(&rmd.status, RMDS, CRC, 1); SET_FIELD(&rmd.status, RMDS, ERR, 1); } } else { SET_FIELD(&rmd.status, RMDS, OFLO, 1); SET_FIELD(&rmd.status, RMDS, BUFF, 1); SET_FIELD(&rmd.status, RMDS, ERR, 1); } RMDSTORE(&rmd, PHYSADDR(s,crda)); s->csr[0] |= 0x0400; #ifdef PCNET_DEBUG printf("RCVRC=%d CRDA=0x%08x BLKS=%d\n", CSR_RCVRC(s), PHYSADDR(s,CSR_CRDA(s)), pktcount); #endif #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif while (pktcount--) { if (CSR_RCVRC(s) <= 1) CSR_RCVRC(s) = CSR_RCVRL(s); else CSR_RCVRC(s)--; } pcnet_rdte_poll(s); } } pcnet_poll(s); pcnet_update_irq(s); return size_; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AppCacheUpdateJob::OnManifestDataWriteComplete(int result) { if (result > 0) { AppCacheEntry entry(AppCacheEntry::MANIFEST, manifest_response_writer_->response_id(), manifest_response_writer_->amount_written()); if (!inprogress_cache_->AddOrModifyEntry(manifest_url_, entry)) duplicate_response_ids_.push_back(entry.response_id()); StoreGroupAndCache(); } else { HandleCacheFailure( blink::mojom::AppCacheErrorDetails( "Failed to write the manifest data to storage", blink::mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR, GURL(), 0, false /*is_cross_origin*/), DISKCACHE_ERROR, GURL()); } } CWE ID: CWE-200 Target: 1 Example 2: Code: static int sortfunc(const void *a, const void *b) { off_t diff = ((* ((struct mschmd_file **) a))->offset) - ((* ((struct mschmd_file **) b))->offset); return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0); } CWE ID: CWE-22 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ProcChangeWindowAttributes(ClientPtr client) { WindowPtr pWin; REQUEST(xChangeWindowAttributesReq); int len, rc; Mask access_mode = 0; REQUEST_AT_LEAST_SIZE(xChangeWindowAttributesReq); access_mode |= (stuff->valueMask & CWEventMask) ? DixReceiveAccess : 0; access_mode |= (stuff->valueMask & ~CWEventMask) ? DixSetAttrAccess : 0; rc = dixLookupWindow(&pWin, stuff->window, client, access_mode); if (rc != Success) return rc; len = client->req_len - bytes_to_int32(sizeof(xChangeWindowAttributesReq)); if (len != Ones(stuff->valueMask)) return BadLength; return ChangeWindowAttributes(pWin, stuff->valueMask, (XID *) &stuff[1], client); } CWE ID: CWE-369 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HostPortAllocatorSession::OnSessionRequestDone( UrlFetcher* url_fetcher, const net::URLRequestStatus& status, int response_code, const std::string& response) { url_fetchers_.erase(url_fetcher); delete url_fetcher; if (response_code != net::HTTP_OK) { LOG(WARNING) << "Received error when allocating relay session: " << response_code; TryCreateRelaySession(); return; } ReceiveSessionResponse(response); } CWE ID: CWE-399 Target: 1 Example 2: Code: void AutoFillManager::DidNavigateMainFramePostCommit( const NavigationController::LoadCommittedDetails& details, const ViewHostMsg_FrameNavigate_Params& 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: int X509_REQ_check_private_key(X509_REQ *x, EVP_PKEY *k) { EVP_PKEY *xk = NULL; int ok = 0; xk = X509_REQ_get_pubkey(x); switch (EVP_PKEY_cmp(xk, k)) { case 1: ok = 1; break; case 0: X509err(X509_F_X509_REQ_CHECK_PRIVATE_KEY, X509_R_KEY_VALUES_MISMATCH); break; case -1: X509err(X509_F_X509_REQ_CHECK_PRIVATE_KEY, X509_R_KEY_TYPE_MISMATCH); break; case -2: #ifndef OPENSSL_NO_EC if (k->type == EVP_PKEY_EC) { X509err(X509_F_X509_REQ_CHECK_PRIVATE_KEY, ERR_R_EC_LIB); break; } #endif #ifndef OPENSSL_NO_DH if (k->type == EVP_PKEY_DH) { /* No idea */ X509err(X509_F_X509_REQ_CHECK_PRIVATE_KEY, X509_R_CANT_CHECK_DH_KEY); break; } #endif X509err(X509_F_X509_REQ_CHECK_PRIVATE_KEY, X509_R_UNKNOWN_KEY_TYPE); } EVP_PKEY_free(xk); return (ok); } 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: store_current_palette(png_store *ps, int *npalette) { /* This is an internal error (the call has been made outside a read * operation.) */ if (ps->current == NULL) store_log(ps, ps->pread, "no current stream for palette", 1); /* The result may be null if there is no palette. */ *npalette = ps->current->npalette; return ps->current->palette; } CWE ID: Target: 1 Example 2: Code: void WaitForInterstitialAttach(content::WebContents* web_contents) { if (web_contents->ShowingInterstitialPage()) return; scoped_refptr<content::MessageLoopRunner> loop_runner( new content::MessageLoopRunner); InterstitialObserver observer(web_contents, loop_runner->QuitClosure(), base::Closure()); loop_runner->Run(); } 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 MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels, float source_sample_rate) { if (number_of_channels != source_number_of_channels_ || source_sample_rate != source_sample_rate_) { if (!number_of_channels || number_of_channels > BaseAudioContext::MaxNumberOfChannels() || !AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) { DLOG(ERROR) << "setFormat(" << number_of_channels << ", " << source_sample_rate << ") - unhandled format change"; Locker<MediaElementAudioSourceHandler> locker(*this); source_number_of_channels_ = 0; source_sample_rate_ = 0; return; } Locker<MediaElementAudioSourceHandler> locker(*this); source_number_of_channels_ = number_of_channels; source_sample_rate_ = source_sample_rate; if (source_sample_rate != Context()->sampleRate()) { double scale_factor = source_sample_rate / Context()->sampleRate(); multi_channel_resampler_ = std::make_unique<MultiChannelResampler>( scale_factor, number_of_channels); } else { multi_channel_resampler_.reset(); } { BaseAudioContext::GraphAutoLocker context_locker(Context()); Output(0).SetNumberOfChannels(number_of_channels); } } } 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: ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { tTcpIpPacketParsingResult res = _res; ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); res.xxpStatus = ppresXxpIncomplete; res.TcpUdp = ppresIsUDP; res.XxpIpHeaderSize = udpDataStart; if (len >= udpDataStart) { UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); USHORT datagramLength = swap_short(pUdpHeader->udp_length); res.xxpStatus = ppresXxpKnown; DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength)); } return res; } CWE ID: CWE-20 Target: 1 Example 2: Code: static void end_polls(struct fuse_conn *fc) { struct rb_node *p; p = rb_first(&fc->polled_files); while (p) { struct fuse_file *ff; ff = rb_entry(p, struct fuse_file, polled_node); wake_up_interruptible_all(&ff->poll_wait); p = rb_next(p); } } 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: AutoResetServer (int sig) { int olderrno = errno; dispatchException |= DE_RESET; isItTimeToYield = TRUE; errno = olderrno; } 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: ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); ND_PRINT((ndo," len=%d method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (1 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < len) { if(!ike_show_somedata(ndo, authdata, ep)) goto trunc; } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } CWE ID: CWE-835 Target: 1 Example 2: Code: handle_nxt_set_controller_id(struct ofconn *ofconn, const struct ofp_header *oh) { const struct nx_controller_id *nci = ofpmsg_body(oh); if (!is_all_zeros(nci->zero, sizeof nci->zero)) { return OFPERR_NXBRC_MUST_BE_ZERO; } ofconn_set_controller_id(ofconn, ntohs(nci->controller_id)); return 0; } CWE ID: CWE-617 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: DWORD OmniboxViewWin::EditDropTarget::OnDragOver(IDataObject* data_object, DWORD key_state, POINT cursor_position, DWORD effect) { if (drag_has_url_) return CopyOrLinkDropEffect(effect); if (drag_has_string_) { UpdateDropHighlightPosition(cursor_position); if (edit_->drop_highlight_position() == -1 && edit_->in_drag()) return DROPEFFECT_NONE; if (edit_->in_drag()) { DCHECK((effect & DROPEFFECT_COPY) && (effect & DROPEFFECT_MOVE)); return (key_state & MK_CONTROL) ? DROPEFFECT_COPY : DROPEFFECT_MOVE; } return CopyOrLinkDropEffect(effect); } return DROPEFFECT_NONE; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int put_chars(u32 vtermno, const char *buf, int count) { struct port *port; struct scatterlist sg[1]; if (unlikely(early_put_chars)) return early_put_chars(vtermno, buf, count); port = find_port_by_vtermno(vtermno); if (!port) return -EPIPE; sg_init_one(sg, buf, count); return __send_to_port(port, sg, 1, count, (void *)buf, false); } CWE ID: CWE-119 Target: 1 Example 2: Code: void WebLocalFrameImpl::SetCaretVisible(bool visible) { GetFrame()->Selection().SetCaretVisible(visible); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: String HTMLFormControlElement::formMethod() const { const AtomicString& formMethodAttr = fastGetAttribute(formmethodAttr); if (formMethodAttr.isNull()) return emptyString(); return FormSubmission::Attributes::methodString(FormSubmission::Attributes::parseMethodType(formMethodAttr)); } 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 XMLHttpRequest::didTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); clearResponse(); clearRequest(); m_error = true; m_exceptionCode = TimeoutError; if (!m_async) { m_state = DONE; m_exceptionCode = TimeoutError; return; } changeState(DONE); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void fib6_net_exit(struct net *net) { rt6_ifdown(net, NULL); del_timer_sync(&net->ipv6.ip6_fib_timer); #ifdef CONFIG_IPV6_MULTIPLE_TABLES inetpeer_invalidate_tree(&net->ipv6.fib6_local_tbl->tb6_peers); kfree(net->ipv6.fib6_local_tbl); #endif inetpeer_invalidate_tree(&net->ipv6.fib6_main_tbl->tb6_peers); kfree(net->ipv6.fib6_main_tbl); kfree(net->ipv6.fib_table_hash); kfree(net->ipv6.rt6_stats); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void _sx_sasl_client_process(sx_t s, sx_plugin_t p, Gsasl_session *sd, const char *mech, const char *in, int inlen) { _sx_sasl_t ctx = (_sx_sasl_t) p->private; _sx_sasl_sess_t sctx = NULL; char *buf = NULL, *out = NULL, *realm = NULL, **ext_id; char hostname[256]; int ret; #ifdef HAVE_SSL int i; #endif size_t buflen, outlen; assert(ctx); assert(ctx->cb); if(mech != NULL) { _sx_debug(ZONE, "auth request from client (mechanism=%s)", mech); if(!gsasl_server_support_p(ctx->gsasl_ctx, mech)) { _sx_debug(ZONE, "client requested mechanism (%s) that we didn't offer", mech); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INVALID_MECHANISM, NULL), 0); return; } /* startup */ ret = gsasl_server_start(ctx->gsasl_ctx, mech, &sd); if(ret != GSASL_OK) { _sx_debug(ZONE, "gsasl_server_start failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_TEMPORARY_FAILURE, gsasl_strerror(ret)), 0); return; } /* get the realm */ (ctx->cb)(sx_sasl_cb_GET_REALM, NULL, (void **) &realm, s, ctx->cbarg); /* cleanup any existing session context */ sctx = gsasl_session_hook_get(sd); if (sctx != NULL) free(sctx); /* allocate and initialize our per session context */ sctx = (_sx_sasl_sess_t) calloc(1, sizeof(struct _sx_sasl_sess_st)); sctx->s = s; sctx->ctx = ctx; gsasl_session_hook_set(sd, (void *) sctx); gsasl_property_set(sd, GSASL_SERVICE, ctx->appname); gsasl_property_set(sd, GSASL_REALM, realm); /* get hostname */ hostname[0] = '\0'; gethostname(hostname, 256); hostname[255] = '\0'; gsasl_property_set(sd, GSASL_HOSTNAME, hostname); /* get EXTERNAL data from the ssl plugin */ ext_id = NULL; #ifdef HAVE_SSL for(i = 0; i < s->env->nplugins; i++) if(s->env->plugins[i]->magic == SX_SSL_MAGIC && s->plugin_data[s->env->plugins[i]->index] != NULL) ext_id = ((_sx_ssl_conn_t) s->plugin_data[s->env->plugins[i]->index])->external_id; if (ext_id != NULL) { /* if there is, store it for later */ for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++) if (ext_id[i] != NULL) { ctx->ext_id[i] = strdup(ext_id[i]); } else { ctx->ext_id[i] = NULL; break; } } #endif _sx_debug(ZONE, "sasl context initialised for %d", s->tag); s->plugin_data[p->index] = (void *) sd; if(strcmp(mech, "ANONYMOUS") == 0) { /* * special case for SASL ANONYMOUS: ignore the initial * response provided by the client and generate a random * authid to use as the jid node for the user, as * specified in XEP-0175 */ (ctx->cb)(sx_sasl_cb_GEN_AUTHZID, NULL, (void **)&out, s, ctx->cbarg); buf = strdup(out); buflen = strlen(buf); } else if (strstr(in, "<") != NULL && strncmp(in, "=", strstr(in, "<") - in ) == 0) { /* XXX The above check is hackish, but `in` is just weird */ /* This is a special case for SASL External c2s. See XEP-0178 */ _sx_debug(ZONE, "gsasl auth string is empty"); buf = strdup(""); buflen = strlen(buf); } else { /* decode and process */ ret = gsasl_base64_from(in, inlen, &buf, &buflen); if (ret != GSASL_OK) { _sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0); if(buf != NULL) free(buf); return; } } ret = gsasl_step(sd, buf, buflen, &out, &outlen); } else { /* decode and process */ ret = gsasl_base64_from(in, inlen, &buf, &buflen); if (ret != GSASL_OK) { _sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0); return; } if(!sd) { _sx_debug(ZONE, "response send before auth request enabling mechanism (decoded: %.*s)", buflen, buf); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_MECH_TOO_WEAK, "response send before auth request enabling mechanism"), 0); if(buf != NULL) free(buf); return; } _sx_debug(ZONE, "response from client (decoded: %.*s)", buflen, buf); ret = gsasl_step(sd, buf, buflen, &out, &outlen); } if(buf != NULL) free(buf); /* auth completed */ if(ret == GSASL_OK) { _sx_debug(ZONE, "sasl handshake completed"); /* encode the leftover response */ ret = gsasl_base64_to(out, outlen, &buf, &buflen); if (ret == GSASL_OK) { /* send success */ _sx_nad_write(s, _sx_sasl_success(s, buf, buflen), 0); free(buf); /* set a notify on the success nad buffer */ ((sx_buf_t) s->wbufq->front->data)->notify = _sx_sasl_notify_success; ((sx_buf_t) s->wbufq->front->data)->notify_arg = (void *) p; } else { _sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0); if(buf != NULL) free(buf); } if(out != NULL) free(out); return; } /* in progress */ if(ret == GSASL_NEEDS_MORE) { _sx_debug(ZONE, "sasl handshake in progress (challenge: %.*s)", outlen, out); /* encode the challenge */ ret = gsasl_base64_to(out, outlen, &buf, &buflen); if (ret == GSASL_OK) { _sx_nad_write(s, _sx_sasl_challenge(s, buf, buflen), 0); free(buf); } else { _sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret)); _sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0); if(buf != NULL) free(buf); } if(out != NULL) free(out); return; } if(out != NULL) free(out); /* its over */ _sx_debug(ZONE, "sasl handshake failed; (%d): %s", ret, gsasl_strerror(ret)); switch (ret) { case GSASL_AUTHENTICATION_ERROR: case GSASL_NO_ANONYMOUS_TOKEN: case GSASL_NO_AUTHID: case GSASL_NO_AUTHZID: case GSASL_NO_PASSWORD: case GSASL_NO_PASSCODE: case GSASL_NO_PIN: case GSASL_NO_SERVICE: case GSASL_NO_HOSTNAME: out = _sasl_err_NOT_AUTHORIZED; break; case GSASL_UNKNOWN_MECHANISM: case GSASL_MECHANISM_PARSE_ERROR: out = _sasl_err_INVALID_MECHANISM; break; case GSASL_BASE64_ERROR: out = _sasl_err_INCORRECT_ENCODING; break; default: out = _sasl_err_MALFORMED_REQUEST; } _sx_nad_write(s, _sx_sasl_failure(s, out, gsasl_strerror(ret)), 0); } CWE ID: CWE-287 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int format8BIM(Image *ifile, Image *ofile) { char temp[MagickPathExtent]; unsigned int foundOSType; int ID, resCount, i, c; ssize_t count; unsigned char *PString, *str; resCount=0; foundOSType=0; /* found the OSType */ (void) foundOSType; c=ReadBlobByte(ifile); while (c != EOF) { if (c == '8') { unsigned char buffer[5]; buffer[0]=(unsigned char) c; for (i=1; i<4; i++) { c=ReadBlobByte(ifile); if (c == EOF) return(-1); buffer[i] = (unsigned char) c; } buffer[4]=0; if (strcmp((const char *)buffer, "8BIM") == 0) foundOSType=1; else continue; } else { c=ReadBlobByte(ifile); continue; } /* We found the OSType (8BIM) and now grab the ID, PString, and Size fields. */ ID=ReadBlobMSBSignedShort(ifile); if (ID < 0) return(-1); { unsigned char plen; c=ReadBlobByte(ifile); if (c == EOF) return(-1); plen = (unsigned char) c; PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+ MagickPathExtent),sizeof(*PString)); if (PString == (unsigned char *) NULL) return 0; for (i=0; i<plen; i++) { c=ReadBlobByte(ifile); if (c == EOF) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } PString[i] = (unsigned char) c; } PString[ plen ] = 0; if ((plen & 0x01) == 0) { c=ReadBlobByte(ifile); if (c == EOF) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } } } count=(ssize_t) ReadBlobMSBSignedLong(ifile); if ((count < 0) || (count > GetBlobSize(ifile))) { PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } /* make a buffer to hold the data and snag it from the input stream */ str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str)); if (str == (unsigned char *) NULL) { PString=(unsigned char *) RelinquishMagickMemory(PString); return 0; } for (i=0; i < (ssize_t) count; i++) { c=ReadBlobByte(ifile); if (c == EOF) { str=(unsigned char *) RelinquishMagickMemory(str); PString=(unsigned char *) RelinquishMagickMemory(PString); return -1; } str[i]=(unsigned char) c; } /* we currently skip thumbnails, since it does not make * any sense preserving them in a real world application */ if (ID != THUMBNAIL_ID) { /* now finish up by formatting this binary data into * ASCII equivalent */ if (strlen((const char *)PString) > 0) (void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID, PString); else (void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID); (void) WriteBlobString(ofile,temp); if (ID == IPTC_ID) { formatString(ofile, "IPTC", 4); formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count); } else formatString(ofile, (char *)str, (ssize_t) count); } str=(unsigned char *) RelinquishMagickMemory(str); PString=(unsigned char *) RelinquishMagickMemory(PString); resCount++; c=ReadBlobByte(ifile); } return resCount; } CWE ID: CWE-119 Target: 1 Example 2: Code: add_script_param(notify_script_t *script, char *param) { /* We store the args as an array of pointers to the args, terminated * by a NULL pointer, followed by the null terminated strings themselves */ if (script->args[script->num_args + 1]) { log_message(LOG_INFO, "notify_fifo_script %s no room to add parameter %s", script->args[0], param); return; } /* Add the extra parameter in the pre-reserved slot at the end */ script->args[script->num_args++] = param; } CWE ID: CWE-59 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ContextState::EnableDisableFramebufferSRGB(bool enable) { if (framebuffer_srgb_valid_ && framebuffer_srgb_ == enable) return; EnableDisable(GL_FRAMEBUFFER_SRGB, enable); framebuffer_srgb_ = enable; framebuffer_srgb_valid_ = true; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 30 && rdesc[29] == 0x05 && rdesc[30] == 0x09) { hid_info(hdev, "fixing up button/consumer in HID report descriptor\n"); rdesc[30] = 0x0c; } return rdesc; } CWE ID: CWE-119 Target: 1 Example 2: Code: void writeInt32(int32_t value) { append(Int32Tag); doWriteUint32(ZigZag::encode(static_cast<uint32_t>(value))); } 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: PNG_FUNCTION(void, (PNGCBAPI error), (png_structp png_ptr, const char *message), static PNG_NORETURN) { display *d = (display*)png_get_error_ptr(png_ptr); fprintf(stderr, "%s(%s): libpng error: %s\n", d->file, d->test, message); display_exit(d); } 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: std::unique_ptr<net::test_server::HttpResponse> GetConfigResponse( const net::test_server::HttpRequest& request) { auto response = std::make_unique<net::test_server::BasicHttpResponse>(); response->set_content(config_.SerializeAsString()); response->set_content_type("text/plain"); if (config_run_loop_) config_run_loop_->Quit(); return response; } CWE ID: CWE-416 Target: 1 Example 2: Code: static void codec_parameters_reset(AVCodecParameters *par) { av_freep(&par->extradata); memset(par, 0, sizeof(*par)); par->codec_type = AVMEDIA_TYPE_UNKNOWN; par->codec_id = AV_CODEC_ID_NONE; par->format = -1; par->field_order = AV_FIELD_UNKNOWN; par->color_range = AVCOL_RANGE_UNSPECIFIED; par->color_primaries = AVCOL_PRI_UNSPECIFIED; par->color_trc = AVCOL_TRC_UNSPECIFIED; par->color_space = AVCOL_SPC_UNSPECIFIED; par->chroma_location = AVCHROMA_LOC_UNSPECIFIED; par->sample_aspect_ratio = (AVRational){ 0, 1 }; par->profile = FF_PROFILE_UNKNOWN; par->level = FF_LEVEL_UNKNOWN; } 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 arm_iommu_unmap_sg(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction dir, struct dma_attrs *attrs) { __iommu_unmap_sg(dev, sg, nents, dir, attrs, false); } 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: get_results(struct iperf_test *test) { int r = 0; cJSON *j; cJSON *j_cpu_util_total; cJSON *j_cpu_util_user; cJSON *j_cpu_util_system; cJSON *j_sender_has_retransmits; int result_has_retransmits; cJSON *j_streams; int n, i; cJSON *j_stream; cJSON *j_id; cJSON *j_bytes; cJSON *j_retransmits; cJSON *j_jitter; cJSON *j_errors; cJSON *j_packets; cJSON *j_server_output; int sid, cerror, pcount; double jitter; iperf_size_t bytes_transferred; int retransmits; struct iperf_stream *sp; j = JSON_read(test->ctrl_sck); if (j == NULL) { i_errno = IERECVRESULTS; r = -1; } else { j_cpu_util_total = cJSON_GetObjectItem(j, "cpu_util_total"); j_cpu_util_user = cJSON_GetObjectItem(j, "cpu_util_user"); j_cpu_util_system = cJSON_GetObjectItem(j, "cpu_util_system"); j_sender_has_retransmits = cJSON_GetObjectItem(j, "sender_has_retransmits"); if (j_cpu_util_total == NULL || j_cpu_util_user == NULL || j_cpu_util_system == NULL || j_sender_has_retransmits == NULL) { i_errno = IERECVRESULTS; r = -1; } else { if (test->debug) { printf("get_results\n%s\n", cJSON_Print(j)); } test->remote_cpu_util[0] = j_cpu_util_total->valuefloat; test->remote_cpu_util[1] = j_cpu_util_user->valuefloat; test->remote_cpu_util[2] = j_cpu_util_system->valuefloat; result_has_retransmits = j_sender_has_retransmits->valueint; if (! test->sender) test->sender_has_retransmits = result_has_retransmits; j_streams = cJSON_GetObjectItem(j, "streams"); if (j_streams == NULL) { i_errno = IERECVRESULTS; r = -1; } else { n = cJSON_GetArraySize(j_streams); for (i=0; i<n; ++i) { j_stream = cJSON_GetArrayItem(j_streams, i); if (j_stream == NULL) { i_errno = IERECVRESULTS; r = -1; } else { j_id = cJSON_GetObjectItem(j_stream, "id"); j_bytes = cJSON_GetObjectItem(j_stream, "bytes"); j_retransmits = cJSON_GetObjectItem(j_stream, "retransmits"); j_jitter = cJSON_GetObjectItem(j_stream, "jitter"); j_errors = cJSON_GetObjectItem(j_stream, "errors"); j_packets = cJSON_GetObjectItem(j_stream, "packets"); if (j_id == NULL || j_bytes == NULL || j_retransmits == NULL || j_jitter == NULL || j_errors == NULL || j_packets == NULL) { i_errno = IERECVRESULTS; r = -1; } else { sid = j_id->valueint; bytes_transferred = j_bytes->valueint; retransmits = j_retransmits->valueint; jitter = j_jitter->valuefloat; cerror = j_errors->valueint; pcount = j_packets->valueint; SLIST_FOREACH(sp, &test->streams, streams) if (sp->id == sid) break; if (sp == NULL) { i_errno = IESTREAMID; r = -1; } else { if (test->sender) { sp->jitter = jitter; sp->cnt_error = cerror; sp->packet_count = pcount; sp->result->bytes_received = bytes_transferred; } else { sp->result->bytes_sent = bytes_transferred; sp->result->stream_retrans = retransmits; } } } } } /* * If we're the client and we're supposed to get remote results, * look them up and process accordingly. */ if (test->role == 'c' && iperf_get_test_get_server_output(test)) { /* Look for JSON. If we find it, grab the object so it doesn't get deleted. */ j_server_output = cJSON_DetachItemFromObject(j, "server_output_json"); if (j_server_output != NULL) { test->json_server_output = j_server_output; } else { /* No JSON, look for textual output. Make a copy of the text for later. */ j_server_output = cJSON_GetObjectItem(j, "server_output_text"); if (j_server_output != NULL) { test->server_output_text = strdup(j_server_output->valuestring); } } } } } cJSON_Delete(j); } return r; } CWE ID: CWE-119 Target: 1 Example 2: Code: void DelegatedFrameHost::ResetCompositorFrameSinkSupport() { if (!support_) return; if (compositor_) compositor_->RemoveFrameSink(frame_sink_id_); support_.reset(); } 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 btu_exec_tap_fd_read(void *p_param) { struct pollfd ufd; int fd = (int)p_param; if (fd == INVALID_FD || fd != btpan_cb.tap_fd) return; for (int i = 0; i < PAN_POOL_MAX && btif_is_enabled() && btpan_cb.flow; i++) { BT_HDR *buffer = (BT_HDR *)GKI_getpoolbuf(PAN_POOL_ID); if (!buffer) { BTIF_TRACE_WARNING("%s unable to allocate buffer for packet.", __func__); break; } buffer->offset = PAN_MINIMUM_OFFSET; buffer->len = GKI_get_buf_size(buffer) - sizeof(BT_HDR) - buffer->offset; UINT8 *packet = (UINT8 *)buffer + sizeof(BT_HDR) + buffer->offset; if (!btpan_cb.congest_packet_size) { ssize_t ret = read(fd, btpan_cb.congest_packet, sizeof(btpan_cb.congest_packet)); switch (ret) { case -1: BTIF_TRACE_ERROR("%s unable to read from driver: %s", __func__, strerror(errno)); GKI_freebuf(buffer); btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0); return; case 0: BTIF_TRACE_WARNING("%s end of file reached.", __func__); GKI_freebuf(buffer); btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0); return; default: btpan_cb.congest_packet_size = ret; break; } } memcpy(packet, btpan_cb.congest_packet, MIN(btpan_cb.congest_packet_size, buffer->len)); buffer->len = MIN(btpan_cb.congest_packet_size, buffer->len); if (buffer->len > sizeof(tETH_HDR) && should_forward((tETH_HDR *)packet)) { tETH_HDR hdr; memcpy(&hdr, packet, sizeof(tETH_HDR)); buffer->len -= sizeof(tETH_HDR); buffer->offset += sizeof(tETH_HDR); if (forward_bnep(&hdr, buffer) != FORWARD_CONGEST) btpan_cb.congest_packet_size = 0; } else { BTIF_TRACE_WARNING("%s dropping packet of length %d", __func__, buffer->len); btpan_cb.congest_packet_size = 0; GKI_freebuf(buffer); } ufd.fd = fd; ufd.events = POLLIN; ufd.revents = 0; if (poll(&ufd, 1, 0) <= 0 || IS_EXCEPTION(ufd.revents)) break; } btsock_thread_add_fd(pan_pth, fd, 0, SOCK_THREAD_FD_RD, 0); } CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int flv_write_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar; FLVContext *flv = s->priv_data; FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; unsigned ts; int size = pkt->size; uint8_t *data = NULL; int flags = -1, flags_size, ret; int64_t cur_offset = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) flags_size = 2; else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) flags_size = 5; else flags_size = 1; if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { av_free(par->extradata); par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!par->extradata) { par->extradata_size = 0; return AVERROR(ENOMEM); } memcpy(par->extradata, side, side_size); par->extradata_size = side_size; flv_write_codec_header(s, par, pkt->dts); } } if (flv->delay == AV_NOPTS_VALUE) flv->delay = -pkt->dts; if (pkt->dts < -flv->delay) { av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with respect to DTS\n"); return AVERROR(EINVAL); } ts = pkt->dts; if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { write_metadata(s, ts); s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; } avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000), pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: avio_w8(pb, FLV_TAG_TYPE_VIDEO); flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id); flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; break; case AVMEDIA_TYPE_AUDIO: flags = get_audio_flags(s, par); av_assert0(size); avio_w8(pb, FLV_TAG_TYPE_AUDIO); break; case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_DATA: avio_w8(pb, FLV_TAG_TYPE_META); break; default: return AVERROR(EINVAL); } if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { /* check if extradata looks like mp4 formatted */ if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1) if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) return ret; } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } /* check Speex packet duration */ if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than " "8 frames per packet. Adobe Flash " "Player cannot handle this!\n"); if (sc->last_ts < ts) sc->last_ts = ts; if (size + flags_size >= 1<<24) { av_log(s, AV_LOG_ERROR, "Too large packet with size %u >= %u\n", size + flags_size, 1<<24); return AVERROR(EINVAL); } avio_wb24(pb, size + flags_size); put_timestamp(pb, ts); avio_wb24(pb, flv->reserved); if (par->codec_type == AVMEDIA_TYPE_DATA || par->codec_type == AVMEDIA_TYPE_SUBTITLE ) { int data_size; int64_t metadata_size_pos = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_TEXT) { avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "onTextData"); avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); avio_wb32(pb, 2); put_amf_string(pb, "type"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "Text"); put_amf_string(pb, "text"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, pkt->data); put_amf_string(pb, ""); avio_w8(pb, AMF_END_OF_OBJECT); } else { avio_write(pb, data ? data : pkt->data, size); } /* write total size of tag */ data_size = avio_tell(pb) - metadata_size_pos; avio_seek(pb, metadata_size_pos - 10, SEEK_SET); avio_wb24(pb, data_size); avio_seek(pb, data_size + 10 - 3, SEEK_CUR); avio_wb32(pb, data_size + 11); } else { av_assert1(flags>=0); avio_w8(pb,flags); if (par->codec_id == AV_CODEC_ID_VP6) avio_w8(pb,0); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) { if (par->extradata_size) avio_w8(pb, par->extradata[0]); else avio_w8(pb, ((FFALIGN(par->width, 16) - par->width) << 4) | (FFALIGN(par->height, 16) - par->height)); } else if (par->codec_id == AV_CODEC_ID_AAC) avio_w8(pb, 1); // AAC raw else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { avio_w8(pb, 1); // AVC NALU avio_wb24(pb, pkt->pts - pkt->dts); } avio_write(pb, data ? data : pkt->data, size); avio_wb32(pb, size + flags_size + 11); // previous tag size flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration); } if (flv->flags & FLV_ADD_KEYFRAME_INDEX) { switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: flv->videosize += (avio_tell(pb) - cur_offset); flv->lasttimestamp = flv->acurframeindex / flv->framerate; if (pkt->flags & AV_PKT_FLAG_KEY) { double ts = flv->acurframeindex / flv->framerate; int64_t pos = cur_offset; flv->lastkeyframetimestamp = flv->acurframeindex / flv->framerate; flv->lastkeyframelocation = pos; flv_append_keyframe_info(s, flv, ts, pos); } flv->acurframeindex++; break; case AVMEDIA_TYPE_AUDIO: flv->audiosize += (avio_tell(pb) - cur_offset); break; default: av_log(s, AV_LOG_WARNING, "par->codec_type is type = [%d]\n", par->codec_type); break; } } av_free(data); return pb->error; } CWE ID: CWE-617 Target: 1 Example 2: Code: rdp_out_newpointer_caps(STREAM s) { out_uint16_le(s, RDP_CAPSET_POINTER); out_uint16_le(s, RDP_CAPLEN_NEWPOINTER); out_uint16_le(s, 1); /* Colour pointer */ out_uint16_le(s, 20); /* Cache size */ out_uint16_le(s, 20); /* Cache size for new pointers */ } 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: perf_event_aux(perf_event_aux_output_cb output, void *data, struct perf_event_context *task_ctx) { struct perf_cpu_context *cpuctx; struct perf_event_context *ctx; struct pmu *pmu; int ctxn; /* * If we have task_ctx != NULL we only notify * the task context itself. The task_ctx is set * only for EXIT events before releasing task * context. */ if (task_ctx) { perf_event_aux_task_ctx(output, data, task_ctx); return; } rcu_read_lock(); list_for_each_entry_rcu(pmu, &pmus, entry) { cpuctx = get_cpu_ptr(pmu->pmu_cpu_context); if (cpuctx->unique_pmu != pmu) goto next; perf_event_aux_ctx(&cpuctx->ctx, output, data); ctxn = pmu->task_ctx_nr; if (ctxn < 0) goto next; ctx = rcu_dereference(current->perf_event_ctxp[ctxn]); if (ctx) perf_event_aux_ctx(ctx, output, data); next: put_cpu_ptr(pmu->pmu_cpu_context); } rcu_read_unlock(); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PlatformSensorFusion::Create( mojo::ScopedSharedBufferMapping mapping, PlatformSensorProvider* provider, std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm, const PlatformSensorProviderBase::CreateSensorCallback& callback) { Factory::CreateSensorFusion(std::move(mapping), std::move(fusion_algorithm), callback, provider); } CWE ID: CWE-732 Target: 1 Example 2: Code: static int cryp_get_device_data(struct cryp_ctx *ctx, struct cryp_device_data **device_data) { int ret; struct klist_iter device_iterator; struct klist_node *device_node; struct cryp_device_data *local_device_data = NULL; pr_debug(DEV_DBG_NAME " [%s]", __func__); /* Wait until a device is available */ ret = down_interruptible(&driver_data.device_allocation); if (ret) return ret; /* Interrupted */ /* Select a device */ klist_iter_init(&driver_data.device_list, &device_iterator); device_node = klist_next(&device_iterator); while (device_node) { local_device_data = container_of(device_node, struct cryp_device_data, list_node); spin_lock(&local_device_data->ctx_lock); /* current_ctx allocates a device, NULL = unallocated */ if (local_device_data->current_ctx) { device_node = klist_next(&device_iterator); } else { local_device_data->current_ctx = ctx; ctx->device = local_device_data; spin_unlock(&local_device_data->ctx_lock); break; } spin_unlock(&local_device_data->ctx_lock); } klist_iter_exit(&device_iterator); if (!device_node) { /** * No free device found. * Since we allocated a device with down_interruptible, this * should not be able to happen. * Number of available devices, which are contained in * device_allocation, is therefore decremented by not doing * an up(device_allocation). */ return -EBUSY; } *device_data = local_device_data; return 0; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int decode_opaque_fixed(struct xdr_stream *xdr, void *buf, size_t len) { __be32 *p; p = xdr_inline_decode(xdr, len); if (likely(p)) { memcpy(buf, p, len); return 0; } print_overflow_msg(__func__, xdr); return -EIO; } 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: IHEVCD_ERROR_T ihevcd_mv_buf_mgr_add_bufs(codec_t *ps_codec) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 i; WORD32 max_dpb_size; WORD32 mv_bank_size_allocated; WORD32 pic_mv_bank_size; sps_t *ps_sps; UWORD8 *pu1_buf; mv_buf_t *ps_mv_buf; /* Initialize MV Bank buffer manager */ ps_sps = ps_codec->s_parse.ps_sps; /* Compute the number of MV Bank buffers needed */ max_dpb_size = ps_sps->ai1_sps_max_dec_pic_buffering[ps_sps->i1_sps_max_sub_layers - 1]; /* Allocate one extra MV Bank to handle current frame * In case of asynchronous parsing and processing, number of buffers should increase here * based on when parsing and processing threads are synchronized */ max_dpb_size++; pu1_buf = (UWORD8 *)ps_codec->pv_mv_bank_buf_base; ps_mv_buf = (mv_buf_t *)pu1_buf; pu1_buf += max_dpb_size * sizeof(mv_buf_t); ps_codec->ps_mv_buf = ps_mv_buf; mv_bank_size_allocated = ps_codec->i4_total_mv_bank_size - max_dpb_size * sizeof(mv_buf_t); /* Compute MV bank size per picture */ pic_mv_bank_size = ihevcd_get_pic_mv_bank_size(ALIGN64(ps_sps->i2_pic_width_in_luma_samples) * ALIGN64(ps_sps->i2_pic_height_in_luma_samples)); for(i = 0; i < max_dpb_size; i++) { WORD32 buf_ret; WORD32 num_pu; WORD32 num_ctb; WORD32 pic_size; pic_size = ALIGN64(ps_sps->i2_pic_width_in_luma_samples) * ALIGN64(ps_sps->i2_pic_height_in_luma_samples); num_pu = pic_size / (MIN_PU_SIZE * MIN_PU_SIZE); num_ctb = pic_size / (MIN_CTB_SIZE * MIN_CTB_SIZE); mv_bank_size_allocated -= pic_mv_bank_size; if(mv_bank_size_allocated < 0) { ps_codec->s_parse.i4_error_code = IHEVCD_INSUFFICIENT_MEM_MVBANK; return IHEVCD_INSUFFICIENT_MEM_MVBANK; } ps_mv_buf->pu4_pic_pu_idx = (UWORD32 *)pu1_buf; pu1_buf += (num_ctb + 1) * sizeof(WORD32); ps_mv_buf->pu1_pic_pu_map = pu1_buf; pu1_buf += num_pu; ps_mv_buf->pu1_pic_slice_map = (UWORD16 *)pu1_buf; pu1_buf += ALIGN4(num_ctb * sizeof(UWORD16)); ps_mv_buf->ps_pic_pu = (pu_t *)pu1_buf; pu1_buf += num_pu * sizeof(pu_t); buf_ret = ihevc_buf_mgr_add((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_mv_buf, i); if(0 != buf_ret) { ps_codec->s_parse.i4_error_code = IHEVCD_BUF_MGR_ERROR; return IHEVCD_BUF_MGR_ERROR; } ps_mv_buf++; } return ret; } CWE ID: Target: 1 Example 2: Code: void vrend_renderer_destroy_sub_ctx(struct vrend_context *ctx, int sub_ctx_id) { struct vrend_sub_context *sub, *tofree = NULL; /* never destroy sub context id 0 */ if (sub_ctx_id == 0) return; LIST_FOR_EACH_ENTRY(sub, &ctx->sub_ctxs, head) { if (sub->sub_ctx_id == sub_ctx_id) { tofree = sub; } } if (tofree) { if (ctx->sub == tofree) { ctx->sub = ctx->sub0; vrend_clicbs->make_current(0, ctx->sub->gl_context); } vrend_destroy_sub_context(tofree); } } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PP_Flash_Menu* ReadMenu(int depth, const IPC::Message* m, PickleIterator* iter) { if (depth > kMaxMenuDepth) return NULL; ++depth; PP_Flash_Menu* menu = new PP_Flash_Menu; menu->items = NULL; if (!m->ReadUInt32(iter, &menu->count)) { FreeMenu(menu); return NULL; } if (menu->count == 0) return menu; menu->items = new PP_Flash_MenuItem[menu->count]; memset(menu->items, 0, sizeof(PP_Flash_MenuItem) * menu->count); for (uint32_t i = 0; i < menu->count; ++i) { if (!ReadMenuItem(depth, m, iter, menu->items + i)) { FreeMenu(menu); return NULL; } } return menu; } 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 WebContentsImpl::LoadingStateChanged(bool to_different_document, bool due_to_interstitial, LoadNotificationDetails* details) { if (ShowingInterstitialPage() && GetRenderManager()->interstitial_page()->pause_throbber() && !due_to_interstitial) { return; } bool is_loading = IsLoading(); if (!is_loading) { load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE, base::string16()); load_state_host_.clear(); upload_size_ = 0; upload_position_ = 0; } GetRenderManager()->SetIsLoading(is_loading); waiting_for_response_ = is_loading; is_load_to_different_document_ = to_different_document; if (delegate_) delegate_->LoadingStateChanged(this, to_different_document); NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD); std::string url = (details ? details->url.possibly_invalid_spec() : "NULL"); if (is_loading) { TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading", this, "URL", url, "Main FrameTreeNode id", GetFrameTree()->root()->frame_tree_node_id()); for (auto& observer : observers_) observer.DidStartLoading(); } else { TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading", this, "URL", url); for (auto& observer : observers_) observer.DidStopLoading(); } int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP; NotificationDetails det = NotificationService::NoDetails(); if (details) det = Details<LoadNotificationDetails>(details); NotificationService::current()->Notify( type, Source<NavigationController>(&controller_), det); } CWE ID: CWE-20 Target: 1 Example 2: Code: base::FilePath GetCustomizedWallpaperDefaultRescaledFileName( const std::string& suffix) { const base::FilePath default_downloaded_file_name = ServicesCustomizationDocument::GetCustomizedWallpaperDownloadedFileName(); const base::FilePath default_cache_dir = ServicesCustomizationDocument::GetCustomizedWallpaperCacheDir(); if (default_downloaded_file_name.empty() || default_cache_dir.empty()) return base::FilePath(); return default_cache_dir.Append( default_downloaded_file_name.BaseName().value() + suffix); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool MediaControlsProgressView::OnMousePressed(const ui::MouseEvent& event) { gfx::Point location_in_bar(event.location()); ConvertPointToTarget(this, this->progress_bar_, &location_in_bar); if (!event.IsOnlyLeftMouseButton() || !progress_bar_->GetLocalBounds().Contains(location_in_bar)) { return false; } HandleSeeking(location_in_bar); return true; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FetchManager::Loader::Start() { if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) && !execution_context_->GetContentSecurityPolicy()->AllowConnectToSource( fetch_request_data_->Url())) { PerformNetworkError( "Refused to connect to '" + fetch_request_data_->Url().ElidedString() + "' because it violates the document's Content Security Policy."); return; } if ((SecurityOrigin::Create(fetch_request_data_->Url()) ->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) || (fetch_request_data_->Url().ProtocolIsData() && fetch_request_data_->SameOriginDataURLFlag()) || (fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) { PerformSchemeFetch(); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) { PerformNetworkError("Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". Request mode is \"same-origin\" but the URL\'s " "origin is not same as the request origin " + fetch_request_data_->Origin()->ToString() + "."); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) { fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting); PerformSchemeFetch(); return; } if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI( fetch_request_data_->Url().Protocol())) { PerformNetworkError( "Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". URL scheme must be \"http\" or \"https\" for CORS request."); return; } fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting); PerformHTTPFetch(); } CWE ID: CWE-200 Target: 1 Example 2: Code: bool WebContentsImpl::IsWaitingForResponse() const { return waiting_for_response_; } 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: NTSTATUS fd_open(struct connection_struct *conn, files_struct *fsp, int flags, mode_t mode) { struct smb_filename *smb_fname = fsp->fsp_name; NTSTATUS status = NT_STATUS_OK; #ifdef O_NOFOLLOW /* * Never follow symlinks on a POSIX client. The * client should be doing this. */ if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) { flags |= O_NOFOLLOW; } #endif fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode); if (fsp->fh->fd == -1) { int posix_errno = errno; #ifdef O_NOFOLLOW #if defined(ENOTSUP) && defined(OSF1) /* handle special Tru64 errno */ if (errno == ENOTSUP) { posix_errno = ELOOP; } #endif /* ENOTSUP */ #ifdef EFTYPE /* fix broken NetBSD errno */ if (errno == EFTYPE) { posix_errno = ELOOP; } #endif /* EFTYPE */ /* fix broken FreeBSD errno */ if (errno == EMLINK) { posix_errno = ELOOP; } #endif /* O_NOFOLLOW */ status = map_nt_error_from_unix(posix_errno); if (errno == EMFILE) { static time_t last_warned = 0L; if (time((time_t *) NULL) > last_warned) { DEBUG(0,("Too many open files, unable " "to open more! smbd's max " "open files = %d\n", lp_max_open_files())); last_warned = time((time_t *) NULL); } } } DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n", smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd, (fsp->fh->fd == -1) ? strerror(errno) : "" )); return status; } CWE ID: CWE-835 Output:
0
Here are some example code snippets. Analyze the following 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 jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_ppm_t *ppm = &ms->parms.ppm; /* Eliminate compiler warning about unused variables. */ cstate = 0; ppm->data = 0; if (ms->len < 1) { goto error; } if (jpc_getuint8(in, &ppm->ind)) { goto error; } ppm->len = ms->len - 1; if (ppm->len > 0) { if (!(ppm->data = jas_malloc(ppm->len))) { goto error; } if (JAS_CAST(uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) { goto error; } } else { ppm->data = 0; } return 0; error: jpc_ppm_destroyparms(ms); return -1; } CWE ID: CWE-190 Target: 1 Example 2: Code: PHP_FUNCTION(pg_ping) { zval *pgsql_link; int id; PGconn *pgsql; PGresult *res; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == SUCCESS) { id = -1; } else { pgsql_link = NULL; id = FETCH_DEFAULT_LINK(); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink); /* ping connection */ res = PQexec(pgsql, "SELECT 1;"); PQclear(res); /* check status. */ if (PQstatus(pgsql) == CONNECTION_OK) RETURN_TRUE; /* reset connection if it's broken */ PQreset(pgsql); if (PQstatus(pgsql) == CONNECTION_OK) { RETURN_TRUE; } RETURN_FALSE; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TEMPLATE(process_block_dec)(decoder_info_t *decoder_info,int size,int yposY,int xposY,int sub) { int width = decoder_info->width; int height = decoder_info->height; stream_t *stream = decoder_info->stream; frame_type_t frame_type = decoder_info->frame_info.frame_type; int split_flag = 0; if (yposY >= height || xposY >= width) return; int decode_this_size = (yposY + size <= height) && (xposY + size <= width); int decode_rectangular_size = !decode_this_size && frame_type != I_FRAME; int bit_start = stream->bitcnt; int mode = MODE_SKIP; block_context_t block_context; TEMPLATE(find_block_contexts)(yposY, xposY, height, width, size, decoder_info->deblock_data, &block_context, decoder_info->use_block_contexts); decoder_info->block_context = &block_context; split_flag = decode_super_mode(decoder_info,size,decode_this_size); mode = decoder_info->mode; /* Read delta_qp and set block-level qp */ if (size == (1<<decoder_info->log2_sb_size) && (split_flag || mode != MODE_SKIP) && decoder_info->max_delta_qp > 0) { /* Read delta_qp */ int delta_qp = read_delta_qp(stream); int prev_qp; if (yposY == 0 && xposY == 0) prev_qp = decoder_info->frame_info.qp; else prev_qp = decoder_info->frame_info.qpb; decoder_info->frame_info.qpb = prev_qp + delta_qp; } decoder_info->bit_count.super_mode[decoder_info->bit_count.stat_frame_type] += (stream->bitcnt - bit_start); if (split_flag){ int new_size = size/2; TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+0*new_size,sub); TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+0*new_size,sub); TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+1*new_size,sub); TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+1*new_size,sub); } else if (decode_this_size || decode_rectangular_size){ decode_block(decoder_info,size,yposY,xposY,sub); } } 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 bpf_int_jit_compile(struct bpf_prog *prog) { struct bpf_binary_header *header = NULL; int proglen, oldproglen = 0; struct jit_context ctx = {}; u8 *image = NULL; int *addrs; int pass; int i; if (!bpf_jit_enable) return; if (!prog || !prog->len) return; addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL); if (!addrs) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < prog->len; i++) { proglen += 64; addrs[i] = proglen; } ctx.cleanup_addr = proglen; for (pass = 0; pass < 10; pass++) { proglen = do_jit(prog, addrs, image, oldproglen, &ctx); if (proglen <= 0) { image = NULL; if (header) bpf_jit_binary_free(header); goto out; } if (image) { if (proglen != oldproglen) { pr_err("bpf_jit: proglen=%d != oldproglen=%d\n", proglen, oldproglen); goto out; } break; } if (proglen == oldproglen) { header = bpf_jit_binary_alloc(proglen, &image, 1, jit_fill_hole); if (!header) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) bpf_jit_dump(prog->len, proglen, 0, image); if (image) { bpf_flush_icache(header, image + proglen); set_memory_ro((unsigned long)header, header->pages); prog->bpf_func = (void *)image; prog->jited = true; } out: kfree(addrs); } CWE ID: CWE-17 Target: 1 Example 2: Code: GLES2DecoderPassthroughImpl::EmulatedColorBuffer::EmulatedColorBuffer( gl::GLApi* api, const EmulatedDefaultFramebufferFormat& format_in) : api(api), format(format_in) { ScopedTexture2DBindingReset scoped_texture_reset(api); GLuint color_buffer_texture = 0; api->glGenTexturesFn(1, &color_buffer_texture); api->glBindTextureFn(GL_TEXTURE_2D, color_buffer_texture); api->glTexParameteriFn(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); api->glTexParameteriFn(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); api->glTexParameteriFn(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); api->glTexParameteriFn(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); texture = new TexturePassthrough(color_buffer_texture, GL_TEXTURE_2D); } 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 TabStripModel::ExecuteContextMenuCommand( int context_index, ContextMenuCommand command_id) { DCHECK(command_id > CommandFirst && command_id < CommandLast); switch (command_id) { case CommandNewTab: content::RecordAction(UserMetricsAction("TabContextMenu_NewTab")); UMA_HISTOGRAM_ENUMERATION("Tab.NewTab", TabStripModel::NEW_TAB_CONTEXT_MENU, TabStripModel::NEW_TAB_ENUM_COUNT); delegate()->AddBlankTabAt(context_index + 1, true); break; case CommandReload: { content::RecordAction(UserMetricsAction("TabContextMenu_Reload")); std::vector<int> indices = GetIndicesForCommand(context_index); for (size_t i = 0; i < indices.size(); ++i) { WebContents* tab = GetWebContentsAt(indices[i]); if (tab) { CoreTabHelperDelegate* core_delegate = CoreTabHelper::FromWebContents(tab)->delegate(); if (!core_delegate || core_delegate->CanReloadContents(tab)) tab->GetController().Reload(true); } } break; } case CommandDuplicate: { content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate")); std::vector<int> indices = GetIndicesForCommand(context_index); std::vector<WebContents*> tabs; for (size_t i = 0; i < indices.size(); ++i) tabs.push_back(GetWebContentsAt(indices[i])); for (size_t i = 0; i < tabs.size(); ++i) { int index = GetIndexOfWebContents(tabs[i]); if (index != -1 && delegate_->CanDuplicateContentsAt(index)) delegate_->DuplicateContentsAt(index); } break; } case CommandCloseTab: { content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab")); InternalCloseTabs(GetIndicesForCommand(context_index), CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE); break; } case CommandCloseOtherTabs: { content::RecordAction( UserMetricsAction("TabContextMenu_CloseOtherTabs")); InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id), CLOSE_CREATE_HISTORICAL_TAB); break; } case CommandCloseTabsToRight: { content::RecordAction( UserMetricsAction("TabContextMenu_CloseTabsToRight")); InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id), CLOSE_CREATE_HISTORICAL_TAB); break; } case CommandRestoreTab: { content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab")); delegate_->RestoreTab(); break; } case CommandTogglePinned: { content::RecordAction( UserMetricsAction("TabContextMenu_TogglePinned")); std::vector<int> indices = GetIndicesForCommand(context_index); bool pin = WillContextMenuPin(context_index); if (pin) { for (size_t i = 0; i < indices.size(); ++i) { if (!IsAppTab(indices[i])) SetTabPinned(indices[i], true); } } else { for (size_t i = indices.size(); i > 0; --i) { if (!IsAppTab(indices[i - 1])) SetTabPinned(indices[i - 1], false); } } break; } case CommandBookmarkAllTabs: { content::RecordAction( UserMetricsAction("TabContextMenu_BookmarkAllTabs")); delegate_->BookmarkAllTabs(); break; } case CommandSelectByDomain: case CommandSelectByOpener: { std::vector<int> indices; if (command_id == CommandSelectByDomain) GetIndicesWithSameDomain(context_index, &indices); else GetIndicesWithSameOpener(context_index, &indices); TabStripSelectionModel selection_model; selection_model.SetSelectedIndex(context_index); for (size_t i = 0; i < indices.size(); ++i) selection_model.AddIndexToSelection(indices[i]); SetSelectionFromModel(selection_model); break; } default: NOTREACHED(); } } 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 wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } CWE ID: CWE-416 Target: 1 Example 2: Code: int SampleTable::CompareIncreasingTime(const void *_a, const void *_b) { const SampleTimeEntry *a = (const SampleTimeEntry *)_a; const SampleTimeEntry *b = (const SampleTimeEntry *)_b; if (a->mCompositionTime < b->mCompositionTime) { return -1; } else if (a->mCompositionTime > b->mCompositionTime) { 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: int num_key_events_dispatched() { return num_key_events_dispatched_; } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8( "ӏ > l; [кĸκ] > k; п > n; [ƅь] > b; в > b; м > m; н > h; " "т > t; [шщ] > w; ട > s;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void StartUsingContext(__GLXclientState *cl, __GLXcontext *glxc) { glxc->isCurrent = GL_TRUE; __glXLastContext = glxc; } 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: struct sk_buff *ip_make_skb(struct sock *sk, struct flowi4 *fl4, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm_cookie *ipc, struct rtable **rtp, unsigned int flags) { struct inet_cork cork; struct sk_buff_head queue; int err; if (flags & MSG_PROBE) return NULL; __skb_queue_head_init(&queue); cork.flags = 0; cork.addr = 0; cork.opt = NULL; err = ip_setup_cork(sk, &cork, ipc, rtp); if (err) return ERR_PTR(err); err = __ip_append_data(sk, fl4, &queue, &cork, &current->task_frag, getfrag, from, length, transhdrlen, flags); if (err) { __ip_flush_pending_frames(sk, &queue, &cork); return ERR_PTR(err); } return __ip_make_skb(sk, fl4, &queue, &cork); } 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: mark_trusted_task_thread_func (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) { MarkTrustedJob *job = task_data; CommonJob *common; common = (CommonJob *) job; nautilus_progress_info_start (job->common.progress); mark_desktop_file_trusted (common, cancellable, job->file, job->interactive); } CWE ID: CWE-20 Target: 1 Example 2: Code: inline bool xs_has_arg(int argc, char *argv[]) { return optind < argc && argv[optind][0] != '-' && argv[optind][0] != '!'; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } 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: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { if (0 != decrypt_response(card, sm->resp, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } CWE ID: CWE-125 Target: 1 Example 2: Code: GF_Err trun_Write(GF_Box *s, GF_BitStream *bs) { GF_TrunEntry *p; GF_Err e; u32 i, count; GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->sample_count); if (ptr->flags & GF_ISOM_TRUN_DATA_OFFSET) { gf_bs_write_u32(bs, ptr->data_offset); } if (ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) { gf_bs_write_u32(bs, ptr->first_sample_flags); } count = gf_list_count(ptr->entries); for (i=0; i<count; i++) { p = (GF_TrunEntry*)gf_list_get(ptr->entries, i); if (ptr->flags & GF_ISOM_TRUN_DURATION) { gf_bs_write_u32(bs, p->Duration); } if (ptr->flags & GF_ISOM_TRUN_SIZE) { gf_bs_write_u32(bs, p->size); } if (ptr->flags & GF_ISOM_TRUN_FLAGS) { gf_bs_write_u32(bs, p->flags); } if (ptr->flags & GF_ISOM_TRUN_CTS_OFFSET) { if (ptr->version==0) { gf_bs_write_u32(bs, p->CTS_Offset); } else { gf_bs_write_u32(bs, (u32) p->CTS_Offset); } } } return GF_OK; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int key_notify_sa_flush(const struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto); hdr->sadb_msg_type = SADB_FLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BindSkiaToInProcessGL() { static bool host_StubGL_installed = false; if (!host_StubGL_installed) { GrGLBinding binding; switch (gfx::GetGLImplementation()) { case gfx::kGLImplementationNone: NOTREACHED(); return; case gfx::kGLImplementationDesktopGL: binding = kDesktop_GrGLBinding; break; case gfx::kGLImplementationOSMesaGL: binding = kDesktop_GrGLBinding; break; case gfx::kGLImplementationEGLGLES2: binding = kES2_GrGLBinding; break; case gfx::kGLImplementationMockGL: NOTREACHED(); return; } static GrGLInterface host_gl_interface = { binding, kProbe_GrGLCapability, // NPOTRenderTargetSupport kProbe_GrGLCapability, // MinRenderTargetHeight kProbe_GrGLCapability, // MinRenderTargetWidth StubGLActiveTexture, StubGLAttachShader, StubGLBindAttribLocation, StubGLBindBuffer, StubGLBindTexture, StubGLBlendColor, StubGLBlendFunc, StubGLBufferData, StubGLBufferSubData, StubGLClear, StubGLClearColor, StubGLClearStencil, NULL, // glClientActiveTexture NULL, // glColor4ub StubGLColorMask, NULL, // glColorPointer StubGLCompileShader, StubGLCompressedTexImage2D, StubGLCreateProgram, StubGLCreateShader, StubGLCullFace, StubGLDeleteBuffers, StubGLDeleteProgram, StubGLDeleteShader, StubGLDeleteTextures, StubGLDepthMask, StubGLDisable, NULL, // glDisableClientState StubGLDisableVertexAttribArray, StubGLDrawArrays, StubGLDrawElements, StubGLEnable, NULL, // glEnableClientState StubGLEnableVertexAttribArray, StubGLFrontFace, StubGLGenBuffers, StubGLGenTextures, StubGLGetBufferParameteriv, StubGLGetError, StubGLGetIntegerv, StubGLGetProgramInfoLog, StubGLGetProgramiv, StubGLGetShaderInfoLog, StubGLGetShaderiv, StubGLGetString, StubGLGetUniformLocation, StubGLLineWidth, StubGLLinkProgram, NULL, // glLoadMatrixf NULL, // glMatrixMode StubGLPixelStorei, NULL, // glPointSize StubGLReadPixels, StubGLScissor, NULL, // glShadeModel StubGLShaderSource, StubGLStencilFunc, StubGLStencilFuncSeparate, StubGLStencilMask, StubGLStencilMaskSeparate, StubGLStencilOp, StubGLStencilOpSeparate, NULL, // glTexCoordPointer NULL, // glTexEnvi StubGLTexImage2D, StubGLTexParameteri, StubGLTexSubImage2D, StubGLUniform1f, StubGLUniform1i, StubGLUniform1fv, StubGLUniform1iv, StubGLUniform2f, StubGLUniform2i, StubGLUniform2fv, StubGLUniform2iv, StubGLUniform3f, StubGLUniform3i, StubGLUniform3fv, StubGLUniform3iv, StubGLUniform4f, StubGLUniform4i, StubGLUniform4fv, StubGLUniform4iv, StubGLUniformMatrix2fv, StubGLUniformMatrix3fv, StubGLUniformMatrix4fv, StubGLUseProgram, StubGLVertexAttrib4fv, StubGLVertexAttribPointer, NULL, // glVertexPointer StubGLViewport, StubGLBindFramebuffer, StubGLBindRenderbuffer, StubGLCheckFramebufferStatus, StubGLDeleteFramebuffers, StubGLDeleteRenderbuffers, StubGLFramebufferRenderbuffer, StubGLFramebufferTexture2D, StubGLGenFramebuffers, StubGLGenRenderbuffers, StubGLRenderBufferStorage, StubGLRenderbufferStorageMultisample, StubGLBlitFramebuffer, NULL, // glResolveMultisampleFramebuffer StubGLMapBuffer, StubGLUnmapBuffer, NULL, // glBindFragDataLocationIndexed GrGLInterface::kStaticInitEndGuard, }; GrGLSetGLInterface(&host_gl_interface); host_StubGL_installed = true; } } CWE ID: CWE-189 Target: 1 Example 2: Code: static void update_cpu_load_active(struct rq *this_rq) { update_cpu_load(this_rq); calc_load_account_active(this_rq); } 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 SimulateMouseMove(int x, int y, int modifiers) { SimulateMouseEvent(WebInputEvent::kMouseMove, x, y, modifiers, false); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int dns_packet_is_reply_for(DnsPacket *p, const DnsResourceKey *key) { int r; assert(p); assert(key); /* Checks if the specified packet is a reply for the specified * key and the specified key is the only one in the question * section. */ if (DNS_PACKET_QR(p) != 1) return 0; /* Let's unpack the packet, if that hasn't happened yet. */ r = dns_packet_extract(p); if (r < 0) return r; if (p->question->n_keys != 1) return 0; return dns_resource_key_equal(p->question->keys[0], key); } CWE ID: CWE-20 Target: 1 Example 2: Code: MODRET add_defaultchdir(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultChdir <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) { while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } *argv = NULL; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } CWE ID: CWE-59 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BOOL LYBadHTML(HTStructured * me) { BOOL code = FALSE; switch ((enumBadHtml) cfg_bad_html) { case BAD_HTML_IGNORE: break; case BAD_HTML_TRACE: code = TRUE; break; case BAD_HTML_MESSAGE: code = TRUE; break; case BAD_HTML_WARN: /* * If we're already tracing, do not add a warning. */ if (!TRACE && !me->inBadHTML) { HTUserMsg(BAD_HTML_USE_TRACE); me->inBadHTML = TRUE; } code = TRACE; break; } return code; } 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: SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { struct smb_rqst rqst; int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; unsigned int total_len; *nbytes = 0; if (n_vec < 1) return rc; rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, (void **) &req, &total_len); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (smb3_encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer)); req->RemainingBytes = 0; trace_smb3_write_enter(xid, io_parms->persistent_fid, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length); iov[0].iov_base = (char *)req; /* 1 for Buffer */ iov[0].iov_len = total_len - 1; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = iov; rqst.rq_nvec = n_vec + 1; rc = cifs_send_recv(xid, io_parms->tcon->ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { trace_smb3_write_err(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, io_parms->length, rc); cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, "Send error in write = %d\n", rc); } else { *nbytes = le32_to_cpu(rsp->DataLength); trace_smb3_write_done(xid, req->PersistentFileId, io_parms->tcon->tid, io_parms->tcon->ses->Suid, io_parms->offset, *nbytes); } free_rsp_buf(resp_buftype, rsp); return rc; } CWE ID: CWE-416 Target: 1 Example 2: Code: struct sk_buff *__pskb_copy(struct sk_buff *skb, int headroom, gfp_t gfp_mask) { unsigned int size = skb_headlen(skb) + headroom; struct sk_buff *n = __alloc_skb(size, gfp_mask, skb_alloc_rx_flag(skb), NUMA_NO_NODE); if (!n) goto out; /* Set the data pointer */ skb_reserve(n, headroom); /* Set the tail pointer and length */ skb_put(n, skb_headlen(skb)); /* Copy the bytes */ skb_copy_from_linear_data(skb, n->data, n->len); n->truesize += skb->data_len; n->data_len = skb->data_len; n->len = skb->len; if (skb_shinfo(skb)->nr_frags) { int i; if (skb_orphan_frags(skb, gfp_mask)) { kfree_skb(n); n = NULL; goto out; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i]; skb_frag_ref(skb, i); } skb_shinfo(n)->nr_frags = i; } if (skb_has_frag_list(skb)) { skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list; skb_clone_fraglist(n); } copy_skb_header(n, skb); out: return n; } 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: int nlmsg_parse(struct nlmsghdr *nlh, int hdrlen, struct nlattr *tb[], int maxtype, struct nla_policy *policy) { if (!nlmsg_valid_hdr(nlh, hdrlen)) return -NLE_MSG_TOOSHORT; return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), policy); } 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: static void bond_setup(struct net_device *bond_dev) { struct bonding *bond = netdev_priv(bond_dev); /* initialize rwlocks */ rwlock_init(&bond->lock); rwlock_init(&bond->curr_slave_lock); bond->params = bonding_defaults; /* Initialize pointers */ bond->dev = bond_dev; INIT_LIST_HEAD(&bond->vlan_list); /* Initialize the device entry points */ ether_setup(bond_dev); bond_dev->netdev_ops = &bond_netdev_ops; bond_dev->ethtool_ops = &bond_ethtool_ops; bond_set_mode_ops(bond, bond->params.mode); bond_dev->destructor = bond_destructor; /* Initialize the device options */ bond_dev->tx_queue_len = 0; bond_dev->flags |= IFF_MASTER|IFF_MULTICAST; bond_dev->priv_flags |= IFF_BONDING; bond_dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; /* At first, we block adding VLANs. That's the only way to * prevent problems that occur when adding VLANs over an * empty bond. The block will be removed once non-challenged * slaves are enslaved. */ bond_dev->features |= NETIF_F_VLAN_CHALLENGED; /* don't acquire bond device's netif_tx_lock when * transmitting */ bond_dev->features |= NETIF_F_LLTX; /* By default, we declare the bond to be fully * VLAN hardware accelerated capable. Special * care is taken in the various xmit functions * when there are slaves that are not hw accel * capable */ bond_dev->hw_features = BOND_VLAN_FEATURES | NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX | NETIF_F_HW_VLAN_FILTER; bond_dev->hw_features &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_NO_CSUM); bond_dev->features |= bond_dev->hw_features; } CWE ID: CWE-264 Target: 1 Example 2: Code: void LayerTreeHostImpl::SetFullViewportDamage() { SetViewportDamage(gfx::Rect(DrawViewportSize())); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev, int type, u32 pid, u32 seq, u32 change, unsigned int flags, u32 ext_filter_mask) { struct ifinfomsg *ifm; struct nlmsghdr *nlh; struct rtnl_link_stats64 temp; const struct rtnl_link_stats64 *stats; struct nlattr *attr, *af_spec; struct rtnl_af_ops *af_ops; struct net_device *upper_dev = netdev_master_upper_dev_get(dev); ASSERT_RTNL(); nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags); if (nlh == NULL) return -EMSGSIZE; ifm = nlmsg_data(nlh); ifm->ifi_family = AF_UNSPEC; ifm->__ifi_pad = 0; ifm->ifi_type = dev->type; ifm->ifi_index = dev->ifindex; ifm->ifi_flags = dev_get_flags(dev); ifm->ifi_change = change; if (nla_put_string(skb, IFLA_IFNAME, dev->name) || nla_put_u32(skb, IFLA_TXQLEN, dev->tx_queue_len) || nla_put_u8(skb, IFLA_OPERSTATE, netif_running(dev) ? dev->operstate : IF_OPER_DOWN) || nla_put_u8(skb, IFLA_LINKMODE, dev->link_mode) || nla_put_u32(skb, IFLA_MTU, dev->mtu) || nla_put_u32(skb, IFLA_GROUP, dev->group) || nla_put_u32(skb, IFLA_PROMISCUITY, dev->promiscuity) || nla_put_u32(skb, IFLA_NUM_TX_QUEUES, dev->num_tx_queues) || #ifdef CONFIG_RPS nla_put_u32(skb, IFLA_NUM_RX_QUEUES, dev->num_rx_queues) || #endif (dev->ifindex != dev->iflink && nla_put_u32(skb, IFLA_LINK, dev->iflink)) || (upper_dev && nla_put_u32(skb, IFLA_MASTER, upper_dev->ifindex)) || nla_put_u8(skb, IFLA_CARRIER, netif_carrier_ok(dev)) || (dev->qdisc && nla_put_string(skb, IFLA_QDISC, dev->qdisc->ops->id)) || (dev->ifalias && nla_put_string(skb, IFLA_IFALIAS, dev->ifalias))) goto nla_put_failure; if (1) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) goto nla_put_failure; } if (dev->addr_len) { if (nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr) || nla_put(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast)) goto nla_put_failure; } attr = nla_reserve(skb, IFLA_STATS, sizeof(struct rtnl_link_stats)); if (attr == NULL) goto nla_put_failure; stats = dev_get_stats(dev, &temp); copy_rtnl_link_stats(nla_data(attr), stats); attr = nla_reserve(skb, IFLA_STATS64, sizeof(struct rtnl_link_stats64)); if (attr == NULL) goto nla_put_failure; copy_rtnl_link_stats64(nla_data(attr), stats); if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF) && nla_put_u32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent))) goto nla_put_failure; if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF)) { int i; struct nlattr *vfinfo, *vf; int num_vfs = dev_num_vf(dev->dev.parent); vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST); if (!vfinfo) goto nla_put_failure; for (i = 0; i < num_vfs; i++) { struct ifla_vf_info ivi; struct ifla_vf_mac vf_mac; struct ifla_vf_vlan vf_vlan; struct ifla_vf_tx_rate vf_tx_rate; struct ifla_vf_spoofchk vf_spoofchk; /* * Not all SR-IOV capable drivers support the * spoofcheck query. Preset to -1 so the user * space tool can detect that the driver didn't * report anything. */ ivi.spoofchk = -1; if (dev->netdev_ops->ndo_get_vf_config(dev, i, &ivi)) break; vf_mac.vf = vf_vlan.vf = vf_tx_rate.vf = vf_spoofchk.vf = ivi.vf; memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac)); vf_vlan.vlan = ivi.vlan; vf_vlan.qos = ivi.qos; vf_tx_rate.rate = ivi.tx_rate; vf_spoofchk.setting = ivi.spoofchk; vf = nla_nest_start(skb, IFLA_VF_INFO); if (!vf) { nla_nest_cancel(skb, vfinfo); goto nla_put_failure; } if (nla_put(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac) || nla_put(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan) || nla_put(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate), &vf_tx_rate) || nla_put(skb, IFLA_VF_SPOOFCHK, sizeof(vf_spoofchk), &vf_spoofchk)) goto nla_put_failure; nla_nest_end(skb, vf); } nla_nest_end(skb, vfinfo); } if (rtnl_port_fill(skb, dev)) goto nla_put_failure; if (dev->rtnl_link_ops) { if (rtnl_link_fill(skb, dev) < 0) goto nla_put_failure; } if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC))) goto nla_put_failure; list_for_each_entry(af_ops, &rtnl_af_ops, list) { if (af_ops->fill_link_af) { struct nlattr *af; int err; if (!(af = nla_nest_start(skb, af_ops->family))) goto nla_put_failure; err = af_ops->fill_link_af(skb, dev); /* * Caller may return ENODATA to indicate that there * was no data to be dumped. This is not an error, it * means we should trim the attribute header and * continue. */ if (err == -ENODATA) nla_nest_cancel(skb, af); else if (err < 0) goto nla_put_failure; nla_nest_end(skb, af); } } nla_nest_end(skb, af_spec); return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int needs_empty_write(sector_t block, struct inode *inode) { int error; struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 }; bh_map.b_size = 1 << inode->i_blkbits; error = gfs2_block_map(inode, block, &bh_map, 0); if (unlikely(error)) return error; return !buffer_mapped(&bh_map); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); perf_event_enable(event); return 0; } CWE ID: CWE-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 put_ucounts(struct ucounts *ucounts) { unsigned long flags; if (atomic_dec_and_test(&ucounts->count)) { spin_lock_irqsave(&ucounts_lock, flags); hlist_del_init(&ucounts->node); spin_unlock_irqrestore(&ucounts_lock, flags); kfree(ucounts); } } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) { LocalizedString localized_strings[] = { {"passwordsAndAutofillPageTitle", IDS_SETTINGS_PASSWORDS_AND_AUTOFILL_PAGE_TITLE}, {"autofill", IDS_SETTINGS_AUTOFILL}, {"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS}, {"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED}, {"addresses", IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING}, {"addAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_ADD_TITLE}, {"editAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_EDIT_TITLE}, {"addressCountry", IDS_SETTINGS_AUTOFILL_ADDRESSES_COUNTRY}, {"addressPhone", IDS_SETTINGS_AUTOFILL_ADDRESSES_PHONE}, {"addressEmail", IDS_SETTINGS_AUTOFILL_ADDRESSES_EMAIL}, {"removeAddress", IDS_SETTINGS_ADDRESS_REMOVE}, {"creditCards", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_HEADING}, {"removeCreditCard", IDS_SETTINGS_CREDIT_CARD_REMOVE}, {"clearCreditCard", IDS_SETTINGS_CREDIT_CARD_CLEAR}, {"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL}, {"creditCardExpiration", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_DATE}, {"creditCardName", IDS_SETTINGS_NAME_ON_CREDIT_CARD}, {"creditCardNumber", IDS_SETTINGS_CREDIT_CARD_NUMBER}, {"creditCardExpirationMonth", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_MONTH}, {"creditCardExpirationYear", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_YEAR}, {"creditCardExpired", IDS_SETTINGS_CREDIT_CARD_EXPIRED}, {"editCreditCardTitle", IDS_SETTINGS_EDIT_CREDIT_CARD_TITLE}, {"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE}, {"autofillDetail", IDS_SETTINGS_AUTOFILL_DETAIL}, {"passwords", IDS_SETTINGS_PASSWORDS}, {"passwordsAutosigninLabel", IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL}, {"passwordsAutosigninDescription", IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC}, {"passwordsDetail", IDS_SETTINGS_PASSWORDS_DETAIL}, {"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING}, {"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING}, {"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION}, {"removePassword", IDS_SETTINGS_PASSWORD_REMOVE}, {"searchPasswords", IDS_SETTINGS_PASSWORD_SEARCH}, {"showPassword", IDS_SETTINGS_PASSWORD_SHOW}, {"hidePassword", IDS_SETTINGS_PASSWORD_HIDE}, {"passwordDetailsTitle", IDS_SETTINGS_PASSWORDS_VIEW_DETAILS_TITLE}, {"passwordViewDetails", IDS_SETTINGS_PASSWORD_DETAILS}, {"editPasswordWebsiteLabel", IDS_SETTINGS_PASSWORDS_WEBSITE}, {"editPasswordUsernameLabel", IDS_SETTINGS_PASSWORDS_USERNAME}, {"editPasswordPasswordLabel", IDS_SETTINGS_PASSWORDS_PASSWORD}, {"noAddressesFound", IDS_SETTINGS_ADDRESS_NONE}, {"noCreditCardsFound", IDS_SETTINGS_CREDIT_CARD_NONE}, {"noCreditCardsPolicy", IDS_SETTINGS_CREDIT_CARD_DISABLED}, {"noPasswordsFound", IDS_SETTINGS_PASSWORDS_NONE}, {"noExceptionsFound", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_NONE}, {"import", IDS_PASSWORD_MANAGER_IMPORT_BUTTON}, {"exportMenuItem", IDS_SETTINGS_PASSWORDS_EXPORT_MENU_ITEM}, {"undoRemovePassword", IDS_SETTINGS_PASSWORD_UNDO}, {"passwordDeleted", IDS_SETTINGS_PASSWORD_DELETED_PASSWORD}, {"exportPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORT_TITLE}, {"exportPasswordsDescription", IDS_SETTINGS_PASSWORDS_EXPORT_DESCRIPTION}, {"exportPasswords", IDS_SETTINGS_PASSWORDS_EXPORT}, {"exportingPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORTING_TITLE}, {"exportPasswordsTryAgain", IDS_SETTINGS_PASSWORDS_EXPORT_TRY_AGAIN}, {"exportPasswordsFailTitle", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TITLE}, {"exportPasswordsFailTips", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIPS}, {"exportPasswordsFailTipsEnoughSpace", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ENOUGH_SPACE}, {"exportPasswordsFailTipsAnotherFolder", IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ANOTHER_FOLDER}}; html_source->AddString( "managePasswordsLabel", l10n_util::GetStringFUTF16( IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS, base::ASCIIToUTF16( password_manager::kPasswordManagerAccountDashboardURL))); html_source->AddString("passwordManagerLearnMoreURL", chrome::kPasswordManagerLearnMoreURL); html_source->AddString("manageAddressesUrl", autofill::payments::GetManageAddressesUrl(0).spec()); html_source->AddString("manageCreditCardsUrl", autofill::payments::GetManageInstrumentsUrl(0).spec()); AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); } CWE ID: CWE-200 Target: 1 Example 2: Code: void init_cdrom_command(struct packet_command *cgc, void *buf, int len, int type) { memset(cgc, 0, sizeof(struct packet_command)); if (buf) memset(buf, 0, len); cgc->buffer = (char *) buf; cgc->buflen = len; cgc->data_direction = type; cgc->timeout = CDROM_DEF_TIMEOUT; } 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: mrb_notimplement_m(mrb_state *mrb, mrb_value self) { mrb_notimplement(mrb); /* not reached */ return mrb_nil_value(); } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void set_active_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { unsigned int i; vpx_active_map_t map = {0}; map.rows = (cfg->g_h + 15) / 16; map.cols = (cfg->g_w + 15) / 16; map.active_map = (uint8_t *)malloc(map.rows * map.cols); for (i = 0; i < map.rows * map.cols; ++i) map.active_map[i] = i % 2; if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map)) die_codec(codec, "Failed to set active map"); free(map.active_map); } CWE ID: CWE-119 Target: 1 Example 2: Code: long keyctl_assume_authority(key_serial_t id) { struct key *authkey; long ret; /* special key IDs aren't permitted */ ret = -EINVAL; if (id < 0) goto error; /* we divest ourselves of authority if given an ID of 0 */ if (id == 0) { ret = keyctl_change_reqkey_auth(NULL); goto error; } /* attempt to assume the authority temporarily granted to us whilst we * instantiate the specified key * - the authorisation key must be in the current task's keyrings * somewhere */ authkey = key_get_instantiation_authkey(id); if (IS_ERR(authkey)) { ret = PTR_ERR(authkey); goto error; } ret = keyctl_change_reqkey_auth(authkey); if (ret < 0) goto error; key_put(authkey); ret = authkey->serial; error: return ret; } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int crypto_report_kpp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_kpp rkpp; strlcpy(rkpp.type, "kpp", sizeof(rkpp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_KPP, sizeof(struct crypto_report_kpp), &rkpp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } 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 FakeBluetoothAgentManagerClient::UnregisterAgent( const dbus::ObjectPath& agent_path, const base::Closure& callback, const ErrorCallback& error_callback) { VLOG(1) << "UnregisterAgent: " << agent_path.value(); if (service_provider_ != NULL) { error_callback.Run(bluetooth_agent_manager::kErrorInvalidArguments, "Agent still registered"); } else { callback.Run(); } } CWE ID: Target: 1 Example 2: Code: composite_to_json(Datum composite, StringInfo result, bool use_line_feeds) { HeapTupleHeader td; Oid tupType; int32 tupTypmod; TupleDesc tupdesc; HeapTupleData tmptup, *tuple; int i; bool needsep = false; const char *sep; sep = use_line_feeds ? ",\n " : ","; td = DatumGetHeapTupleHeader(composite); /* Extract rowtype info and find a tupdesc */ tupType = HeapTupleHeaderGetTypeId(td); tupTypmod = HeapTupleHeaderGetTypMod(td); tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod); /* Build a temporary HeapTuple control structure */ tmptup.t_len = HeapTupleHeaderGetDatumLength(td); tmptup.t_data = td; tuple = &tmptup; appendStringInfoChar(result, '{'); for (i = 0; i < tupdesc->natts; i++) { Datum val; bool isnull; char *attname; JsonTypeCategory tcategory; Oid outfuncoid; if (tupdesc->attrs[i]->attisdropped) continue; if (needsep) appendStringInfoString(result, sep); needsep = true; attname = NameStr(tupdesc->attrs[i]->attname); escape_json(result, attname); appendStringInfoChar(result, ':'); val = heap_getattr(tuple, i + 1, tupdesc, &isnull); if (isnull) { tcategory = JSONTYPE_NULL; outfuncoid = InvalidOid; } else json_categorize_type(tupdesc->attrs[i]->atttypid, &tcategory, &outfuncoid); datum_to_json(val, isnull, result, tcategory, outfuncoid, false); } appendStringInfoChar(result, '}'); ReleaseTupleDesc(tupdesc); } 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 muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen) { muscle_private_t* priv = MUSCLE_DATA(card); mscfs_t *fs = priv->fs; int x; int count = 0; mscfs_check_cache(priv->fs); for(x = 0; x < fs->cache.size; x++) { u8* oid= fs->cache.array[x].objectId.id; sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "FILE: %02X%02X%02X%02X\n", oid[0],oid[1],oid[2],oid[3]); if(0 == memcmp(fs->currentPath, oid, 2)) { buf[0] = oid[2]; buf[1] = oid[3]; if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */ buf += 2; count+=2; } } return count; } CWE ID: CWE-415 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: GLboolean WebGLRenderingContextBase::isRenderbuffer( WebGLRenderbuffer* renderbuffer) { if (!renderbuffer || isContextLost()) return 0; if (!renderbuffer->HasEverBeenBound()) return 0; if (renderbuffer->IsDeleted()) return 0; return ContextGL()->IsRenderbuffer(renderbuffer->Object()); } CWE ID: CWE-119 Target: 1 Example 2: Code: PlatformSensorConfiguration PlatformSensorFusion::GetDefaultConfiguration() { PlatformSensorConfiguration default_configuration; for (const auto& pair : source_sensors_) { double frequency = pair.second->GetDefaultConfiguration().frequency(); if (frequency > default_configuration.frequency()) default_configuration.set_frequency(frequency); } return default_configuration; } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int proc_keys_show(struct seq_file *m, void *v) { struct rb_node *_p = v; struct key *key = rb_entry(_p, struct key, serial_node); struct timespec now; unsigned long timo; key_ref_t key_ref, skey_ref; char xbuf[16]; int rc; struct keyring_search_context ctx = { .index_key.type = key->type, .index_key.description = key->description, .cred = m->file->f_cred, .match_data.cmp = lookup_user_key_possessed, .match_data.raw_data = key, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; key_ref = make_key_ref(key, 0); /* determine if the key is possessed by this process (a test we can * skip if the key does not indicate the possessor can view it */ if (key->perm & KEY_POS_VIEW) { skey_ref = search_my_process_keyrings(&ctx); if (!IS_ERR(skey_ref)) { key_ref_put(skey_ref); key_ref = make_key_ref(key, 1); } } /* check whether the current task is allowed to view the key */ rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW); if (rc < 0) return 0; now = current_kernel_time(); rcu_read_lock(); /* come up with a suitable timeout value */ if (key->expiry == 0) { memcpy(xbuf, "perm", 5); } else if (now.tv_sec >= key->expiry) { memcpy(xbuf, "expd", 5); } else { timo = key->expiry - now.tv_sec; if (timo < 60) sprintf(xbuf, "%lus", timo); else if (timo < 60*60) sprintf(xbuf, "%lum", timo / 60); else if (timo < 60*60*24) sprintf(xbuf, "%luh", timo / (60*60)); else if (timo < 60*60*24*7) sprintf(xbuf, "%lud", timo / (60*60*24)); else sprintf(xbuf, "%luw", timo / (60*60*24*7)); } #define showflag(KEY, LETTER, FLAG) \ (test_bit(FLAG, &(KEY)->flags) ? LETTER : '-') seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ", key->serial, showflag(key, 'I', KEY_FLAG_INSTANTIATED), showflag(key, 'R', KEY_FLAG_REVOKED), showflag(key, 'D', KEY_FLAG_DEAD), showflag(key, 'Q', KEY_FLAG_IN_QUOTA), showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT), showflag(key, 'N', KEY_FLAG_NEGATIVE), showflag(key, 'i', KEY_FLAG_INVALIDATED), refcount_read(&key->usage), xbuf, key->perm, from_kuid_munged(seq_user_ns(m), key->uid), from_kgid_munged(seq_user_ns(m), key->gid), key->type->name); #undef showflag if (key->type->describe) key->type->describe(key, m); seq_putc(m, '\n'); rcu_read_unlock(); return 0; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *isk = inet_sk(sk); int family = sk->sk_family; struct sk_buff *skb; int copied, err; pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num); err = -EOPNOTSUPP; if (flags & MSG_OOB) goto out; if (flags & MSG_ERRQUEUE) { if (family == AF_INET) { return ip_recv_error(sk, msg, len); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { return pingv6_ops.ipv6_recv_error(sk, msg, len); #endif } } skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* Don't bother checking the checksum */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address and add cmsg data. */ if (family == AF_INET) { struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; sin->sin_family = AF_INET; sin->sin_port = 0 /* skb->h.uh->source */; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); if (isk->cmsg_flags) ip_cmsg_recv(msg, skb); #if IS_ENABLED(CONFIG_IPV6) } else if (family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6hdr *ip6 = ipv6_hdr(skb); struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ip6->saddr; sin6->sin6_flowinfo = 0; if (np->sndflow) sin6->sin6_flowinfo = ip6_flowinfo(ip6); sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); *addr_len = sizeof(*sin6); if (inet6_sk(sk)->rxopt.all) pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb); #endif } else { BUG(); } err = copied; done: skb_free_datagram(sk, skb); out: pr_debug("ping_recvmsg -> %d\n", err); return err; } CWE ID: Target: 1 Example 2: Code: void SaveCardBubbleControllerImpl::OnLegalMessageLinkClicked(const GURL& url) { OpenUrl(url); AutofillMetrics::LogSaveCardPromptMetric( AutofillMetrics::SAVE_CARD_PROMPT_DISMISS_CLICK_LEGAL_MESSAGE, is_uploading_, is_reshow_, pref_service_->GetInteger( prefs::kAutofillAcceptSaveCreditCardPromptState)); } 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 user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %u", key->datalen); } 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: image_transform_png_set_rgb_to_gray_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; return (colour_type & PNG_COLOR_MASK_COLOR) != 0; } CWE ID: Target: 1 Example 2: Code: GF_Err snro_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_SeqOffHintEntryBox *ptr = (GF_SeqOffHintEntryBox *)s; if (ptr == NULL) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->SeqOffset); return GF_OK; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static long restore_tm_user_regs(struct pt_regs *regs, struct mcontext __user *sr, struct mcontext __user *tm_sr) { long err; unsigned long msr, msr_hi; #ifdef CONFIG_VSX int i; #endif /* * restore general registers but not including MSR or SOFTE. Also * take care of keeping r2 (TLS) intact if not a signal. * See comment in signal_64.c:restore_tm_sigcontexts(); * TFHAR is restored from the checkpointed NIP; TEXASR and TFIAR * were set by the signal delivery. */ err = restore_general_regs(regs, tm_sr); err |= restore_general_regs(&current->thread.ckpt_regs, sr); err |= __get_user(current->thread.tm_tfhar, &sr->mc_gregs[PT_NIP]); err |= __get_user(msr, &sr->mc_gregs[PT_MSR]); if (err) return 1; /* Restore the previous little-endian mode */ regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE); /* * Do this before updating the thread state in * current->thread.fpr/vr/evr. That way, if we get preempted * and another task grabs the FPU/Altivec/SPE, it won't be * tempted to save the current CPU state into the thread_struct * and corrupt what we are writing there. */ discard_lazy_cpu_state(); #ifdef CONFIG_ALTIVEC regs->msr &= ~MSR_VEC; if (msr & MSR_VEC) { /* restore altivec registers from the stack */ if (__copy_from_user(&current->thread.vr_state, &sr->mc_vregs, sizeof(sr->mc_vregs)) || __copy_from_user(&current->thread.transact_vr, &tm_sr->mc_vregs, sizeof(sr->mc_vregs))) return 1; } else if (current->thread.used_vr) { memset(&current->thread.vr_state, 0, ELF_NVRREG * sizeof(vector128)); memset(&current->thread.transact_vr, 0, ELF_NVRREG * sizeof(vector128)); } /* Always get VRSAVE back */ if (__get_user(current->thread.vrsave, (u32 __user *)&sr->mc_vregs[32]) || __get_user(current->thread.transact_vrsave, (u32 __user *)&tm_sr->mc_vregs[32])) return 1; if (cpu_has_feature(CPU_FTR_ALTIVEC)) mtspr(SPRN_VRSAVE, current->thread.vrsave); #endif /* CONFIG_ALTIVEC */ regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1); if (copy_fpr_from_user(current, &sr->mc_fregs) || copy_transact_fpr_from_user(current, &tm_sr->mc_fregs)) return 1; #ifdef CONFIG_VSX regs->msr &= ~MSR_VSX; if (msr & MSR_VSX) { /* * Restore altivec registers from the stack to a local * buffer, then write this out to the thread_struct */ if (copy_vsx_from_user(current, &sr->mc_vsregs) || copy_transact_vsx_from_user(current, &tm_sr->mc_vsregs)) return 1; } else if (current->thread.used_vsr) for (i = 0; i < 32 ; i++) { current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0; current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0; } #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE /* SPE regs are not checkpointed with TM, so this section is * simply the same as in restore_user_regs(). */ regs->msr &= ~MSR_SPE; if (msr & MSR_SPE) { if (__copy_from_user(current->thread.evr, &sr->mc_vregs, ELF_NEVRREG * sizeof(u32))) return 1; } else if (current->thread.used_spe) memset(current->thread.evr, 0, ELF_NEVRREG * sizeof(u32)); /* Always get SPEFSCR back */ if (__get_user(current->thread.spefscr, (u32 __user *)&sr->mc_vregs + ELF_NEVRREG)) return 1; #endif /* CONFIG_SPE */ /* Now, recheckpoint. This loads up all of the checkpointed (older) * registers, including FP and V[S]Rs. After recheckpointing, the * transactional versions should be loaded. */ tm_enable(); /* Make sure the transaction is marked as failed */ current->thread.tm_texasr |= TEXASR_FS; /* This loads the checkpointed FP/VEC state, if used */ tm_recheckpoint(&current->thread, msr); /* Get the top half of the MSR */ if (__get_user(msr_hi, &tm_sr->mc_gregs[PT_MSR])) return 1; /* Pull in MSR TM from user context */ regs->msr = (regs->msr & ~MSR_TS_MASK) | ((msr_hi<<32) & MSR_TS_MASK); /* This loads the speculative FP/VEC state, if used */ if (msr & MSR_FP) { do_load_up_transact_fpu(&current->thread); regs->msr |= (MSR_FP | current->thread.fpexc_mode); } #ifdef CONFIG_ALTIVEC if (msr & MSR_VEC) { do_load_up_transact_altivec(&current->thread); regs->msr |= MSR_VEC; } #endif return 0; } 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 PermissionsData::CanRunOnPage(const Extension* extension, const GURL& document_url, const GURL& top_frame_url, int tab_id, int process_id, const URLPatternSet& permitted_url_patterns, std::string* error) const { if (g_policy_delegate && !g_policy_delegate->CanExecuteScriptOnPage( extension, document_url, top_frame_url, tab_id, process_id, error)) { return false; } bool can_execute_everywhere = CanExecuteScriptEverywhere(extension); if (!can_execute_everywhere && !ExtensionsClient::Get()->IsScriptableURL(document_url, error)) { return false; } if (!base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kExtensionsOnChromeURLs)) { if (document_url.SchemeIs(content::kChromeUIScheme) && !can_execute_everywhere) { if (error) *error = manifest_errors::kCannotAccessChromeUrl; return false; } } if (top_frame_url.SchemeIs(kExtensionScheme) && top_frame_url.GetOrigin() != Extension::GetBaseURLFromExtensionId(extension->id()).GetOrigin() && !can_execute_everywhere) { if (error) *error = manifest_errors::kCannotAccessExtensionUrl; return false; } if (HasTabSpecificPermissionToExecuteScript(tab_id, top_frame_url)) return true; bool can_access = permitted_url_patterns.MatchesURL(document_url); if (!can_access && error) { *error = ErrorUtils::FormatErrorMessage(manifest_errors::kCannotAccessPage, document_url.spec()); } return can_access; } CWE ID: CWE-264 Target: 1 Example 2: Code: swapReplace(int start, int end, const TranslationTableHeader *table, const InString *input, OutString *output, int *posMapping, const widechar *passInstructions, int passIC) { TranslationTableOffset swapRuleOffset; TranslationTableRule *swapRule; widechar *replacements; int p; swapRuleOffset = (passInstructions[passIC + 1] << 16) | passInstructions[passIC + 2]; swapRule = (TranslationTableRule *)&table->ruleArea[swapRuleOffset]; replacements = &swapRule->charsdots[swapRule->charslen]; for (p = start; p < end; p++) { int rep; int test; int k; if (swapRule->opcode == CTO_SwapDd) { for (test = 0; test * 2 + 1 < swapRule->charslen; test++) if (input->chars[p] == swapRule->charsdots[test * 2 + 1]) break; if (test * 2 == swapRule->charslen) continue; } else { for (test = 0; test < swapRule->charslen; test++) if (input->chars[p] == swapRule->charsdots[test]) break; if (test == swapRule->charslen) continue; } k = 0; for (rep = 0; rep < test; rep++) if (swapRule->opcode == CTO_SwapCc) k++; else k += replacements[k]; if (swapRule->opcode == CTO_SwapCc) { if ((output->length + 1) > output->maxlength) return 0; posMapping[output->length] = p; output->chars[output->length++] = replacements[k]; } else { int l = replacements[k] - 1; int d = output->length + l; if (d > output->maxlength) return 0; while (--d >= output->length) posMapping[d] = p; memcpy(&output->chars[output->length], &replacements[k + 1], l * sizeof(*output->chars)); output->length += l; } } return 1; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool InspectorPageAgent::forceCompositingMode(ErrorString* errorString) { Settings& settings = m_page->settings(); if (!settings.acceleratedCompositingEnabled()) { if (errorString) *errorString = "Compositing mode is not supported"; return false; } if (settings.forceCompositingMode()) return true; settings.setForceCompositingMode(true); Frame* mainFrame = m_page->mainFrame(); if (mainFrame) mainFrame->view()->updateCompositingLayersAfterStyleChange(); 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: mm_answer_pam_init_ctx(int sock, Buffer *m) { debug3("%s", __func__); authctxt->user = buffer_get_string(m, NULL); sshpam_ctxt = (sshpam_device.init_ctx)(authctxt); sshpam_authok = NULL; buffer_clear(m); if (sshpam_ctxt != NULL) { monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1); buffer_put_int(m, 1); } else { buffer_put_int(m, 0); } mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m); return (0); } CWE ID: CWE-20 Target: 1 Example 2: Code: bool HTMLFormControlElement::isDisabledFormControl() const { if (fastHasAttribute(disabledAttr)) return true; if (m_ancestorDisabledState == AncestorDisabledStateUnknown) updateAncestorDisabledState(); return m_ancestorDisabledState == AncestorDisabledStateDisabled; } CWE ID: CWE-1021 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl(ScriptExecutionContext* context, PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback) : ActiveDOMObject(context, this) , m_successCallback(successCallback) , m_errorCallback(errorCallback) { } 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 set_task_blockstep(struct task_struct *task, bool on) { unsigned long debugctl; /* * Ensure irq/preemption can't change debugctl in between. * Note also that both TIF_BLOCKSTEP and debugctl should * be changed atomically wrt preemption. * FIXME: this means that set/clear TIF_BLOCKSTEP is simply * wrong if task != current, SIGKILL can wakeup the stopped * tracee and set/clear can play with the running task, this * can confuse the next __switch_to_xtra(). */ local_irq_disable(); debugctl = get_debugctlmsr(); if (on) { debugctl |= DEBUGCTLMSR_BTF; set_tsk_thread_flag(task, TIF_BLOCKSTEP); } else { debugctl &= ~DEBUGCTLMSR_BTF; clear_tsk_thread_flag(task, TIF_BLOCKSTEP); } if (task == current) update_debugctlmsr(debugctl); local_irq_enable(); } CWE ID: CWE-362 Target: 1 Example 2: Code: void dup_userfaultfd_complete(struct list_head *fcs) { struct userfaultfd_fork_ctx *fctx, *n; list_for_each_entry_safe(fctx, n, fcs, list) { dup_fctx(fctx); list_del(&fctx->list); kfree(fctx); } } 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: xmlParseMisc(xmlParserCtxtPtr ctxt) { while (((RAW == '<') && (NXT(1) == '?')) || (CMP4(CUR_PTR, '<', '!', '-', '-')) || IS_BLANK_CH(CUR)) { if ((RAW == '<') && (NXT(1) == '?')) { xmlParsePI(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else xmlParseComment(ctxt); } } 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: v8::Local<v8::Object> V8Console::createConsole(InspectedContext* inspectedContext, bool hasMemoryAttribute) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Context::Scope contextScope(context); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> console = v8::Object::New(isolate); createBoundFunctionProperty(context, console, "debug", V8Console::debugCallback); createBoundFunctionProperty(context, console, "error", V8Console::errorCallback); createBoundFunctionProperty(context, console, "info", V8Console::infoCallback); createBoundFunctionProperty(context, console, "log", V8Console::logCallback); createBoundFunctionProperty(context, console, "warn", V8Console::warnCallback); createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback); createBoundFunctionProperty(context, console, "dirxml", V8Console::dirxmlCallback); createBoundFunctionProperty(context, console, "table", V8Console::tableCallback); createBoundFunctionProperty(context, console, "trace", V8Console::traceCallback); createBoundFunctionProperty(context, console, "group", V8Console::groupCallback); createBoundFunctionProperty(context, console, "groupCollapsed", V8Console::groupCollapsedCallback); createBoundFunctionProperty(context, console, "groupEnd", V8Console::groupEndCallback); createBoundFunctionProperty(context, console, "clear", V8Console::clearCallback); createBoundFunctionProperty(context, console, "count", V8Console::countCallback); createBoundFunctionProperty(context, console, "assert", V8Console::assertCallback); createBoundFunctionProperty(context, console, "markTimeline", V8Console::markTimelineCallback); createBoundFunctionProperty(context, console, "profile", V8Console::profileCallback); createBoundFunctionProperty(context, console, "profileEnd", V8Console::profileEndCallback); createBoundFunctionProperty(context, console, "timeline", V8Console::timelineCallback); createBoundFunctionProperty(context, console, "timelineEnd", V8Console::timelineEndCallback); createBoundFunctionProperty(context, console, "time", V8Console::timeCallback); createBoundFunctionProperty(context, console, "timeEnd", V8Console::timeEndCallback); createBoundFunctionProperty(context, console, "timeStamp", V8Console::timeStampCallback); bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false); DCHECK(success); if (hasMemoryAttribute) console->SetAccessorProperty(toV8StringInternalized(isolate, "memory"), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memoryGetterCallback, console, 0).ToLocalChecked(), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memorySetterCallback, v8::Local<v8::Value>(), 0).ToLocalChecked(), static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT); console->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return console; } CWE ID: CWE-79 Target: 1 Example 2: Code: static vaddr_t select_va_in_range(vaddr_t prev_end, uint32_t prev_attr, vaddr_t next_begin, uint32_t next_attr, const struct vm_region *reg) { size_t granul; const uint32_t a = TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT; size_t pad; vaddr_t begin_va; vaddr_t end_va; /* * Insert an unmapped entry to separate regions with differing * TEE_MATTR_EPHEMERAL TEE_MATTR_PERMANENT bits as they never are * to be contiguous with another region. */ if (prev_attr && (prev_attr & a) != (reg->attr & a)) pad = SMALL_PAGE_SIZE; else pad = 0; granul = SMALL_PAGE_SIZE; #ifndef CFG_WITH_LPAE if ((prev_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE)) granul = CORE_MMU_PGDIR_SIZE; #endif begin_va = ROUNDUP(prev_end + pad, granul); if (reg->va) { if (reg->va < begin_va) return 0; begin_va = reg->va; } if (next_attr && (next_attr & a) != (reg->attr & a)) pad = SMALL_PAGE_SIZE; else pad = 0; granul = SMALL_PAGE_SIZE; #ifndef CFG_WITH_LPAE if ((next_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE)) granul = CORE_MMU_PGDIR_SIZE; #endif end_va = ROUNDUP(begin_va + reg->size + pad, granul); if (end_va <= next_begin) { assert(!reg->va || reg->va == begin_va); return begin_va; } return 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: cib_remote_signon(cib_t * cib, const char *name, enum cib_conn_type type) { int rc = pcmk_ok; cib_remote_opaque_t *private = cib->variant_opaque; if (private->passwd == NULL) { struct termios settings; int rc; rc = tcgetattr(0, &settings); settings.c_lflag &= ~ECHO; rc = tcsetattr(0, TCSANOW, &settings); fprintf(stderr, "Password: "); private->passwd = calloc(1, 1024); rc = scanf("%s", private->passwd); fprintf(stdout, "\n"); /* fprintf(stderr, "entered: '%s'\n", buffer); */ if (rc < 1) { private->passwd = NULL; } settings.c_lflag |= ECHO; rc = tcsetattr(0, TCSANOW, &settings); } if (private->server == NULL || private->user == NULL) { rc = -EINVAL; } if (rc == pcmk_ok) { rc = cib_tls_signon(cib, &(private->command)); } if (rc == pcmk_ok) { rc = cib_tls_signon(cib, &(private->callback)); } if (rc == pcmk_ok) { xmlNode *hello = cib_create_op(0, private->callback.token, CRM_OP_REGISTER, NULL, NULL, NULL, 0, NULL); crm_xml_add(hello, F_CIB_CLIENTNAME, name); crm_send_remote_msg(private->command.session, hello, private->command.encrypted); free_xml(hello); } if (rc == pcmk_ok) { fprintf(stderr, "%s: Opened connection to %s:%d\n", name, private->server, private->port); cib->state = cib_connected_command; cib->type = cib_command; } else { fprintf(stderr, "%s: Connection to %s:%d failed: %s\n", name, private->server, private->port, pcmk_strerror(rc)); } return rc; } 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: bool SVGElement::HasSVGParent() const { return ParentOrShadowHostElement() && ParentOrShadowHostElement()->IsSVGElement(); } CWE ID: CWE-704 Target: 1 Example 2: Code: static void activityLoggingAccessForIsolatedWorldsPerWorldBindingsLongAttributeAttributeGetterCallbackForMainWorld(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectPythonV8Internal::activityLoggingAccessForIsolatedWorldsPerWorldBindingsLongAttributeAttributeGetterForMainWorld(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 int udf_load_logicalvol(struct super_block *sb, sector_t block, struct kernel_lb_addr *fileset) { struct logicalVolDesc *lvd; int i, j, offset; uint8_t type; struct udf_sb_info *sbi = UDF_SB(sb); struct genericPartitionMap *gpm; uint16_t ident; struct buffer_head *bh; unsigned int table_len; int ret = 0; bh = udf_read_tagged(sb, block, block, &ident); if (!bh) return 1; BUG_ON(ident != TAG_IDENT_LVD); lvd = (struct logicalVolDesc *)bh->b_data; table_len = le32_to_cpu(lvd->mapTableLength); if (sizeof(*lvd) + table_len > sb->s_blocksize) { udf_err(sb, "error loading logical volume descriptor: " "Partition table too long (%u > %lu)\n", table_len, sb->s_blocksize - sizeof(*lvd)); goto out_bh; } ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps)); if (ret) goto out_bh; for (i = 0, offset = 0; i < sbi->s_partitions && offset < table_len; i++, offset += gpm->partitionMapLength) { struct udf_part_map *map = &sbi->s_partmaps[i]; gpm = (struct genericPartitionMap *) &(lvd->partitionMaps[offset]); type = gpm->partitionMapType; if (type == 1) { struct genericPartitionMap1 *gpm1 = (struct genericPartitionMap1 *)gpm; map->s_partition_type = UDF_TYPE1_MAP15; map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum); map->s_partition_num = le16_to_cpu(gpm1->partitionNum); map->s_partition_func = NULL; } else if (type == 2) { struct udfPartitionMap2 *upm2 = (struct udfPartitionMap2 *)gpm; if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL, strlen(UDF_ID_VIRTUAL))) { u16 suf = le16_to_cpu(((__le16 *)upm2->partIdent. identSuffix)[0]); if (suf < 0x0200) { map->s_partition_type = UDF_VIRTUAL_MAP15; map->s_partition_func = udf_get_pblock_virt15; } else { map->s_partition_type = UDF_VIRTUAL_MAP20; map->s_partition_func = udf_get_pblock_virt20; } } else if (!strncmp(upm2->partIdent.ident, UDF_ID_SPARABLE, strlen(UDF_ID_SPARABLE))) { uint32_t loc; struct sparingTable *st; struct sparablePartitionMap *spm = (struct sparablePartitionMap *)gpm; map->s_partition_type = UDF_SPARABLE_MAP15; map->s_type_specific.s_sparing.s_packet_len = le16_to_cpu(spm->packetLength); for (j = 0; j < spm->numSparingTables; j++) { struct buffer_head *bh2; loc = le32_to_cpu( spm->locSparingTable[j]); bh2 = udf_read_tagged(sb, loc, loc, &ident); map->s_type_specific.s_sparing. s_spar_map[j] = bh2; if (bh2 == NULL) continue; st = (struct sparingTable *)bh2->b_data; if (ident != 0 || strncmp( st->sparingIdent.ident, UDF_ID_SPARING, strlen(UDF_ID_SPARING))) { brelse(bh2); map->s_type_specific.s_sparing. s_spar_map[j] = NULL; } } map->s_partition_func = udf_get_pblock_spar15; } else if (!strncmp(upm2->partIdent.ident, UDF_ID_METADATA, strlen(UDF_ID_METADATA))) { struct udf_meta_data *mdata = &map->s_type_specific.s_metadata; struct metadataPartitionMap *mdm = (struct metadataPartitionMap *) &(lvd->partitionMaps[offset]); udf_debug("Parsing Logical vol part %d type %d id=%s\n", i, type, UDF_ID_METADATA); map->s_partition_type = UDF_METADATA_MAP25; map->s_partition_func = udf_get_pblock_meta25; mdata->s_meta_file_loc = le32_to_cpu(mdm->metadataFileLoc); mdata->s_mirror_file_loc = le32_to_cpu(mdm->metadataMirrorFileLoc); mdata->s_bitmap_file_loc = le32_to_cpu(mdm->metadataBitmapFileLoc); mdata->s_alloc_unit_size = le32_to_cpu(mdm->allocUnitSize); mdata->s_align_unit_size = le16_to_cpu(mdm->alignUnitSize); if (mdm->flags & 0x01) mdata->s_flags |= MF_DUPLICATE_MD; udf_debug("Metadata Ident suffix=0x%x\n", le16_to_cpu(*(__le16 *) mdm->partIdent.identSuffix)); udf_debug("Metadata part num=%d\n", le16_to_cpu(mdm->partitionNum)); udf_debug("Metadata part alloc unit size=%d\n", le32_to_cpu(mdm->allocUnitSize)); udf_debug("Metadata file loc=%d\n", le32_to_cpu(mdm->metadataFileLoc)); udf_debug("Mirror file loc=%d\n", le32_to_cpu(mdm->metadataMirrorFileLoc)); udf_debug("Bitmap file loc=%d\n", le32_to_cpu(mdm->metadataBitmapFileLoc)); udf_debug("Flags: %d %d\n", mdata->s_flags, mdm->flags); } else { udf_debug("Unknown ident: %s\n", upm2->partIdent.ident); continue; } map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum); map->s_partition_num = le16_to_cpu(upm2->partitionNum); } udf_debug("Partition (%d:%d) type %d on volume %d\n", i, map->s_partition_num, type, map->s_volumeseqnum); } if (fileset) { struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]); *fileset = lelb_to_cpu(la->extLocation); udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n", fileset->logicalBlockNum, fileset->partitionReferenceNum); } if (lvd->integritySeqExt.extLength) udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt)); out_bh: brelse(bh); return ret; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { int i; png_uint_16 freq[256]; /* libpng takes the count from the PLTE count; we don't check it here but we * do set the array to 0 for unspecified entries. */ memset(freq, 0, sizeof freq); for (i=0; i<nparams; ++i) { char *endptr = NULL; unsigned long int l = strtoul(params[i], &endptr, 0/*base*/); if (params[i][0] && *endptr == 0 && l <= 65535) freq[i] = (png_uint_16)l; else { fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]); exit(1); } } png_set_hIST(png_ptr, info_ptr, freq); } CWE ID: Target: 1 Example 2: Code: static int untrap_errors(void) { XSetErrorHandler(old_error_handler); return trapped_error_code; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void mq_flush_data_end_io(struct request *rq, int error) { struct request_queue *q = rq->q; struct blk_mq_hw_ctx *hctx; struct blk_mq_ctx *ctx = rq->mq_ctx; unsigned long flags; struct blk_flush_queue *fq = blk_get_flush_queue(q, ctx); hctx = q->mq_ops->map_queue(q, ctx->cpu); /* * After populating an empty queue, kick it to avoid stall. Read * the comment in flush_end_io(). */ spin_lock_irqsave(&fq->mq_flush_lock, flags); if (blk_flush_complete_seq(rq, fq, REQ_FSEQ_DATA, error)) blk_mq_run_hw_queue(hctx, true); spin_unlock_irqrestore(&fq->mq_flush_lock, flags); } 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: dns_stricmp(const char* str1, const char* str2) { char c1, c2; *----------------------------------------------------------------------------*/ /* DNS variables */ static struct udp_pcb *dns_pcb; static u8_t dns_seqno; static struct dns_table_entry dns_table[DNS_TABLE_SIZE]; static struct dns_req_entry dns_requests[DNS_MAX_REQUESTS]; if (c1_upc != c2_upc) { /* still not equal */ /* don't care for < or > */ return 1; } } else { /* characters are not equal but none is in the alphabet range */ return 1; } CWE ID: CWE-345 Target: 1 Example 2: Code: bool Document::hasSVGRootNode() const { return isSVGSVGElement(documentElement()); } 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: bool HTMLMediaElement::supportsSave() const { return webMediaPlayer() && webMediaPlayer()->supportsSave(); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void skcipher_release(void *private) { crypto_free_skcipher(private); } CWE ID: CWE-476 Target: 1 Example 2: Code: _polkit_unix_process_get_owner (PolkitUnixProcess *process, GError **error) { gint result; gchar *contents; gchar **lines; #if defined(HAVE_FREEBSD) || defined(HAVE_OPENBSD) return start_time; } 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 ProfileChooserView::SignOutAllWebAccounts() { Hide(); ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile()) ->RevokeAllCredentials(); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(locale_compose) { smart_str loc_name_s = {0}; smart_str *loc_name = &loc_name_s; zval* arr = NULL; HashTable* hash_arr = NULL; int result = 0; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } hash_arr = HASH_OF( arr ); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) RETURN_FALSE; /* Check for grandfathered first */ result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG); if( result == SUCCESS){ RETURN_SMART_STR(loc_name); } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Not grandfathered */ result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG); if( result == LOC_NOT_FOUND ){ intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC ); smart_str_free(loc_name); RETURN_FALSE; } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Extlang */ result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Script */ result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Region */ result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Variant */ result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Private */ result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } RETURN_SMART_STR(loc_name); } CWE ID: CWE-125 Target: 1 Example 2: Code: long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) { if (m_pos >= 0 || m_pUnknownSize == NULL) return E_PARSE_FAILED; 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 const long long start = m_pUnknownSize->m_element_start; const long long size = m_pUnknownSize->GetElementSize(); if (size < 0) return E_FILE_FORMAT_INVALID; pos = start + size; m_pos = pos; m_pUnknownSize = 0; return 2; // continue parsing } 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: v8::Local<v8::Object> V8InjectedScriptHost::create(v8::Local<v8::Context> context, V8InspectorImpl* inspector) { v8::Isolate* isolate = inspector->isolate(); v8::Local<v8::Object> injectedScriptHost = v8::Object::New(isolate); v8::Local<v8::External> debuggerExternal = v8::External::New(isolate, inspector); setFunctionProperty(context, injectedScriptHost, "internalConstructorName", V8InjectedScriptHost::internalConstructorNameCallback, debuggerExternal); setFunctionProperty(context, injectedScriptHost, "formatAccessorsAsProperties", V8InjectedScriptHost::formatAccessorsAsProperties, debuggerExternal); setFunctionProperty(context, injectedScriptHost, "subtype", V8InjectedScriptHost::subtypeCallback, debuggerExternal); setFunctionProperty(context, injectedScriptHost, "getInternalProperties", V8InjectedScriptHost::getInternalPropertiesCallback, debuggerExternal); setFunctionProperty(context, injectedScriptHost, "objectHasOwnProperty", V8InjectedScriptHost::objectHasOwnPropertyCallback, debuggerExternal); setFunctionProperty(context, injectedScriptHost, "bind", V8InjectedScriptHost::bindCallback, debuggerExternal); setFunctionProperty(context, injectedScriptHost, "proxyTargetValue", V8InjectedScriptHost::proxyTargetValueCallback, debuggerExternal); return injectedScriptHost; } CWE ID: CWE-79 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: ptaReadStream(FILE *fp) { char typestr[128]; l_int32 i, n, ix, iy, type, version; l_float32 x, y; PTA *pta; PROCNAME("ptaReadStream"); if (!fp) return (PTA *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, "\n Pta Version %d\n", &version) != 1) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (version != PTA_VERSION_NUMBER) return (PTA *)ERROR_PTR("invalid pta version", procName, NULL); if (fscanf(fp, " Number of pts = %d; format = %s\n", &n, typestr) != 2) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (!strcmp(typestr, "float")) type = 0; else /* typestr is "integer" */ type = 1; if ((pta = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = 0; i < n; i++) { if (type == 0) { /* data is float */ if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading floats", procName, NULL); } ptaAddPt(pta, x, y); } else { /* data is integer */ if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading ints", procName, NULL); } ptaAddPt(pta, ix, iy); } } return pta; } CWE ID: CWE-119 Target: 1 Example 2: Code: find_map(struct mixer_build *state, int unitid, int control) { const struct usbmix_name_map *p = state->map; if (!p) return NULL; for (p = state->map; p->id; p++) { if (p->id == unitid && (!control || !p->control || control == p->control)) return p; } return NULL; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int n_tty_ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg) { struct n_tty_data *ldata = tty->disc_data; int retval; switch (cmd) { case TIOCOUTQ: return put_user(tty_chars_in_buffer(tty), (int __user *) arg); case TIOCINQ: down_write(&tty->termios_rwsem); if (L_ICANON(tty)) retval = inq_canon(ldata); else retval = read_cnt(ldata); up_write(&tty->termios_rwsem); return put_user(retval, (unsigned int __user *) arg); default: return n_tty_ioctl_helper(tty, file, cmd, arg); } } CWE ID: CWE-704 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: NavigationPolicy EffectiveNavigationPolicy(NavigationPolicy policy, const WebInputEvent* current_event, const WebWindowFeatures& features) { if (policy == kNavigationPolicyIgnore) return GetNavigationPolicy(current_event, features); if (policy == kNavigationPolicyNewBackgroundTab && GetNavigationPolicy(current_event, features) != kNavigationPolicyNewBackgroundTab && !UIEventWithKeyState::NewTabModifierSetFromIsolatedWorld()) { return kNavigationPolicyNewForegroundTab; } return policy; } CWE ID: Target: 1 Example 2: Code: void VerifyPrintPreviewFailed(bool did_fail) { bool print_preview_failed = (render_thread_.sink().GetUniqueMessageMatching( PrintHostMsg_PrintPreviewFailed::ID) != NULL); EXPECT_EQ(did_fail, print_preview_failed); } 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: rpl_dao_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp; const char *dagid_str = "<elided>"; ND_TCHECK(*dao); if (length < ND_RPL_DAO_MIN_LEN) goto tooshort; bp += ND_RPL_DAO_MIN_LEN; length -= ND_RPL_DAO_MIN_LEN; if(RPL_DAO_D(dao->rpl_flags)) { ND_TCHECK2(dao->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, dao->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]", dagid_str, dao->rpl_daoseq, dao->rpl_instanceid, RPL_DAO_K(dao->rpl_flags) ? ",acK":"", RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"", dao->rpl_flags)); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|truncated]")); return; tooshort: ND_PRINT((ndo," [|length too short]")); return; } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool cgm_bind_dir(const char *root, const char *dirname) { nih_local char *cgpath = NULL; /* /sys should have been mounted by now */ cgpath = NIH_MUST( nih_strdup(NULL, root) ); NIH_MUST( nih_strcat(&cgpath, NULL, "/sys/fs/cgroup") ); if (!dir_exists(cgpath)) { ERROR("%s does not exist", cgpath); return false; } /* mount a tmpfs there so we can create subdirs */ if (mount("cgroup", cgpath, "tmpfs", 0, "size=10000,mode=755")) { SYSERROR("Failed to mount tmpfs at %s", cgpath); return false; } NIH_MUST( nih_strcat(&cgpath, NULL, "/cgmanager") ); if (mkdir(cgpath, 0755) < 0) { SYSERROR("Failed to create %s", cgpath); return false; } if (mount(dirname, cgpath, "none", MS_BIND, 0)) { SYSERROR("Failed to bind mount %s to %s", dirname, cgpath); return false; } return true; } CWE ID: CWE-59 Target: 1 Example 2: Code: void HTMLInputElement::listAttributeTargetChanged() { m_inputType->listAttributeTargetChanged(); } 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 AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { net_warn_ratelimited("Tx-ring is not supported.\n"); goto out; } rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (packet_read_pending(rb)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(!PAGE_ALIGNED(req->tp_block_size))) goto out; if (po->tp_version >= TPACKET_V3 && (int)(req->tp_block_size - BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size / req->tp_frame_size; if (unlikely(rb->frames_per_block == 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Transmit path is not supported. We checked * it above but just being paranoid */ if (!tx_ring) init_prb_bdqc(po, rb, pg_vec, req_u); break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } lock_sock(sk); /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, rb_queue); } release_sock(sk); if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: return err; } CWE ID: CWE-416 Target: 1 Example 2: Code: static ssize_t slabs_show(struct kmem_cache *s, char *buf) { return show_slab_objects(s, buf, SO_ALL); } 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 inline int get_stack_long(struct task_struct *task, int offset) { unsigned char *stack; stack = (unsigned char *)task_pt_regs(task); stack += offset; return (*((int *)stack)); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintPreviewMessageHandler::OnMetafileReadyForPrinting( const PrintHostMsg_DidPreviewDocument_Params& params) { StopWorker(params.document_cookie); if (params.expected_pages_count <= 0) { NOTREACHED(); return; } PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; scoped_refptr<base::RefCountedBytes> data_bytes = GetDataFromHandle(params.metafile_data_handle, params.data_size); if (!data_bytes || !data_bytes->size()) return; print_preview_ui->SetPrintPreviewDataForIndex(COMPLETE_PREVIEW_DOCUMENT_INDEX, std::move(data_bytes)); print_preview_ui->OnPreviewDataIsAvailable( params.expected_pages_count, params.preview_request_id); } CWE ID: CWE-254 Target: 1 Example 2: Code: GPMF_ERR GPMF_SeekToSamples(GPMF_stream *ms) { GPMF_stream prevstate; if (ms) { if (ms->pos+1 < ms->buffer_size_longs) { uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (type == GPMF_TYPE_NEST) GPMF_Next(ms, GPMF_RECURSE_LEVELS); // open STRM and recurse in while (0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL)) { uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) { memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_BAD_STRUCTURE; } type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type == GPMF_TYPE_NEST) // Nest with-in nest { return GPMF_OK; //found match } if (size + 2 == ms->nest_size[ms->nest_level]) { uint32_t key = GPMF_Key(ms); if (GPMF_ERROR_RESERVED == GPMF_Reserved(key)) return GPMF_ERROR_FIND; return GPMF_OK; //found match } if (ms->buffer[ms->pos] == ms->buffer[ms->pos + size + 2]) // Matching tags { return GPMF_OK; //found match } } memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } 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: MagickExport void RemoveDuplicateLayers(Image **images, ExceptionInfo *exception) { register Image *curr, *next; RectangleInfo bounds; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); curr=GetFirstImageInList(*images); for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next) { if ( curr->columns != next->columns || curr->rows != next->rows || curr->page.x != next->page.x || curr->page.y != next->page.y ) continue; bounds=CompareImagesBounds(curr,next,CompareAnyLayer,exception); if ( bounds.x < 0 ) { /* the two images are the same, merge time delays and delete one. */ size_t time; time = curr->delay*1000/curr->ticks_per_second; time += next->delay*1000/next->ticks_per_second; next->ticks_per_second = 100L; next->delay = time*curr->ticks_per_second/1000; next->iterations = curr->iterations; *images = curr; (void) DeleteImageFromList(images); } } *images = GetFirstImageInList(*images); } 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: AriaCurrentState AXNodeObject::ariaCurrentState() const { const AtomicString& attributeValue = getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent); if (attributeValue.isNull()) return AriaCurrentStateUndefined; if (attributeValue.isEmpty() || equalIgnoringCase(attributeValue, "false")) return AriaCurrentStateFalse; if (equalIgnoringCase(attributeValue, "true")) return AriaCurrentStateTrue; if (equalIgnoringCase(attributeValue, "page")) return AriaCurrentStatePage; if (equalIgnoringCase(attributeValue, "step")) return AriaCurrentStateStep; if (equalIgnoringCase(attributeValue, "location")) return AriaCurrentStateLocation; if (equalIgnoringCase(attributeValue, "date")) return AriaCurrentStateDate; if (equalIgnoringCase(attributeValue, "time")) return AriaCurrentStateTime; if (!attributeValue.isEmpty()) return AriaCurrentStateTrue; return AXObject::ariaCurrentState(); } CWE ID: CWE-254 Target: 1 Example 2: Code: long UnserializeFloat(IMkvReader* pReader, long long pos, long long size_, double& result) { if (!pReader || pos < 0 || ((size_ != 4) && (size_ != 8))) return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); unsigned char buf[8]; const int status = pReader->Read(pos, size, buf); if (status < 0) // error return status; if (size == 4) { union { float f; unsigned long ff; }; ff = 0; for (int i = 0;;) { ff |= buf[i]; if (++i >= 4) break; ff <<= 8; } result = f; } else { union { double d; unsigned long long dd; }; dd = 0; for (int i = 0;;) { dd |= buf[i]; if (++i >= 8) break; dd <<= 8; } result = d; } if (std::isinf(result) || std::isnan(result)) return E_FILE_FORMAT_INVALID; return 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct sco_pinfo *pi = sco_pi(sk); lock_sock(sk); if (sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) { hci_conn_accept(pi->conn->hcon, 0); sk->sk_state = BT_CONFIG; release_sock(sk); return 0; } release_sock(sk); return bt_sock_recvmsg(iocb, sock, msg, len, flags); } CWE ID: CWE-200 Target: 1 Example 2: Code: void efx_process_channel_now(struct efx_channel *channel) { struct efx_nic *efx = channel->efx; BUG_ON(channel->channel >= efx->n_channels); BUG_ON(!channel->enabled); BUG_ON(!efx->loopback_selftest); /* Disable interrupts and wait for ISRs to complete */ efx_nic_disable_interrupts(efx); if (efx->legacy_irq) { synchronize_irq(efx->legacy_irq); efx->legacy_irq_enabled = false; } if (channel->irq) synchronize_irq(channel->irq); /* Wait for any NAPI processing to complete */ napi_disable(&channel->napi_str); /* Poll the channel */ efx_process_channel(channel, channel->eventq_mask + 1); /* Ack the eventq. This may cause an interrupt to be generated * when they are reenabled */ efx_channel_processed(channel); napi_enable(&channel->napi_str); if (efx->legacy_irq) efx->legacy_irq_enabled = true; efx_nic_enable_interrupts(efx); } 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: views::View* contents_view() const { return media_controls_view_->contents_view_; } 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: ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx) { struct sta_info *sta = tx->sta; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_local *local = tx->local; if (unlikely(!sta)) return TX_CONTINUE; if (unlikely((test_sta_flag(sta, WLAN_STA_PS_STA) || test_sta_flag(sta, WLAN_STA_PS_DRIVER)) && !(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER))) { int ac = skb_get_queue_mapping(tx->skb); ps_dbg(sta->sdata, "STA %pM aid %d: PS buffer for AC %d\n", sta->sta.addr, sta->sta.aid, ac); if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER) purge_old_ps_buffers(tx->local); if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) { struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]); ps_dbg(tx->sdata, "STA %pM TX buffer for AC %d full - dropping oldest frame\n", sta->sta.addr, ac); ieee80211_free_txskb(&local->hw, old); } else tx->local->total_ps_buffered++; info->control.jiffies = jiffies; info->control.vif = &tx->sdata->vif; info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING; info->flags &= ~IEEE80211_TX_TEMPORARY_FLAGS; skb_queue_tail(&sta->ps_tx_buf[ac], tx->skb); if (!timer_pending(&local->sta_cleanup)) mod_timer(&local->sta_cleanup, round_jiffies(jiffies + STA_INFO_CLEANUP_INTERVAL)); /* * We queued up some frames, so the TIM bit might * need to be set, recalculate it. */ sta_info_recalc_tim(sta); return TX_QUEUED; } else if (unlikely(test_sta_flag(sta, WLAN_STA_PS_STA))) { ps_dbg(tx->sdata, "STA %pM in PS mode, but polling/in SP -> send frame\n", sta->sta.addr); } return TX_CONTINUE; } CWE ID: CWE-362 Target: 1 Example 2: Code: void setEndLine(RootInlineBox* line) { m_endLine = line; } 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: spnego_gss_process_context_token( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t token_buffer) { OM_uint32 ret; ret = gss_process_context_token(minor_status, context_handle, token_buffer); return (ret); } CWE ID: CWE-18 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: do_ssh2_kex(void) { char *myproposal[PROPOSAL_MAX] = { KEX_SERVER }; struct kex *kex; int r; myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal( options.kex_algorithms); myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal( options.ciphers); myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal( options.ciphers); myproposal[PROPOSAL_MAC_ALGS_CTOS] = myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; if (options.compression == COMP_NONE) { myproposal[PROPOSAL_COMP_ALGS_CTOS] = myproposal[PROPOSAL_COMP_ALGS_STOC] = "none"; } else if (options.compression == COMP_DELAYED) { myproposal[PROPOSAL_COMP_ALGS_CTOS] = myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,[email protected]"; } if (options.rekey_limit || options.rekey_interval) packet_set_rekey_limits(options.rekey_limit, (time_t)options.rekey_interval); myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal( list_hostkey_types()); /* start key exchange */ if ((r = kex_setup(active_state, myproposal)) != 0) fatal("kex_setup: %s", ssh_err(r)); kex = active_state->kex; #ifdef WITH_OPENSSL kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server; kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server; kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server; kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; kex->kex[KEX_ECDH_SHA2] = kexecdh_server; #endif kex->kex[KEX_C25519_SHA256] = kexc25519_server; kex->server = 1; kex->client_version_string=client_version_string; kex->server_version_string=server_version_string; kex->load_host_public_key=&get_hostkey_public_by_type; kex->load_host_private_key=&get_hostkey_private_by_type; kex->host_key_index=&get_hostkey_index; kex->sign = sshd_hostkey_sign; dispatch_run(DISPATCH_BLOCK, &kex->done, active_state); session_id2 = kex->session_id; session_id2_len = kex->session_id_len; #ifdef DEBUG_KEXDH /* send 1st encrypted/maced/compressed message */ packet_start(SSH2_MSG_IGNORE); packet_put_cstring("markus"); packet_send(); packet_write_wait(); #endif debug("KEX done"); } CWE ID: CWE-119 Target: 1 Example 2: Code: LocalDOMWindow* Document::ExecutingWindow() const { if (LocalDOMWindow* owning_window = domWindow()) return owning_window; if (HTMLImportsController* import = ImportsController()) return import->Master()->domWindow(); return nullptr; } 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: sync_min_store(struct mddev *mddev, const char *buf, size_t len) { unsigned int min; int rv; if (strncmp(buf, "system", 6)==0) { min = 0; } else { rv = kstrtouint(buf, 10, &min); if (rv < 0) return rv; if (min == 0) return -EINVAL; } mddev->sync_speed_min = min; return len; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int fanout_add(struct sock *sk, u16 id, u16 type_flags) { struct packet_sock *po = pkt_sk(sk); struct packet_fanout *f, *match; u8 type = type_flags & 0xff; u8 flags = type_flags >> 8; int err; switch (type) { case PACKET_FANOUT_ROLLOVER: if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER) return -EINVAL; case PACKET_FANOUT_HASH: case PACKET_FANOUT_LB: case PACKET_FANOUT_CPU: case PACKET_FANOUT_RND: case PACKET_FANOUT_QM: case PACKET_FANOUT_CBPF: case PACKET_FANOUT_EBPF: break; default: return -EINVAL; } if (!po->running) return -EINVAL; if (po->fanout) return -EALREADY; if (type == PACKET_FANOUT_ROLLOVER || (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) { po->rollover = kzalloc(sizeof(*po->rollover), GFP_KERNEL); if (!po->rollover) return -ENOMEM; atomic_long_set(&po->rollover->num, 0); atomic_long_set(&po->rollover->num_huge, 0); atomic_long_set(&po->rollover->num_failed, 0); } mutex_lock(&fanout_mutex); match = NULL; list_for_each_entry(f, &fanout_list, list) { if (f->id == id && read_pnet(&f->net) == sock_net(sk)) { match = f; break; } } err = -EINVAL; if (match && match->flags != flags) goto out; if (!match) { err = -ENOMEM; match = kzalloc(sizeof(*match), GFP_KERNEL); if (!match) goto out; write_pnet(&match->net, sock_net(sk)); match->id = id; match->type = type; match->flags = flags; INIT_LIST_HEAD(&match->list); spin_lock_init(&match->lock); atomic_set(&match->sk_ref, 0); fanout_init_data(match); match->prot_hook.type = po->prot_hook.type; match->prot_hook.dev = po->prot_hook.dev; match->prot_hook.func = packet_rcv_fanout; match->prot_hook.af_packet_priv = match; match->prot_hook.id_match = match_fanout_group; dev_add_pack(&match->prot_hook); list_add(&match->list, &fanout_list); } err = -EINVAL; if (match->type == type && match->prot_hook.type == po->prot_hook.type && match->prot_hook.dev == po->prot_hook.dev) { err = -ENOSPC; if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) { __dev_remove_pack(&po->prot_hook); po->fanout = match; atomic_inc(&match->sk_ref); __fanout_link(sk, po); err = 0; } } out: mutex_unlock(&fanout_mutex); if (err) { kfree(po->rollover); po->rollover = NULL; } return err; } CWE ID: CWE-416 Target: 1 Example 2: Code: static int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg, size_t size) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_sendmsg_nosec(&iocb, sock, msg, size); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } 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 RenderProcessHostImpl::CreateMediaStreamDispatcherHost( MediaStreamManager* media_stream_manager, mojom::MediaStreamDispatcherHostRequest request) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!media_stream_dispatcher_host_) { media_stream_dispatcher_host_.reset( new MediaStreamDispatcherHost(GetID(), media_stream_manager)); } media_stream_dispatcher_host_->BindRequest(std::move(request)); } CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SubpelVarianceTest<vp9_subp_avg_variance_fn_t>::RefTest() { for (int x = 0; x < 16; ++x) { for (int y = 0; y < 16; ++y) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); sec_[j] = rnd.Rand8(); } for (int j = 0; j < block_size_ + width_ + height_ + 1; j++) { ref_[j] = rnd.Rand8(); } unsigned int sse1, sse2; unsigned int var1; REGISTER_STATE_CHECK(var1 = subpel_variance_(ref_, width_ + 1, x, y, src_, width_, &sse1, sec_)); const unsigned int var2 = subpel_avg_variance_ref(ref_, src_, sec_, log2width_, log2height_, x, y, &sse2); EXPECT_EQ(sse1, sse2) << "at position " << x << ", " << y; EXPECT_EQ(var1, var2) << "at position " << x << ", " << y; } } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int ip6_finish_output2(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct net_device *dev = dst->dev; struct neighbour *neigh; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(skb->sk) && ((mroute6_socket(dev_net(dev), skb) && !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) || ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr))) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); /* Do not check for IFF_ALLMULTI; multicast routing is not supported in any case. */ if (newskb) NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, newskb, NULL, newskb->dev, ip6_dev_loopback_xmit); if (ipv6_hdr(skb)->hop_limit == 0) { IP6_INC_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } } IP6_UPD_PO_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTMCAST, skb->len); } neigh = dst_get_neighbour(dst); if (neigh) return neigh_output(neigh, skb); IP6_INC_STATS_BH(dev_net(dst->dev), ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EINVAL; } 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: base::HistogramBase* GetCreatedHistogram(int index) { DCHECK_GT(kMaxCreateHistograms, index); return created_histograms_[index]; } 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: int tls_get_message_header(SSL *s, int *mt) { /* s->init_num < SSL3_HM_HEADER_LENGTH */ int skip_message, i, recvd_type, al; unsigned char *p; unsigned long l; p = (unsigned char *)s->init_buf->data; do { while (s->init_num < SSL3_HM_HEADER_LENGTH) { i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type, &p[s->init_num], SSL3_HM_HEADER_LENGTH - s->init_num, 0); if (i <= 0) { s->rwstate = SSL_READING; return 0; } if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) { /* * A ChangeCipherSpec must be a single byte and may not occur * in the middle of a handshake message. */ if (s->init_num != 0 || i != 1 || p[0] != SSL3_MT_CCS) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_BAD_CHANGE_CIPHER_SPEC); goto f_err; } s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC; s->init_num = i - 1; s->s3->tmp.message_size = i; return 1; } else if (recvd_type != SSL3_RT_HANDSHAKE) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY); goto f_err; } s->init_num += i; } skip_message = 0; if (!s->server) if (p[0] == SSL3_MT_HELLO_REQUEST) /* * The server may always send 'Hello Request' messages -- * we are doing a handshake anyway now, so ignore them if * their format is correct. Does not count for 'Finished' * MAC. */ if (p[1] == 0 && p[2] == 0 && p[3] == 0) { s->init_num = 0; skip_message = 1; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, SSL3_HM_HEADER_LENGTH, s, s->msg_callback_arg); } } while (skip_message); /* s->init_num == SSL3_HM_HEADER_LENGTH */ *mt = *p; s->s3->tmp.message_type = *(p++); if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) { /* * Only happens with SSLv3+ in an SSLv2 backward compatible * ClientHello * * Total message size is the remaining record bytes to read * plus the SSL3_HM_HEADER_LENGTH bytes that we already read */ l = RECORD_LAYER_get_rrec_length(&s->rlayer) + SSL3_HM_HEADER_LENGTH; if (l && !BUF_MEM_grow_clean(s->init_buf, (int)l)) { SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, ERR_R_BUF_LIB); goto err; } s->s3->tmp.message_size = l; s->init_msg = s->init_buf->data; } s->s3->tmp.message_size = l; s->init_msg = s->init_buf->data; s->init_num = SSL3_HM_HEADER_LENGTH; } else { SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE); goto f_err; } CWE ID: CWE-400 Target: 1 Example 2: Code: test_bson_clear (void) { bson_t *doc = NULL; bson_clear (&doc); BSON_ASSERT (doc == NULL); doc = bson_new (); BSON_ASSERT (doc != NULL); bson_clear (&doc); BSON_ASSERT (doc == NULL); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void V8TestObject::ActivityLoggingSetterForAllWorldsLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_activityLoggingSetterForAllWorldsLongAttribute_Getter"); test_object_v8_internal::ActivityLoggingSetterForAllWorldsLongAttributeAttributeGetter(info); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: InputMethodStatusConnection* ChromeOSMonitorInputMethodStatus( void* language_library, LanguageCurrentInputMethodMonitorFunction current_input_method_changed, LanguageRegisterImePropertiesFunction register_ime_properties, LanguageUpdateImePropertyFunction update_ime_property, LanguageConnectionChangeMonitorFunction connection_changed) { DLOG(INFO) << "MonitorInputMethodStatus"; return InputMethodStatusConnection::GetConnection( language_library, current_input_method_changed, register_ime_properties, update_ime_property, connection_changed); } CWE ID: CWE-399 Target: 1 Example 2: Code: static u32 dw210x_i2c_func(struct i2c_adapter *adapter) { return I2C_FUNC_I2C; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool is_ereg(u32 reg) { return (1 << reg) & (BIT(BPF_REG_5) | BIT(AUX_REG) | BIT(BPF_REG_7) | BIT(BPF_REG_8) | BIT(BPF_REG_9)); } 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: bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct bsg_device *bd = file->private_data; ssize_t bytes_written; int ret; dprintk("%s: write %Zd bytes\n", bd->name, count); bsg_set_block(bd, file); bytes_written = 0; ret = __bsg_write(bd, buf, count, &bytes_written, file->f_mode & FMODE_WRITE); *ppos = bytes_written; /* * return bytes written on non-fatal errors */ if (!bytes_written || err_block_err(ret)) bytes_written = ret; dprintk("%s: returning %Zd\n", bd->name, bytes_written); return bytes_written; } CWE ID: CWE-416 Target: 1 Example 2: Code: v8::Local<v8::Value> ModuleSystem::RunString(v8::Local<v8::String> code, v8::Local<v8::String> name) { return context_->RunScript( name, code, base::Bind(&ExceptionHandler::HandleUncaughtException, base::Unretained(exception_handler_.get()))); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AudioRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, int input_channels) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(LookupById(stream_id) == NULL); media::AudioParameters audio_params(params); uint32 buffer_size = media::AudioBus::CalculateMemorySize(audio_params); DCHECK_GT(buffer_size, 0U); DCHECK_LE(buffer_size, static_cast<uint32>(media::limits::kMaxPacketSizeInBytes)); DCHECK_GE(input_channels, 0); DCHECK_LT(input_channels, media::limits::kMaxChannels); int output_memory_size = AudioBus::CalculateMemorySize(audio_params); DCHECK_GT(output_memory_size, 0); int frames = audio_params.frames_per_buffer(); int input_memory_size = AudioBus::CalculateMemorySize(input_channels, frames); DCHECK_GE(input_memory_size, 0); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 io_buffer_size = output_memory_size + input_memory_size; uint32 shared_memory_size = media::TotalSharedMemorySizeInBytes(io_buffer_size); if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioSyncReader> reader( new AudioSyncReader(&entry->shared_memory, params, input_channels)); if (!reader->Init()) { SendErrorMessage(stream_id); return; } entry->reader.reset(reader.release()); entry->controller = media::AudioOutputController::Create( audio_manager_, this, audio_params, entry->reader.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); if (media_observer_) media_observer_->OnSetAudioStreamStatus(this, stream_id, "created"); } 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 ExtensionTtsPlatformImpl::set_error(const std::string& error) { error_ = error; } CWE ID: CWE-20 Target: 1 Example 2: Code: void ChildProcessLauncherHelper::ResetRegisteredFilesForTesting() { ResetFilesToShareForTestingPosix(); } CWE ID: CWE-664 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 crypto_ccm_module_init(void) { int err; err = crypto_register_template(&crypto_cbcmac_tmpl); if (err) goto out; err = crypto_register_template(&crypto_ccm_base_tmpl); if (err) goto out_undo_cbcmac; err = crypto_register_template(&crypto_ccm_tmpl); if (err) goto out_undo_base; err = crypto_register_template(&crypto_rfc4309_tmpl); if (err) goto out_undo_ccm; out: return err; out_undo_ccm: crypto_unregister_template(&crypto_ccm_tmpl); out_undo_base: crypto_unregister_template(&crypto_ccm_base_tmpl); out_undo_cbcmac: crypto_register_template(&crypto_cbcmac_tmpl); goto out; } 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: AudioSource::AudioSource( audio_source_t inputSource, const String16 &opPackageName, uint32_t sampleRate, uint32_t channelCount, uint32_t outSampleRate) : mStarted(false), mSampleRate(sampleRate), mOutSampleRate(outSampleRate > 0 ? outSampleRate : sampleRate), mPrevSampleTimeUs(0), mFirstSampleTimeUs(-1ll), mNumFramesReceived(0), mNumClientOwnedBuffers(0) { ALOGV("sampleRate: %u, outSampleRate: %u, channelCount: %u", sampleRate, outSampleRate, channelCount); CHECK(channelCount == 1 || channelCount == 2); CHECK(sampleRate > 0); size_t minFrameCount; status_t status = AudioRecord::getMinFrameCount(&minFrameCount, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount)); if (status == OK) { uint32_t frameCount = kMaxBufferSize / sizeof(int16_t) / channelCount; size_t bufCount = 2; while ((bufCount * frameCount) < minFrameCount) { bufCount++; } mRecord = new AudioRecord( inputSource, sampleRate, AUDIO_FORMAT_PCM_16_BIT, audio_channel_in_mask_from_count(channelCount), opPackageName, (size_t) (bufCount * frameCount), AudioRecordCallbackFunction, this, frameCount /*notificationFrames*/); mInitCheck = mRecord->initCheck(); if (mInitCheck != OK) { mRecord.clear(); } } else { mInitCheck = status; } } CWE ID: CWE-200 Target: 1 Example 2: Code: SiteInstanceTestBrowserClient() : privileged_process_id_(-1) { } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static st64 read_sleb128(ulebr *r, ut8 *end) { st64 result = 0; int bit = 0; ut8 byte = 0; ut8 *p = r->p; do { if (p == end) { eprintf ("malformed sleb128"); break; } byte = *p++; result |= (((st64)(byte & 0x7f)) << bit); bit += 7; } while (byte & 0x80); if ((byte & 0x40)) { result |= (-1LL) << bit; } r->p = p; return result; } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sctp_init_sock(struct sock *sk) { struct net *net = sock_net(sk); struct sctp_sock *sp; pr_debug("%s: sk:%p\n", __func__, sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = net->sctp.max_burst; sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init; sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = net->sctp.rto_initial; sp->rtoinfo.srto_max = net->sctp.rto_max; sp->rtoinfo.srto_min = net->sctp.rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = net->sctp.hb_interval; sp->pathmaxrxt = net->sctp.max_retrans_path; sp->pathmtu = 0; /* allow default discovery */ sp->sackdelay = net->sctp.sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; sp->recvrcvinfo = 0; sp->recvnxtinfo = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ sp->ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!sp->ep) return -ENOMEM; sp->hmac = NULL; sk->sk_destruct = sctp_destruct_sock; SCTP_DBG_OBJCNT_INC(sock); local_bh_disable(); percpu_counter_inc(&sctp_sockets_allocated); sock_prot_inuse_add(net, sk->sk_prot, 1); if (net->sctp.default_auto_asconf) { list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; } else sp->do_auto_asconf = 0; local_bh_enable(); return 0; } CWE ID: CWE-362 Target: 1 Example 2: Code: ProcXFixesDestroyRegion(ClientPtr client) { REQUEST(xXFixesDestroyRegionReq); RegionPtr pRegion; REQUEST_SIZE_MATCH(xXFixesDestroyRegionReq); VERIFY_REGION(pRegion, stuff->region, client, DixWriteAccess); FreeResource(stuff->region, RT_NONE); return Success; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool append_ptyname(char **pp, char *name) { char *p; if (!*pp) { *pp = malloc(strlen(name) + strlen("container_ttys=") + 1); if (!*pp) return false; sprintf(*pp, "container_ttys=%s", name); return true; } p = realloc(*pp, strlen(*pp) + strlen(name) + 2); if (!p) return false; *pp = p; strcat(p, " "); strcat(p, name); return true; } CWE ID: CWE-59 Output:
0
Here are some example code snippets. Analyze the following 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 FindBarController::Show() { FindManager* find_manager = tab_contents_->GetFindManager(); if (!find_manager->find_ui_active()) { MaybeSetPrepopulateText(); find_manager->set_find_ui_active(true); find_bar_->Show(true); } find_bar_->SetFocusAndSelection(); } CWE ID: CWE-20 Target: 1 Example 2: Code: MediaPlayerService::Client::ServiceDeathNotifier::ServiceDeathNotifier( const sp<IBinder>& service, const sp<MediaPlayerBase>& listener, int which) { mService = service; mListener = listener; mWhich = which; } 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: InspectorAgentRegistry::InspectorAgentRegistry(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState) : m_instrumentingAgents(instrumentingAgents) , m_inspectorState(inspectorState) { } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int cuse_channel_release(struct inode *inode, struct file *file) { struct fuse_dev *fud = file->private_data; struct cuse_conn *cc = fc_to_cc(fud->fc); int rc; /* remove from the conntbl, no more access from this point on */ mutex_lock(&cuse_lock); list_del_init(&cc->list); mutex_unlock(&cuse_lock); /* remove device */ if (cc->dev) device_unregister(cc->dev); if (cc->cdev) { unregister_chrdev_region(cc->cdev->dev, 1); cdev_del(cc->cdev); } rc = fuse_dev_release(inode, file); /* puts the base reference */ return rc; } CWE ID: CWE-399 Target: 1 Example 2: Code: xmlGetNamespace(xmlParserCtxtPtr ctxt, const xmlChar *prefix) { int i; if (prefix == ctxt->str_xml) return(ctxt->str_xml_ns); for (i = ctxt->nsNr - 2;i >= 0;i-=2) if (ctxt->nsTab[i] == prefix) { if ((prefix == NULL) && (*ctxt->nsTab[i + 1] == 0)) return(NULL); return(ctxt->nsTab[i + 1]); } return(NULL); } CWE ID: CWE-835 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { char path[PATH_MAX]; struct passwd *pwd; { char path[PATH_MAX]; struct passwd *pwd; FILE *fp; int i, save_errno; uid_t fsuid; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); save_errno = errno; setfsuid(fsuid); if (fp != NULL) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } } 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: kdc_process_s4u2self_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_const_principal client_princ, krb5_const_principal header_srv_princ, krb5_boolean issuing_referral, const krb5_db_entry *server, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_timestamp kdc_time, krb5_pa_s4u_x509_user **s4u_x509_user, krb5_db_entry **princ_ptr, const char **status) { krb5_error_code code; krb5_boolean is_local_tgt; krb5_pa_data *pa_data; int flags; krb5_db_entry *princ; *princ_ptr = NULL; pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_S4U_X509_USER); if (pa_data != NULL) { code = kdc_process_s4u_x509_user(kdc_context, request, pa_data, tgs_subkey, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else { pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_FOR_USER); if (pa_data != NULL) { code = kdc_process_for_user(kdc_active_realm, pa_data, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else return 0; } /* * We need to compare the client name in the TGT with the requested * server name. Supporting server name aliases without assuming a * global name service makes this difficult to do. * * The comparison below handles the following cases (note that the * term "principal name" below excludes the realm). * * (1) The requested service is a host-based service with two name * components, in which case we assume the principal name to * contain sufficient qualifying information. The realm is * ignored for the purpose of comparison. * * (2) The requested service name is an enterprise principal name: * the service principal name is compared with the unparsed * form of the client name (including its realm). * * (3) The requested service is some other name type: an exact * match is required. * * An alternative would be to look up the server once again with * FLAG_CANONICALIZE | FLAG_CLIENT_REFERRALS_ONLY set, do an exact * match between the returned name and client_princ. However, this * assumes that the client set FLAG_CANONICALIZE when requesting * the TGT and that we have a global name service. */ flags = 0; switch (krb5_princ_type(kdc_context, request->server)) { case KRB5_NT_SRV_HST: /* (1) */ if (krb5_princ_size(kdc_context, request->server) == 2) flags |= KRB5_PRINCIPAL_COMPARE_IGNORE_REALM; break; case KRB5_NT_ENTERPRISE_PRINCIPAL: /* (2) */ flags |= KRB5_PRINCIPAL_COMPARE_ENTERPRISE; break; default: /* (3) */ break; } if (!krb5_principal_compare_flags(kdc_context, request->server, client_princ, flags)) { *status = "INVALID_S4U2SELF_REQUEST"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error code */ } /* * Protocol transition is mutually exclusive with renew/forward/etc * as well as user-to-user and constrained delegation. This check * is also made in validate_as_request(). * * We can assert from this check that the header ticket was a TGT, as * that is validated previously in validate_tgs_request(). */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KRB5KDC_ERR_BADOPTION; } /* * Valid S4U2Self requests can occur in the following combinations: * * (1) local TGT, local user, local server * (2) cross TGT, local user, issuing referral * (3) cross TGT, non-local user, issuing referral * (4) cross TGT, non-local user, local server * * The first case is for a single-realm S4U2Self scenario; the second, * third, and fourth cases are for the initial, intermediate (if any), and * final cross-realm requests in a multi-realm scenario. */ is_local_tgt = !is_cross_tgs_principal(header_srv_princ); if (is_local_tgt && issuing_referral) { /* The requesting server appears to no longer exist, and we found * a referral instead. Treat this as a server lookup failure. */ *status = "LOOKING_UP_SERVER"; return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; } /* * Do not attempt to lookup principals in foreign realms. */ if (is_local_principal(kdc_active_realm, (*s4u_x509_user)->user_id.user)) { krb5_db_entry no_server; krb5_pa_data **e_data = NULL; if (!is_local_tgt && !issuing_referral) { /* A local server should not need a cross-realm TGT to impersonate * a local principal. */ *status = "NOT_CROSS_REALM_REQUEST"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error */ } code = krb5_db_get_principal(kdc_context, (*s4u_x509_user)->user_id.user, KRB5_KDB_FLAG_INCLUDE_PAC, &princ); if (code == KRB5_KDB_NOENTRY) { *status = "UNKNOWN_S4U2SELF_PRINCIPAL"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; } else if (code) { *status = "LOOKING_UP_S4U2SELF_PRINCIPAL"; return code; /* caller can free for_user */ } memset(&no_server, 0, sizeof(no_server)); code = validate_as_request(kdc_active_realm, request, *princ, no_server, kdc_time, status, &e_data); if (code) { krb5_db_free_principal(kdc_context, princ); krb5_free_pa_data(kdc_context, e_data); return code; } *princ_ptr = princ; } else if (is_local_tgt) { /* * The server is asking to impersonate a principal from another realm, * using a local TGT. It should instead ask that principal's realm and * follow referrals back to us. */ *status = "S4U2SELF_CLIENT_NOT_OURS"; return KRB5KDC_ERR_POLICY; /* match Windows error */ } return 0; } CWE ID: CWE-617 Target: 1 Example 2: Code: static inline bool is_last_gpte(struct kvm_mmu *mmu, unsigned level, unsigned gpte) { unsigned index; index = level - 1; index |= (gpte & PT_PAGE_SIZE_MASK) >> (PT_PAGE_SIZE_SHIFT - 2); return mmu->last_pte_bitmap & (1 << index); } 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 BaseMultipleFieldsDateAndTimeInputType::hasBadInput() const { return element()->value().isEmpty() && m_dateTimeEditElement && m_dateTimeEditElement->anyEditableFieldsHaveValues(); } 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 filter_frame(AVFilterLink *inlink, AVFrame *in) { GradFunContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int p, direct; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { direct = 0; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } for (p = 0; p < 4 && in->data[p]; p++) { int w = inlink->w; int h = inlink->h; int r = s->radius; if (p) { w = s->chroma_w; h = s->chroma_h; r = s->chroma_r; } if (FFMIN(w, h) > 2 * r) filter(s, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r); else if (out->data[p] != in->data[p]) av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); } CWE ID: CWE-119 Target: 1 Example 2: Code: PDFiumEngine::~PDFiumEngine() { for (auto& page : pages_) page->Unload(); if (doc_) { FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC); #if defined(PDF_ENABLE_XFA) FPDF_CloseDocument(doc_); FPDFDOC_ExitFormFillEnvironment(form_); #else FPDFDOC_ExitFormFillEnvironment(form_); FPDF_CloseDocument(doc_); #endif } FPDFAvail_Destroy(fpdf_availability_); base::STLDeleteElements(&pages_); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void gen_op_jmp_v(TCGv dest) { tcg_gen_st_tl(dest, cpu_env, offsetof(CPUX86State, eip)); } CWE ID: CWE-94 Output:
0