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 enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) { enum hrtimer_restart ret = HRTIMER_RESTART; struct perf_sample_data data; struct pt_regs *regs; struct perf_event *event; u64 period; event = container_of(hrtimer, struct perf_event, hw.hrtimer); if (event->state != PERF_EVENT_STATE_ACTIVE) return HRTIMER_NORESTART; event->pmu->read(event); perf_sample_data_init(&data, 0); data.period = event->hw.last_period; regs = get_irq_regs(); if (regs && !perf_exclude_event(event, regs)) { if (!(event->attr.exclude_idle && current->pid == 0)) if (perf_event_overflow(event, 0, &data, regs)) ret = HRTIMER_NORESTART; } period = max_t(u64, 10000, event->hw.sample_period); hrtimer_forward_now(hrtimer, ns_to_ktime(period)); return ret; } CWE ID: CWE-399 Target: 1 Example 2: Code: static inline unsigned ip_vs_rs_hashkey(int af, const union nf_inet_addr *addr, __be16 port) { register unsigned porth = ntohs(port); __be32 addr_fold = addr->ip; #ifdef CONFIG_IP_VS_IPV6 if (af == AF_INET6) addr_fold = addr->ip6[0]^addr->ip6[1]^ addr->ip6[2]^addr->ip6[3]; #endif return (ntohl(addr_fold)^(porth>>IP_VS_RTAB_BITS)^porth) & IP_VS_RTAB_MASK; } 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: level_store(struct mddev *mddev, const char *buf, size_t len) { char clevel[16]; ssize_t rv; size_t slen = len; struct md_personality *pers, *oldpers; long level; void *priv, *oldpriv; struct md_rdev *rdev; if (slen == 0 || slen >= sizeof(clevel)) return -EINVAL; rv = mddev_lock(mddev); if (rv) return rv; if (mddev->pers == NULL) { strncpy(mddev->clevel, buf, slen); if (mddev->clevel[slen-1] == '\n') slen--; mddev->clevel[slen] = 0; mddev->level = LEVEL_NONE; rv = len; goto out_unlock; } rv = -EROFS; if (mddev->ro) goto out_unlock; /* request to change the personality. Need to ensure: * - array is not engaged in resync/recovery/reshape * - old personality can be suspended * - new personality will access other array. */ rv = -EBUSY; if (mddev->sync_thread || test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) || mddev->reshape_position != MaxSector || mddev->sysfs_active) goto out_unlock; rv = -EINVAL; if (!mddev->pers->quiesce) { printk(KERN_WARNING "md: %s: %s does not support online personality change\n", mdname(mddev), mddev->pers->name); goto out_unlock; } /* Now find the new personality */ strncpy(clevel, buf, slen); if (clevel[slen-1] == '\n') slen--; clevel[slen] = 0; if (kstrtol(clevel, 10, &level)) level = LEVEL_NONE; if (request_module("md-%s", clevel) != 0) request_module("md-level-%s", clevel); spin_lock(&pers_lock); pers = find_pers(level, clevel); if (!pers || !try_module_get(pers->owner)) { spin_unlock(&pers_lock); printk(KERN_WARNING "md: personality %s not loaded\n", clevel); rv = -EINVAL; goto out_unlock; } spin_unlock(&pers_lock); if (pers == mddev->pers) { /* Nothing to do! */ module_put(pers->owner); rv = len; goto out_unlock; } if (!pers->takeover) { module_put(pers->owner); printk(KERN_WARNING "md: %s: %s does not support personality takeover\n", mdname(mddev), clevel); rv = -EINVAL; goto out_unlock; } rdev_for_each(rdev, mddev) rdev->new_raid_disk = rdev->raid_disk; /* ->takeover must set new_* and/or delta_disks * if it succeeds, and may set them when it fails. */ priv = pers->takeover(mddev); if (IS_ERR(priv)) { mddev->new_level = mddev->level; mddev->new_layout = mddev->layout; mddev->new_chunk_sectors = mddev->chunk_sectors; mddev->raid_disks -= mddev->delta_disks; mddev->delta_disks = 0; mddev->reshape_backwards = 0; module_put(pers->owner); printk(KERN_WARNING "md: %s: %s would not accept array\n", mdname(mddev), clevel); rv = PTR_ERR(priv); goto out_unlock; } /* Looks like we have a winner */ mddev_suspend(mddev); mddev_detach(mddev); spin_lock(&mddev->lock); oldpers = mddev->pers; oldpriv = mddev->private; mddev->pers = pers; mddev->private = priv; strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel)); mddev->level = mddev->new_level; mddev->layout = mddev->new_layout; mddev->chunk_sectors = mddev->new_chunk_sectors; mddev->delta_disks = 0; mddev->reshape_backwards = 0; mddev->degraded = 0; spin_unlock(&mddev->lock); if (oldpers->sync_request == NULL && mddev->external) { /* We are converting from a no-redundancy array * to a redundancy array and metadata is managed * externally so we need to be sure that writes * won't block due to a need to transition * clean->dirty * until external management is started. */ mddev->in_sync = 0; mddev->safemode_delay = 0; mddev->safemode = 0; } oldpers->free(mddev, oldpriv); if (oldpers->sync_request == NULL && pers->sync_request != NULL) { /* need to add the md_redundancy_group */ if (sysfs_create_group(&mddev->kobj, &md_redundancy_group)) printk(KERN_WARNING "md: cannot register extra attributes for %s\n", mdname(mddev)); mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, "sync_action"); } if (oldpers->sync_request != NULL && pers->sync_request == NULL) { /* need to remove the md_redundancy_group */ if (mddev->to_remove == NULL) mddev->to_remove = &md_redundancy_group; } rdev_for_each(rdev, mddev) { if (rdev->raid_disk < 0) continue; if (rdev->new_raid_disk >= mddev->raid_disks) rdev->new_raid_disk = -1; if (rdev->new_raid_disk == rdev->raid_disk) continue; sysfs_unlink_rdev(mddev, rdev); } rdev_for_each(rdev, mddev) { if (rdev->raid_disk < 0) continue; if (rdev->new_raid_disk == rdev->raid_disk) continue; rdev->raid_disk = rdev->new_raid_disk; if (rdev->raid_disk < 0) clear_bit(In_sync, &rdev->flags); else { if (sysfs_link_rdev(mddev, rdev)) printk(KERN_WARNING "md: cannot register rd%d" " for %s after level change\n", rdev->raid_disk, mdname(mddev)); } } if (pers->sync_request == NULL) { /* this is now an array without redundancy, so * it must always be in_sync */ mddev->in_sync = 1; del_timer_sync(&mddev->safemode_timer); } blk_set_stacking_limits(&mddev->queue->limits); pers->run(mddev); set_bit(MD_CHANGE_DEVS, &mddev->flags); mddev_resume(mddev); if (!mddev->thread) md_update_sb(mddev, 1); sysfs_notify(&mddev->kobj, NULL, "level"); md_new_event(mddev); rv = len; out_unlock: mddev_unlock(mddev); return rv; } 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 BOOL nsc_context_initialize_encode(NSC_CONTEXT* context) { int i; UINT32 length; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); /* The maximum length a decoded plane can reach in all cases */ length = tempWidth * tempHeight + 16; if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) { BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length); if (!tmp) goto fail; context->priv->PlaneBuffers[i] = tmp; } context->priv->PlaneBuffersLength = length; } if (context->ChromaSubsamplingLevel) { context->OrgByteCount[0] = tempWidth * context->height; context->OrgByteCount[1] = tempWidth * tempHeight / 4; context->OrgByteCount[2] = tempWidth * tempHeight / 4; context->OrgByteCount[3] = context->width * context->height; } else { context->OrgByteCount[0] = context->width * context->height; context->OrgByteCount[1] = context->width * context->height; context->OrgByteCount[2] = context->width * context->height; context->OrgByteCount[3] = context->width * context->height; } return TRUE; fail: if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) free(context->priv->PlaneBuffers[i]); } return FALSE; } CWE ID: CWE-787 Target: 1 Example 2: Code: CuePoint::~CuePoint() { delete[] m_track_positions; } 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: otp_verify(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *pa, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_verify_respond_fn respond, void *arg) { krb5_keyblock *armor_key = NULL; krb5_pa_otp_req *req = NULL; struct request_state *rs; krb5_error_code retval; krb5_data d, plaintext; char *config; enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH; /* Get the FAST armor key. */ armor_key = cb->fast_armor(context, rock); if (armor_key == NULL) { retval = KRB5KDC_ERR_PREAUTH_FAILED; com_err("otp", retval, "No armor key found when verifying padata"); goto error; } /* Decode the request. */ d = make_data(pa->contents, pa->length); retval = decode_krb5_pa_otp_req(&d, &req); if (retval != 0) { com_err("otp", retval, "Unable to decode OTP request"); goto error; } /* Decrypt the nonce from the request. */ retval = decrypt_encdata(context, armor_key, req, &plaintext); if (retval != 0) { com_err("otp", retval, "Unable to decrypt nonce"); goto error; } /* Verify the nonce or timestamp. */ retval = nonce_verify(context, armor_key, &plaintext); if (retval != 0) retval = timestamp_verify(context, &plaintext); krb5_free_data_contents(context, &plaintext); if (retval != 0) { com_err("otp", retval, "Unable to verify nonce or timestamp"); goto error; } /* Create the request state. */ rs = k5alloc(sizeof(struct request_state), &retval); if (rs == NULL) goto error; rs->arg = arg; rs->respond = respond; /* Get the principal's OTP configuration string. */ retval = cb->get_string(context, rock, "otp", &config); if (retval == 0 && config == NULL) retval = KRB5_PREAUTH_FAILED; if (retval != 0) { free(rs); goto error; } /* Send the request. */ otp_state_verify((otp_state *)moddata, cb->event_context(context, rock), request->client, config, req, on_response, rs); cb->free_string(context, rock, config); k5_free_pa_otp_req(context, req); return; error: k5_free_pa_otp_req(context, req); (*respond)(arg, retval, NULL, NULL, NULL); } 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: SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; iov.iov_len = size; iov.iov_base = ubuf; iov_iter_init(&msg.msg_iter, READ, &iov, 1, size); /* Save some cycles and don't copy the address if not needed */ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; /* We assume all kernel code knows the size of sockaddr_storage */ msg.msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } CWE ID: CWE-264 Target: 1 Example 2: Code: void V8TestObject::LimitedToOnlyOtherAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_limitedToOnlyOtherAttribute_Getter"); test_object_v8_internal::LimitedToOnlyOtherAttributeAttributeGetter(info); } 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: SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ } 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: void DataReductionProxySettings::MaybeActivateDataReductionProxy( bool at_startup) { DCHECK(thread_checker_.CalledOnValidThread()); PrefService* prefs = GetOriginalProfilePrefs(); if (!prefs) return; if (spdy_proxy_auth_enabled_.GetValue() && at_startup) { int64_t last_enabled_time = prefs->GetInt64(prefs::kDataReductionProxyLastEnabledTime); if (last_enabled_time != 0) { RecordDaysSinceEnabledMetric( (clock_->Now() - base::Time::FromInternalValue(last_enabled_time)) .InDays()); } int64_t last_savings_cleared_time = prefs->GetInt64( prefs::kDataReductionProxySavingsClearedNegativeSystemClock); if (last_savings_cleared_time != 0) { int32_t days_since_savings_cleared = (clock_->Now() - base::Time::FromInternalValue(last_savings_cleared_time)) .InDays(); if (days_since_savings_cleared == 0) days_since_savings_cleared = 1; UMA_HISTOGRAM_CUSTOM_COUNTS( "DataReductionProxy.DaysSinceSavingsCleared.NegativeSystemClock", days_since_savings_cleared, 1, 365, 50); } } if (spdy_proxy_auth_enabled_.GetValue() && !prefs->GetBoolean(prefs::kDataReductionProxyWasEnabledBefore)) { prefs->SetBoolean(prefs::kDataReductionProxyWasEnabledBefore, true); ResetDataReductionStatistics(); } if (!at_startup) { if (IsDataReductionProxyEnabled()) { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON); prefs->SetInt64(prefs::kDataReductionProxyLastEnabledTime, clock_->Now().ToInternalValue()); RecordDaysSinceEnabledMetric(0); } else { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF); } } if (at_startup && !data_reduction_proxy_service_->Initialized()) deferred_initialization_ = true; else UpdateIOData(at_startup); } CWE ID: CWE-119 Target: 1 Example 2: Code: void V8TestObject::CallWithThisValueMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_callWithThisValue"); test_object_v8_internal::CallWithThisValueMethod(info); } 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 ResourceFetcher::ClearPreloads(ClearPreloadsPolicy policy) { LogPreloadStats(policy); Vector<PreloadKey> keys_to_be_removed; for (const auto& pair : preloads_) { Resource* resource = pair.value; if (policy == kClearAllPreloads || !resource->IsLinkPreload()) { GetMemoryCache()->Remove(resource); keys_to_be_removed.push_back(pair.key); } } preloads_.RemoveAll(keys_to_be_removed); matched_preloads_.clear(); } 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: LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (istreq(str, "all")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, "none")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; } CWE ID: CWE-476 Target: 1 Example 2: Code: WebView* RenderViewImpl::createView( WebFrame* creator, const WebURLRequest& request, const WebWindowFeatures& features, const WebString& frame_name, WebNavigationPolicy policy) { if (shared_popup_counter_->data > kMaximumNumberOfUnacknowledgedPopups) return NULL; ViewHostMsg_CreateWindow_Params params; params.opener_id = routing_id_; params.user_gesture = creator->isProcessingUserGesture(); params.window_container_type = WindowFeaturesToContainerType(features); params.session_storage_namespace_id = session_storage_namespace_id_; params.frame_name = frame_name; params.opener_frame_id = creator->identifier(); params.opener_url = creator->document().url(); params.opener_security_origin = creator->document().securityOrigin().toString().utf8(); params.opener_suppressed = creator->willSuppressOpenerInNewFrame(); params.disposition = NavigationPolicyToDisposition(policy); if (!request.isNull()) params.target_url = request.url(); int32 routing_id = MSG_ROUTING_NONE; int32 surface_id = 0; int64 cloned_session_storage_namespace_id; RenderThread::Get()->Send( new ViewHostMsg_CreateWindow(params, &routing_id, &surface_id, &cloned_session_storage_namespace_id)); if (routing_id == MSG_ROUTING_NONE) return NULL; RenderViewImpl* view = RenderViewImpl::Create( 0, routing_id_, renderer_preferences_, webkit_preferences_, shared_popup_counter_, routing_id, surface_id, cloned_session_storage_namespace_id, frame_name, 1, screen_info_, guest_); view->opened_by_user_gesture_ = params.user_gesture; view->opener_suppressed_ = params.opener_suppressed; GURL creator_url(creator->document().securityOrigin().toString().utf8()); if (!creator_url.is_valid() || !creator_url.IsStandard()) creator_url = GURL(); view->creator_url_ = creator_url; view->alternate_error_page_url_ = alternate_error_page_url_; return view->webview(); } 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: vpx_codec_err_t Decoder::DecodeFrame(const uint8_t *cxdata, size_t size) { vpx_codec_err_t res_dec; InitOnce(); REGISTER_STATE_CHECK( res_dec = vpx_codec_decode(&decoder_, cxdata, static_cast<unsigned int>(size), NULL, 0)); return res_dec; } 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: FramebufferInfoTest() : manager_(1, 1), feature_info_(new FeatureInfo()), renderbuffer_manager_(NULL, kMaxRenderbufferSize, kMaxSamples, kDepth24Supported) { texture_manager_.reset(new TextureManager(NULL, feature_info_.get(), kMaxTextureSize, kMaxCubemapSize, kUseDefaultTextures)); } CWE ID: CWE-119 Target: 1 Example 2: Code: void DelegatedFrameHost::OnBeginFrame(const viz::BeginFrameArgs& args) { if (renderer_compositor_frame_sink_) renderer_compositor_frame_sink_->OnBeginFrame(args); client_->OnBeginFrame(); } 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 ChromeMetricsServiceClient::RegisterMetricsServiceProviders() { PrefService* local_state = g_browser_process->local_state(); metrics_service_->RegisterMetricsProvider( std::make_unique<SubprocessMetricsProvider>()); #if BUILDFLAG(ENABLE_EXTENSIONS) metrics_service_->RegisterMetricsProvider( std::make_unique<ExtensionsMetricsProvider>(metrics_state_manager_)); #endif metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::NetworkMetricsProvider>( content::CreateNetworkConnectionTrackerAsyncGetter(), std::make_unique<metrics::NetworkQualityEstimatorProviderImpl>())); metrics_service_->RegisterMetricsProvider( std::make_unique<OmniboxMetricsProvider>( base::Bind(&chrome::IsIncognitoSessionActive))); metrics_service_->RegisterMetricsProvider( std::make_unique<ChromeStabilityMetricsProvider>(local_state)); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::GPUMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::ScreenInfoMetricsProvider>()); metrics_service_->RegisterMetricsProvider(CreateFileMetricsProvider( metrics_state_manager_->IsMetricsReportingEnabled())); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::DriveMetricsProvider>( chrome::FILE_LOCAL_STATE)); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::CallStackProfileMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::SamplingMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<translate::TranslateRankerMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<metrics::ComponentMetricsProvider>( g_browser_process->component_updater())); #if defined(OS_ANDROID) metrics_service_->RegisterMetricsProvider( std::make_unique<AndroidMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<PageLoadMetricsProvider>()); #endif // defined(OS_ANDROID) #if defined(OS_WIN) metrics_service_->RegisterMetricsProvider( std::make_unique<GoogleUpdateMetricsProviderWin>()); base::FilePath user_data_dir; base::FilePath crash_dir; if (!base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir) || !base::PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dir)) { user_data_dir = base::FilePath(); crash_dir = base::FilePath(); } metrics_service_->RegisterMetricsProvider( std::make_unique<browser_watcher::WatcherMetricsProviderWin>( chrome::GetBrowserExitCodesRegistryPath(), user_data_dir, crash_dir, base::Bind(&GetExecutableVersionDetails))); metrics_service_->RegisterMetricsProvider( std::make_unique<AntiVirusMetricsProvider>()); #endif // defined(OS_WIN) #if BUILDFLAG(ENABLE_PLUGINS) plugin_metrics_provider_ = new PluginMetricsProvider(local_state); metrics_service_->RegisterMetricsProvider( std::unique_ptr<metrics::MetricsProvider>(plugin_metrics_provider_)); #endif // BUILDFLAG(ENABLE_PLUGINS) #if defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( std::make_unique<ChromeOSMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<SigninStatusMetricsProviderChromeOS>()); if (metrics::GetMetricsReportingDefaultState(local_state) == metrics::EnableMetricsDefault::DEFAULT_UNKNOWN) { metrics::RecordMetricsReportingDefaultState( local_state, metrics::EnableMetricsDefault::OPT_OUT); } metrics_service_->RegisterMetricsProvider( std::make_unique<chromeos::PrinterMetricsProvider>()); #endif // defined(OS_CHROMEOS) #if !defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( SigninStatusMetricsProvider::CreateInstance( std::make_unique<ChromeSigninStatusMetricsProviderDelegate>())); #endif // !defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( std::make_unique<syncer::DeviceCountMetricsProvider>( base::Bind(&browser_sync::ChromeSyncClient::GetDeviceInfoTrackers))); metrics_service_->RegisterMetricsProvider( std::make_unique<HttpsEngagementMetricsProvider>()); metrics_service_->RegisterMetricsProvider( std::make_unique<CertificateReportingMetricsProvider>()); #if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) metrics_service_->RegisterMetricsProvider( std::make_unique<UpgradeMetricsProvider>()); #endif //! defined(OS_ANDROID) && !defined(OS_CHROMEOS) #if defined(OS_MACOSX) metrics_service_->RegisterMetricsProvider( std::make_unique<PowerMetricsProvider>()); #endif #if BUILDFLAG(ENABLE_CROS_ASSISTANT) metrics_service_->RegisterMetricsProvider( std::make_unique<AssistantServiceMetricsProvider>()); #endif // BUILDFLAG(ENABLE_CROS_ASSISTANT) } 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: int jas_seq2d_output(jas_matrix_t *matrix, FILE *out) { #define MAXLINELEN 80 int i; int j; jas_seqent_t x; char buf[MAXLINELEN + 1]; char sbuf[MAXLINELEN + 1]; int n; fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_seq2d_xstart(matrix), jas_seq2d_ystart(matrix)); fprintf(out, "%"PRIiFAST32" %"PRIiFAST32"\n", jas_matrix_numcols(matrix), jas_matrix_numrows(matrix)); buf[0] = '\0'; for (i = 0; i < jas_matrix_numrows(matrix); ++i) { for (j = 0; j < jas_matrix_numcols(matrix); ++j) { x = jas_matrix_get(matrix, i, j); sprintf(sbuf, "%s%4ld", (strlen(buf) > 0) ? " " : "", JAS_CAST(long, x)); n = JAS_CAST(int, strlen(buf)); if (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } strcat(buf, sbuf); if (j == jas_matrix_numcols(matrix) - 1) { fputs(buf, out); fputs("\n", out); buf[0] = '\0'; } } } fputs(buf, out); return 0; } CWE ID: CWE-190 Target: 1 Example 2: Code: static void qeth_check_outbound_queue(struct qeth_qdio_out_q *queue) { int index; int flush_cnt = 0; int q_was_packing = 0; /* * check if weed have to switch to non-packing mode or if * we have to get a pci flag out on the queue */ if ((atomic_read(&queue->used_buffers) <= QETH_LOW_WATERMARK_PACK) || !atomic_read(&queue->set_pci_flags_count)) { if (atomic_xchg(&queue->state, QETH_OUT_Q_LOCKED_FLUSH) == QETH_OUT_Q_UNLOCKED) { /* * If we get in here, there was no action in * do_send_packet. So, we check if there is a * packing buffer to be flushed here. */ netif_stop_queue(queue->card->dev); index = queue->next_buf_to_fill; q_was_packing = queue->do_pack; /* queue->do_pack may change */ barrier(); flush_cnt += qeth_switch_to_nonpacking_if_needed(queue); if (!flush_cnt && !atomic_read(&queue->set_pci_flags_count)) flush_cnt += qeth_flush_buffers_on_no_pci(queue); if (queue->card->options.performance_stats && q_was_packing) queue->card->perf_stats.bufs_sent_pack += flush_cnt; if (flush_cnt) qeth_flush_buffers(queue, index, flush_cnt); atomic_set(&queue->state, QETH_OUT_Q_UNLOCKED); } } } 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: png_read_start_row(png_structp png_ptr) { #ifdef PNG_READ_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif int max_pixel_depth; png_size_t row_bytes; png_debug(1, "in png_read_start_row"); png_ptr->zstream.avail_in = 0; png_init_read_transformations(png_ptr); #ifdef PNG_READ_INTERLACING_SUPPORTED if (png_ptr->interlaced) { if (!(png_ptr->transformations & PNG_INTERLACE)) png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; else png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; } else #endif /* PNG_READ_INTERLACING_SUPPORTED */ { png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = png_ptr->width; } max_pixel_depth = png_ptr->pixel_depth; #ifdef PNG_READ_PACK_SUPPORTED if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8) max_pixel_depth = 8; #endif #ifdef PNG_READ_EXPAND_SUPPORTED if (png_ptr->transformations & PNG_EXPAND) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (png_ptr->num_trans) max_pixel_depth = 32; else max_pixel_depth = 24; } else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth < 8) max_pixel_depth = 8; if (png_ptr->num_trans) max_pixel_depth *= 2; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { if (png_ptr->num_trans) { max_pixel_depth *= 4; max_pixel_depth /= 3; } } } #endif #ifdef PNG_READ_FILLER_SUPPORTED if (png_ptr->transformations & (PNG_FILLER)) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) max_pixel_depth = 32; else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth <= 8) max_pixel_depth = 16; else max_pixel_depth = 32; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { if (max_pixel_depth <= 32) max_pixel_depth = 32; else max_pixel_depth = 64; } } #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED if (png_ptr->transformations & PNG_GRAY_TO_RGB) { if ( #ifdef PNG_READ_EXPAND_SUPPORTED (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) || #endif #ifdef PNG_READ_FILLER_SUPPORTED (png_ptr->transformations & (PNG_FILLER)) || #endif png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (max_pixel_depth <= 16) max_pixel_depth = 32; else max_pixel_depth = 64; } else { if (max_pixel_depth <= 8) { if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) max_pixel_depth = 32; else max_pixel_depth = 24; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) max_pixel_depth = 64; else max_pixel_depth = 48; } } #endif #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) if (png_ptr->transformations & PNG_USER_TRANSFORM) { int user_pixel_depth = png_ptr->user_transform_depth* png_ptr->user_transform_channels; if (user_pixel_depth > max_pixel_depth) max_pixel_depth=user_pixel_depth; } #endif /* Align the width on the next larger 8 pixels. Mainly used * for interlacing */ row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7)); /* Calculate the maximum bytes needed, adding a byte and a pixel * for safety's sake */ row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) + 1 + ((max_pixel_depth + 7) >> 3); #ifdef PNG_MAX_MALLOC_64K if (row_bytes > (png_uint_32)65536L) png_error(png_ptr, "This image requires a row greater than 64KB"); #endif if (row_bytes + 64 > png_ptr->old_big_row_buf_size) { png_free(png_ptr, png_ptr->big_row_buf); if (png_ptr->interlaced) png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr, row_bytes + 64); else png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 64); png_ptr->old_big_row_buf_size = row_bytes + 64; /* Use 32 bytes of padding before and after row_buf. */ png_ptr->row_buf = png_ptr->big_row_buf + 32; png_ptr->old_big_row_buf_size = row_bytes + 64; } #ifdef PNG_MAX_MALLOC_64K if ((png_uint_32)row_bytes + 1 > (png_uint_32)65536L) png_error(png_ptr, "This image requires a row greater than 64KB"); #endif if ((png_uint_32)row_bytes > (png_uint_32)(PNG_SIZE_MAX - 1)) png_error(png_ptr, "Row has too many bytes to allocate in memory."); if (row_bytes + 1 > png_ptr->old_prev_row_size) { png_free(png_ptr, png_ptr->prev_row); png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)( row_bytes + 1)); png_memset_check(png_ptr, png_ptr->prev_row, 0, row_bytes + 1); png_ptr->old_prev_row_size = row_bytes + 1; } png_ptr->rowbytes = row_bytes; png_debug1(3, "width = %lu,", png_ptr->width); png_debug1(3, "height = %lu,", png_ptr->height); png_debug1(3, "iwidth = %lu,", png_ptr->iwidth); png_debug1(3, "num_rows = %lu,", png_ptr->num_rows); png_debug1(3, "rowbytes = %lu,", png_ptr->rowbytes); png_debug1(3, "irowbytes = %lu", PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1); png_ptr->flags |= PNG_FLAG_ROW_INIT; } 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: qedi_dbg_notice(struct qedi_dbg_ctx *qedi, const char *func, u32 line, const char *fmt, ...) { va_list va; struct va_format vaf; char nfunc[32]; memset(nfunc, 0, sizeof(nfunc)); memcpy(nfunc, func, sizeof(nfunc) - 1); va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & QEDI_LOG_NOTICE)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_notice("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev), nfunc, line, qedi->host_no, &vaf); else pr_notice("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf); ret: va_end(va); } CWE ID: CWE-125 Target: 1 Example 2: Code: void SynchronizeVisualPropertiesMessageFilter::OnUpdatedFrameSinkIdOnUI() { frame_sink_id_run_loop_.Quit(); } 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 ThreadableBlobRegistry::unregisterBlobURL(const KURL& url) { if (BlobURL::getOrigin(url) == "null") originMap()->remove(url.string()); if (isMainThread()) blobRegistry().unregisterBlobURL(url); else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url)); callOnMainThread(&unregisterBlobURLTask, context.leakPtr()); } } 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 nsc_rle_decompress_data(NSC_CONTEXT* context) { UINT16 i; BYTE* rle; UINT32 planeSize; UINT32 originalSize; rle = context->Planes; for (i = 0; i < 4; i++) { originalSize = context->OrgByteCount[i]; planeSize = context->PlaneByteCount[i]; if (planeSize == 0) FillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF); else if (planeSize < originalSize) nsc_rle_decode(rle, context->priv->PlaneBuffers[i], originalSize); else CopyMemory(context->priv->PlaneBuffers[i], rle, originalSize); rle += planeSize; } } CWE ID: CWE-787 Target: 1 Example 2: Code: ScopedTextureBinder::~ScopedTextureBinder() { ScopedGLErrorSuppressor suppressor( "ScopedTextureBinder::dtor", state_->GetErrorState()); RestoreCurrentTextureBindings(state_, target_, 0); state_->RestoreActiveTexture(); } 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: xmlReadFile(const char *filename, const char *encoding, int options) { xmlParserCtxtPtr ctxt; xmlInitParser(); ctxt = xmlCreateURLParserCtxt(filename, options); if (ctxt == NULL) return (NULL); return (xmlDoRead(ctxt, NULL, encoding, options, 0)); } CWE ID: CWE-611 Output:
0
Here are some example code snippets. Analyze the following 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 a2dp_command(struct a2dp_stream_common *common, char cmd) { char ack; DEBUG("A2DP COMMAND %s", dump_a2dp_ctrl_event(cmd)); /* send command */ if (send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL) == -1) { ERROR("cmd failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } /* wait for ack byte */ if (a2dp_ctrl_receive(common, &ack, 1) < 0) return -1; DEBUG("A2DP COMMAND %s DONE STATUS %d", dump_a2dp_ctrl_event(cmd), ack); if (ack == A2DP_CTRL_ACK_INCALL_FAILURE) return ack; if (ack != A2DP_CTRL_ACK_SUCCESS) return -1; return 0; } CWE ID: CWE-284 Target: 1 Example 2: Code: uint32_t GetCompressedFormatDepthPitch(const CompressedFormatInfo& info, uint32_t width, uint32_t height) { uint32_t num_blocks_high = (height + info.block_size - 1) / info.block_size; return num_blocks_high * GetCompressedFormatRowPitch(info, width); } 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 v8::Handle<v8::Value> supplementalMethod4Callback(const v8::Arguments& args) { INC_STATS("DOM.TestInterface.supplementalMethod4"); TestSupplemental::supplementalMethod4(); return v8::Handle<v8::Value>(); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void coroutine_fn v9fs_wstat(void *opaque) { int32_t fid; int err = 0; int16_t unused; V9fsStat v9stat; size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsPDU *pdu = opaque; v9fs_stat_init(&v9stat); err = pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat); goto out_nofid; } CWE ID: CWE-362 Target: 1 Example 2: Code: void rtmsg_ifinfo(int type, struct net_device *dev, unsigned int change) { struct net *net = dev_net(dev); struct sk_buff *skb; int err = -ENOBUFS; size_t if_info_size; skb = nlmsg_new((if_info_size = if_nlmsg_size(dev, 0)), GFP_KERNEL); if (skb == NULL) goto errout; err = rtnl_fill_ifinfo(skb, dev, type, 0, 0, change, 0, 0); if (err < 0) { /* -EMSGSIZE implies BUG in if_nlmsg_size() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, GFP_KERNEL); return; errout: if (err < 0) rtnl_set_sk_err(net, RTNLGRP_LINK, err); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void NavigationControllerImpl::CancelPendingReload() { DCHECK(pending_reload_ != ReloadType::NONE); pending_reload_ = ReloadType::NONE; } CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn, struct xfrm_replay_state_esn **preplay_esn, struct nlattr *rta) { struct xfrm_replay_state_esn *p, *pp, *up; if (!rta) return 0; up = nla_data(rta); p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!p) return -ENOMEM; pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!pp) { kfree(p); return -ENOMEM; } *replay_esn = p; *preplay_esn = pp; return 0; } CWE ID: CWE-200 Target: 1 Example 2: Code: void hns_rcb_set_tx_ring_bs(struct hnae_queue *q, u32 buf_size) { u32 bd_size_type = hns_rcb_buf_size2type(buf_size); dsaf_write_dev(q, RCB_RING_TX_RING_BD_LEN_REG, bd_size_type); } 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: explicit HeaderTestDispatcherHostDelegate(const GURL& watch_url) : watch_url_(watch_url) {} 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: ft_bitmap_assure_buffer( FT_Memory memory, FT_Bitmap* bitmap, FT_UInt xpixels, FT_UInt ypixels ) { FT_Error error; int pitch; int new_pitch; FT_UInt bpp; FT_Int i, width, height; unsigned char* buffer = NULL; width = bitmap->width; height = bitmap->rows; pitch = bitmap->pitch; if ( pitch < 0 ) pitch = -pitch; switch ( bitmap->pixel_mode ) { case FT_PIXEL_MODE_MONO: bpp = 1; new_pitch = ( width + xpixels + 7 ) >> 3; break; case FT_PIXEL_MODE_GRAY2: bpp = 2; new_pitch = ( width + xpixels + 3 ) >> 2; break; case FT_PIXEL_MODE_GRAY4: bpp = 4; new_pitch = ( width + xpixels + 1 ) >> 1; break; case FT_PIXEL_MODE_GRAY: case FT_PIXEL_MODE_LCD: case FT_PIXEL_MODE_LCD_V: bpp = 8; new_pitch = ( width + xpixels ); break; default: return FT_THROW( Invalid_Glyph_Format ); } /* if no need to allocate memory */ if ( ypixels == 0 && new_pitch <= pitch ) { /* zero the padding */ FT_Int bit_width = pitch * 8; FT_Int bit_last = ( width + xpixels ) * bpp; if ( bit_last < bit_width ) { FT_Byte* line = bitmap->buffer + ( bit_last >> 3 ); FT_Byte* end = bitmap->buffer + pitch; FT_Int shift = bit_last & 7; FT_UInt mask = 0xFF00U >> shift; FT_Int count = height; for ( ; count > 0; count--, line += pitch, end += pitch ) { FT_Byte* write = line; if ( shift > 0 ) { write[0] = (FT_Byte)( write[0] & mask ); write++; } if ( write < end ) FT_MEM_ZERO( write, end - write ); } } return FT_Err_Ok; } /* otherwise allocate new buffer */ if ( FT_QALLOC_MULT( buffer, new_pitch, bitmap->rows + ypixels ) ) return error; /* new rows get added at the top of the bitmap, */ /* thus take care of the flow direction */ if ( bitmap->pitch > 0 ) { FT_Int len = ( width * bpp + 7 ) >> 3; for ( i = 0; i < bitmap->rows; i++ ) FT_MEM_COPY( buffer + new_pitch * ( ypixels + i ), bitmap->buffer + pitch * i, len ); } else { FT_Int len = ( width * bpp + 7 ) >> 3; for ( i = 0; i < bitmap->rows; i++ ) FT_MEM_COPY( buffer + new_pitch * i, bitmap->buffer + pitch * i, len ); } FT_FREE( bitmap->buffer ); bitmap->buffer = buffer; if ( bitmap->pitch < 0 ) new_pitch = -new_pitch; /* set pitch only, width and height are left untouched */ bitmap->pitch = new_pitch; return FT_Err_Ok; } CWE ID: CWE-119 Target: 1 Example 2: Code: void OMXNodeInstance::freeActiveBuffers() { for (size_t i = mActiveBuffers.size(); i > 0;) { i--; freeBuffer(mActiveBuffers[i].mPortIndex, mActiveBuffers[i].mID); } } 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: asn1_der_decoding_startEnd (asn1_node element, const void *ider, int ider_len, const char *name_element, int *start, int *end) { asn1_node node, node_to_find; int result = ASN1_DER_ERROR; node = element; if (node == NULL) return ASN1_ELEMENT_NOT_FOUND; node_to_find = asn1_find_node (node, name_element); if (node_to_find == NULL) return ASN1_ELEMENT_NOT_FOUND; *start = node_to_find->start; *end = node_to_find->end; if (*start == 0 && *end == 0) { if (ider == NULL || ider_len == 0) return ASN1_GENERIC_ERROR; /* it seems asn1_der_decoding() wasn't called before. Do it now */ result = asn1_der_decoding (&node, ider, ider_len, NULL); if (result != ASN1_SUCCESS) { warn(); return result; } node_to_find = asn1_find_node (node, name_element); if (node_to_find == NULL) return ASN1_ELEMENT_NOT_FOUND; *start = node_to_find->start; *end = node_to_find->end; } if (*end < *start) return ASN1_GENERIC_ERROR; return ASN1_SUCCESS; } 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: v8::MaybeLocal<v8::Array> V8Debugger::internalProperties(v8::Local<v8::Context> context, v8::Local<v8::Value> value) { v8::Local<v8::Array> properties; if (!v8::Debug::GetInternalProperties(m_isolate, value).ToLocal(&properties)) return v8::MaybeLocal<v8::Array>(); if (value->IsFunction()) { v8::Local<v8::Function> function = value.As<v8::Function>(); v8::Local<v8::Value> location = functionLocation(context, function); if (location->IsObject()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[FunctionLocation]]")); properties->Set(properties->Length(), location); } if (function->IsGeneratorFunction()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[IsGenerator]]")); properties->Set(properties->Length(), v8::True(m_isolate)); } } if (!enabled()) return properties; if (value->IsMap() || value->IsWeakMap() || value->IsSet() || value->IsWeakSet() || value->IsSetIterator() || value->IsMapIterator()) { v8::Local<v8::Value> entries = collectionEntries(context, v8::Local<v8::Object>::Cast(value)); if (entries->IsArray()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Entries]]")); properties->Set(properties->Length(), entries); } } if (value->IsGeneratorObject()) { v8::Local<v8::Value> location = generatorObjectLocation(v8::Local<v8::Object>::Cast(value)); if (location->IsObject()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[GeneratorLocation]]")); properties->Set(properties->Length(), location); } } if (value->IsFunction()) { v8::Local<v8::Function> function = value.As<v8::Function>(); v8::Local<v8::Value> boundFunction = function->GetBoundFunction(); v8::Local<v8::Value> scopes; if (boundFunction->IsUndefined() && functionScopes(function).ToLocal(&scopes)) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Scopes]]")); properties->Set(properties->Length(), scopes); } } return properties; } CWE ID: CWE-79 Target: 1 Example 2: Code: void Pack<WebGLImageConversion::kDataFormatRG32F, WebGLImageConversion::kAlphaDoNothing, float, float>(const float* source, float* destination, unsigned pixels_per_row) { for (unsigned i = 0; i < pixels_per_row; ++i) { destination[0] = source[0]; destination[1] = source[1]; source += 4; destination += 2; } } 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 BackTexture::Copy() { DCHECK_NE(id(), 0u); ScopedGLErrorSuppressor suppressor("BackTexture::Copy", decoder_->error_state_.get()); ScopedTextureBinder binder(&decoder_->state_, decoder_->error_state_.get(), id(), Target()); api()->glCopyTexSubImage2DFn(Target(), 0, // level 0, 0, 0, 0, size_.width(), size_.height()); } 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: transform_info_imp(transform_display *dp, png_structp pp, png_infop pi) { /* Reuse the standard stuff as appropriate. */ standard_info_part1(&dp->this, pp, pi); /* Now set the list of transforms. */ dp->transform_list->set(dp->transform_list, dp, pp, pi); /* Update the info structure for these transforms: */ { int i = dp->this.use_update_info; /* Always do one call, even if use_update_info is 0. */ do png_read_update_info(pp, pi); while (--i > 0); } /* And get the output information into the standard_display */ standard_info_part2(&dp->this, pp, pi, 1/*images*/); /* Plus the extra stuff we need for the transform tests: */ dp->output_colour_type = png_get_color_type(pp, pi); dp->output_bit_depth = png_get_bit_depth(pp, pi); /* Validate the combination of colour type and bit depth that we are getting * out of libpng; the semantics of something not in the PNG spec are, at * best, unclear. */ switch (dp->output_colour_type) { case PNG_COLOR_TYPE_PALETTE: if (dp->output_bit_depth > 8) goto error; /*FALL THROUGH*/ case PNG_COLOR_TYPE_GRAY: if (dp->output_bit_depth == 1 || dp->output_bit_depth == 2 || dp->output_bit_depth == 4) break; /*FALL THROUGH*/ default: if (dp->output_bit_depth == 8 || dp->output_bit_depth == 16) break; /*FALL THROUGH*/ error: { char message[128]; size_t pos; pos = safecat(message, sizeof message, 0, "invalid final bit depth: colour type("); pos = safecatn(message, sizeof message, pos, dp->output_colour_type); pos = safecat(message, sizeof message, pos, ") with bit depth: "); pos = safecatn(message, sizeof message, pos, dp->output_bit_depth); png_error(pp, message); } } /* Use a test pixel to check that the output agrees with what we expect - * this avoids running the whole test if the output is unexpected. */ { image_pixel test_pixel; memset(&test_pixel, 0, sizeof test_pixel); test_pixel.colour_type = dp->this.colour_type; /* input */ test_pixel.bit_depth = dp->this.bit_depth; if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE) test_pixel.sample_depth = 8; else test_pixel.sample_depth = test_pixel.bit_depth; /* Don't need sBIT here, but it must be set to non-zero to avoid * arithmetic overflows. */ test_pixel.have_tRNS = dp->this.is_transparent; test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT = test_pixel.alpha_sBIT = test_pixel.sample_depth; dp->transform_list->mod(dp->transform_list, &test_pixel, pp, dp); if (test_pixel.colour_type != dp->output_colour_type) { char message[128]; size_t pos = safecat(message, sizeof message, 0, "colour type "); pos = safecatn(message, sizeof message, pos, dp->output_colour_type); pos = safecat(message, sizeof message, pos, " expected "); pos = safecatn(message, sizeof message, pos, test_pixel.colour_type); png_error(pp, message); } if (test_pixel.bit_depth != dp->output_bit_depth) { char message[128]; size_t pos = safecat(message, sizeof message, 0, "bit depth "); pos = safecatn(message, sizeof message, pos, dp->output_bit_depth); pos = safecat(message, sizeof message, pos, " expected "); pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth); png_error(pp, message); } /* If both bit depth and colour type are correct check the sample depth. * I believe these are both internal errors. */ if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE) { if (test_pixel.sample_depth != 8) /* oops - internal error! */ png_error(pp, "pngvalid: internal: palette sample depth not 8"); } else if (test_pixel.sample_depth != dp->output_bit_depth) { char message[128]; size_t pos = safecat(message, sizeof message, 0, "internal: sample depth "); pos = safecatn(message, sizeof message, pos, dp->output_bit_depth); pos = safecat(message, sizeof message, pos, " expected "); pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth); png_error(pp, message); } } } CWE ID: Target: 1 Example 2: Code: MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict q; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y, pixel,exception)); q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); return(CopyPixel(image,q,pixel)); } 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: parse_interface_number(const char *device) { long devnum; char *end; devnum = strtol(device, &end, 10); if (device != end && *end == '\0') { /* * It's all-numeric, but is it a valid number? */ if (devnum <= 0) { /* * No, it's not an ordinal. */ error("Invalid adapter index"); } return (devnum); } else { /* * It's not all-numeric; return -1, so our caller * knows that. */ return (-1); } } CWE ID: CWE-120 Output:
0
Here are some example code snippets. Analyze the following 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 xen_netbk_get_extras(struct xenvif *vif, struct xen_netif_extra_info *extras, int work_to_do) { struct xen_netif_extra_info extra; RING_IDX cons = vif->tx.req_cons; do { if (unlikely(work_to_do-- <= 0)) { netdev_dbg(vif->dev, "Missing extra info\n"); return -EBADR; } memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons), sizeof(extra)); if (unlikely(!extra.type || extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) { vif->tx.req_cons = ++cons; netdev_dbg(vif->dev, "Invalid extra type: %d\n", extra.type); return -EINVAL; } memcpy(&extras[extra.type - 1], &extra, sizeof(extra)); vif->tx.req_cons = ++cons; } while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE); return work_to_do; } CWE ID: CWE-20 Target: 1 Example 2: Code: void onLoadingChanged(QWebLoadRequest* loadRequest) { if (loadRequest->status() == QQuickWebView::LoadStartedStatus) { QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection); QCOMPARE(m_webView->loading(), 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: static unsigned int stack_maxrandom_size(void) { unsigned int max = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { max = ((-1U) & STACK_RND_MASK) << PAGE_SHIFT; } return max; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderFlexibleBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { RenderBlock::styleDidChange(diff, oldStyle); if (oldStyle && oldStyle->alignItems() == ItemPositionStretch && diff == StyleDifferenceLayout) { for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) { ItemPosition previousAlignment = resolveAlignment(oldStyle, child->style()); if (previousAlignment == ItemPositionStretch && previousAlignment != resolveAlignment(style(), child->style())) child->setChildNeedsLayout(MarkOnlyThis); } } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void remote_socket_shutdown(asocket* s) { D("entered remote_socket_shutdown RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd, s->peer ? s->peer->fd : -1); apacket* p = get_apacket(); p->msg.command = A_CLSE; if (s->peer) { p->msg.arg0 = s->peer->id; } p->msg.arg1 = s->id; send_packet(p, s->transport); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter) { double width_d; double scale_f_d = 1.0; const double filter_width_d = DEFAULT_BOX_RADIUS; int windows_size; unsigned int u; LineContribType *res; if (scale_d < 1.0) { width_d = filter_width_d / scale_d; scale_f_d = scale_d; } else { width_d= filter_width_d; } windows_size = 2 * (int)ceil(width_d) + 1; res = _gdContributionsAlloc(line_size, windows_size); for (u = 0; u < line_size; u++) { const double dCenter = (double)u / scale_d; /* get the significant edge points affecting the pixel */ register int iLeft = MAX(0, (int)floor (dCenter - width_d)); int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1); double dTotalWeight = 0.0; int iSrc; res->ContribRow[u].Left = iLeft; res->ContribRow[u].Right = iRight; /* Cut edge points to fit in filter window in case of spill-off */ if (iRight - iLeft + 1 > windows_size) { if (iLeft < ((int)src_size - 1 / 2)) { iLeft++; } else { iRight--; } } for (iSrc = iLeft; iSrc <= iRight; iSrc++) { dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc))); } if (dTotalWeight < 0.0) { _gdContributionsFree(res); return NULL; } if (dTotalWeight > 0.0) { for (iSrc = iLeft; iSrc <= iRight; iSrc++) { res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight; } } } return res; } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb) { struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH]; int i; if (xp->xfrm_nr == 0) return 0; for (i = 0; i < xp->xfrm_nr; i++) { struct xfrm_user_tmpl *up = &vec[i]; struct xfrm_tmpl *kp = &xp->xfrm_vec[i]; memcpy(&up->id, &kp->id, sizeof(up->id)); up->family = kp->encap_family; memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr)); up->reqid = kp->reqid; up->mode = kp->mode; up->share = kp->share; up->optional = kp->optional; up->aalgos = kp->aalgos; up->ealgos = kp->ealgos; up->calgos = kp->calgos; } return nla_put(skb, XFRMA_TMPL, sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec); } CWE ID: CWE-200 Target: 1 Example 2: Code: void ID3::Iterator::findFrame() { for (;;) { mFrameData = NULL; mFrameSize = 0; if (mParent.mVersion == ID3_V2_2) { if (mOffset + 6 > mParent.mSize) { return; } if (!memcmp(&mParent.mData[mOffset], "\0\0\0", 3)) { return; } mFrameSize = (mParent.mData[mOffset + 3] << 16) | (mParent.mData[mOffset + 4] << 8) | mParent.mData[mOffset + 5]; if (mFrameSize == 0) { return; } mFrameSize += 6; // add tag id and size field if (SIZE_MAX - mOffset <= mFrameSize) { return; } if (mOffset + mFrameSize > mParent.mSize) { ALOGV("partial frame at offset %zu (size = %zu, bytes-remaining = %zu)", mOffset, mFrameSize, mParent.mSize - mOffset - (size_t)6); return; } mFrameData = &mParent.mData[mOffset + 6]; if (!mID) { break; } char id[4]; memcpy(id, &mParent.mData[mOffset], 3); id[3] = '\0'; if (!strcmp(id, mID)) { break; } } else if (mParent.mVersion == ID3_V2_3 || mParent.mVersion == ID3_V2_4) { if (mOffset + 10 > mParent.mSize) { return; } if (!memcmp(&mParent.mData[mOffset], "\0\0\0\0", 4)) { return; } size_t baseSize = 0; if (mParent.mVersion == ID3_V2_4) { if (!ParseSyncsafeInteger( &mParent.mData[mOffset + 4], &baseSize)) { return; } } else { baseSize = U32_AT(&mParent.mData[mOffset + 4]); } if (baseSize == 0) { return; } if (SIZE_MAX - 10 <= baseSize) { return; } mFrameSize = 10 + baseSize; // add tag id, size field and flags if (SIZE_MAX - mOffset <= mFrameSize) { return; } if (mOffset + mFrameSize > mParent.mSize) { ALOGV("partial frame at offset %zu (size = %zu, bytes-remaining = %zu)", mOffset, mFrameSize, mParent.mSize - mOffset - (size_t)10); return; } uint16_t flags = U16_AT(&mParent.mData[mOffset + 8]); if ((mParent.mVersion == ID3_V2_4 && (flags & 0x000c)) || (mParent.mVersion == ID3_V2_3 && (flags & 0x00c0))) { ALOGV("Skipping unsupported frame (compression, encryption " "or per-frame unsynchronization flagged"); mOffset += mFrameSize; continue; } mFrameData = &mParent.mData[mOffset + 10]; if (!mID) { break; } char id[5]; memcpy(id, &mParent.mData[mOffset], 4); id[4] = '\0'; if (!strcmp(id, mID)) { break; } } else { CHECK(mParent.mVersion == ID3_V1 || mParent.mVersion == ID3_V1_1); if (mOffset >= mParent.mSize) { return; } mFrameData = &mParent.mData[mOffset]; switch (mOffset) { case 3: case 33: case 63: mFrameSize = 30; break; case 93: mFrameSize = 4; break; case 97: if (mParent.mVersion == ID3_V1) { mFrameSize = 30; } else { mFrameSize = 29; } break; case 126: mFrameSize = 1; break; case 127: mFrameSize = 1; break; default: CHECK(!"Should not be here, invalid offset."); break; } if (!mID) { break; } String8 id; getID(&id); if (id == mID) { break; } } mOffset += mFrameSize; } } 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: evdns_server_request_get_requesting_addr(struct evdns_server_request *req_, struct sockaddr *sa, int addr_len) { struct server_request *req = TO_SERVER_REQUEST(req_); if (addr_len < (int)req->addrlen) return -1; memcpy(sa, &(req->addr), req->addrlen); return req->addrlen; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FragmentPaintPropertyTreeBuilder::UpdatePerspective() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsPerspective(object_)) { const ComputedStyle& style = object_.StyleRef(); TransformPaintPropertyNode::State state; state.matrix.ApplyPerspective(style.Perspective()); state.origin = PerspectiveOrigin(ToLayoutBox(object_)) + ToLayoutSize(context_.current.paint_offset); state.flattens_inherited_transform = context_.current.should_flatten_inherited_transform; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) state.rendering_context_id = context_.current.rendering_context_id; OnUpdate(properties_->UpdatePerspective(context_.current.transform, std::move(state))); } else { OnClear(properties_->ClearPerspective()); } } if (properties_->Perspective()) { context_.current.transform = properties_->Perspective(); context_.current.should_flatten_inherited_transform = false; } } CWE ID: Target: 1 Example 2: Code: int ConvertMockKeyboardModifier(MockKeyboard::Modifiers modifiers) { static struct ModifierMap { MockKeyboard::Modifiers src; int dst; } kModifierMap[] = { { MockKeyboard::LEFT_SHIFT, ui::EF_SHIFT_DOWN }, { MockKeyboard::RIGHT_SHIFT, ui::EF_SHIFT_DOWN }, { MockKeyboard::LEFT_CONTROL, ui::EF_CONTROL_DOWN }, { MockKeyboard::RIGHT_CONTROL, ui::EF_CONTROL_DOWN }, { MockKeyboard::LEFT_ALT, ui::EF_ALT_DOWN }, { MockKeyboard::RIGHT_ALT, ui::EF_ALT_DOWN }, }; int flags = 0; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kModifierMap); ++i) { if (kModifierMap[i].src & modifiers) { flags |= kModifierMap[i].dst; } } return flags; } 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: status_t OMXNodeInstance::allocateBufferWithBackup( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid; BufferMeta *buffer_meta = new BufferMeta( params, portIndex, (portIndex == kPortIndexInput) && copy /* copyToOmx */, (portIndex == kPortIndexOutput) && copy /* copyFromOmx */, NULL /* data */); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); memset(header->pBuffer, 0, header->nAllocLen); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; } 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 CtcpHandler::parse(Message::Type messageType, const QString &prefix, const QString &target, const QByteArray &message) { QByteArray ctcp; QByteArray dequotedMessage = lowLevelDequote(message); CtcpType ctcptype = messageType == Message::Notice ? CtcpReply : CtcpQuery; Message::Flags flags = (messageType == Message::Notice && !network()->isChannelName(target)) ? Message::Redirected : Message::None; int xdelimPos = -1; int xdelimEndPos = -1; int spacePos = -1; while((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) { if(xdelimPos > 0) displayMsg(messageType, target, userDecode(target, dequotedMessage.left(xdelimPos)), prefix, flags); xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1); if(xdelimEndPos == -1) { xdelimEndPos = dequotedMessage.count(); } ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1)); dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1); QString ctcpcmd = userDecode(target, ctcp.left(spacePos)); QString ctcpparam = userDecode(target, ctcp.mid(spacePos + 1)); spacePos = ctcp.indexOf(' '); if(spacePos != -1) { ctcpcmd = userDecode(target, ctcp.left(spacePos)); ctcpparam = userDecode(target, ctcp.mid(spacePos + 1)); } else { ctcpcmd = userDecode(target, ctcp); ctcpparam = QString(); ctcpparam = QString(); } handle(ctcpcmd, Q_ARG(CtcpType, ctcptype), Q_ARG(QString, prefix), Q_ARG(QString, target), Q_ARG(QString, ctcpparam)); } if(!dequotedMessage.isEmpty()) void CtcpHandler::query(const QString &bufname, const QString &ctcpTag, const QString &message) { QList<QByteArray> params; params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message))); emit putCmd("PRIVMSG", params); } void CtcpHandler::reply(const QString &bufname, const QString &ctcpTag, const QString &message) { QList<QByteArray> params; params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message))); emit putCmd("NOTICE", params); } void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(ctcptype) emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix); } emit putCmd("NOTICE", params); } CWE ID: CWE-399 Target: 1 Example 2: Code: static int pf_atapi(struct pf_unit *pf, char *cmd, int dlen, char *buf, char *fun) { int r; r = pf_command(pf, cmd, dlen, fun); mdelay(1); if (!r) r = pf_completion(pf, buf, fun); if (r) pf_req_sense(pf, !fun); return r; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int snd_seq_ioctl_query_next_client(struct snd_seq_client *client, void __user *arg) { struct snd_seq_client *cptr = NULL; struct snd_seq_client_info info; if (copy_from_user(&info, arg, sizeof(info))) return -EFAULT; /* search for next client */ info.client++; if (info.client < 0) info.client = 0; for (; info.client < SNDRV_SEQ_MAX_CLIENTS; info.client++) { cptr = snd_seq_client_use_ptr(info.client); if (cptr) break; /* found */ } if (cptr == NULL) return -ENOENT; get_client_info(cptr, &info); snd_seq_client_unlock(cptr); if (copy_to_user(arg, &info, sizeof(info))) return -EFAULT; return 0; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WorkerProcessLauncher::Core::StopWorker() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); if (launch_success_timer_->IsRunning()) { launch_success_timer_->Stop(); launch_backoff_.InformOfRequest(false); } self_ = this; ipc_enabled_ = false; if (process_watcher_.GetWatchedObject() != NULL) { launcher_delegate_->KillProcess(CONTROL_C_EXIT); return; } DCHECK(process_watcher_.GetWatchedObject() == NULL); ipc_error_timer_->Stop(); process_exit_event_.Close(); if (stopping_) { ipc_error_timer_.reset(); launch_timer_.reset(); self_ = NULL; return; } self_ = NULL; DWORD exit_code = launcher_delegate_->GetExitCode(); if (kMinPermanentErrorExitCode <= exit_code && exit_code <= kMaxPermanentErrorExitCode) { worker_delegate_->OnPermanentError(); return; } launch_timer_->Start(FROM_HERE, launch_backoff_.GetTimeUntilRelease(), this, &Core::LaunchWorker); } CWE ID: CWE-399 Target: 1 Example 2: Code: compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out) { u_char buf[4096]; int r, status; if (ssh->state->compression_out_started != 1) return SSH_ERR_INTERNAL_ERROR; /* This case is not handled below. */ if (sshbuf_len(in) == 0) return 0; /* Input is the contents of the input buffer. */ if ((ssh->state->compression_out_stream.next_in = sshbuf_mutable_ptr(in)) == NULL) return SSH_ERR_INTERNAL_ERROR; ssh->state->compression_out_stream.avail_in = sshbuf_len(in); /* Loop compressing until deflate() returns with avail_out != 0. */ do { /* Set up fixed-size output buffer. */ ssh->state->compression_out_stream.next_out = buf; ssh->state->compression_out_stream.avail_out = sizeof(buf); /* Compress as much data into the buffer as possible. */ status = deflate(&ssh->state->compression_out_stream, Z_PARTIAL_FLUSH); switch (status) { case Z_MEM_ERROR: return SSH_ERR_ALLOC_FAIL; case Z_OK: /* Append compressed data to output_buffer. */ if ((r = sshbuf_put(out, buf, sizeof(buf) - ssh->state->compression_out_stream.avail_out)) != 0) return r; break; case Z_STREAM_ERROR: default: ssh->state->compression_out_failures++; return SSH_ERR_INVALID_FORMAT; } } while (ssh->state->compression_out_stream.avail_out == 0); return 0; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FakeCrosDisksClient::Mount(const std::string& source_path, const std::string& source_format, const std::string& mount_label, const std::vector<std::string>& mount_options, MountAccessMode access_mode, RemountOption remount, VoidDBusMethodCallback callback) { MountType type = source_format.empty() ? MOUNT_TYPE_DEVICE : MOUNT_TYPE_ARCHIVE; if (GURL(source_path).is_valid()) type = MOUNT_TYPE_NETWORK_STORAGE; base::FilePath mounted_path; switch (type) { case MOUNT_TYPE_ARCHIVE: mounted_path = GetArchiveMountPoint().Append( base::FilePath::FromUTF8Unsafe(mount_label)); break; case MOUNT_TYPE_DEVICE: mounted_path = GetRemovableDiskMountPoint().Append( base::FilePath::FromUTF8Unsafe(mount_label)); break; case MOUNT_TYPE_NETWORK_STORAGE: if (custom_mount_point_callback_) { mounted_path = custom_mount_point_callback_.Run(source_path, mount_options); } break; case MOUNT_TYPE_INVALID: NOTREACHED(); return; } mounted_paths_.insert(mounted_path); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&PerformFakeMount, source_path, mounted_path), base::BindOnce(&FakeCrosDisksClient::DidMount, weak_ptr_factory_.GetWeakPtr(), source_path, type, mounted_path, std::move(callback))); } 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: CompositedLayerRasterInvalidator::ChunkPropertiesChanged( const RefCountedPropertyTreeState& new_chunk_state, const PaintChunkInfo& new_chunk, const PaintChunkInfo& old_chunk, const PropertyTreeState& layer_state) const { if (!ApproximatelyEqual(new_chunk.chunk_to_layer_transform, old_chunk.chunk_to_layer_transform)) return PaintInvalidationReason::kPaintProperty; if (new_chunk_state.Effect() != old_chunk.effect_state || new_chunk_state.Effect()->Changed(*layer_state.Effect())) return PaintInvalidationReason::kPaintProperty; if (new_chunk.chunk_to_layer_clip.IsTight() && old_chunk.chunk_to_layer_clip.IsTight()) { if (new_chunk.chunk_to_layer_clip == old_chunk.chunk_to_layer_clip) return PaintInvalidationReason::kNone; if (ClipByLayerBounds(new_chunk.chunk_to_layer_clip.Rect()) == ClipByLayerBounds(old_chunk.chunk_to_layer_clip.Rect())) return PaintInvalidationReason::kNone; return PaintInvalidationReason::kIncremental; } if (new_chunk_state.Clip() != old_chunk.clip_state || new_chunk_state.Clip()->Changed(*layer_state.Clip())) return PaintInvalidationReason::kPaintProperty; return PaintInvalidationReason::kNone; } CWE ID: Target: 1 Example 2: Code: compat_find_calc_match(struct xt_entry_match *m, const struct ip6t_ip6 *ipv6, int *size) { struct xt_match *match; match = xt_request_find_match(NFPROTO_IPV6, m->u.user.name, m->u.user.revision); if (IS_ERR(match)) return PTR_ERR(match); m->u.kernel.match = match; *size += xt_compat_match_offset(match); return 0; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct wif *net_open(char *iface) { struct wif *wi; struct priv_net *pn; int s; /* setup wi struct */ wi = wi_alloc(sizeof(*pn)); if (!wi) return NULL; wi->wi_read = net_read; wi->wi_write = net_write; wi->wi_set_channel = net_set_channel; wi->wi_get_channel = net_get_channel; wi->wi_set_rate = net_set_rate; wi->wi_get_rate = net_get_rate; wi->wi_close = net_close; wi->wi_fd = net_fd; wi->wi_get_mac = net_get_mac; wi->wi_get_monitor = net_get_monitor; /* setup iface */ s = do_net_open(iface); if (s == -1) { do_net_free(wi); return NULL; } /* setup private state */ pn = wi_priv(wi); pn->pn_s = s; pn->pn_queue.q_next = pn->pn_queue.q_prev = &pn->pn_queue; pn->pn_queue_free.q_next = pn->pn_queue_free.q_prev = &pn->pn_queue_free; return wi; } 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: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): JBIG2Segment(segNumA) { w = bitmap->w; h = bitmap->h; line = bitmap->line; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmalloc(h * line + 1); memcpy(data, bitmap->data, h * line); data[h * line] = 0; } CWE ID: CWE-189 Target: 1 Example 2: Code: mrb_module_get(mrb_state *mrb, const char *name) { return mrb_module_get_under(mrb, mrb->object_class, name); } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static MagickBooleanType load_level(Image *image,XCFDocInfo *inDocInfo, XCFLayerInfo *inLayerInfo) { ExceptionInfo *exception; int destLeft = 0, destTop = 0; Image* tile_image; MagickBooleanType status; MagickOffsetType saved_pos, offset, offset2; register ssize_t i; size_t width, height, ntiles, ntile_rows, ntile_cols, tile_image_width, tile_image_height; /* start reading the data */ exception=inDocInfo->exception; width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); /* Read in the first tile offset. If it is '0', then this tile level is empty and we can simply return. */ offset=(MagickOffsetType) ReadBlobMSBLong(image); if (offset == 0) return(MagickTrue); /* Initialize the reference for the in-memory tile-compression. */ ntile_rows=(height+TILE_HEIGHT-1)/TILE_HEIGHT; ntile_cols=(width+TILE_WIDTH-1)/TILE_WIDTH; ntiles=ntile_rows*ntile_cols; for (i = 0; i < (ssize_t) ntiles; i++) { status=MagickFalse; if (offset == 0) ThrowBinaryException(CorruptImageError,"NotEnoughTiles",image->filename); /* save the current position as it is where the * next tile offset is stored. */ saved_pos=TellBlob(image); /* read in the offset of the next tile so we can calculate the amount of data needed for this tile*/ offset2=(MagickOffsetType)ReadBlobMSBLong(image); /* if the offset is 0 then we need to read in the maximum possible allowing for negative compression */ if (offset2 == 0) offset2=(MagickOffsetType) (offset + TILE_WIDTH * TILE_WIDTH * 4* 1.5); /* seek to the tile offset */ if (SeekBlob(image, offset, SEEK_SET) != offset) ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile", image->filename); /* allocate the image for the tile NOTE: the last tile in a row or column may not be a full tile! */ tile_image_width=(size_t) (destLeft == (int) ntile_cols-1 ? (int) width % TILE_WIDTH : TILE_WIDTH); if (tile_image_width == 0) tile_image_width=TILE_WIDTH; tile_image_height = (size_t) (destTop == (int) ntile_rows-1 ? (int) height % TILE_HEIGHT : TILE_HEIGHT); if (tile_image_height == 0) tile_image_height=TILE_HEIGHT; tile_image=CloneImage(inLayerInfo->image,tile_image_width, tile_image_height,MagickTrue,exception); /* read in the tile */ switch (inDocInfo->compression) { case COMPRESS_NONE: if (load_tile(image,tile_image,inDocInfo,inLayerInfo,(size_t) (offset2-offset)) == 0) status=MagickTrue; break; case COMPRESS_RLE: if (load_tile_rle (image,tile_image,inDocInfo,inLayerInfo, (int) (offset2-offset)) == 0) status=MagickTrue; break; case COMPRESS_ZLIB: ThrowBinaryException(CoderError,"ZipCompressNotSupported", image->filename) case COMPRESS_FRACTAL: ThrowBinaryException(CoderError,"FractalCompressNotSupported", image->filename) } /* composite the tile onto the layer's image, and then destroy it */ (void) CompositeImage(inLayerInfo->image,CopyCompositeOp,tile_image, destLeft * TILE_WIDTH,destTop*TILE_HEIGHT); tile_image=DestroyImage(tile_image); /* adjust tile position */ destLeft++; if (destLeft >= (int) ntile_cols) { destLeft = 0; destTop++; } if (status != MagickFalse) return(MagickFalse); /* restore the saved position so we'll be ready to * read the next offset. */ offset=SeekBlob(image, saved_pos, SEEK_SET); /* read in the offset of the next tile */ offset=(MagickOffsetType) ReadBlobMSBLong(image); } if (offset != 0) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename) return(MagickTrue); } 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 userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx, struct userfaultfd_wait_queue *ewq) { struct userfaultfd_ctx *release_new_ctx; if (WARN_ON_ONCE(current->flags & PF_EXITING)) goto out; ewq->ctx = ctx; init_waitqueue_entry(&ewq->wq, current); release_new_ctx = NULL; spin_lock(&ctx->event_wqh.lock); /* * After the __add_wait_queue the uwq is visible to userland * through poll/read(). */ __add_wait_queue(&ctx->event_wqh, &ewq->wq); for (;;) { set_current_state(TASK_KILLABLE); if (ewq->msg.event == 0) break; if (READ_ONCE(ctx->released) || fatal_signal_pending(current)) { /* * &ewq->wq may be queued in fork_event, but * __remove_wait_queue ignores the head * parameter. It would be a problem if it * didn't. */ __remove_wait_queue(&ctx->event_wqh, &ewq->wq); if (ewq->msg.event == UFFD_EVENT_FORK) { struct userfaultfd_ctx *new; new = (struct userfaultfd_ctx *) (unsigned long) ewq->msg.arg.reserved.reserved1; release_new_ctx = new; } break; } spin_unlock(&ctx->event_wqh.lock); wake_up_poll(&ctx->fd_wqh, EPOLLIN); schedule(); spin_lock(&ctx->event_wqh.lock); } __set_current_state(TASK_RUNNING); spin_unlock(&ctx->event_wqh.lock); if (release_new_ctx) { struct vm_area_struct *vma; struct mm_struct *mm = release_new_ctx->mm; /* the various vma->vm_userfaultfd_ctx still points to it */ down_write(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) { vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING); } up_write(&mm->mmap_sem); userfaultfd_ctx_put(release_new_ctx); } /* * ctx may go away after this if the userfault pseudo fd is * already released. */ out: WRITE_ONCE(ctx->mmap_changing, false); userfaultfd_ctx_put(ctx); } CWE ID: CWE-362 Target: 1 Example 2: Code: static void customSetterImplementedAsLongAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectPythonV8Internal::customSetterImplementedAsLongAttributeAttributeGetter(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: SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { return __sys_getpeername(fd, usockaddr, usockaddr_len); } 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: DefragIPv4NoDataTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int id = 12; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* This packet has an offset > 0, more frags set to 0 and no data. */ p = BuildTestPacket(id, 1, 0, 'A', 0); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; /* The fragment should have been ignored so no fragments should * have been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; } CWE ID: CWE-358 Target: 1 Example 2: Code: t_hash_show(struct seq_file *m, struct ftrace_iterator *iter) { struct ftrace_func_probe *rec; rec = iter->probe; if (WARN_ON_ONCE(!rec)) return -EIO; if (rec->ops->print) return rec->ops->print(m, rec->ip, rec->ops, rec->data); seq_printf(m, "%ps:%ps", (void *)rec->ip, (void *)rec->ops->func); if (rec->data) seq_printf(m, ":%p", rec->data); seq_putc(m, '\n'); return 0; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(curl_unescape) { char *str = NULL, *out = NULL; size_t str_len = 0; int out_len; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (str_len > INT_MAX) { RETURN_FALSE; } if ((out = curl_easy_unescape(ch->cp, str, str_len, &out_len))) { RETVAL_STRINGL(out, out_len); curl_free(out); } else { RETURN_FALSE; } } 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: char *FLTGetIsLikeComparisonCommonExpression(FilterEncodingNode *psFilterNode) { const size_t bufferSize = 1024; char szBuffer[1024]; char szTmp[256]; char *pszValue = NULL; const char *pszWild = NULL; const char *pszSingle = NULL; const char *pszEscape = NULL; int bCaseInsensitive = 0; FEPropertyIsLike* propIsLike; int nLength=0, i=0, iTmp=0; if (!psFilterNode || !psFilterNode->pOther || !psFilterNode->psLeftNode || !psFilterNode->psRightNode || !psFilterNode->psRightNode->pszValue) return NULL; propIsLike = (FEPropertyIsLike *)psFilterNode->pOther; pszWild = propIsLike->pszWildCard; pszSingle = propIsLike->pszSingleChar; pszEscape = propIsLike->pszEscapeChar; bCaseInsensitive = propIsLike->bCaseInsensitive; if (!pszWild || strlen(pszWild) == 0 || !pszSingle || strlen(pszSingle) == 0 || !pszEscape || strlen(pszEscape) == 0) return NULL; /* -------------------------------------------------------------------- */ /* Use operand with regular expressions. */ /* -------------------------------------------------------------------- */ szBuffer[0] = '\0'; sprintf(szTmp, "%s", "(\"["); szTmp[4] = '\0'; strlcat(szBuffer, szTmp, bufferSize); /* attribute */ strlcat(szBuffer, psFilterNode->psLeftNode->pszValue, bufferSize); szBuffer[strlen(szBuffer)] = '\0'; /* #3521 */ if (bCaseInsensitive == 1) sprintf(szTmp, "%s", "]\" ~* \""); else sprintf(szTmp, "%s", "]\" ~ \""); szTmp[7] = '\0'; strlcat(szBuffer, szTmp, bufferSize); szBuffer[strlen(szBuffer)] = '\0'; pszValue = psFilterNode->psRightNode->pszValue; nLength = strlen(pszValue); iTmp =0; if (nLength > 0 && pszValue[0] != pszWild[0] && pszValue[0] != pszSingle[0] && pszValue[0] != pszEscape[0]) { szTmp[iTmp]= '^'; iTmp++; } for (i=0; i<nLength; i++) { if (pszValue[i] != pszWild[0] && pszValue[i] != pszSingle[0] && pszValue[i] != pszEscape[0]) { szTmp[iTmp] = pszValue[i]; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszSingle[0]) { szTmp[iTmp] = '.'; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszEscape[0]) { szTmp[iTmp] = '\\'; iTmp++; szTmp[iTmp] = '\0'; } else if (pszValue[i] == pszWild[0]) { szTmp[iTmp++] = '.'; szTmp[iTmp++] = '*'; szTmp[iTmp] = '\0'; } } szTmp[iTmp] = '"'; szTmp[++iTmp] = '\0'; strlcat(szBuffer, szTmp, bufferSize); strlcat(szBuffer, ")", bufferSize); return msStrdup(szBuffer); } CWE ID: CWE-119 Target: 1 Example 2: Code: NotificationsEngine::~NotificationsEngine() { QDBusConnection dbus = QDBusConnection::sessionBus(); dbus.unregisterService( QStringLiteral("org.freedesktop.Notifications") ); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void reds_handle_ticket(void *opaque) { RedLinkInfo *link = (RedLinkInfo *)opaque; char password[SPICE_MAX_PASSWORD_LENGTH]; time_t ltime; time(&ltime); RSA_private_decrypt(link->tiTicketing.rsa_size, link->tiTicketing.encrypted_ticket.encrypted_data, (unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING); if (ticketing_enabled && !link->skip_auth) { int expired = taTicket.expiration_time < ltime; if (strlen(taTicket.password) == 0) { reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); spice_warning("Ticketing is enabled, but no password is set. " "please set a ticket first"); reds_link_free(link); return; } if (expired || strncmp(password, taTicket.password, SPICE_MAX_PASSWORD_LENGTH) != 0) { if (expired) { spice_warning("Ticket has expired"); } else { spice_warning("Invalid password"); } reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); reds_link_free(link); return; } } reds_handle_link(link); } 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 HeapAllocator::backingFree(void* address) { if (!address) return; ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return; ASSERT(!state->isInGC()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); ASSERT(header->checkHeader()); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); state->promptlyFreed(header->gcInfoIndex()); arena->promptlyFreeObject(header); } CWE ID: CWE-119 Target: 1 Example 2: Code: void DesktopWindowTreeHostX11::Maximize() { if (ui::HasWMSpecProperty(window_properties_, gfx::GetAtom("_NET_WM_STATE_FULLSCREEN"))) { SetWMSpecState(false, gfx::GetAtom("_NET_WM_STATE_FULLSCREEN"), x11::None); gfx::Rect adjusted_bounds_in_pixels(bounds_in_pixels_.origin(), AdjustSize(bounds_in_pixels_.size())); if (adjusted_bounds_in_pixels != bounds_in_pixels_) SetBoundsInPixels(adjusted_bounds_in_pixels); } should_maximize_after_map_ = !window_mapped_in_client_; restored_bounds_in_pixels_ = bounds_in_pixels_; SetWMSpecState(true, gfx::GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"), gfx::GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ")); if (IsMinimized()) Show(ui::SHOW_STATE_NORMAL, gfx::Rect()); } 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: bool __net_get_random_once(void *buf, int nbytes, bool *done, struct static_key *done_key) { static DEFINE_SPINLOCK(lock); unsigned long flags; spin_lock_irqsave(&lock, flags); if (*done) { spin_unlock_irqrestore(&lock, flags); return false; } get_random_bytes(buf, nbytes); *done = true; spin_unlock_irqrestore(&lock, flags); __net_random_once_disable_jump(done_key); 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: ft_var_readpackedpoints( FT_Stream stream, FT_UInt *point_cnt ) { FT_UShort *points; FT_Int n; FT_Int runcnt; FT_Int i; FT_Int j; FT_Int first; FT_Memory memory = stream->memory; FT_Error error = TT_Err_Ok; FT_UNUSED( error ); *point_cnt = n = FT_GET_BYTE(); if ( n == 0 ) return ALL_POINTS; if ( n & GX_PT_POINTS_ARE_WORDS ) n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 ); if ( FT_NEW_ARRAY( points, n ) ) return NULL; i = 0; while ( i < n ) { runcnt = FT_GET_BYTE(); if ( runcnt & GX_PT_POINTS_ARE_WORDS ) { runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK; first = points[i++] = FT_GET_USHORT(); if ( runcnt < 1 ) goto Exit; /* first point not included in runcount */ for ( j = 0; j < runcnt; ++j ) points[i++] = (FT_UShort)( first += FT_GET_USHORT() ); } else { first = points[i++] = FT_GET_BYTE(); if ( runcnt < 1 ) goto Exit; for ( j = 0; j < runcnt; ++j ) points[i++] = (FT_UShort)( first += FT_GET_BYTE() ); } } Exit: return points; } CWE ID: CWE-119 Target: 1 Example 2: Code: const SSLStatus& ssl() { return ssl_; } 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 BaseSettingChange::Apply(Browser* browser) { } 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: check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: monitor_reset_key_state(void) { /* reset state */ free(key_blob); free(hostbased_cuser); free(hostbased_chost); key_blob = NULL; key_bloblen = 0; key_blobtype = MM_NOKEY; hostbased_cuser = NULL; hostbased_chost = NULL; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t MediaHTTP::connect( const char *uri, const KeyedVector<String8, String8> *headers, off64_t /* offset */) { if (mInitCheck != OK) { return mInitCheck; } KeyedVector<String8, String8> extHeaders; if (headers != NULL) { extHeaders = *headers; } if (extHeaders.indexOfKey(String8("User-Agent")) < 0) { extHeaders.add(String8("User-Agent"), String8(MakeUserAgent().c_str())); } bool success = mHTTPConnection->connect(uri, &extHeaders); mLastHeaders = extHeaders; mLastURI = uri; mCachedSizeValid = false; if (success) { AString sanitized = uriDebugString(uri); mName = String8::format("MediaHTTP(%s)", sanitized.c_str()); } return success ? OK : UNKNOWN_ERROR; } 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 PageSerializer::serializeFrame(Frame* frame) { Document* document = frame->document(); KURL url = document->url(); if (!url.isValid() || url.isBlankURL()) { url = urlForBlankFrame(frame); } if (m_resourceURLs.contains(url)) { return; } if (document->isImageDocument()) { ImageDocument* imageDocument = toImageDocument(document); addImageToResources(imageDocument->cachedImage(), imageDocument->imageElement()->renderer(), url); return; } Vector<Node*> nodes; OwnPtr<SerializerMarkupAccumulator> accumulator; if (m_URLs) accumulator = adoptPtr(new LinkChangeSerializerMarkupAccumulator(this, document, &nodes, m_URLs, m_directory)); else accumulator = adoptPtr(new SerializerMarkupAccumulator(this, document, &nodes)); String text = accumulator->serializeNodes(document, IncludeNode); WTF::TextEncoding textEncoding(document->charset()); CString frameHTML = textEncoding.normalizeAndEncode(text, WTF::EntitiesForUnencodables); m_resources->append(SerializedResource(url, document->suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length()))); m_resourceURLs.add(url); for (Vector<Node*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) { Node* node = *iter; if (!node->isElementNode()) continue; Element* element = toElement(node); if (element->isStyledElement()) { retrieveResourcesForProperties(element->inlineStyle(), document); retrieveResourcesForProperties(element->presentationAttributeStyle(), document); } if (element->hasTagName(HTMLNames::imgTag)) { HTMLImageElement* imageElement = toHTMLImageElement(element); KURL url = document->completeURL(imageElement->getAttribute(HTMLNames::srcAttr)); ImageResource* cachedImage = imageElement->cachedImage(); addImageToResources(cachedImage, imageElement->renderer(), url); } else if (element->hasTagName(HTMLNames::inputTag)) { HTMLInputElement* inputElement = toHTMLInputElement(element); if (inputElement->isImageButton() && inputElement->hasImageLoader()) { KURL url = inputElement->src(); ImageResource* cachedImage = inputElement->imageLoader()->image(); addImageToResources(cachedImage, inputElement->renderer(), url); } } else if (element->hasTagName(HTMLNames::linkTag)) { HTMLLinkElement* linkElement = toHTMLLinkElement(element); if (CSSStyleSheet* sheet = linkElement->sheet()) { KURL url = document->completeURL(linkElement->getAttribute(HTMLNames::hrefAttr)); serializeCSSStyleSheet(sheet, url); ASSERT(m_resourceURLs.contains(url)); } } else if (element->hasTagName(HTMLNames::styleTag)) { HTMLStyleElement* styleElement = toHTMLStyleElement(element); if (CSSStyleSheet* sheet = styleElement->sheet()) serializeCSSStyleSheet(sheet, KURL()); } } for (Frame* childFrame = frame->tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling()) serializeFrame(childFrame); } CWE ID: CWE-119 Target: 1 Example 2: Code: void clear() { key_received_ = key_handled_ = false; event_flags_ = 0; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline unsigned int ip_vs_rs_hashkey(int af, const union nf_inet_addr *addr, __be16 port) { register unsigned int porth = ntohs(port); __be32 addr_fold = addr->ip; #ifdef CONFIG_IP_VS_IPV6 if (af == AF_INET6) addr_fold = addr->ip6[0]^addr->ip6[1]^ addr->ip6[2]^addr->ip6[3]; #endif return (ntohl(addr_fold)^(porth>>IP_VS_RTAB_BITS)^porth) & IP_VS_RTAB_MASK; } 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 void sycc444_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; unsigned int maxw, maxh, max, i; int offset, upb; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * (size_t)max); d1 = g = (int*)malloc(sizeof(int) * (size_t)max); d2 = b = (int*)malloc(sizeof(int) * (size_t)max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i = 0U; i < max; ++i) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++cb; ++cr; ++r; ++g; ++b; } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; return; fails: if(r) free(r); if(g) free(g); if(b) free(b); }/* sycc444_to_rgb() */ CWE ID: CWE-125 Target: 1 Example 2: Code: virtual status_t setTransformHint(uint32_t hint) { Parcel data, reply; data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor()); data.writeInt32(hint); status_t result = remote()->transact(SET_TRANSFORM_HINT, data, &reply); if (result != NO_ERROR) { return result; } return reply.readInt32(); } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; /* * Check any passed addresses */ if (addr_len) *addr_len = sizeof(*sin); if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::SubmitDecode( const scoped_refptr<VP9Picture>& pic, const Vp9SegmentationParams& seg, const Vp9LoopFilterParams& lf, const std::vector<scoped_refptr<VP9Picture>>& ref_pictures, const base::Closure& done_cb) { DCHECK(done_cb.is_null()); VADecPictureParameterBufferVP9 pic_param; memset(&pic_param, 0, sizeof(pic_param)); const Vp9FrameHeader* frame_hdr = pic->frame_hdr.get(); DCHECK(frame_hdr); pic_param.frame_width = base::checked_cast<uint16_t>(frame_hdr->frame_width); pic_param.frame_height = base::checked_cast<uint16_t>(frame_hdr->frame_height); CHECK_EQ(ref_pictures.size(), arraysize(pic_param.reference_frames)); for (size_t i = 0; i < arraysize(pic_param.reference_frames); ++i) { VASurfaceID va_surface_id; if (ref_pictures[i]) { scoped_refptr<VaapiDecodeSurface> surface = VP9PictureToVaapiDecodeSurface(ref_pictures[i]); va_surface_id = surface->va_surface()->id(); } else { va_surface_id = VA_INVALID_SURFACE; } pic_param.reference_frames[i] = va_surface_id; } #define FHDR_TO_PP_PF1(a) pic_param.pic_fields.bits.a = frame_hdr->a #define FHDR_TO_PP_PF2(a, b) pic_param.pic_fields.bits.a = b FHDR_TO_PP_PF2(subsampling_x, frame_hdr->subsampling_x == 1); FHDR_TO_PP_PF2(subsampling_y, frame_hdr->subsampling_y == 1); FHDR_TO_PP_PF2(frame_type, frame_hdr->IsKeyframe() ? 0 : 1); FHDR_TO_PP_PF1(show_frame); FHDR_TO_PP_PF1(error_resilient_mode); FHDR_TO_PP_PF1(intra_only); FHDR_TO_PP_PF1(allow_high_precision_mv); FHDR_TO_PP_PF2(mcomp_filter_type, frame_hdr->interpolation_filter); FHDR_TO_PP_PF1(frame_parallel_decoding_mode); FHDR_TO_PP_PF1(reset_frame_context); FHDR_TO_PP_PF1(refresh_frame_context); FHDR_TO_PP_PF2(frame_context_idx, frame_hdr->frame_context_idx_to_save_probs); FHDR_TO_PP_PF2(segmentation_enabled, seg.enabled); FHDR_TO_PP_PF2(segmentation_temporal_update, seg.temporal_update); FHDR_TO_PP_PF2(segmentation_update_map, seg.update_map); FHDR_TO_PP_PF2(last_ref_frame, frame_hdr->ref_frame_idx[0]); FHDR_TO_PP_PF2(last_ref_frame_sign_bias, frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_LAST]); FHDR_TO_PP_PF2(golden_ref_frame, frame_hdr->ref_frame_idx[1]); FHDR_TO_PP_PF2(golden_ref_frame_sign_bias, frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_GOLDEN]); FHDR_TO_PP_PF2(alt_ref_frame, frame_hdr->ref_frame_idx[2]); FHDR_TO_PP_PF2(alt_ref_frame_sign_bias, frame_hdr->ref_frame_sign_bias[Vp9RefType::VP9_FRAME_ALTREF]); FHDR_TO_PP_PF2(lossless_flag, frame_hdr->quant_params.IsLossless()); #undef FHDR_TO_PP_PF2 #undef FHDR_TO_PP_PF1 pic_param.filter_level = lf.level; pic_param.sharpness_level = lf.sharpness; pic_param.log2_tile_rows = frame_hdr->tile_rows_log2; pic_param.log2_tile_columns = frame_hdr->tile_cols_log2; pic_param.frame_header_length_in_bytes = frame_hdr->uncompressed_header_size; pic_param.first_partition_size = frame_hdr->header_size_in_bytes; ARRAY_MEMCPY_CHECKED(pic_param.mb_segment_tree_probs, seg.tree_probs); ARRAY_MEMCPY_CHECKED(pic_param.segment_pred_probs, seg.pred_probs); pic_param.profile = frame_hdr->profile; pic_param.bit_depth = frame_hdr->bit_depth; DCHECK((pic_param.profile == 0 && pic_param.bit_depth == 8) || (pic_param.profile == 2 && pic_param.bit_depth == 10)); if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, sizeof(pic_param), &pic_param)) return false; VASliceParameterBufferVP9 slice_param; memset(&slice_param, 0, sizeof(slice_param)); slice_param.slice_data_size = frame_hdr->frame_size; slice_param.slice_data_offset = 0; slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; static_assert(arraysize(Vp9SegmentationParams::feature_enabled) == arraysize(slice_param.seg_param), "seg_param array of incorrect size"); for (size_t i = 0; i < arraysize(slice_param.seg_param); ++i) { VASegmentParameterVP9& seg_param = slice_param.seg_param[i]; #define SEG_TO_SP_SF(a, b) seg_param.segment_flags.fields.a = b SEG_TO_SP_SF( segment_reference_enabled, seg.FeatureEnabled(i, Vp9SegmentationParams::SEG_LVL_REF_FRAME)); SEG_TO_SP_SF(segment_reference, seg.FeatureData(i, Vp9SegmentationParams::SEG_LVL_REF_FRAME)); SEG_TO_SP_SF(segment_reference_skipped, seg.FeatureEnabled(i, Vp9SegmentationParams::SEG_LVL_SKIP)); #undef SEG_TO_SP_SF ARRAY_MEMCPY_CHECKED(seg_param.filter_level, lf.lvl[i]); seg_param.luma_dc_quant_scale = seg.y_dequant[i][0]; seg_param.luma_ac_quant_scale = seg.y_dequant[i][1]; seg_param.chroma_dc_quant_scale = seg.uv_dequant[i][0]; seg_param.chroma_ac_quant_scale = seg.uv_dequant[i][1]; } if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType, sizeof(slice_param), &slice_param)) return false; void* non_const_ptr = const_cast<uint8_t*>(frame_hdr->data); if (!vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, frame_hdr->frame_size, non_const_ptr)) return false; scoped_refptr<VaapiDecodeSurface> dec_surface = VP9PictureToVaapiDecodeSurface(pic); return vaapi_dec_->DecodeSurface(dec_surface); } CWE ID: CWE-362 Target: 1 Example 2: Code: void BluetoothAdapter::StartDiscoverySessionWithFilter( std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter, const DiscoverySessionCallback& callback, const ErrorCallback& error_callback) { std::unique_ptr<BluetoothDiscoverySession> new_session( new BluetoothDiscoverySession(this, std::move(discovery_filter))); discovery_sessions_.insert(new_session.get()); auto new_session_callbacks = base::WrapUnique(new StartOrStopDiscoveryCallback( base::BindOnce(callback, std::move(new_session)), error_callback)); discovery_callback_queue_.push(std::move(new_session_callbacks)); if (discovery_request_pending_) { return; } ProcessDiscoveryQueue(); } 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: ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1) : mIsValid(false), mData(NULL), mSize(0), mFirstFrameOffset(0), mVersion(ID3_UNKNOWN), mRawSize(0) { sp<MemorySource> source = new MemorySource(data, size); mIsValid = parseV2(source, 0); if (!mIsValid && !ignoreV1) { mIsValid = parseV1(source); } } 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(imageaffinematrixget) { double affine[6]; long type; zval *options; zval **tmp; int res = GD_FALSE, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) { return; } switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; if (Z_TYPE_P(options) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options"); } if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) { convert_to_double_ex(tmp); x = Z_DVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) { convert_to_double_ex(tmp); y = Z_DVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; convert_to_double_ex(&options); angle = Z_DVAL_P(options); if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type); RETURN_FALSE; } if (res == GD_FALSE) { RETURN_FALSE; } else { array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, affine[i]); } } } CWE ID: CWE-189 Target: 1 Example 2: Code: void RenderFrame::ForEach(RenderFrameVisitor* visitor) { FrameMap* frames = g_frame_map.Pointer(); for (auto it = frames->begin(); it != frames->end(); ++it) { if (!visitor->Visit(it->second)) return; } } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: my_object_terminate (MyObject *obj, GError **error) { g_main_loop_quit (loop); return TRUE; } 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 Image *ReadTTFImage(const ImageInfo *image_info,ExceptionInfo *exception) { char buffer[MaxTextExtent], *text; const char *Text = (char *) "abcdefghijklmnopqrstuvwxyz\n" "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n" "0123456789.:,;(*!?}^)#${%^&-+@\n"; const TypeInfo *type_info; DrawInfo *draw_info; Image *image; MagickBooleanType status; PixelPacket background_color; register ssize_t i, x; register PixelPacket *q; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); image->columns=800; image->rows=480; type_info=GetTypeInfo(image_info->filename,exception); if ((type_info != (const TypeInfo *) NULL) && (type_info->glyphs != (char *) NULL)) (void) CopyMagickString(image->filename,type_info->glyphs,MaxTextExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Color canvas with background color */ background_color=image_info->background_color; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) *q++=background_color; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) CopyMagickString(image->magick,image_info->magick,MaxTextExtent); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); /* Prepare drawing commands */ y=20; draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->font=AcquireString(image->filename); ConcatenateString(&draw_info->primitive,"push graphic-context\n"); (void) FormatLocaleString(buffer,MaxTextExtent," viewbox 0 0 %.20g %.20g\n", (double) image->columns,(double) image->rows); ConcatenateString(&draw_info->primitive,buffer); ConcatenateString(&draw_info->primitive," font-size 18\n"); (void) FormatLocaleString(buffer,MaxTextExtent," text 10,%.20g '",(double) y); ConcatenateString(&draw_info->primitive,buffer); text=EscapeString(Text,'"'); ConcatenateString(&draw_info->primitive,text); text=DestroyString(text); (void) FormatLocaleString(buffer,MaxTextExtent,"'\n"); ConcatenateString(&draw_info->primitive,buffer); y+=20*(ssize_t) MultilineCensus((char *) Text)+20; for (i=12; i <= 72; i+=6) { y+=i+12; ConcatenateString(&draw_info->primitive," font-size 18\n"); (void) FormatLocaleString(buffer,MaxTextExtent," text 10,%.20g '%.20g'\n", (double) y,(double) i); ConcatenateString(&draw_info->primitive,buffer); (void) FormatLocaleString(buffer,MaxTextExtent," font-size %.20g\n", (double) i); ConcatenateString(&draw_info->primitive,buffer); (void) FormatLocaleString(buffer,MaxTextExtent," text 50,%.20g " "'That which does not destroy me, only makes me stronger.'\n",(double) y); ConcatenateString(&draw_info->primitive,buffer); if (i >= 24) i+=6; } ConcatenateString(&draw_info->primitive,"pop graphic-context"); (void) DrawImage(image,draw_info); /* Relinquish resources. */ draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } CWE ID: CWE-119 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoFramebufferTextureLayer( GLenum target, GLenum attachment, GLuint client_texture_id, GLint level, GLint layer) { const char* function_name = "glFramebufferTextureLayer"; TextureRef* texture_ref = nullptr; Framebuffer* framebuffer = GetFramebufferInfoForTarget(target); if (!framebuffer) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, function_name, "no framebuffer bound."); return; } GLuint service_id = 0; GLenum texture_target = 0; if (client_texture_id) { texture_ref = GetTexture(client_texture_id); if (!texture_ref) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, function_name, "unknown texture"); return; } service_id = texture_ref->service_id(); texture_target = texture_ref->texture()->target(); switch (texture_target) { case GL_TEXTURE_3D: case GL_TEXTURE_2D_ARRAY: break; default: LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, function_name, "texture is neither TEXTURE_3D nor TEXTURE_2D_ARRAY"); return; } if (!texture_manager()->ValidForTarget(texture_target, level, 0, 0, layer)) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, function_name, "invalid level or layer"); return; } } api()->glFramebufferTextureLayerFn(target, attachment, service_id, level, layer); if (attachment == GL_DEPTH_STENCIL_ATTACHMENT) { framebuffer->AttachTextureLayer( GL_DEPTH_ATTACHMENT, texture_ref, texture_target, level, layer); framebuffer->AttachTextureLayer( GL_STENCIL_ATTACHMENT, texture_ref, texture_target, level, layer); } else { framebuffer->AttachTextureLayer( attachment, texture_ref, texture_target, level, layer); } if (framebuffer == framebuffer_state_.bound_draw_framebuffer.get()) { framebuffer_state_.clear_state_dirty = true; } } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WORD32 ih264d_decode_gaps_in_frame_num(dec_struct_t *ps_dec, UWORD16 u2_frame_num) { UWORD32 u4_next_frm_num, u4_start_frm_num; UWORD32 u4_max_frm_num; pocstruct_t s_tmp_poc; WORD32 i4_poc; dec_slice_params_t *ps_cur_slice; dec_pic_params_t *ps_pic_params; WORD8 i1_gap_idx; WORD32 *i4_gaps_start_frm_num; dpb_manager_t *ps_dpb_mgr; WORD32 i4_frame_gaps; WORD8 *pi1_gaps_per_seq; WORD32 ret; ps_cur_slice = ps_dec->ps_cur_slice; if(ps_cur_slice->u1_field_pic_flag) { if(ps_dec->u2_prev_ref_frame_num == u2_frame_num) return 0; } u4_next_frm_num = ps_dec->u2_prev_ref_frame_num + 1; u4_max_frm_num = ps_dec->ps_cur_sps->u2_u4_max_pic_num_minus1 + 1; if(u4_next_frm_num >= u4_max_frm_num) { u4_next_frm_num -= u4_max_frm_num; } if(u4_next_frm_num == u2_frame_num) { return (0); } if((ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) && (u4_next_frm_num >= u2_frame_num)) { return (0); } u4_start_frm_num = u4_next_frm_num; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; s_tmp_poc.i4_pic_order_cnt_lsb = 0; s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; ps_cur_slice = ps_dec->ps_cur_slice; ps_pic_params = ps_dec->ps_cur_pps; ps_cur_slice->u1_field_pic_flag = 0; i4_frame_gaps = 0; ps_dpb_mgr = ps_dec->ps_dpb_mgr; /* Find a empty slot to store gap seqn info */ i4_gaps_start_frm_num = ps_dpb_mgr->ai4_gaps_start_frm_num; for(i1_gap_idx = 0; i1_gap_idx < MAX_FRAMES; i1_gap_idx++) { if(INVALID_FRAME_NUM == i4_gaps_start_frm_num[i1_gap_idx]) break; } if(MAX_FRAMES == i1_gap_idx) { UWORD32 i4_error_code; i4_error_code = ERROR_DBP_MANAGER_T; return i4_error_code; } i4_poc = 0; i4_gaps_start_frm_num[i1_gap_idx] = u4_start_frm_num; ps_dpb_mgr->ai4_gaps_end_frm_num[i1_gap_idx] = u2_frame_num - 1; pi1_gaps_per_seq = ps_dpb_mgr->ai1_gaps_per_seq; pi1_gaps_per_seq[i1_gap_idx] = 0; while(u4_next_frm_num != u2_frame_num) { ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr); if(ps_pic_params->ps_sps->u1_pic_order_cnt_type) { /* allocate a picture buffer and insert it as ST node */ ret = ih264d_decode_pic_order_cnt(0, u4_next_frm_num, &ps_dec->s_prev_pic_poc, &s_tmp_poc, ps_cur_slice, ps_pic_params, 1, 0, 0, &i4_poc); if(ret != OK) return ret; /* Display seq no calculations */ if(i4_poc >= ps_dec->i4_max_poc) ps_dec->i4_max_poc = i4_poc; /* IDR Picture or POC wrap around */ if(i4_poc == 0) { ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + ps_dec->i4_max_poc + ps_dec->u1_max_dec_frame_buffering + 1; ps_dec->i4_max_poc = 0; } ps_cur_slice->u1_mmco_equalto5 = 0; ps_cur_slice->u2_frame_num = u4_next_frm_num; } if(ps_dpb_mgr->i1_poc_buf_id_entries >= ps_dec->u1_max_dec_frame_buffering) { ret = ih264d_assign_display_seq(ps_dec); if(ret != OK) return ret; } ret = ih264d_insert_pic_in_display_list( ps_dec->ps_dpb_mgr, (WORD8) DO_NOT_DISP, (WORD32)(ps_dec->i4_prev_max_display_seq + i4_poc), u4_next_frm_num); if(ret != OK) return ret; pi1_gaps_per_seq[i1_gap_idx]++; ret = ih264d_do_mmco_for_gaps(ps_dpb_mgr, ps_dec->ps_cur_sps->u1_num_ref_frames); if(ret != OK) return ret; ih264d_delete_nonref_nondisplay_pics(ps_dpb_mgr); u4_next_frm_num++; if(u4_next_frm_num >= u4_max_frm_num) { u4_next_frm_num -= u4_max_frm_num; } i4_frame_gaps++; } return OK; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t OMXNodeInstance::allocateBufferWithBackup( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, portIndex, true); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; } CWE ID: CWE-200 Target: 1 Example 2: Code: void DiscardableSharedMemoryManager::ClientDeletedDiscardableSharedMemory( int32_t id, int client_id) { DeletedDiscardableSharedMemory(id, client_id); } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu) { unsigned long *msr_bitmap; if (is_guest_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_nested; else if (vcpu->arch.apic_base & X2APIC_ENABLE) { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode_x2apic; else msr_bitmap = vmx_msr_bitmap_legacy_x2apic; } else { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode; else msr_bitmap = vmx_msr_bitmap_legacy; } vmcs_write64(MSR_BITMAP, __pa(msr_bitmap)); } 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: PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero"); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, ncolors); RETURN_TRUE; } CWE ID: CWE-787 Target: 1 Example 2: Code: void HTMLFormControlElement::setNeedsWillValidateCheck() { bool newWillValidate = recalcWillValidate(); if (m_willValidateInitialized && m_willValidate == newWillValidate) return; m_willValidateInitialized = true; m_willValidate = newWillValidate; setNeedsValidityCheck(); setNeedsStyleRecalc(); if (!m_willValidate) hideVisibleValidationMessage(); } 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 GraphicsContext::setLineDash(const DashArray&, float dashOffset) { notImplemented(); } 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: do_command (unsigned char c) { static int dtr_up = 0; int newbaud, newflow, newparity, newbits; const char *xfr_cmd; char *fname; int r; switch (c) { case KEY_EXIT: return 1; case KEY_QUIT: term_set_hupcl(tty_fd, 0); term_flush(tty_fd); term_apply(tty_fd); term_erase(tty_fd); return 1; case KEY_STATUS: show_status(dtr_up); break; case KEY_PULSE: fd_printf(STO, "\r\n*** pulse DTR ***\r\n"); if ( term_pulse_dtr(tty_fd) < 0 ) fd_printf(STO, "*** FAILED\r\n"); break; case KEY_TOGGLE: if ( dtr_up ) r = term_lower_dtr(tty_fd); else r = term_raise_dtr(tty_fd); if ( r >= 0 ) dtr_up = ! dtr_up; fd_printf(STO, "\r\n*** DTR: %s ***\r\n", dtr_up ? "up" : "down"); break; case KEY_BAUD_UP: case KEY_BAUD_DN: if (c == KEY_BAUD_UP) opts.baud = baud_up(opts.baud); else opts.baud = baud_down(opts.baud); term_set_baudrate(tty_fd, opts.baud); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbaud = term_get_baudrate(tty_fd, NULL); if ( opts.baud != newbaud ) { fd_printf(STO, "\r\n*** baud: %d (%d) ***\r\n", opts.baud, newbaud); } else { fd_printf(STO, "\r\n*** baud: %d ***\r\n", opts.baud); } set_tty_write_sz(newbaud); break; case KEY_FLOW: opts.flow = flow_next(opts.flow); term_set_flowcntrl(tty_fd, opts.flow); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newflow = term_get_flowcntrl(tty_fd); if ( opts.flow != newflow ) { fd_printf(STO, "\r\n*** flow: %s (%s) ***\r\n", flow_str[opts.flow], flow_str[newflow]); } else { fd_printf(STO, "\r\n*** flow: %s ***\r\n", flow_str[opts.flow]); } break; case KEY_PARITY: opts.parity = parity_next(opts.parity); term_set_parity(tty_fd, opts.parity); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newparity = term_get_parity(tty_fd); if (opts.parity != newparity ) { fd_printf(STO, "\r\n*** parity: %s (%s) ***\r\n", parity_str[opts.parity], parity_str[newparity]); } else { fd_printf(STO, "\r\n*** parity: %s ***\r\n", parity_str[opts.parity]); } break; case KEY_BITS: opts.databits = bits_next(opts.databits); term_set_databits(tty_fd, opts.databits); tty_q.len = 0; term_flush(tty_fd); term_apply(tty_fd); newbits = term_get_databits(tty_fd); if (opts.databits != newbits ) { fd_printf(STO, "\r\n*** databits: %d (%d) ***\r\n", opts.databits, newbits); } else { fd_printf(STO, "\r\n*** databits: %d ***\r\n", opts.databits); } break; case KEY_LECHO: opts.lecho = ! opts.lecho; fd_printf(STO, "\r\n*** local echo: %s ***\r\n", opts.lecho ? "yes" : "no"); break; case KEY_SEND: case KEY_RECEIVE: xfr_cmd = (c == KEY_SEND) ? opts.send_cmd : opts.receive_cmd; if ( xfr_cmd[0] == '\0' ) { fd_printf(STO, "\r\n*** command disabled ***\r\n"); break; } fname = read_filename(); if (fname == NULL) { fd_printf(STO, "*** cannot read filename ***\r\n"); break; } run_cmd(tty_fd, xfr_cmd, fname, NULL); free(fname); break; case KEY_BREAK: term_break(tty_fd); fd_printf(STO, "\r\n*** break sent ***\r\n"); break; default: break; } return 0; } CWE ID: CWE-77 Target: 1 Example 2: Code: virDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckPositiveArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetMemoryParameters) { int ret; ret = conn->driver->domainSetMemoryParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int getSingletonPos(const char* str) { int result =-1; int i=0; int len = 0; if( str && ((len=strlen(str))>0) ){ for( i=0; i<len ; i++){ if( isIDSeparator(*(str+i)) ){ if( i==1){ /* string is of the form x-avy or a-prv1 */ result =0; break; } else { /* delimiter found; check for singleton */ if( isIDSeparator(*(str+i+2)) ){ /* a singleton; so send the position of separator before singleton */ result = i+1; break; } } } }/* end of for */ } return result; } 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 void f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); } CWE ID: CWE-17 Target: 1 Example 2: Code: static struct tcp_md5sig_key *tcp_v4_reqsk_md5_lookup(struct sock *sk, struct request_sock *req) { return tcp_v4_md5_do_lookup(sk, inet_rsk(req)->rmt_addr); } 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 PHP_MINIT_FUNCTION(zip) { #ifdef PHP_ZIP_USE_OO zend_class_entry ce; memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); zip_object_handlers.clone_obj = NULL; zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr; zip_object_handlers.get_properties = php_zip_get_properties; zip_object_handlers.read_property = php_zip_read_property; zip_object_handlers.has_property = php_zip_has_property; INIT_CLASS_ENTRY(ce, "ZipArchive", zip_class_functions); ce.create_object = php_zip_object_new; zip_class_entry = zend_register_internal_class(&ce TSRMLS_CC); zend_hash_init(&zip_prop_handlers, 0, NULL, NULL, 1); php_zip_register_prop_handler(&zip_prop_handlers, "status", php_zip_status, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, "statusSys", php_zip_status_sys, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, "numFiles", php_zip_get_num_files, NULL, NULL, IS_LONG TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, "filename", NULL, NULL, php_zipobj_get_filename, IS_STRING TSRMLS_CC); php_zip_register_prop_handler(&zip_prop_handlers, "comment", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING TSRMLS_CC); REGISTER_ZIP_CLASS_CONST_LONG("CREATE", ZIP_CREATE); REGISTER_ZIP_CLASS_CONST_LONG("EXCL", ZIP_EXCL); REGISTER_ZIP_CLASS_CONST_LONG("CHECKCONS", ZIP_CHECKCONS); REGISTER_ZIP_CLASS_CONST_LONG("OVERWRITE", ZIP_OVERWRITE); REGISTER_ZIP_CLASS_CONST_LONG("FL_NOCASE", ZIP_FL_NOCASE); REGISTER_ZIP_CLASS_CONST_LONG("FL_NODIR", ZIP_FL_NODIR); REGISTER_ZIP_CLASS_CONST_LONG("FL_COMPRESSED", ZIP_FL_COMPRESSED); REGISTER_ZIP_CLASS_CONST_LONG("FL_UNCHANGED", ZIP_FL_UNCHANGED); REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFAULT", ZIP_CM_DEFAULT); REGISTER_ZIP_CLASS_CONST_LONG("CM_STORE", ZIP_CM_STORE); REGISTER_ZIP_CLASS_CONST_LONG("CM_SHRINK", ZIP_CM_SHRINK); REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_1", ZIP_CM_REDUCE_1); REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_2", ZIP_CM_REDUCE_2); REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_3", ZIP_CM_REDUCE_3); REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_4", ZIP_CM_REDUCE_4); REGISTER_ZIP_CLASS_CONST_LONG("CM_IMPLODE", ZIP_CM_IMPLODE); REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE", ZIP_CM_DEFLATE); REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE64", ZIP_CM_DEFLATE64); REGISTER_ZIP_CLASS_CONST_LONG("CM_PKWARE_IMPLODE", ZIP_CM_PKWARE_IMPLODE); REGISTER_ZIP_CLASS_CONST_LONG("CM_BZIP2", ZIP_CM_BZIP2); REGISTER_ZIP_CLASS_CONST_LONG("CM_LZMA", ZIP_CM_LZMA); REGISTER_ZIP_CLASS_CONST_LONG("CM_TERSE", ZIP_CM_TERSE); REGISTER_ZIP_CLASS_CONST_LONG("CM_LZ77", ZIP_CM_LZ77); REGISTER_ZIP_CLASS_CONST_LONG("CM_WAVPACK", ZIP_CM_WAVPACK); REGISTER_ZIP_CLASS_CONST_LONG("CM_PPMD", ZIP_CM_PPMD); /* Error code */ REGISTER_ZIP_CLASS_CONST_LONG("ER_OK", ZIP_ER_OK); /* N No error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_MULTIDISK", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */ REGISTER_ZIP_CLASS_CONST_LONG("ER_RENAME", ZIP_ER_RENAME); /* S Renaming temporary file failed */ REGISTER_ZIP_CLASS_CONST_LONG("ER_CLOSE", ZIP_ER_CLOSE); /* S Closing zip archive failed */ REGISTER_ZIP_CLASS_CONST_LONG("ER_SEEK", ZIP_ER_SEEK); /* S Seek error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_READ", ZIP_ER_READ); /* S Read error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_WRITE", ZIP_ER_WRITE); /* S Write error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_CRC", ZIP_ER_CRC); /* N CRC error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_ZIPCLOSED", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */ REGISTER_ZIP_CLASS_CONST_LONG("ER_NOENT", ZIP_ER_NOENT); /* N No such file */ REGISTER_ZIP_CLASS_CONST_LONG("ER_EXISTS", ZIP_ER_EXISTS); /* N File already exists */ REGISTER_ZIP_CLASS_CONST_LONG("ER_OPEN", ZIP_ER_OPEN); /* S Can't open file */ REGISTER_ZIP_CLASS_CONST_LONG("ER_TMPOPEN", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */ REGISTER_ZIP_CLASS_CONST_LONG("ER_ZLIB", ZIP_ER_ZLIB); /* Z Zlib error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_MEMORY", ZIP_ER_MEMORY); /* N Malloc failure */ REGISTER_ZIP_CLASS_CONST_LONG("ER_CHANGED", ZIP_ER_CHANGED); /* N Entry has been changed */ REGISTER_ZIP_CLASS_CONST_LONG("ER_COMPNOTSUPP", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */ REGISTER_ZIP_CLASS_CONST_LONG("ER_EOF", ZIP_ER_EOF); /* N Premature EOF */ REGISTER_ZIP_CLASS_CONST_LONG("ER_INVAL", ZIP_ER_INVAL); /* N Invalid argument */ REGISTER_ZIP_CLASS_CONST_LONG("ER_NOZIP", ZIP_ER_NOZIP); /* N Not a zip archive */ REGISTER_ZIP_CLASS_CONST_LONG("ER_INTERNAL", ZIP_ER_INTERNAL); /* N Internal error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_INCONS", ZIP_ER_INCONS); /* N Zip archive inconsistent */ REGISTER_ZIP_CLASS_CONST_LONG("ER_REMOVE", ZIP_ER_REMOVE); /* S Can't remove file */ REGISTER_ZIP_CLASS_CONST_LONG("ER_DELETED", ZIP_ER_DELETED); /* N Entry has been deleted */ php_register_url_stream_wrapper("zip", &php_stream_zip_wrapper TSRMLS_CC); #endif le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number); le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number); return SUCCESS; } 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: xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf, int len, int size) { int q, ql; int r, rl; int cur, l; int count = 0; int inputid; inputid = ctxt->input->id; if (buf == NULL) { len = 0; size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return; } } GROW; /* Assure there's enough input data */ q = CUR_CHAR(ql); if (q == 0) goto not_terminated; if (!IS_CHAR(q)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseComment: invalid xmlChar value %d\n", q); xmlFree (buf); return; } NEXTL(ql); r = CUR_CHAR(rl); if (r == 0) goto not_terminated; if (!IS_CHAR(r)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseComment: invalid xmlChar value %d\n", q); xmlFree (buf); return; } NEXTL(rl); cur = CUR_CHAR(l); if (cur == 0) goto not_terminated; while (IS_CHAR(cur) && /* checked */ ((cur != '>') || (r != '-') || (q != '-'))) { if ((r == '-') && (q == '-')) { xmlFatalErr(ctxt, XML_ERR_HYPHEN_IN_COMMENT, NULL); } if (len + 5 >= size) { xmlChar *new_buf; size *= 2; new_buf = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (new_buf == NULL) { xmlFree (buf); xmlErrMemory(ctxt, NULL); return; } buf = new_buf; } COPY_BUF(ql,buf,len,q); q = r; ql = rl; r = cur; rl = l; count++; if (count > 50) { GROW; count = 0; } NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { SHRINK; GROW; cur = CUR_CHAR(l); } } buf[len] = 0; if (cur == 0) { xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, "Comment not terminated \n<!--%.50s\n", buf); } else if (!IS_CHAR(cur)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseComment: invalid xmlChar value %d\n", cur); } else { if (inputid != ctxt->input->id) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "Comment doesn't start and stop in the same entity\n"); } NEXT; if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) && (!ctxt->disableSAX)) ctxt->sax->comment(ctxt->userData, buf); } xmlFree(buf); return; not_terminated: xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, "Comment not terminated\n", NULL); xmlFree(buf); return; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int iwgif_read(struct iwgifrcontext *rctx, iw_byte *buf, size_t buflen) { int ret; size_t bytesread = 0; ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr, buf,buflen,&bytesread); if(!ret || bytesread!=buflen) { return 0; } return 1; } CWE ID: CWE-369 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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_icr(E1000ECore *core, int index, uint32_t val) { if ((core->mac[ICR] & E1000_ICR_ASSERTED) && (core->mac[CTRL_EXT] & E1000_CTRL_EXT_IAME)) { trace_e1000e_irq_icr_process_iame(); e1000e_clear_ims_bits(core, core->mac[IAM]); } trace_e1000e_irq_icr_write(val, core->mac[ICR], core->mac[ICR] & ~val); core->mac[ICR] &= ~val; e1000e_update_interrupt_state(core); } 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: SPL_METHOD(SplFileObject, eof) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(php_stream_eof(intern->u.file.stream)); } /* }}} */ /* {{{ proto void SplFileObject::valid() CWE ID: CWE-190 Target: 1 Example 2: Code: PHP_METHOD(SoapServer, setClass) { soapServicePtr service; char *classname; zend_class_entry **ce; int classname_len, found, num_args = 0; zval ***argv = NULL; SOAP_SERVER_BEGIN_CODE(); FETCH_THIS_SERVICE(service); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s*", &classname, &classname_len, &argv, &num_args) == FAILURE) { return; } found = zend_lookup_class(classname, classname_len, &ce TSRMLS_CC); if (found != FAILURE) { service->type = SOAP_CLASS; service->soap_class.ce = *ce; service->soap_class.persistance = SOAP_PERSISTENCE_REQUEST; service->soap_class.argc = num_args; if (service->soap_class.argc > 0) { int i; service->soap_class.argv = safe_emalloc(sizeof(zval), service->soap_class.argc, 0); for (i = 0;i < service->soap_class.argc;i++) { service->soap_class.argv[i] = *(argv[i]); zval_add_ref(&service->soap_class.argv[i]); } } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Tried to set a non existent class (%s)", classname); return; } if (argv) { efree(argv); } SOAP_SERVER_END_CODE(); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(forward_static_call_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 (EG(called_scope) && instanceof_function(EG(called_scope), fci_cache.calling_scope TSRMLS_CC)) { fci_cache.called_scope = EG(called_scope); } 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: static void init_vmcb(struct vcpu_svm *svm) { struct vmcb_control_area *control = &svm->vmcb->control; struct vmcb_save_area *save = &svm->vmcb->save; svm->vcpu.fpu_active = 1; svm->vcpu.arch.hflags = 0; set_cr_intercept(svm, INTERCEPT_CR0_READ); set_cr_intercept(svm, INTERCEPT_CR3_READ); set_cr_intercept(svm, INTERCEPT_CR4_READ); set_cr_intercept(svm, INTERCEPT_CR0_WRITE); set_cr_intercept(svm, INTERCEPT_CR3_WRITE); set_cr_intercept(svm, INTERCEPT_CR4_WRITE); set_cr_intercept(svm, INTERCEPT_CR8_WRITE); set_dr_intercepts(svm); set_exception_intercept(svm, PF_VECTOR); set_exception_intercept(svm, UD_VECTOR); set_exception_intercept(svm, MC_VECTOR); set_intercept(svm, INTERCEPT_INTR); set_intercept(svm, INTERCEPT_NMI); set_intercept(svm, INTERCEPT_SMI); set_intercept(svm, INTERCEPT_SELECTIVE_CR0); set_intercept(svm, INTERCEPT_RDPMC); set_intercept(svm, INTERCEPT_CPUID); set_intercept(svm, INTERCEPT_INVD); set_intercept(svm, INTERCEPT_HLT); set_intercept(svm, INTERCEPT_INVLPG); set_intercept(svm, INTERCEPT_INVLPGA); set_intercept(svm, INTERCEPT_IOIO_PROT); set_intercept(svm, INTERCEPT_MSR_PROT); set_intercept(svm, INTERCEPT_TASK_SWITCH); set_intercept(svm, INTERCEPT_SHUTDOWN); set_intercept(svm, INTERCEPT_VMRUN); set_intercept(svm, INTERCEPT_VMMCALL); set_intercept(svm, INTERCEPT_VMLOAD); set_intercept(svm, INTERCEPT_VMSAVE); set_intercept(svm, INTERCEPT_STGI); set_intercept(svm, INTERCEPT_CLGI); set_intercept(svm, INTERCEPT_SKINIT); set_intercept(svm, INTERCEPT_WBINVD); set_intercept(svm, INTERCEPT_MONITOR); set_intercept(svm, INTERCEPT_MWAIT); set_intercept(svm, INTERCEPT_XSETBV); control->iopm_base_pa = iopm_base; control->msrpm_base_pa = __pa(svm->msrpm); control->int_ctl = V_INTR_MASKING_MASK; init_seg(&save->es); init_seg(&save->ss); init_seg(&save->ds); init_seg(&save->fs); init_seg(&save->gs); save->cs.selector = 0xf000; save->cs.base = 0xffff0000; /* Executable/Readable Code Segment */ save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK; save->cs.limit = 0xffff; save->gdtr.limit = 0xffff; save->idtr.limit = 0xffff; init_sys_seg(&save->ldtr, SEG_TYPE_LDT); init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16); svm_set_efer(&svm->vcpu, 0); save->dr6 = 0xffff0ff0; kvm_set_rflags(&svm->vcpu, 2); save->rip = 0x0000fff0; svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip; /* * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0. * It also updates the guest-visible cr0 value. */ svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET); kvm_mmu_reset_context(&svm->vcpu); save->cr4 = X86_CR4_PAE; /* rdx = ?? */ if (npt_enabled) { /* Setup VMCB for Nested Paging */ control->nested_ctl = 1; clr_intercept(svm, INTERCEPT_INVLPG); clr_exception_intercept(svm, PF_VECTOR); clr_cr_intercept(svm, INTERCEPT_CR3_READ); clr_cr_intercept(svm, INTERCEPT_CR3_WRITE); save->g_pat = svm->vcpu.arch.pat; save->cr3 = 0; save->cr4 = 0; } svm->asid_generation = 0; svm->nested.vmcb = 0; svm->vcpu.arch.hflags = 0; if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) { control->pause_filter_count = 3000; set_intercept(svm, INTERCEPT_PAUSE); } mark_all_dirty(svm->vmcb); enable_gif(svm); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void key_gc_timer_func(unsigned long data) { kenter(""); key_gc_next_run = LONG_MAX; key_schedule_gc_links(); } 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 get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) { const int nb10sz = 16; memcpy (res, dbg_data, nb10sz); res->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz); } 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 ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree) { int i; switch (tree->operation) { case LDB_OP_AND: case LDB_OP_OR: asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1)); for (i=0; i<tree->u.list.num_elements; i++) { if (!ldap_push_filter(data, tree->u.list.elements[i])) { return false; } } asn1_pop_tag(data); break; case LDB_OP_NOT: asn1_push_tag(data, ASN1_CONTEXT(2)); if (!ldap_push_filter(data, tree->u.isnot.child)) { return false; } asn1_pop_tag(data); break; case LDB_OP_EQUALITY: /* equality test */ asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, tree->u.equality.attr, strlen(tree->u.equality.attr)); asn1_write_OctetString(data, tree->u.equality.value.data, tree->u.equality.value.length); asn1_pop_tag(data); break; case LDB_OP_SUBSTRING: /* SubstringFilter ::= SEQUENCE { type AttributeDescription, -- at least one must be present substrings SEQUENCE OF CHOICE { initial [0] LDAPString, any [1] LDAPString, final [2] LDAPString } } */ asn1_push_tag(data, ASN1_CONTEXT(4)); asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr)); asn1_push_tag(data, ASN1_SEQUENCE(0)); if (tree->u.substring.chunks && tree->u.substring.chunks[0]) { i = 0; if (!tree->u.substring.start_with_wildcard) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); asn1_pop_tag(data); i++; } while (tree->u.substring.chunks[i]) { int ctx; if (( ! tree->u.substring.chunks[i + 1]) && (tree->u.substring.end_with_wildcard == 0)) { ctx = 2; } else { ctx = 1; } asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx)); asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); asn1_pop_tag(data); i++; } } asn1_pop_tag(data); asn1_pop_tag(data); break; case LDB_OP_GREATER: /* greaterOrEqual test */ asn1_push_tag(data, ASN1_CONTEXT(5)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_LESS: /* lessOrEqual test */ asn1_push_tag(data, ASN1_CONTEXT(6)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_PRESENT: /* present test */ asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7)); asn1_write_LDAPString(data, tree->u.present.attr); asn1_pop_tag(data); return !data->has_error; case LDB_OP_APPROX: /* approx test */ asn1_push_tag(data, ASN1_CONTEXT(8)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_EXTENDED: /* MatchingRuleAssertion ::= SEQUENCE { matchingRule [1] MatchingRuleID OPTIONAL, type [2] AttributeDescription OPTIONAL, matchValue [3] AssertionValue, dnAttributes [4] BOOLEAN DEFAULT FALSE } */ asn1_push_tag(data, ASN1_CONTEXT(9)); if (tree->u.extended.rule_id) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1)); asn1_write_LDAPString(data, tree->u.extended.rule_id); asn1_pop_tag(data); } if (tree->u.extended.attr) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2)); asn1_write_LDAPString(data, tree->u.extended.attr); asn1_pop_tag(data); } asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3)); asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value); asn1_pop_tag(data); asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4)); asn1_write_uint8(data, tree->u.extended.dnAttributes); asn1_pop_tag(data); asn1_pop_tag(data); break; default: return false; } return !data->has_error; } CWE ID: CWE-399 Target: 1 Example 2: Code: AppProto AppLayerProtoDetectGetProtoByName(const char *alproto_name) { SCEnter(); AppProto a; for (a = 0; a < ALPROTO_MAX; a++) { if (alpd_ctx.alproto_names[a] != NULL && strlen(alpd_ctx.alproto_names[a]) == strlen(alproto_name) && (SCMemcmp(alpd_ctx.alproto_names[a], alproto_name, strlen(alproto_name)) == 0)) { SCReturnCT(a, "AppProto"); } } SCReturnCT(ALPROTO_UNKNOWN, "AppProto"); } 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 inline u32 nfsd4_readlink_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op) { return (op_encode_hdr_size + 1) * sizeof(__be32) + PAGE_SIZE; } CWE ID: CWE-404 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) { goto end; } if (IPV4_GET_HLEN(reassembled) != 20) { goto end; } if (IPV4_GET_IPLEN(reassembled) != 39) { goto end; } /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') { goto end; } } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') { goto end; } } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; } CWE ID: CWE-358 Target: 1 Example 2: Code: static int ocfs2_readpage_inline(struct inode *inode, struct page *page) { int ret; struct buffer_head *di_bh = NULL; BUG_ON(!PageLocked(page)); BUG_ON(!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)); ret = ocfs2_read_inode_block(inode, &di_bh); if (ret) { mlog_errno(ret); goto out; } ret = ocfs2_read_inline_data(inode, page, di_bh); out: unlock_page(page); brelse(di_bh); 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: int yr_object_array_set_item( YR_OBJECT* object, YR_OBJECT* item, int index) { YR_OBJECT_ARRAY* array; int i; int count; assert(index >= 0); assert(object->type == OBJECT_TYPE_ARRAY); array = object_as_array(object); if (array->items == NULL) { count = yr_max(64, (index + 1) * 2); array->items = (YR_ARRAY_ITEMS*) yr_malloc( sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(array->items->objects, 0, count * sizeof(YR_OBJECT*)); array->items->count = count; } else if (index >= array->items->count) { count = array->items->count * 2; array->items = (YR_ARRAY_ITEMS*) yr_realloc( array->items, sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = array->items->count; i < count; i++) array->items->objects[i] = NULL; array->items->count = count; } item->parent = object; array->items->objects[index] = item; return ERROR_SUCCESS; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: nfs3svc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readargs *args) { unsigned int len; int v; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); len = min(args->count, max_blocksize); /* set up the kvec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return xdr_argsize_check(rqstp, p); } CWE ID: CWE-404 Target: 1 Example 2: Code: GLenum Framebuffer::GetColorAttachmentFormat() const { AttachmentMap::const_iterator it = attachments_.find(GL_COLOR_ATTACHMENT0); if (it == attachments_.end()) { return 0; } const Attachment* attachment = it->second.get(); return attachment->internal_format(); } 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 RenderLayerCompositor::removeCompositedChildren(RenderLayer* layer) { ASSERT(layer->hasCompositedLayerMapping()); GraphicsLayer* hostingLayer = layer->compositedLayerMapping()->parentForSublayers(); hostingLayer->removeAllChildren(); } 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 MediaControlVolumeSliderElement::defaultEventHandler(Event* event) { if (event->isMouseEvent() && toMouseEvent(event)->button() != static_cast<short>(WebPointerProperties::Button::Left)) return; if (!isConnected() || !document().isActive()) return; MediaControlInputElement::defaultEventHandler(event); if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove) return; if (event->type() == EventTypeNames::mousedown) Platform::current()->recordAction( UserMetricsAction("Media.Controls.VolumeChangeBegin")); if (event->type() == EventTypeNames::mouseup) Platform::current()->recordAction( UserMetricsAction("Media.Controls.VolumeChangeEnd")); double volume = value().toDouble(); mediaElement().setVolume(volume); mediaElement().setMuted(false); } CWE ID: CWE-119 Target: 1 Example 2: Code: void BackgroundLoaderOffliner::CanDownload( base::OnceCallback<void(bool)> callback) { if (!pending_request_.get()) { std::move(callback).Run(false); // Shouldn't happen though... return; } bool should_allow_downloads = false; Offliner::RequestStatus final_status = Offliner::RequestStatus::LOADING_FAILED_DOWNLOAD; if (offline_page_model_->GetPolicyController() ->AllowsConversionToBackgroundFileDownload( pending_request_.get()->client_id().name_space)) { should_allow_downloads = true; final_status = Offliner::RequestStatus::DOWNLOAD_THROTTLED; } std::move(callback).Run(should_allow_downloads); SavePageRequest request(*pending_request_.get()); std::move(completion_callback_).Run(request, final_status); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&BackgroundLoaderOffliner::ResetState, weak_ptr_factory_.GetWeakPtr())); } 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 vmxnet3_interrupt_asserted(VMXNET3State *s, int lidx) { return s->interrupt_states[lidx].is_asserted; } 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 DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ if((i->width > i->parent->width) || (i->height > i->parent->height)) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n"); #endif return -1; } if((i->posX + i->width) > i->parent->width) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n"); #endif i->posX = i->parent->width - i->width; } if((i->posY + i->height) > i->parent->height) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n"); #endif i->posY = i->parent->height - i->height; } context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; k<localpalsize; k++) { i->palette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, "interlaced "); fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le "buffer" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); casspecial = (u8)act_code; old_code = act_code; WritePixel(i, &context, casspecial); npix--; } else { read_byt = act_code; if(act_code >= free) { /* code pas encore dans alphabet */ /* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf("actcode=%d\n", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return 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: init_ext2_xattr(void) { ext2_xattr_cache = mb_cache_create("ext2_xattr", 6); if (!ext2_xattr_cache) return -ENOMEM; return 0; } CWE ID: CWE-19 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 altivec_unavailable_exception(struct pt_regs *regs) { #if !defined(CONFIG_ALTIVEC) if (user_mode(regs)) { /* A user program has executed an altivec instruction, but this kernel doesn't support altivec. */ _exception(SIGILL, regs, ILL_ILLOPC, regs->nip); return; } #endif printk(KERN_EMERG "Unrecoverable VMX/Altivec Unavailable Exception " "%lx at %lx\n", regs->trap, regs->nip); die("Unrecoverable VMX/Altivec Unavailable Exception", regs, SIGABRT); } CWE ID: CWE-19 Target: 1 Example 2: Code: void Con_CheckResize( void ) { int i, j, width, oldwidth, oldtotallines, numlines, numchars; short tbuf[CON_TEXTSIZE]; width = ( SCREEN_WIDTH / SMALLCHAR_WIDTH ) - 2; if ( width == con.linewidth ) { return; } if ( width < 1 ) { // video hasn't been initialized yet width = DEFAULT_CONSOLE_WIDTH; con.linewidth = width; con.totallines = CON_TEXTSIZE / con.linewidth; for ( i = 0; i < CON_TEXTSIZE; i++ ) con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' '; } else { oldwidth = con.linewidth; con.linewidth = width; oldtotallines = con.totallines; con.totallines = CON_TEXTSIZE / con.linewidth; numlines = oldtotallines; if ( con.totallines < numlines ) { numlines = con.totallines; } numchars = oldwidth; if ( con.linewidth < numchars ) { numchars = con.linewidth; } memcpy( tbuf, con.text, CON_TEXTSIZE * sizeof( short ) ); for ( i = 0; i < CON_TEXTSIZE; i++ ) con.text[i] = ( ColorIndex( COLNSOLE_COLOR ) << 8 ) | ' '; for ( i = 0 ; i < numlines ; i++ ) { for ( j = 0 ; j < numchars ; j++ ) { con.text[( con.totallines - 1 - i ) * con.linewidth + j] = tbuf[( ( con.current - i + oldtotallines ) % oldtotallines ) * oldwidth + j]; } } Con_ClearNotify(); } con.current = con.totallines - 1; con.display = con.current; } CWE ID: CWE-269 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void lua_insert_filter_harness(request_rec *r) { /* ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "LuaHookInsertFilter not yet implemented"); */ } 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: bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper, NaClSubprocess* subprocess, const Manifest* manifest, bool should_report_uma, ErrorInfo* error_info, pp::CompletionCallback init_done_cb, pp::CompletionCallback crash_cb) { ServiceRuntime* new_service_runtime = new ServiceRuntime(this, manifest, should_report_uma, init_done_cb, crash_cb); subprocess->set_service_runtime(new_service_runtime); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n", static_cast<void*>(new_service_runtime))); if (NULL == new_service_runtime) { error_info->SetReport(ERROR_SEL_LDR_INIT, "sel_ldr init failure " + subprocess->description()); return false; } bool service_runtime_started = new_service_runtime->Start(wrapper, error_info, manifest_base_url()); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n", service_runtime_started)); if (!service_runtime_started) { return false; } const PPB_NaCl_Private* ppb_nacl = GetNaclInterface(); if (ppb_nacl->StartPpapiProxy(pp_instance())) { using_ipc_proxy_ = true; CHECK(init_done_cb.pp_completion_callback().func != NULL); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon, started ipc proxy.\n")); pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb, PP_OK); } return true; } CWE ID: CWE-399 Target: 1 Example 2: Code: void ClearResources() { for (int i = 0; i < num_ui_resources_; i++) ui_resources_[i] = nullptr; } 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 Instance::NavigateTo(const std::string& url, bool open_in_new_tab) { std::string url_copy(url); if (!url_copy.empty()) { if (url_copy[0] == '#') { url_copy = url_ + url_copy; if (!open_in_new_tab) { int page_number = GetInitialPage(url_copy); if (page_number >= 0) ScrollToPage(page_number); } } if (url_copy.find("://") == std::string::npos && url_copy.find("mailto:") == std::string::npos) { url_copy = "http://" + url_copy; } if (url_copy.find("http://") != 0 && url_copy.find("https://") != 0 && url_copy.find("ftp://") != 0 && url_copy.find("file://") != 0 && url_copy.find("mailto:") != 0) { return; } if (url_copy == "http://" || url_copy == "https://" || url_copy == "ftp://" || url_copy == "file://" || url_copy == "mailto:") { return; } } if (open_in_new_tab) { GetWindowObject().Call("open", url_copy); } else { GetWindowObject().GetProperty("top").GetProperty("location"). SetProperty("href", url_copy); } } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 **pissuer, int *pscore, unsigned int *preasons, STACK_OF(X509_CRL) *crls) { int i, crl_score, best_score = *pscore; unsigned int reasons, best_reasons = 0; X509 *x = ctx->current_cert; X509_CRL *crl, *best_crl = NULL; X509 *crl_issuer = NULL, *best_crl_issuer = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); reasons = *preasons; crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); if (crl_score < best_score) continue; /* If current CRL is equivalent use it if it is newer */ if (crl_score == best_score) { int day, sec; if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl), X509_CRL_get_lastUpdate(crl)) == 0) continue; /* * ASN1_TIME_diff never returns inconsistent signs for |day| * and |sec|. */ if (day <= 0 && sec <= 0) continue; } best_crl = crl; best_crl_issuer = crl_issuer; best_score = crl_score; best_reasons = reasons; } if (best_crl) { if (*pcrl) X509_CRL_free(*pcrl); *pcrl = best_crl; *pissuer = best_crl_issuer; *pscore = best_score; *preasons = best_reasons; CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL); if (*pdcrl) { X509_CRL_free(*pdcrl); *pdcrl = NULL; } get_delta_sk(ctx, pdcrl, pscore, best_crl, crls); } if (best_score >= CRL_SCORE_VALID) return 1; return 0; } CWE ID: CWE-476 Target: 1 Example 2: Code: ReadUserLogState::ScoreFile( const StatStructType &statbuf, int rot ) const { int score = 0; if ( rot < 0 ) { rot = m_cur_rot; } bool is_recent = ( time(NULL) < (m_update_time + m_recent_thresh) ); bool is_current = ( rot == m_cur_rot ); bool same_size = ( statbuf.st_size == m_stat_buf.st_size ); bool has_grown = ( statbuf.st_size > m_stat_buf.st_size ); MyString MatchList = ""; // For debugging if ( m_stat_buf.st_ino == statbuf.st_ino ) { score += m_score_fact_inode; if ( DebugFlags & D_FULLDEBUG ) MatchList += "inode "; } if ( m_stat_buf.st_ctime == statbuf.st_ctime ) { score += m_score_fact_ctime; if ( DebugFlags & D_FULLDEBUG ) MatchList += "ctime "; } if ( same_size ) { score += m_score_fact_same_size; if ( DebugFlags & D_FULLDEBUG ) MatchList += "same-size "; } else if ( is_recent && is_current && has_grown ) { score += m_score_fact_grown; if ( DebugFlags & D_FULLDEBUG ) MatchList += "grown "; } if ( m_stat_buf.st_size > statbuf.st_size ) { score += m_score_fact_shrunk; if ( DebugFlags & D_FULLDEBUG ) MatchList += "shrunk "; } if ( DebugFlags & D_FULLDEBUG ) { dprintf( D_FULLDEBUG, "ScoreFile: match list: %s\n", MatchList.Value() ); } if ( score < 0 ) { score = 0; } return score; } CWE ID: CWE-134 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type) { M_list_str_t *parts; const char *part; char *out; size_t len; size_t i; size_t count; if (path == NULL) { return NULL; } len = M_list_str_len(path); if (len == 0) { return NULL; } sys_type = M_fs_path_get_system_type(sys_type); /* Remove any empty parts (except for the first part which denotes an abs path on Unix * or a UNC path on Windows). */ parts = M_list_str_duplicate(path); for (i=len-1; i>0; i--) { part = M_list_str_at(parts, i); if (part == NULL || *part == '\0') { M_list_str_remove_at(parts, i); } } len = M_list_str_len(parts); /* Join puts the sep between items. If there are no items then the sep * won't be written. */ part = M_list_str_at(parts, 0); if (len == 1 && (part == NULL || *part == '\0')) { M_list_str_destroy(parts); if (sys_type == M_FS_SYSTEM_WINDOWS) { return M_strdup("\\\\"); } return M_strdup("/"); } /* Handle windows abs path because they need two separators. */ if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) { part = M_list_str_at(parts, 0); /* If we have 1 item we need to add two empties so we get the second separator. */ count = (len == 1) ? 2 : 1; /* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */ if (part != NULL && *part == '\0') { for (i=0; i<count; i++) { M_list_str_insert_at(parts, "", 0); } } else if (M_fs_path_isabs(part, sys_type) && len == 1) { /* We need to add an empty so we get a separator after the drive. */ M_list_str_insert_at(parts, "", 1); } } out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type)); M_list_str_destroy(parts); return out; } CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void do_free_upto(BIO *f, BIO *upto) { if (upto) { BIO *tbio; do { tbio = BIO_pop(f); BIO_free(f); f = tbio; } while (f != upto); } else BIO_free_all(f); } CWE ID: CWE-399 Target: 1 Example 2: Code: void WebGLRenderingContextBase::SetIsHidden(bool hidden) { is_hidden_ = hidden; if (GetDrawingBuffer()) GetDrawingBuffer()->SetIsHidden(hidden); if (!hidden && isContextLost() && restore_allowed_ && auto_recovery_method_ == kAuto) { DCHECK(!restore_timer_.IsActive()); restore_timer_.StartOneShot(0, BLINK_FROM_HERE); } } 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: _shift_data_right_pages(struct page **pages, size_t pgto_base, size_t pgfrom_base, size_t len) { struct page **pgfrom, **pgto; char *vfrom, *vto; size_t copy; BUG_ON(pgto_base <= pgfrom_base); pgto_base += len; pgfrom_base += len; pgto = pages + (pgto_base >> PAGE_CACHE_SHIFT); pgfrom = pages + (pgfrom_base >> PAGE_CACHE_SHIFT); pgto_base &= ~PAGE_CACHE_MASK; pgfrom_base &= ~PAGE_CACHE_MASK; do { /* Are any pointers crossing a page boundary? */ if (pgto_base == 0) { pgto_base = PAGE_CACHE_SIZE; pgto--; } if (pgfrom_base == 0) { pgfrom_base = PAGE_CACHE_SIZE; pgfrom--; } copy = len; if (copy > pgto_base) copy = pgto_base; if (copy > pgfrom_base) copy = pgfrom_base; pgto_base -= copy; pgfrom_base -= copy; vto = kmap_atomic(*pgto, KM_USER0); vfrom = kmap_atomic(*pgfrom, KM_USER1); memmove(vto + pgto_base, vfrom + pgfrom_base, copy); flush_dcache_page(*pgto); kunmap_atomic(vfrom, KM_USER1); kunmap_atomic(vto, KM_USER0); } while ((len -= copy) != 0); } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ReturnsValidPath(int dir_type) { base::FilePath path; bool result = PathService::Get(dir_type, &path); bool check_path_exists = true; #if defined(OS_POSIX) if (dir_type == base::DIR_CACHE) check_path_exists = false; #endif #if defined(OS_LINUX) if (dir_type == base::DIR_USER_DESKTOP) check_path_exists = false; #endif #if defined(OS_WIN) if (dir_type == base::DIR_DEFAULT_USER_QUICK_LAUNCH) { if (base::win::GetVersion() < base::win::VERSION_VISTA) { wchar_t default_profile_path[MAX_PATH]; DWORD size = arraysize(default_profile_path); return (result && ::GetDefaultUserProfileDirectory(default_profile_path, &size) && StartsWith(path.value(), default_profile_path, false)); } } else if (dir_type == base::DIR_TASKBAR_PINS) { if (base::win::GetVersion() < base::win::VERSION_WIN7) check_path_exists = false; } #endif #if defined(OS_MAC) if (dir_type != base::DIR_EXE && dir_type != base::DIR_MODULE && dir_type != base::FILE_EXE && dir_type != base::FILE_MODULE) { if (path.ReferencesParent()) return false; } #else if (path.ReferencesParent()) return false; #endif return result && !path.empty() && (!check_path_exists || file_util::PathExists(path)); } CWE ID: CWE-264 Target: 1 Example 2: Code: bool ChromotingInstance::ParseAuthMethods(const std::string& auth_methods_str, ClientConfig* config) { std::vector<std::string> auth_methods; base::SplitString(auth_methods_str, ',', &auth_methods); for (std::vector<std::string>::iterator it = auth_methods.begin(); it != auth_methods.end(); ++it) { protocol::AuthenticationMethod authentication_method = protocol::AuthenticationMethod::FromString(*it); if (authentication_method.is_valid()) config->authentication_methods.push_back(authentication_method); } if (config->authentication_methods.empty()) { LOG(ERROR) << "No valid authentication methods specified."; return false; } return true; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ll_find_deltas(struct object_entry **list, unsigned list_size, int window, int depth, unsigned *processed) { struct thread_params *p; int i, ret, active_threads = 0; init_threaded_search(); if (delta_search_threads <= 1) { find_deltas(list, &list_size, window, depth, processed); cleanup_threaded_search(); return; } if (progress > pack_to_stdout) fprintf(stderr, "Delta compression using up to %d threads.\n", delta_search_threads); p = xcalloc(delta_search_threads, sizeof(*p)); /* Partition the work amongst work threads. */ for (i = 0; i < delta_search_threads; i++) { unsigned sub_size = list_size / (delta_search_threads - i); /* don't use too small segments or no deltas will be found */ if (sub_size < 2*window && i+1 < delta_search_threads) sub_size = 0; p[i].window = window; p[i].depth = depth; p[i].processed = processed; p[i].working = 1; p[i].data_ready = 0; /* try to split chunks on "path" boundaries */ while (sub_size && sub_size < list_size && list[sub_size]->hash && list[sub_size]->hash == list[sub_size-1]->hash) sub_size++; p[i].list = list; p[i].list_size = sub_size; p[i].remaining = sub_size; list += sub_size; list_size -= sub_size; } /* Start work threads. */ for (i = 0; i < delta_search_threads; i++) { if (!p[i].list_size) continue; pthread_mutex_init(&p[i].mutex, NULL); pthread_cond_init(&p[i].cond, NULL); ret = pthread_create(&p[i].thread, NULL, threaded_find_deltas, &p[i]); if (ret) die("unable to create thread: %s", strerror(ret)); active_threads++; } /* * Now let's wait for work completion. Each time a thread is done * with its work, we steal half of the remaining work from the * thread with the largest number of unprocessed objects and give * it to that newly idle thread. This ensure good load balancing * until the remaining object list segments are simply too short * to be worth splitting anymore. */ while (active_threads) { struct thread_params *target = NULL; struct thread_params *victim = NULL; unsigned sub_size = 0; progress_lock(); for (;;) { for (i = 0; !target && i < delta_search_threads; i++) if (!p[i].working) target = &p[i]; if (target) break; pthread_cond_wait(&progress_cond, &progress_mutex); } for (i = 0; i < delta_search_threads; i++) if (p[i].remaining > 2*window && (!victim || victim->remaining < p[i].remaining)) victim = &p[i]; if (victim) { sub_size = victim->remaining / 2; list = victim->list + victim->list_size - sub_size; while (sub_size && list[0]->hash && list[0]->hash == list[-1]->hash) { list++; sub_size--; } if (!sub_size) { /* * It is possible for some "paths" to have * so many objects that no hash boundary * might be found. Let's just steal the * exact half in that case. */ sub_size = victim->remaining / 2; list -= sub_size; } target->list = list; victim->list_size -= sub_size; victim->remaining -= sub_size; } target->list_size = sub_size; target->remaining = sub_size; target->working = 1; progress_unlock(); pthread_mutex_lock(&target->mutex); target->data_ready = 1; pthread_cond_signal(&target->cond); pthread_mutex_unlock(&target->mutex); if (!sub_size) { pthread_join(target->thread, NULL); pthread_cond_destroy(&target->cond); pthread_mutex_destroy(&target->mutex); active_threads--; } } cleanup_threaded_search(); free(p); } 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: xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name = NULL; xmlChar *ExternalID = NULL; xmlChar *URI = NULL; /* * We know that '<!DOCTYPE' has been detected. */ SKIP(9); SKIP_BLANKS; /* * Parse the DOCTYPE name. */ name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseDocTypeDecl : no DOCTYPE name !\n"); } ctxt->intSubName = name; SKIP_BLANKS; /* * Check for SystemID and ExternalID */ URI = xmlParseExternalID(ctxt, &ExternalID, 1); if ((URI != NULL) || (ExternalID != NULL)) { ctxt->hasExternalSubset = 1; } ctxt->extSubURI = URI; ctxt->extSubSystem = ExternalID; SKIP_BLANKS; /* * Create and update the internal subset. */ if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); /* * Is there any internal subset declarations ? * they are handled separately in xmlParseInternalSubset() */ if (RAW == '[') return; /* * We should be at the end of the DOCTYPE declaration. */ if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL); } NEXT; } CWE ID: CWE-119 Target: 1 Example 2: Code: ptaCopy(PTA *pta) { l_int32 i; l_float32 x, y; PTA *npta; PROCNAME("ptaCopy"); if (!pta) return (PTA *)ERROR_PTR("pta not defined", procName, NULL); if ((npta = ptaCreate(pta->nalloc)) == NULL) return (PTA *)ERROR_PTR("npta not made", procName, NULL); for (i = 0; i < pta->n; i++) { ptaGetPt(pta, i, &x, &y); ptaAddPt(npta, x, y); } return npta; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int am_check_url(request_rec *r, const char *url) { const char *i; for (i = url; *i; i++) { if (*i >= 0 && *i < ' ') { /* Deny all control-characters. */ AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r, "Control character detected in URL."); return HTTP_BAD_REQUEST; } } return OK; } CWE ID: CWE-601 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 asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) { CWE ID: CWE-400 Target: 1 Example 2: Code: int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent) { return 1; } 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: g_NPN_InvalidateRect(NPP instance, NPRect *invalidRect) { if (!thread_check()) { npw_printf("WARNING: NPN_InvalidateRect not called from the main thread\n"); return; } if (instance == NULL) return; PluginInstance *plugin = PLUGIN_INSTANCE(instance); if (plugin == NULL) return; if (invalidRect == NULL) return; D(bugiI("NPN_InvalidateRect instance=%p\n", PLUGIN_INSTANCE_NPP(plugin))); npw_plugin_instance_ref(plugin); invoke_NPN_InvalidateRect(plugin, invalidRect); npw_plugin_instance_unref(plugin); D(bugiD("NPN_InvalidateRect done\n")); } 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: WORD32 ih264d_parse_islice(dec_struct_t *ps_dec, UWORD16 u2_first_mb_in_slice) { dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst; UWORD32 u4_temp; WORD32 i_temp; WORD32 ret; /*--------------------------------------------------------------------*/ /* Read remaining contents of the slice header */ /*--------------------------------------------------------------------*/ /* dec_ref_pic_marking function */ /* G050 */ if(ps_slice->u1_nal_ref_idc != 0) { if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read) ps_dec->u4_bitoffset = ih264d_read_mmco_commands( ps_dec); else ps_dec->ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset; } /* G050 */ /* Read slice_qp_delta */ i_temp = ps_pps->u1_pic_init_qp + ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if((i_temp < 0) || (i_temp > 51)) return ERROR_INV_RANGE_QP_T; ps_slice->u1_slice_qp = i_temp; COPYTHECONTEXT("SH: slice_qp_delta", ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp); if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp); if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED) { return ERROR_INV_SLICE_HDR_T; } ps_slice->u1_disable_dblk_filter_idc = u4_temp; if(u4_temp != 1) { i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_alpha_c0_offset = i_temp; COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2", ps_slice->i1_slice_alpha_c0_offset >> 1); i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_beta_offset = i_temp; COPYTHECONTEXT("SH: slice_beta_offset_div2", ps_slice->i1_slice_beta_offset >> 1); } else { ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } } else { ps_slice->u1_disable_dblk_filter_idc = 0; ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } /* Initialization to check if number of motion vector per 2 Mbs */ /* are exceeding the range or not */ ps_dec->u2_mv_2mb[0] = 0; ps_dec->u2_mv_2mb[1] = 0; /*set slice header cone to 2 ,to indicate correct header*/ ps_dec->u1_slice_header_done = 2; if(ps_pps->u1_entropy_coding_mode) { SWITCHOFFTRACE; SWITCHONTRACECABAC; if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff; } else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff; ret = ih264d_parse_islice_data_cabac(ps_dec, ps_slice, u2_first_mb_in_slice); if(ret != OK) return ret; SWITCHONTRACE; SWITCHOFFTRACECABAC; } else { if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff; } else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff; ret = ih264d_parse_islice_data_cavlc(ps_dec, ps_slice, u2_first_mb_in_slice); if(ret != OK) return ret; } return OK; } CWE ID: CWE-119 Target: 1 Example 2: Code: int part_get_info(struct blk_desc *dev_desc, int part, disk_partition_t *info) { #ifdef CONFIG_HAVE_BLOCK_DEVICE struct part_driver *drv; #if CONFIG_IS_ENABLED(PARTITION_UUIDS) /* The common case is no UUID support */ info->uuid[0] = 0; #endif #ifdef CONFIG_PARTITION_TYPE_GUID info->type_guid[0] = 0; #endif drv = part_driver_lookup_type(dev_desc); if (!drv) { debug("## Unknown partition table type %x\n", dev_desc->part_type); return -EPROTONOSUPPORT; } if (!drv->get_info) { PRINTF("## Driver %s does not have the get_info() method\n", drv->name); return -ENOSYS; } if (drv->get_info(dev_desc, part, info) == 0) { PRINTF("## Valid %s partition found ##\n", drv->name); return 0; } #endif /* CONFIG_HAVE_BLOCK_DEVICE */ return -1; } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int null_compress(struct crypto_tfm *tfm, const u8 *src, unsigned int slen, u8 *dst, unsigned int *dlen) { if (slen > *dlen) return -EINVAL; memcpy(dst, src, slen); *dlen = slen; return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t* buf, int buf_size) { int size, i; uint8_t *ppcm[4] = {0}; if (buf_size < DV_PROFILE_BYTES || !(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) || buf_size < c->sys->frame_size) { return -1; /* Broken frame, or not enough data */ } /* Queueing audio packet */ /* FIXME: in case of no audio/bad audio we have to do something */ size = dv_extract_audio_info(c, buf); for (i = 0; i < c->ach; i++) { c->audio_pkt[i].size = size; c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate; ppcm[i] = c->audio_buf[i]; } dv_extract_audio(buf, ppcm, c->sys); /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ if (buf[1] & 0x0C) { c->audio_pkt[2].size = c->audio_pkt[3].size = 0; } else { c->audio_pkt[0].size = c->audio_pkt[1].size = 0; c->abytes += size; } } else { c->abytes += size; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int snd_seq_ioctl_client_id(struct snd_seq_client *client, void *arg) { int *client_id = arg; *client_id = client->number; return 0; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline int btif_hl_select_wakeup(void){ char sig_on = btif_hl_signal_select_wakeup; BTIF_TRACE_DEBUG("btif_hl_select_wakeup"); return send(signal_fds[1], &sig_on, sizeof(sig_on), 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 __get_data_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create, int flag, pgoff_t *next_pgofs) { struct f2fs_map_blocks map; int err; map.m_lblk = iblock; map.m_len = bh->b_size >> inode->i_blkbits; map.m_next_pgofs = next_pgofs; err = f2fs_map_blocks(inode, &map, create, flag); if (!err) { map_bh(bh, inode->i_sb, map.m_pblk); bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags; bh->b_size = map.m_len << inode->i_blkbits; } return err; } CWE ID: CWE-190 Target: 1 Example 2: Code: bool PageInfoUI::ContentSettingsTypeInPageInfo(ContentSettingsType type) { for (const PermissionsUIInfo& info : GetContentSettingsUIInfo()) { if (info.type == type) return true; } return false; } 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: uint32_t reds_get_mm_time(void) { struct timespec time_space; clock_gettime(CLOCK_MONOTONIC, &time_space); return time_space.tv_sec * 1000 + time_space.tv_nsec / 1000 / 1000; } 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: mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_TCHECK_16BITS(&bp[i+2]); ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_TCHECK_16BITS(&bp[i+2]); ND_TCHECK_16BITS(&bp[i+4]); ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; } CWE ID: CWE-125 Target: 1 Example 2: Code: void WebGL2RenderingContextBase::beginQuery(GLenum target, WebGLQuery* query) { bool deleted; DCHECK(query); if (!CheckObjectToBeBound("beginQuery", query, deleted)) return; if (deleted) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "attempted to begin a deleted query object"); return; } if (query->GetTarget() && query->GetTarget() != target) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "query type does not match target"); return; } switch (target) { case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: { if (current_boolean_occlusion_query_) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "a query is already active for target"); return; } current_boolean_occlusion_query_ = query; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: { if (current_transform_feedback_primitives_written_query_) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "a query is already active for target"); return; } current_transform_feedback_primitives_written_query_ = query; } break; case GL_TIME_ELAPSED_EXT: { if (!ExtensionEnabled(kEXTDisjointTimerQueryWebGL2Name)) { SynthesizeGLError(GL_INVALID_ENUM, "beginQuery", "invalid target"); return; } if (current_elapsed_query_) { SynthesizeGLError(GL_INVALID_OPERATION, "beginQuery", "a query is already active for target"); return; } current_elapsed_query_ = query; } break; default: SynthesizeGLError(GL_INVALID_ENUM, "beginQuery", "invalid target"); return; } if (!query->GetTarget()) query->SetTarget(target); ContextGL()->BeginQueryEXT(target, query->Object()); } 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 jspKill() { jspSoftKill(); JsVar *r = jsvFindOrCreateRoot(); jsvUnRef(r); jsvUnLock(r); } 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 inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data) { struct l2cap_conf_req *req = (struct l2cap_conf_req *) data; u16 dcid, flags; u8 rsp[64]; struct sock *sk; int len; dcid = __le16_to_cpu(req->dcid); flags = __le16_to_cpu(req->flags); BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags); sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid); if (!sk) return -ENOENT; if (sk->sk_state == BT_DISCONN) goto unlock; /* Reject if config buffer is too small. */ len = cmd_len - sizeof(*req); if (l2cap_pi(sk)->conf_len + len > sizeof(l2cap_pi(sk)->conf_req)) { l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, l2cap_build_conf_rsp(sk, rsp, L2CAP_CONF_REJECT, flags), rsp); goto unlock; } /* Store config. */ memcpy(l2cap_pi(sk)->conf_req + l2cap_pi(sk)->conf_len, req->data, len); l2cap_pi(sk)->conf_len += len; if (flags & 0x0001) { /* Incomplete config. Send empty response. */ l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, l2cap_build_conf_rsp(sk, rsp, L2CAP_CONF_SUCCESS, 0x0001), rsp); goto unlock; } /* Complete config. */ len = l2cap_parse_conf_req(sk, rsp); if (len < 0) goto unlock; l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp); /* Reset config buffer. */ l2cap_pi(sk)->conf_len = 0; if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE)) goto unlock; if (l2cap_pi(sk)->conf_state & L2CAP_CONF_INPUT_DONE) { sk->sk_state = BT_CONNECTED; l2cap_chan_ready(sk); goto unlock; } if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_REQ_SENT)) { u8 buf[64]; l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(sk, buf), buf); } unlock: bh_unlock_sock(sk); return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: struct ImapData *imap_conn_find(const struct Account *account, int flags) { struct Connection *conn = NULL; struct Account *creds = NULL; struct ImapData *idata = NULL; bool new = false; while ((conn = mutt_conn_find(conn, account))) { if (!creds) creds = &conn->account; else memcpy(&conn->account, creds, sizeof(struct Account)); idata = conn->data; if (flags & MUTT_IMAP_CONN_NONEW) { if (!idata) { /* This should only happen if we've come to the end of the list */ mutt_socket_free(conn); return NULL; } else if (idata->state < IMAP_AUTHENTICATED) continue; } if (flags & MUTT_IMAP_CONN_NOSELECT && idata && idata->state >= IMAP_SELECTED) continue; if (idata && idata->status == IMAP_FATAL) continue; break; } if (!conn) return NULL; /* this happens when the initial connection fails */ if (!idata) { /* The current connection is a new connection */ idata = imap_new_idata(); if (!idata) { mutt_socket_free(conn); return NULL; } conn->data = idata; idata->conn = conn; new = true; } if (idata->state == IMAP_DISCONNECTED) imap_open_connection(idata); if (idata->state == IMAP_CONNECTED) { if (imap_authenticate(idata) == IMAP_AUTH_SUCCESS) { idata->state = IMAP_AUTHENTICATED; FREE(&idata->capstr); new = true; if (idata->conn->ssf) mutt_debug(2, "Communication encrypted at %d bits\n", idata->conn->ssf); } else mutt_account_unsetpass(&idata->conn->account); } if (new && idata->state == IMAP_AUTHENTICATED) { /* capabilities may have changed */ imap_exec(idata, "CAPABILITY", IMAP_CMD_QUEUE); /* enable RFC6855, if the server supports that */ if (mutt_bit_isset(idata->capabilities, ENABLE)) imap_exec(idata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE); /* get root delimiter, '/' as default */ idata->delim = '/'; imap_exec(idata, "LIST \"\" \"\"", IMAP_CMD_QUEUE); /* we may need the root delimiter before we open a mailbox */ imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); } return idata; } CWE ID: CWE-77 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { PNGDecContext *psrc = src->priv_data; PNGDecContext *pdst = dst->priv_data; int ret; if (dst == src) return 0; ff_thread_release_buffer(dst, &pdst->picture); if (psrc->picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0) return ret; if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) { pdst->width = psrc->width; pdst->height = psrc->height; pdst->bit_depth = psrc->bit_depth; pdst->color_type = psrc->color_type; pdst->compression_type = psrc->compression_type; pdst->interlace_type = psrc->interlace_type; pdst->filter_type = psrc->filter_type; pdst->cur_w = psrc->cur_w; pdst->cur_h = psrc->cur_h; pdst->x_offset = psrc->x_offset; pdst->y_offset = psrc->y_offset; pdst->has_trns = psrc->has_trns; memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be)); pdst->dispose_op = psrc->dispose_op; memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette)); pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE); ff_thread_release_buffer(dst, &pdst->last_picture); if (psrc->last_picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0) return ret; ff_thread_release_buffer(dst, &pdst->previous_picture); if (psrc->previous_picture.f->data[0] && (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0) return ret; } return 0; } 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: virtual bool InputMethodIsActivated(const std::string& input_method_id) { scoped_ptr<InputMethodDescriptors> active_input_method_descriptors( GetActiveInputMethods()); for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) { if (active_input_method_descriptors->at(i).id == input_method_id) { return true; } } return false; } CWE ID: CWE-399 Target: 1 Example 2: Code: MagickExport void ResetImagePropertyIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->properties); } 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: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlXPathObjectPtr obj; xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } xmlXPathFreeObject(obj); } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } val = (long)((char *)cur - (char *)doc); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); } 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: xmlParsePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParsePEReference: no name\n"); return; } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return; } NEXT; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "Internal: %%%s; is not a parameter entity\n", name, NULL); } else if (ctxt->input->free != deallocblankswrapper) { input = xmlNewBlanksWrapperInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; } else { /* * TODO !!! * handle the extra spaces added before and after * c.f. http://www.w3.org/TR/REC-xml#as-PE */ input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing * right here */ ctxt->instate = XML_PARSER_EOF; return; } } } } ctxt->hasPErefs = 1; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int rio_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct netdev_private *np = netdev_priv(dev); if (np->phy_media) { /* fiber device */ cmd->supported = SUPPORTED_Autoneg | SUPPORTED_FIBRE; cmd->advertising= ADVERTISED_Autoneg | ADVERTISED_FIBRE; cmd->port = PORT_FIBRE; cmd->transceiver = XCVR_INTERNAL; } else { /* copper device */ cmd->supported = SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_1000baseT_Full | SUPPORTED_Autoneg | SUPPORTED_MII; cmd->advertising = ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | ADVERTISED_1000baseT_Full| ADVERTISED_Autoneg | ADVERTISED_MII; cmd->port = PORT_MII; cmd->transceiver = XCVR_INTERNAL; } if ( np->link_status ) { ethtool_cmd_speed_set(cmd, np->speed); cmd->duplex = np->full_duplex ? DUPLEX_FULL : DUPLEX_HALF; } else { ethtool_cmd_speed_set(cmd, -1); cmd->duplex = -1; } if ( np->an_enable) cmd->autoneg = AUTONEG_ENABLE; else cmd->autoneg = AUTONEG_DISABLE; cmd->phy_address = np->phy_addr; 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: Extension::State ExtensionPrefs::GetExtensionState( const std::string& extension_id) const { const DictionaryValue* extension = GetExtensionPref(extension_id); if (!extension) return Extension::ENABLED; int state = -1; if (!extension->GetInteger(kPrefState, &state) || state < 0 || state >= Extension::NUM_STATES) { LOG(ERROR) << "Bad or missing pref 'state' for extension '" << extension_id << "'"; return Extension::ENABLED; } return static_cast<Extension::State>(state); } 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: SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } CWE ID: CWE-190 Target: 1 Example 2: Code: static int __init cma_init(void) { int ret; cma_wq = create_singlethread_workqueue("rdma_cm"); if (!cma_wq) return -ENOMEM; ib_sa_register_client(&sa_client); rdma_addr_register_client(&addr_client); register_netdevice_notifier(&cma_nb); ret = ib_register_client(&cma_client); if (ret) goto err; if (ibnl_add_client(RDMA_NL_RDMA_CM, RDMA_NL_RDMA_CM_NUM_OPS, cma_cb_table)) printk(KERN_WARNING "RDMA CMA: failed to add netlink callback\n"); return 0; err: unregister_netdevice_notifier(&cma_nb); rdma_addr_unregister_client(&addr_client); ib_sa_unregister_client(&sa_client); destroy_workqueue(cma_wq); return ret; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr); close(sk); return 0; } CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE SoftVPXEncoder::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR param) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: return internalSetBitrateParams( (const OMX_VIDEO_PARAM_BITRATETYPE *)param); case OMX_IndexParamVideoVp8: return internalSetVp8Params( (const OMX_VIDEO_PARAM_VP8TYPE *)param); case OMX_IndexParamVideoAndroidVp8Encoder: return internalSetAndroidVp8Params( (const OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *)param); default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, param); } } CWE ID: CWE-119 Target: 1 Example 2: Code: str_to_nat_range(const char *s, struct ofpact_nat *on) { char ipv6_s[IPV6_SCAN_LEN + 1]; int n = 0; on->range_af = AF_UNSPEC; if (ovs_scan_len(s, &n, IP_SCAN_FMT, IP_SCAN_ARGS(&on->range.addr.ipv4.min))) { on->range_af = AF_INET; if (s[n] == '-') { n++; if (!ovs_scan_len(s, &n, IP_SCAN_FMT, IP_SCAN_ARGS(&on->range.addr.ipv4.max)) || (ntohl(on->range.addr.ipv4.max) < ntohl(on->range.addr.ipv4.min))) { goto error; } } } else if ((ovs_scan_len(s, &n, IPV6_SCAN_FMT, ipv6_s) || ovs_scan_len(s, &n, "["IPV6_SCAN_FMT"]", ipv6_s)) && inet_pton(AF_INET6, ipv6_s, &on->range.addr.ipv6.min) == 1) { on->range_af = AF_INET6; if (s[n] == '-') { n++; if (!(ovs_scan_len(s, &n, IPV6_SCAN_FMT, ipv6_s) || ovs_scan_len(s, &n, "["IPV6_SCAN_FMT"]", ipv6_s)) || inet_pton(AF_INET6, ipv6_s, &on->range.addr.ipv6.max) != 1 || memcmp(&on->range.addr.ipv6.max, &on->range.addr.ipv6.min, sizeof on->range.addr.ipv6.max) < 0) { goto error; } } } if (on->range_af != AF_UNSPEC && s[n] == ':') { n++; if (!ovs_scan_len(s, &n, "%"SCNu16, &on->range.proto.min)) { goto error; } if (s[n] == '-') { n++; if (!ovs_scan_len(s, &n, "%"SCNu16, &on->range.proto.max) || on->range.proto.max < on->range.proto.min) { goto error; } } } if (strlen(s) != n) { return xasprintf("garbage (%s) after nat range \"%s\" (pos: %d)", &s[n], s, n); } return NULL; error: return xasprintf("invalid nat range \"%s\"", s); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int trigger_fpga_config(void) { int ret = 0; /* if the FPGA is already configured, we do not want to * reconfigure it */ skip = 0; if (fpga_done()) { printf("PCIe FPGA config: skipped\n"); skip = 1; return 0; } if (check_boco2()) { /* we have a BOCO2, this has to be triggered here */ /* make sure the FPGA_can access the EEPROM */ ret = boco_clear_bits(SPI_REG, CFG_EEPROM); if (ret) return ret; /* trigger the config start */ ret = boco_clear_bits(SPI_REG, FPGA_PROG | FPGA_INIT_B); if (ret) return ret; /* small delay for the pulse */ udelay(10); /* up signal for pulse end */ ret = boco_set_bits(SPI_REG, FPGA_PROG); if (ret) return ret; /* finally, raise INIT_B to remove the config delay */ ret = boco_set_bits(SPI_REG, FPGA_INIT_B); if (ret) return ret; } else { /* we do it the old way, with the gpio pin */ kw_gpio_set_valid(KM_XLX_PROGRAM_B_PIN, 1); kw_gpio_direction_output(KM_XLX_PROGRAM_B_PIN, 0); /* small delay for the pulse */ udelay(10); kw_gpio_direction_input(KM_XLX_PROGRAM_B_PIN); } return 0; } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct mount *clone_mnt(struct mount *old, struct dentry *root, int flag) { struct super_block *sb = old->mnt.mnt_sb; struct mount *mnt; int err; mnt = alloc_vfsmnt(old->mnt_devname); if (!mnt) return ERR_PTR(-ENOMEM); if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE)) mnt->mnt_group_id = 0; /* not a peer of original */ else mnt->mnt_group_id = old->mnt_group_id; if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) { err = mnt_alloc_group_id(mnt); if (err) goto out_free; } mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~(MNT_WRITE_HOLD|MNT_MARKED); /* Don't allow unprivileged users to change mount flags */ if ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY)) mnt->mnt.mnt_flags |= MNT_LOCK_READONLY; /* Don't allow unprivileged users to reveal what is under a mount */ if ((flag & CL_UNPRIVILEGED) && list_empty(&old->mnt_expire)) mnt->mnt.mnt_flags |= MNT_LOCKED; atomic_inc(&sb->s_active); mnt->mnt.mnt_sb = sb; mnt->mnt.mnt_root = dget(root); mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; lock_mount_hash(); list_add_tail(&mnt->mnt_instance, &sb->s_mounts); unlock_mount_hash(); if ((flag & CL_SLAVE) || ((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) { list_add(&mnt->mnt_slave, &old->mnt_slave_list); mnt->mnt_master = old; CLEAR_MNT_SHARED(mnt); } else if (!(flag & CL_PRIVATE)) { if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old)) list_add(&mnt->mnt_share, &old->mnt_share); if (IS_MNT_SLAVE(old)) list_add(&mnt->mnt_slave, &old->mnt_slave); mnt->mnt_master = old->mnt_master; } if (flag & CL_MAKE_SHARED) set_mnt_shared(mnt); /* stick the duplicate mount on the same expiry list * as the original if that was on one */ if (flag & CL_EXPIRE) { if (!list_empty(&old->mnt_expire)) list_add(&mnt->mnt_expire, &old->mnt_expire); } return mnt; out_free: mnt_free_id(mnt); free_vfsmnt(mnt); return ERR_PTR(err); } CWE ID: CWE-264 Target: 1 Example 2: Code: GF_Err stsg_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->grouping_type); gf_bs_write_u16(bs, ptr->nb_groups); for (i = 0; i < ptr->nb_groups; i++) { gf_bs_write_u32(bs, ptr->group_description_index[i]); } 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: int CLASS fgetc(FILE *stream) { int chr = ::fgetc(stream); if (stream==ifp) ifpProgress(1); return chr; } 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: EncodedJSValue JSC_HOST_CALL JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor(ExecState* exec) { JSTestNamedConstructorNamedConstructor* castedThis = jsCast<JSTestNamedConstructorNamedConstructor*>(exec->callee()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); ExceptionCode ec = 0; const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str3(ustringToString(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); RefPtr<TestNamedConstructor> object = TestNamedConstructor::createForJSConstructor(castedThis->document(), str1, str2, str3, ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get()))); } CWE ID: CWE-20 Target: 1 Example 2: Code: static int get8_packet_raw(vorb *f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } 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 DateTimeChooserImpl::endChooser() { if (!m_popup) return; m_chromeClient->closePagePopup(m_popup); } CWE ID: CWE-22 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: void LocalFrame::DeviceScaleFactorChanged() { GetDocument()->MediaQueryAffectingValueChanged(); GetDocument()->SetNeedsStyleRecalc( kSubtreeStyleChange, StyleChangeReasonForTracing::Create(StyleChangeReason::kZoom)); for (Frame* child = Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) ToLocalFrame(child)->DeviceScaleFactorChanged(); } } CWE ID: CWE-285 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebMediaPlayerImpl::OnFrameHidden() { DCHECK(main_task_runner_->BelongsToCurrentThread()); if (IsHidden()) video_locked_when_paused_when_hidden_ = true; if (watch_time_reporter_) watch_time_reporter_->OnHidden(); if (video_decode_stats_reporter_) video_decode_stats_reporter_->OnHidden(); UpdateBackgroundVideoOptimizationState(); UpdatePlayState(); ScheduleIdlePauseTimer(); } CWE ID: CWE-732 Output:
0
Here are some example code snippets. Analyze the following 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 EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod3(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(strArg); return JSValue::encode(jsUndefined()); } CWE ID: CWE-20 Target: 1 Example 2: Code: void irc_servers_reconnect_deinit(void) { signal_remove("server connect copy", (SIGNAL_FUNC) sig_server_connect_copy); signal_remove("server reconnect save status", (SIGNAL_FUNC) sig_server_reconnect_save_status); signal_remove("event connected", (SIGNAL_FUNC) sig_connected); signal_remove("event 436", (SIGNAL_FUNC) event_nick_collision); signal_remove("event kill", (SIGNAL_FUNC) event_kill); } 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: OJPEGCleanup(TIFF* tif) { OJPEGState* sp=(OJPEGState*)tif->tif_data; if (sp!=0) { tif->tif_tagmethods.vgetfield=sp->vgetparent; tif->tif_tagmethods.vsetfield=sp->vsetparent; tif->tif_tagmethods.printdir=sp->printdir; if (sp->qtable[0]!=0) _TIFFfree(sp->qtable[0]); if (sp->qtable[1]!=0) _TIFFfree(sp->qtable[1]); if (sp->qtable[2]!=0) _TIFFfree(sp->qtable[2]); if (sp->qtable[3]!=0) _TIFFfree(sp->qtable[3]); if (sp->dctable[0]!=0) _TIFFfree(sp->dctable[0]); if (sp->dctable[1]!=0) _TIFFfree(sp->dctable[1]); if (sp->dctable[2]!=0) _TIFFfree(sp->dctable[2]); if (sp->dctable[3]!=0) _TIFFfree(sp->dctable[3]); if (sp->actable[0]!=0) _TIFFfree(sp->actable[0]); if (sp->actable[1]!=0) _TIFFfree(sp->actable[1]); if (sp->actable[2]!=0) _TIFFfree(sp->actable[2]); if (sp->actable[3]!=0) _TIFFfree(sp->actable[3]); if (sp->libjpeg_session_active!=0) OJPEGLibjpegSessionAbort(tif); if (sp->subsampling_convert_ycbcrbuf!=0) _TIFFfree(sp->subsampling_convert_ycbcrbuf); if (sp->subsampling_convert_ycbcrimage!=0) _TIFFfree(sp->subsampling_convert_ycbcrimage); if (sp->skip_buffer!=0) _TIFFfree(sp->skip_buffer); _TIFFfree(sp); tif->tif_data=NULL; _TIFFSetDefaultCompressionState(tif); } } 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: static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "givcipher"); snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s", alg->cra_ablkcipher.geniv ?: "<built-in>"); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize; rblkcipher.ivsize = alg->cra_ablkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } CWE ID: CWE-310 Target: 1 Example 2: Code: void GetData(GtkClipboard* clipboard, GtkSelectionData* selection_data, guint info, gpointer user_data) { Clipboard::TargetMap* data_map = reinterpret_cast<Clipboard::TargetMap*>(user_data); std::string target_string = GdkAtomToString(selection_data->target); Clipboard::TargetMap::iterator iter = data_map->find(target_string); if (iter == data_map->end()) return; if (target_string == kMimeTypeBitmap) { gtk_selection_data_set_pixbuf(selection_data, reinterpret_cast<GdkPixbuf*>(iter->second.first)); } else { gtk_selection_data_set(selection_data, selection_data->target, 8, reinterpret_cast<guchar*>(iter->second.first), iter->second.second); } } 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: call_refreshresult(struct rpc_task *task) { int status = task->tk_status; dprint_status(task); task->tk_status = 0; task->tk_action = call_refresh; switch (status) { case 0: if (rpcauth_uptodatecred(task)) task->tk_action = call_allocate; return; case -ETIMEDOUT: rpc_delay(task, 3*HZ); case -EAGAIN: status = -EACCES; if (!task->tk_cred_retry) break; task->tk_cred_retry--; dprintk("RPC: %5u %s: retry refresh creds\n", task->tk_pid, __func__); return; } dprintk("RPC: %5u %s: refresh creds failed with error %d\n", task->tk_pid, __func__, status); rpc_exit(task, status); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool AcceleratedStaticBitmapImage::CopyToTexture( gpu::gles2::GLES2Interface* dest_gl, GLenum dest_target, GLuint dest_texture_id, bool unpack_premultiply_alpha, bool unpack_flip_y, const IntPoint& dest_point, const IntRect& source_sub_rectangle) { CheckThread(); if (!IsValid()) return false; DCHECK(texture_holder_->IsCrossThread() || dest_gl != ContextProviderWrapper()->ContextProvider()->ContextGL()); EnsureMailbox(kUnverifiedSyncToken, GL_NEAREST); dest_gl->WaitSyncTokenCHROMIUM( texture_holder_->GetSyncToken().GetConstData()); GLuint source_texture_id = dest_gl->CreateAndConsumeTextureCHROMIUM( texture_holder_->GetMailbox().name); dest_gl->CopySubTextureCHROMIUM( source_texture_id, 0, dest_target, dest_texture_id, 0, dest_point.X(), dest_point.Y(), source_sub_rectangle.X(), source_sub_rectangle.Y(), source_sub_rectangle.Width(), source_sub_rectangle.Height(), unpack_flip_y ? GL_FALSE : GL_TRUE, GL_FALSE, unpack_premultiply_alpha ? GL_FALSE : GL_TRUE); dest_gl->DeleteTextures(1, &source_texture_id); gpu::SyncToken sync_token; dest_gl->GenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); texture_holder_->UpdateSyncToken(sync_token); return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: static enum test_return test_binary_replace_impl(const char* key, uint8_t cmd) { uint64_t value = 0xdeadbeefdeadcafe; union { protocol_binary_request_no_extras request; protocol_binary_response_no_extras response; char bytes[1024]; } send, receive; size_t len = storage_command(send.bytes, sizeof(send.bytes), cmd, key, strlen(key), &value, sizeof(value), 0, 0); safe_send(send.bytes, len, false); safe_recv_packet(receive.bytes, sizeof(receive.bytes)); validate_response_header(&receive.response, cmd, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT); len = storage_command(send.bytes, sizeof(send.bytes), PROTOCOL_BINARY_CMD_ADD, key, strlen(key), &value, sizeof(value), 0, 0); safe_send(send.bytes, len, false); safe_recv_packet(receive.bytes, sizeof(receive.bytes)); validate_response_header(&receive.response, PROTOCOL_BINARY_CMD_ADD, PROTOCOL_BINARY_RESPONSE_SUCCESS); len = storage_command(send.bytes, sizeof(send.bytes), cmd, key, strlen(key), &value, sizeof(value), 0, 0); int ii; for (ii = 0; ii < 10; ++ii) { safe_send(send.bytes, len, false); if (cmd == PROTOCOL_BINARY_CMD_REPLACE) { safe_recv_packet(receive.bytes, sizeof(receive.bytes)); validate_response_header(&receive.response, PROTOCOL_BINARY_CMD_REPLACE, PROTOCOL_BINARY_RESPONSE_SUCCESS); } } if (cmd == PROTOCOL_BINARY_CMD_REPLACEQ) { test_binary_noop(); } return TEST_PASS; } 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: QuotaTask::QuotaTask(QuotaTaskObserver* observer) : observer_(observer), original_task_runner_(base::MessageLoopProxy::current()) { } 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 v8::Handle<v8::Value> overloadedMethod1Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.overloadedMethod1"); if (args.Length() < 2) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); imp->overloadedMethod(objArg, strArg); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: void TaskManagerView::OnSelectionChanged() { bool selection_contains_browser_process = false; for (views::TableSelectionIterator iter = tab_table_->SelectionBegin(); iter != tab_table_->SelectionEnd(); ++iter) { if (task_manager_->IsBrowserProcess(*iter)) { selection_contains_browser_process = true; break; } } kill_button_->SetEnabled(!selection_contains_browser_process && tab_table_->SelectedRowCount() > 0); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int nfs4_proc_exchange_id(struct nfs_client *clp, struct rpc_cred *cred) { nfs4_verifier verifier; struct nfs41_exchange_id_args args = { .client = clp, .flags = EXCHGID4_FLAG_SUPP_MOVED_REFER, }; struct nfs41_exchange_id_res res = { .client = clp, }; int status; struct rpc_message msg = { .rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_EXCHANGE_ID], .rpc_argp = &args, .rpc_resp = &res, .rpc_cred = cred, }; __be32 *p; dprintk("--> %s\n", __func__); BUG_ON(clp == NULL); p = (u32 *)verifier.data; *p++ = htonl((u32)clp->cl_boot_time.tv_sec); *p = htonl((u32)clp->cl_boot_time.tv_nsec); args.verifier = &verifier; args.id_len = scnprintf(args.id, sizeof(args.id), "%s/%s.%s/%u", clp->cl_ipaddr, init_utsname()->nodename, init_utsname()->domainname, clp->cl_rpcclient->cl_auth->au_flavor); res.server_scope = kzalloc(sizeof(struct server_scope), GFP_KERNEL); if (unlikely(!res.server_scope)) return -ENOMEM; status = rpc_call_sync(clp->cl_rpcclient, &msg, RPC_TASK_TIMEOUT); if (!status) status = nfs4_check_cl_exchange_flags(clp->cl_exchange_flags); if (!status) { if (clp->server_scope && !nfs41_same_server_scope(clp->server_scope, res.server_scope)) { dprintk("%s: server_scope mismatch detected\n", __func__); set_bit(NFS4CLNT_SERVER_SCOPE_MISMATCH, &clp->cl_state); kfree(clp->server_scope); clp->server_scope = NULL; } if (!clp->server_scope) clp->server_scope = res.server_scope; else kfree(res.server_scope); } dprintk("<-- %s status= %d\n", __func__, status); return status; } 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: OMX_ERRORTYPE SoftAMR::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 0) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (!isConfigured()) { amrParams->nBitRate = 0; amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused; } else { amrParams->nBitRate = 0; amrParams->eAMRBandMode = mMode == MODE_NARROW ? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->nChannels = 1; pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->nSamplingRate = (mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int list_keys(void) { int r, idx = 0; sc_path_t path; u8 buf[2048], *p = buf; size_t keysize, i; int mod_lens[] = { 512, 768, 1024, 2048 }; size_t sizes[] = { 167, 247, 327, 647 }; r = select_app_df(); if (r) return 1; sc_format_path("I1012", &path); r = sc_select_file(card, &path, NULL); if (r) { fprintf(stderr, "Unable to select public key file: %s\n", sc_strerror(r)); return 2; } do { int mod_len = -1; r = sc_read_binary(card, idx, buf, 3, 0); if (r < 0) { fprintf(stderr, "Unable to read public key file: %s\n", sc_strerror(r)); return 2; } keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; idx += keysize; for (i = 0; i < sizeof(sizes)/sizeof(sizes[ 0]); i++) if (sizes[i] == keysize) mod_len = mod_lens[i]; if (mod_len < 0) printf("Key %d -- unknown modulus length\n", p[2] & 0x0F); else printf("Key %d -- Modulus length %d\n", p[2] & 0x0F, mod_len); } while (1); return 0; } CWE ID: CWE-415 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: sctp_disposition_t sctp_sf_do_9_2_shutdown_ack( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = (struct sctp_chunk *) arg; struct sctp_chunk *reply; /* There are 2 ways of getting here: * 1) called in response to a SHUTDOWN chunk * 2) called when SCTP_EVENT_NO_PENDING_TSN event is issued. * * For the case (2), the arg parameter is set to NULL. We need * to check that we have a chunk before accessing it's fields. */ if (chunk) { if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the SHUTDOWN chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); } /* If it has no more outstanding DATA chunks, the SHUTDOWN receiver * shall send a SHUTDOWN ACK ... */ reply = sctp_make_shutdown_ack(asoc, chunk); if (!reply) goto nomem; /* Set the transport for the SHUTDOWN ACK chunk and the timeout for * the T2-shutdown timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply)); /* and start/restart a T2-shutdown timer of its own, */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); /* Enter the SHUTDOWN-ACK-SENT state. */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_SHUTDOWN_ACK_SENT)); /* sctp-implguide 2.10 Issues with Heartbeating and failover * * HEARTBEAT ... is discontinued after sending either SHUTDOWN * or SHUTDOWN-ACK. */ sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } 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 UserActivityDetector::MaybeNotify() { base::TimeTicks now = base::TimeTicks::Now(); if (last_observer_notification_time_.is_null() || (now - last_observer_notification_time_).InSecondsF() >= kNotifyIntervalSec) { FOR_EACH_OBSERVER(UserActivityObserver, observers_, OnUserActivity()); last_observer_notification_time_ = now; } } CWE ID: CWE-79 Target: 1 Example 2: Code: long sys_swapcontext(struct ucontext __user *old_ctx, struct ucontext __user *new_ctx, int ctx_size, int r6, int r7, int r8, struct pt_regs *regs) { unsigned char tmp; int ctx_has_vsx_region = 0; #ifdef CONFIG_PPC64 unsigned long new_msr = 0; if (new_ctx) { struct mcontext __user *mcp; u32 cmcp; /* * Get pointer to the real mcontext. No need for * access_ok since we are dealing with compat * pointers. */ if (__get_user(cmcp, &new_ctx->uc_regs)) return -EFAULT; mcp = (struct mcontext __user *)(u64)cmcp; if (__get_user(new_msr, &mcp->mc_gregs[PT_MSR])) return -EFAULT; } /* * Check that the context is not smaller than the original * size (with VMX but without VSX) */ if (ctx_size < UCONTEXTSIZEWITHOUTVSX) return -EINVAL; /* * If the new context state sets the MSR VSX bits but * it doesn't provide VSX state. */ if ((ctx_size < sizeof(struct ucontext)) && (new_msr & MSR_VSX)) return -EINVAL; /* Does the context have enough room to store VSX data? */ if (ctx_size >= sizeof(struct ucontext)) ctx_has_vsx_region = 1; #else /* Context size is for future use. Right now, we only make sure * we are passed something we understand */ if (ctx_size < sizeof(struct ucontext)) return -EINVAL; #endif if (old_ctx != NULL) { struct mcontext __user *mctx; /* * old_ctx might not be 16-byte aligned, in which * case old_ctx->uc_mcontext won't be either. * Because we have the old_ctx->uc_pad2 field * before old_ctx->uc_mcontext, we need to round down * from &old_ctx->uc_mcontext to a 16-byte boundary. */ mctx = (struct mcontext __user *) ((unsigned long) &old_ctx->uc_mcontext & ~0xfUL); if (!access_ok(VERIFY_WRITE, old_ctx, ctx_size) || save_user_regs(regs, mctx, NULL, 0, ctx_has_vsx_region) || put_sigset_t(&old_ctx->uc_sigmask, &current->blocked) || __put_user(to_user_ptr(mctx), &old_ctx->uc_regs)) return -EFAULT; } if (new_ctx == NULL) return 0; if (!access_ok(VERIFY_READ, new_ctx, ctx_size) || __get_user(tmp, (u8 __user *) new_ctx) || __get_user(tmp, (u8 __user *) new_ctx + ctx_size - 1)) return -EFAULT; /* * If we get a fault copying the context into the kernel's * image of the user's registers, we can't just return -EFAULT * because the user's registers will be corrupted. For instance * the NIP value may have been updated but not some of the * other registers. Given that we have done the access_ok * and successfully read the first and last bytes of the region * above, this should only happen in an out-of-memory situation * or if another thread unmaps the region containing the context. * We kill the task with a SIGSEGV in this situation. */ if (do_setcontext(new_ctx, regs, 0)) do_exit(SIGSEGV); set_thread_flag(TIF_RESTOREALL); 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: int nfs4_lock_delegation_recall(struct file_lock *fl, struct nfs4_state *state, const nfs4_stateid *stateid) { struct nfs_server *server = NFS_SERVER(state->inode); int err; err = nfs4_set_lock_state(state, fl); if (err != 0) return err; err = _nfs4_do_setlk(state, F_SETLK, fl, NFS_LOCK_NEW); return nfs4_handle_delegation_recall_error(server, state, stateid, err); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void __exit xfrm6_tunnel_fini(void) { unregister_pernet_subsys(&xfrm6_tunnel_net_ops); xfrm6_tunnel_spi_fini(); xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET); xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6); xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6); } CWE ID: CWE-362 Target: 1 Example 2: Code: void DelegatedFrameHost::OnCompositingShuttingDown(ui::Compositor* compositor) { DCHECK_EQ(compositor, compositor_); ResetCompositor(); DCHECK(!compositor_); } 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 CL_SetServerInfo(serverInfo_t *server, const char *info, int ping) { if (server) { if (info) { server->clients = atoi(Info_ValueForKey(info, "clients")); Q_strncpyz(server->hostName,Info_ValueForKey(info, "hostname"), MAX_NAME_LENGTH); Q_strncpyz(server->mapName, Info_ValueForKey(info, "mapname"), MAX_NAME_LENGTH); server->maxClients = atoi(Info_ValueForKey(info, "sv_maxclients")); Q_strncpyz(server->game,Info_ValueForKey(info, "game"), MAX_NAME_LENGTH); server->gameType = atoi(Info_ValueForKey(info, "gametype")); server->netType = atoi(Info_ValueForKey(info, "nettype")); server->minPing = atoi(Info_ValueForKey(info, "minping")); server->maxPing = atoi(Info_ValueForKey(info, "maxping")); server->punkbuster = atoi(Info_ValueForKey(info, "punkbuster")); server->g_humanplayers = atoi(Info_ValueForKey(info, "g_humanplayers")); server->g_needpass = atoi(Info_ValueForKey(info, "g_needpass")); } server->ping = ping; } } CWE ID: CWE-269 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CreateFile(const FilePath& file_path) { const std::string kFoo = "foo"; ASSERT_TRUE(file_util::WriteFile(file_path, kFoo.data(), kFoo.size())) << ": " << file_path.value(); } CWE ID: CWE-119 Target: 1 Example 2: Code: _gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt) { int ncx, ncy, cx, cy; int x, y, ylo, yhi, xlo, xhi; int chunkLen; int chunkNum = 0; char *chunkData = NULL; /* So we can gdFree it with impunity. */ char *compData = NULL; /* So we can gdFree it with impunity. */ uLongf compLen; int idxPos = 0; int idxSize; t_chunk_info *chunkIdx = NULL; int posSave; int bytesPerPixel = im->trueColor ? 4 : 1; int compMax = 0; /*printf("Trying to write GD2 file\n"); */ /* */ /* Force fmt to a valid value since we don't return anything. */ /* */ if ((fmt != GD2_FMT_RAW) && (fmt != GD2_FMT_COMPRESSED)) { fmt = GD2_FMT_COMPRESSED; }; if (im->trueColor) { fmt += 2; } /* */ /* Make sure chunk size is valid. These are arbitrary values; 64 because it seems */ /* a little silly to expect performance improvements on a 64x64 bit scale, and */ /* 4096 because we buffer one chunk, and a 16MB buffer seems a little large - it may be */ /* OK for one user, but for another to read it, they require the buffer. */ /* */ if (cs == 0) { cs = GD2_CHUNKSIZE; } else if (cs < GD2_CHUNKSIZE_MIN) { cs = GD2_CHUNKSIZE_MIN; } else if (cs > GD2_CHUNKSIZE_MAX) { cs = GD2_CHUNKSIZE_MAX; }; /* Work out number of chunks. */ ncx = (im->sx + cs - 1) / cs; ncy = (im->sy + cs - 1) / cs; /* Write the standard header. */ _gd2PutHeader (im, out, cs, fmt, ncx, ncy); if (gd2_compressed (fmt)) { /* */ /* Work out size of buffer for compressed data, If CHUNKSIZE is large, */ /* then these will be large! */ /* */ /* The zlib notes say output buffer size should be (input size) * 1.01 * 12 */ /* - we'll use 1.02 to be paranoid. */ /* */ compMax = cs * bytesPerPixel * cs * 1.02 + 12; /* */ /* Allocate the buffers. */ /* */ chunkData = gdCalloc (cs * bytesPerPixel * cs, 1); if (!chunkData) { goto fail; } compData = gdCalloc (compMax, 1); if (!compData) { goto fail; } /* */ /* Save the file position of chunk index, and allocate enough space for */ /* each chunk_info block . */ /* */ idxPos = gdTell (out); idxSize = ncx * ncy * sizeof (t_chunk_info); GD2_DBG (printf ("Index size is %d\n", idxSize)); gdSeek (out, idxPos + idxSize); chunkIdx = gdCalloc (idxSize * sizeof (t_chunk_info), 1); if (!chunkIdx) { goto fail; } }; _gdPutColors (im, out); GD2_DBG (printf ("Size: %dx%d\n", im->sx, im->sy)); GD2_DBG (printf ("Chunks: %dx%d\n", ncx, ncy)); for (cy = 0; (cy < ncy); cy++) { for (cx = 0; (cx < ncx); cx++) { ylo = cy * cs; yhi = ylo + cs; if (yhi > im->sy) { yhi = im->sy; }; GD2_DBG (printf ("Processing Chunk (%dx%d), y from %d to %d\n", cx, cy, ylo, yhi)); chunkLen = 0; for (y = ylo; (y < yhi); y++) { /*GD2_DBG(printf("y=%d: ",y)); */ xlo = cx * cs; xhi = xlo + cs; if (xhi > im->sx) { xhi = im->sx; }; if (gd2_compressed (fmt)) { for (x = xlo; x < xhi; x++) { /* 2.0.11: use truecolor pixel array. TBB */ /*GD2_DBG(printf("%d...",x)); */ if (im->trueColor) { int p = im->tpixels[y][x]; chunkData[chunkLen++] = gdTrueColorGetAlpha (p); chunkData[chunkLen++] = gdTrueColorGetRed (p); chunkData[chunkLen++] = gdTrueColorGetGreen (p); chunkData[chunkLen++] = gdTrueColorGetBlue (p); } else { int p = im->pixels[y][x]; chunkData[chunkLen++] = p; } }; } else { for (x = xlo; x < xhi; x++) { /*GD2_DBG(printf("%d, ",x)); */ if (im->trueColor) { gdPutInt (im->tpixels[y][x], out); } else { gdPutC ((unsigned char) im->pixels[y][x], out); } }; }; /*GD2_DBG(printf("y=%d done.\n",y)); */ }; if (gd2_compressed (fmt)) { compLen = compMax; if (compress ((unsigned char *) &compData[0], &compLen, (unsigned char *) &chunkData[0], chunkLen) != Z_OK) { printf ("Error from compressing\n"); } else { chunkIdx[chunkNum].offset = gdTell (out); chunkIdx[chunkNum++].size = compLen; GD2_DBG (printf ("Chunk %d size %d offset %d\n", chunkNum, chunkIdx[chunkNum - 1].size, chunkIdx[chunkNum - 1].offset)); if (gdPutBuf (compData, compLen, out) <= 0) { gd_error("gd write error\n"); }; }; }; }; }; if (gd2_compressed (fmt)) { /* Save the position, write the index, restore position (paranoia). */ GD2_DBG (printf ("Seeking %d to write index\n", idxPos)); posSave = gdTell (out); gdSeek (out, idxPos); GD2_DBG (printf ("Writing index\n")); for (x = 0; x < chunkNum; x++) { GD2_DBG (printf ("Chunk %d size %d offset %d\n", x, chunkIdx[x].size, chunkIdx[x].offset)); gdPutInt (chunkIdx[x].offset, out); gdPutInt (chunkIdx[x].size, out); }; /* We don't use fwrite for *endian reasons. */ /*fwrite(chunkIdx, sizeof(int)*2, chunkNum, out); */ gdSeek (out, posSave); }; /*printf("Memory block size is %d\n",gdTell(out)); */ fail: GD2_DBG (printf ("Freeing memory\n")); if (chunkData) { gdFree (chunkData); } if (compData) { gdFree (compData); } if (chunkIdx) { gdFree (chunkIdx); } GD2_DBG (printf ("Done\n")); } 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: PHP_METHOD(Phar, extractTo) { char *error = NULL; php_stream *fp; php_stream_statbuf ssb; phar_entry_info *entry; char *pathto, *filename; size_t pathto_len, filename_len; int ret, i; int nelems; zval *zval_files = NULL; zend_bool overwrite = 0; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) { return; } fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL); if (!fp) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, %s cannot be found", phar_obj->archive->fname); return; } php_stream_close(fp); if (pathto_len < 1) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, extraction path must be non-zero length"); return; } if (pathto_len >= MAXPATHLEN) { char *tmp = estrndup(pathto, 50); /* truncate for error message */ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp); efree(tmp); return; } if (php_stream_stat_path(pathto, &ssb) < 0) { ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL); if (!ret) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to create path \"%s\" for extraction", pathto); return; } } else if (!(ssb.sb.st_mode & S_IFDIR)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto); return; } if (zval_files) { switch (Z_TYPE_P(zval_files)) { case IS_NULL: goto all_files; case IS_STRING: filename = Z_STRVAL_P(zval_files); filename_len = Z_STRLEN_P(zval_files); break; case IS_ARRAY: nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files)); if (nelems == 0 ) { RETURN_FALSE; } for (i = 0; i < nelems; i++) { zval *zval_file; if ((zval_file = zend_hash_index_find(Z_ARRVAL_P(zval_files), i)) != NULL) { switch (Z_TYPE_P(zval_file)) { case IS_STRING: break; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, array of filenames to extract contains non-string value"); return; } if (NULL == (entry = zend_hash_find_ptr(&phar_obj->archive->manifest, Z_STR_P(zval_file)))) { zend_throw_exception_ex(phar_ce_PharException, 0, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", Z_STRVAL_P(zval_file), phar_obj->archive->fname); } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error); efree(error); return; } } } RETURN_TRUE; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, expected a filename (string) or array of filenames"); return; } if (NULL == (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, filename, filename_len))) { zend_throw_exception_ex(phar_ce_PharException, 0, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", filename, phar_obj->archive->fname); return; } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error); efree(error); return; } } else { phar_archive_data *phar; all_files: phar = phar_obj->archive; /* Extract all files */ if (!zend_hash_num_elements(&(phar->manifest))) { RETURN_TRUE; } ZEND_HASH_FOREACH_PTR(&phar->manifest, entry) { if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar->fname, error); efree(error); return; } } ZEND_HASH_FOREACH_END(); } RETURN_TRUE; } 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 HostCache::RecordSet(SetOutcome outcome, base::TimeTicks now, const Entry* old_entry, const Entry& new_entry) { CACHE_HISTOGRAM_ENUM("Set", outcome, MAX_SET_OUTCOME); switch (outcome) { case SET_INSERT: case SET_UPDATE_VALID: break; case SET_UPDATE_STALE: { EntryStaleness stale; old_entry->GetStaleness(now, network_changes_, &stale); CACHE_HISTOGRAM_TIME("UpdateStale.ExpiredBy", stale.expired_by); CACHE_HISTOGRAM_COUNT("UpdateStale.NetworkChanges", stale.network_changes); CACHE_HISTOGRAM_COUNT("UpdateStale.StaleHits", stale.stale_hits); if (old_entry->error() == OK && new_entry.error() == OK) { AddressListDeltaType delta = FindAddressListDeltaType( old_entry->addresses(), new_entry.addresses()); RecordUpdateStale(delta, stale); } break; } case MAX_SET_OUTCOME: NOTREACHED(); break; } } CWE ID: Target: 1 Example 2: Code: void V8ValueConverterImpl::SetDateAllowed(bool val) { date_allowed_ = val; } 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 RenderFrameHostImpl::OnRunBeforeUnloadConfirm( const GURL& frame_url, bool is_reload, IPC::Message* reply_msg) { GetProcess()->SetIgnoreInputEvents(true); for (RenderFrameHostImpl* frame = this; frame; frame = frame->GetParent()) { if (frame->beforeunload_timeout_) frame->beforeunload_timeout_->Stop(); } delegate_->RunBeforeUnloadConfirm(this, is_reload, reply_msg); } CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void sctp_generate_proto_unreach_event(unsigned long data) { struct sctp_transport *transport = (struct sctp_transport *) data; struct sctp_association *asoc = transport->asoc; struct net *net = sock_net(asoc->base.sk); bh_lock_sock(asoc->base.sk); if (sock_owned_by_user(asoc->base.sk)) { pr_debug("%s: sock is busy\n", __func__); /* Try again later. */ if (!mod_timer(&transport->proto_unreach_timer, jiffies + (HZ/20))) sctp_association_hold(asoc); goto out_unlock; } /* Is this structure just waiting around for us to actually * get destroyed? */ if (asoc->base.dead) goto out_unlock; sctp_do_sm(net, SCTP_EVENT_T_OTHER, SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH), asoc->state, asoc->ep, asoc, transport, GFP_ATOMIC); out_unlock: bh_unlock_sock(asoc->base.sk); sctp_association_put(asoc); } CWE ID: CWE-362 Target: 1 Example 2: Code: SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid, u64 volatile_fid, int level) { struct smb_rqst rqst; struct smb2_query_info_rsp *rsp = NULL; struct kvec iov; struct kvec rsp_iov; int rc = 0; int resp_buftype, max_len, min_len; struct cifs_ses *ses = tcon->ses; unsigned int rsp_len, offset; int flags = 0; if (level == FS_DEVICE_INFORMATION) { max_len = sizeof(FILE_SYSTEM_DEVICE_INFO); min_len = sizeof(FILE_SYSTEM_DEVICE_INFO); } else if (level == FS_ATTRIBUTE_INFORMATION) { max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO); min_len = MIN_FS_ATTR_INFO_SIZE; } else if (level == FS_SECTOR_SIZE_INFORMATION) { max_len = sizeof(struct smb3_fs_ss_info); min_len = sizeof(struct smb3_fs_ss_info); } else if (level == FS_VOLUME_INFORMATION) { max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN; min_len = sizeof(struct smb3_fs_vol_info); } else { cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level); return -EINVAL; } rc = build_qfs_info_req(&iov, tcon, level, max_len, persistent_fid, volatile_fid); if (rc) return rc; if (smb3_encryption_required(tcon)) flags |= CIFS_TRANSFORM_REQ; memset(&rqst, 0, sizeof(struct smb_rqst)); rqst.rq_iov = &iov; rqst.rq_nvec = 1; rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(iov.iov_base); if (rc) { cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE); goto qfsattr_exit; } rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base; rsp_len = le32_to_cpu(rsp->OutputBufferLength); offset = le16_to_cpu(rsp->OutputBufferOffset); rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len); if (rc) goto qfsattr_exit; if (level == FS_ATTRIBUTE_INFORMATION) memcpy(&tcon->fsAttrInfo, offset + (char *)rsp, min_t(unsigned int, rsp_len, max_len)); else if (level == FS_DEVICE_INFORMATION) memcpy(&tcon->fsDevInfo, offset + (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO)); else if (level == FS_SECTOR_SIZE_INFORMATION) { struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *) (offset + (char *)rsp); tcon->ss_flags = le32_to_cpu(ss_info->Flags); tcon->perf_sector_size = le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf); } else if (level == FS_VOLUME_INFORMATION) { struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *) (offset + (char *)rsp); tcon->vol_serial_number = vol_info->VolumeSerialNumber; tcon->vol_create_time = vol_info->VolumeCreationTime; } qfsattr_exit: free_rsp_buf(resp_buftype, rsp_iov.iov_base); return rc; } 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 OnTraceUploadComplete(TraceCrashServiceUploader* uploader, bool success, const std::string& feedback) { if (!success) { LOG(ERROR) << "Cannot upload trace file: " << feedback; return; } LOG(WARNING) << "slow-reports sent: '" << feedback << '"'; } 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: std::string SanitizeEndpoint(const std::string& value) { if (value.find('&') != std::string::npos || value.find('?') != std::string::npos) return std::string(); return value; } CWE ID: CWE-200 Target: 1 Example 2: Code: static int send_mpa_reject(struct iwch_ep *ep, const void *pdata, u8 plen) { int mpalen; struct tx_data_wr *req; struct mpa_message *mpa; struct sk_buff *skb; PDBG("%s ep %p plen %d\n", __func__, ep, plen); mpalen = sizeof(*mpa) + plen; skb = get_skb(NULL, mpalen + sizeof(*req), GFP_KERNEL); if (!skb) { printk(KERN_ERR MOD "%s - cannot alloc skb!\n", __func__); return -ENOMEM; } skb_reserve(skb, sizeof(*req)); mpa = (struct mpa_message *) skb_put(skb, mpalen); memset(mpa, 0, sizeof(*mpa)); memcpy(mpa->key, MPA_KEY_REP, sizeof(mpa->key)); mpa->flags = MPA_REJECT; mpa->revision = mpa_rev; mpa->private_data_size = htons(plen); if (plen) memcpy(mpa->private_data, pdata, plen); /* * Reference the mpa skb again. This ensures the data area * will remain in memory until the hw acks the tx. * Function tx_ack() will deref it. */ skb_get(skb); skb->priority = CPL_PRIORITY_DATA; set_arp_failure_handler(skb, arp_failure_discard); skb_reset_transport_header(skb); req = (struct tx_data_wr *) skb_push(skb, sizeof(*req)); req->wr_hi = htonl(V_WR_OP(FW_WROPCODE_OFLD_TX_DATA)|F_WR_COMPL); req->wr_lo = htonl(V_WR_TID(ep->hwtid)); req->len = htonl(mpalen); req->param = htonl(V_TX_PORT(ep->l2t->smt_idx) | V_TX_SNDBUF(snd_win>>15)); req->flags = htonl(F_TX_INIT); req->sndseq = htonl(ep->snd_seq); BUG_ON(ep->mpa_skb); ep->mpa_skb = skb; return iwch_l2t_send(ep->com.tdev, skb, ep->l2t); } 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: smb2_flush(smb_request_t *sr) { smb_ofile_t *of = NULL; uint16_t StructSize; uint16_t reserved1; uint32_t reserved2; smb2fid_t smb2fid; uint32_t status; int rc = 0; /* * SMB2 Flush request */ rc = smb_mbc_decodef( &sr->smb_data, "wwlqq", &StructSize, /* w */ &reserved1, /* w */ &reserved2, /* l */ &smb2fid.persistent, /* q */ &smb2fid.temporal); /* q */ if (rc) return (SDRC_ERROR); if (StructSize != 24) return (SDRC_ERROR); status = smb2sr_lookup_fid(sr, &smb2fid); if (status) { smb2sr_put_error(sr, status); return (SDRC_SUCCESS); } of = sr->fid_ofile; /* * XXX - todo: * Flush named pipe should drain writes. */ if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0) (void) smb_fsop_commit(sr, of->f_cr, of->f_node); /* * SMB2 Flush reply */ (void) smb_mbc_encodef( &sr->reply, "wwl", 4, /* StructSize */ /* w */ 0); /* reserved */ /* w */ return (SDRC_SUCCESS); } 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: update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu) { struct ring_buffer *buf; if (tr->stop_count) return; WARN_ON_ONCE(!irqs_disabled()); if (!tr->allocated_snapshot) { /* Only the nop tracer should hit this when disabling */ WARN_ON_ONCE(tr->current_trace != &nop_trace); return; } arch_spin_lock(&tr->max_lock); buf = tr->trace_buffer.buffer; tr->trace_buffer.buffer = tr->max_buffer.buffer; tr->max_buffer.buffer = buf; __update_max_tr(tr, tsk, cpu); arch_spin_unlock(&tr->max_lock); } CWE ID: CWE-787 Target: 1 Example 2: Code: SplashClip *Splash::getClip() { return state->clip; } 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: mrb_gc_mark(mrb_state *mrb, struct RBasic *obj) { if (obj == 0) return; if (!is_white(obj)) return; mrb_assert((obj)->tt != MRB_TT_FREE); add_gray_list(mrb, &mrb->gc, obj); } 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: horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tmsize_t stride = sp->stride; uint32 *wp = (uint32*) cp0; tmsize_t wc = cc/4; assert((cc%(4*stride))==0); if (wc > stride) { wc -= stride; wp += wc - 1; do { REPEAT4(stride, wp[stride] -= wp[0]; wp--) wc -= stride; } while (wc > 0); } } CWE ID: CWE-119 Target: 1 Example 2: Code: bool HFSIterator::IsDecmpfsCompressed() { if (IsDirectory()) return false; const HFSPlusCatalogFile* file = catalog_->current_record()->file; return file->bsdInfo.ownerFlags & UF_COMPRESSED; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vmsvga_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); k->realize = pci_vmsvga_realize; k->romfile = "vgabios-vmware.bin"; k->vendor_id = PCI_VENDOR_ID_VMWARE; k->device_id = SVGA_PCI_DEVICE_ID; k->class_id = PCI_CLASS_DISPLAY_VGA; k->subsystem_vendor_id = PCI_VENDOR_ID_VMWARE; k->subsystem_id = SVGA_PCI_DEVICE_ID; dc->reset = vmsvga_reset; dc->vmsd = &vmstate_vmware_vga; dc->props = vga_vmware_properties; dc->hotpluggable = false; set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories); } 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: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } CWE ID: CWE-310 Target: 1 Example 2: Code: GF_Err stsd_Size(GF_Box *s) { GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s; ptr->size += 4; 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: void WebGL2RenderingContextBase::texSubImage2D( ExecutionContext* execution_context, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, HTMLCanvasElement* canvas, ExceptionState& exception_state) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage2D", "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } TexImageHelperHTMLCanvasElement( execution_context->GetSecurityOrigin(), kTexSubImage2D, target, level, 0, format, type, xoffset, yoffset, 0, canvas, GetTextureSourceSubRectangle(width, height), 1, 0, exception_state); } 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 m_stop(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; struct vm_area_struct *vma = v; vma_stop(priv, vma); if (priv->task) put_task_struct(priv->task); } CWE ID: CWE-20 Target: 1 Example 2: Code: void LoginPromptBrowserTestObserver::RemoveHandler(LoginHandler* handler) { std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(), handlers_.end(), handler); EXPECT_TRUE(i != handlers_.end()); if (i != handlers_.end()) handlers_.erase(i); } 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 opj_bool pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } CWE ID: CWE-369 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BluetoothDeviceChromeOS::RequestPinCode( const dbus::ObjectPath& device_path, const PinCodeCallback& callback) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": RequestPinCode"; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_REQUEST_PINCODE, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); DCHECK(pincode_callback_.is_null()); pincode_callback_ = callback; pairing_delegate_->RequestPinCode(this); pairing_delegate_used_ = true; } CWE ID: Target: 1 Example 2: Code: AppListService* GetAppListServiceWin() { return AppListController::GetInstance(); } 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 proc_sys_setattr(struct dentry *dentry, struct iattr *attr) { struct inode *inode = d_inode(dentry); int error; if (attr->ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)) return -EPERM; error = setattr_prepare(dentry, attr); if (error) return error; setattr_copy(inode, attr); mark_inode_dirty(inode); return 0; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN); subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, "\n\t MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, "\n\t AUX-MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + sizeof(struct isis_subtlv_spb_mcid); len = len - sizeof(struct isis_subtlv_spb_mcid); break; } case ISIS_SUBTLV_SPB_DIGEST: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN); ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, "\n\t Digest: ")); for(i=1;i<=8; i++) { ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, "\n\t ")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { ND_TCHECK2(*(tptr), stlv_len); while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN); ND_PRINT((ndo, "\n\t ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } CWE ID: CWE-125 Target: 1 Example 2: Code: static int context_init(H264Context *h) { ERContext *er = &h->er; int mb_array_size = h->mb_height * h->mb_stride; int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1); int c_size = h->mb_stride * (h->mb_height + 1); int yc_size = y_size + 2 * c_size; int x, y, i; FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0], h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail) FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1], h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail) h->ref_cache[0][scan8[5] + 1] = h->ref_cache[0][scan8[7] + 1] = h->ref_cache[0][scan8[13] + 1] = h->ref_cache[1][scan8[5] + 1] = h->ref_cache[1][scan8[7] + 1] = h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE; if (CONFIG_ERROR_RESILIENCE) { /* init ER */ er->avctx = h->avctx; er->dsp = &h->dsp; er->decode_mb = h264_er_decode_mb; er->opaque = h; er->quarter_sample = 1; er->mb_num = h->mb_num; er->mb_width = h->mb_width; er->mb_height = h->mb_height; er->mb_stride = h->mb_stride; er->b8_stride = h->mb_width * 2 + 1; FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int), fail); // error ressilience code looks cleaner with this for (y = 0; y < h->mb_height; y++) for (x = 0; x < h->mb_width; x++) er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride; er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) * h->mb_stride + h->mb_width; FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table, mb_array_size * sizeof(uint8_t), fail); FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail); memset(er->mbintra_table, 1, mb_array_size); FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail); FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride, fail); FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail); er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2; er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1; er->dc_val[2] = er->dc_val[1] + c_size; for (i = 0; i < yc_size; i++) h->dc_val_base[i] = 1024; } return 0; fail: return AVERROR(ENOMEM); // free_tables will clean up for us } 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: main(int argc, char *argv[]) { OM_uint32 minor, major; gss_ctx_id_t context; gss_union_ctx_id_desc uctx; krb5_gss_ctx_id_rec kgctx; krb5_key k1, k2; krb5_keyblock kb1, kb2; gss_buffer_desc in, out; unsigned char k1buf[32], k2buf[32], outbuf[44]; size_t i; /* * Fake up just enough of a krb5 GSS context to make gss_pseudo_random * work, with chosen subkeys and acceptor subkeys. If we implement * gss_import_lucid_sec_context, we can rewrite this to use public * interfaces and stop using private headers and internal knowledge of the * implementation. */ context = (gss_ctx_id_t)&uctx; uctx.mech_type = &mech_krb5; uctx.internal_ctx_id = (gss_ctx_id_t)&kgctx; kgctx.k5_context = NULL; kgctx.have_acceptor_subkey = 1; kb1.contents = k1buf; kb2.contents = k2buf; for (i = 0; i < sizeof(tests) / sizeof(*tests); i++) { /* Set up the keys for this test. */ kb1.enctype = tests[i].enctype; kb1.length = fromhex(tests[i].key1, k1buf); check_k5err(NULL, "create_key", krb5_k_create_key(NULL, &kb1, &k1)); kgctx.subkey = k1; kb2.enctype = tests[i].enctype; kb2.length = fromhex(tests[i].key2, k2buf); check_k5err(NULL, "create_key", krb5_k_create_key(NULL, &kb2, &k2)); kgctx.acceptor_subkey = k2; /* Generate a PRF value with the subkey and an empty input, and compare * it to the first expected output. */ in.length = 0; in.value = NULL; major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_PARTIAL, &in, 44, &out); check_gsserr("gss_pseudo_random", major, minor); (void)fromhex(tests[i].out1, outbuf); assert(out.length == 44 && memcmp(out.value, outbuf, 44) == 0); (void)gss_release_buffer(&minor, &out); /* Generate a PRF value with the acceptor subkey and the 61-byte input * string, and compare it to the second expected output. */ in.length = strlen(inputstr); in.value = (char *)inputstr; major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_FULL, &in, 44, &out); check_gsserr("gss_pseudo_random", major, minor); (void)fromhex(tests[i].out2, outbuf); assert(out.length == 44 && memcmp(out.value, outbuf, 44) == 0); (void)gss_release_buffer(&minor, &out); /* Also check that generating zero bytes of output works. */ major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_FULL, &in, 0, &out); check_gsserr("gss_pseudo_random", major, minor); assert(out.length == 0); (void)gss_release_buffer(&minor, &out); krb5_k_free_key(NULL, k1); krb5_k_free_key(NULL, k2); } return 0; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) { int r, len; switch (node->type) { case BAG_MEMORY: r = compile_bag_memory_node(node, reg, env); break; case BAG_OPTION: r = compile_option_node(node, reg, env); break; case BAG_STOP_BACKTRACK: if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { QuantNode* qn = QUANT_(NODE_BAG_BODY(node)); r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); if (r != 0) return r; len = compile_length_tree(NODE_QUANT_BODY(qn), reg); if (len < 0) return len; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP; r = compile_tree(NODE_QUANT_BODY(qn), reg, env); if (r != 0) return r; r = add_op(reg, OP_POP_OUT); if (r != 0) return r; r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT); } else { r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; r = compile_tree(NODE_BAG_BODY(node), reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); } break; case BAG_IF_ELSE: { int cond_len, then_len, jump_len; Node* cond = NODE_BAG_BODY(node); Node* Then = node->te.Then; Node* Else = node->te.Else; r = add_op(reg, OP_ATOMIC_START); if (r != 0) return r; cond_len = compile_length_tree(cond, reg); if (cond_len < 0) return cond_len; if (IS_NOT_NULL(Then)) { then_len = compile_length_tree(Then, reg); if (then_len < 0) return then_len; } else then_len = 0; jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; r = add_op(reg, OP_PUSH); if (r != 0) return r; COP(reg)->push.addr = SIZE_INC_OP + jump_len; r = compile_tree(cond, reg, env); if (r != 0) return r; r = add_op(reg, OP_ATOMIC_END); if (r != 0) return r; if (IS_NOT_NULL(Then)) { r = compile_tree(Then, reg, env); if (r != 0) return r; } if (IS_NOT_NULL(Else)) { int else_len = compile_length_tree(Else, reg); r = add_op(reg, OP_JUMP); if (r != 0) return r; COP(reg)->jump.addr = else_len + SIZE_INC_OP; r = compile_tree(Else, reg, env); } } break; } return r; } CWE ID: CWE-476 Target: 1 Example 2: Code: void Browser::CloseWindow() { UserMetrics::RecordAction(UserMetricsAction("CloseWindow")); window_->Close(); } 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: png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn) { png_debug(1, "in png_set_read_user_chunk_fn"); if (png_ptr == NULL) return; png_ptr->read_user_chunk_fn = read_user_chunk_fn; png_ptr->user_chunk_ptr = user_chunk_ptr; } 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: xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr) { /* This function is copied verbatim from plfont.c */ int table_length; int table_offset; ulong format; uint numGlyphs; uint glyph_name_index; const byte *postp; /* post table pointer */ /* guess if the font type is not truetype */ if ( pfont->FontType != ft_TrueType ) { pstr->size = strlen((char*)pstr->data); return 0; } else { return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void f2fs_sb_release(struct kobject *kobj) { struct f2fs_sb_info *sbi = container_of(kobj, struct f2fs_sb_info, s_kobj); complete(&sbi->s_kobj_unregister); } CWE ID: CWE-129 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xps_encode_font_char_imp(xps_font_t *font, int code) { byte *table; /* no cmap selected: return identity */ if (font->cmapsubtable <= 0) return code; table = font->data + font->cmapsubtable; switch (u16(table)) { case 0: /* Apple standard 1-to-1 mapping. */ return table[code + 6]; case 4: /* Microsoft/Adobe segmented mapping. */ { int segCount2 = u16(table + 6); byte *endCount = table + 14; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; int i2; for (i2 = 0; i2 < segCount2 - 3; i2 += 2) { int delta, roff; int start = u16(startCount + i2); continue; delta = s16(idDelta + i2); roff = s16(idRangeOffset + i2); if ( roff == 0 ) { return ( code + delta ) & 0xffff; /* mod 65536 */ return 0; } if ( roff == 0 ) { return ( code + delta ) & 0xffff; /* mod 65536 */ return 0; } glyph = u16(idRangeOffset + i2 + roff + ((code - start) << 1)); return (glyph == 0 ? 0 : glyph + delta); } case 6: /* Single interval lookup. */ { int firstCode = u16(table + 6); int entryCount = u16(table + 8); if ( code < firstCode || code >= firstCode + entryCount ) return 0; return u16(table + 10 + ((code - firstCode) << 1)); } case 10: /* Trimmed array (like 6) */ { int startCharCode = u32(table + 12); int numChars = u32(table + 16); if ( code < startCharCode || code >= startCharCode + numChars ) return 0; return u32(table + 20 + (code - startCharCode) * 4); } case 12: /* Segmented coverage. (like 4) */ { int nGroups = u32(table + 12); byte *group = table + 16; int i; for (i = 0; i < nGroups; i++) { int startCharCode = u32(group + 0); int endCharCode = u32(group + 4); int startGlyphID = u32(group + 8); if ( code < startCharCode ) return 0; if ( code <= endCharCode ) return startGlyphID + (code - startCharCode); group += 12; } return 0; } case 2: /* High-byte mapping through table. */ case 8: /* Mixed 16-bit and 32-bit coverage (like 2) */ default: gs_warn1("unknown cmap format: %d\n", u16(table)); return 0; } return 0; } /* * Given a GID, reverse the CMAP subtable lookup to turn it back into a character code * We need a Unicode return value, so we might need to do some fixed tables for * certain kinds of CMAP subtables (ie non-Unicode ones). That would be a future enhancement * if we ever encounter such a beast. */ static int xps_decode_font_char_imp(xps_font_t *font, int code) { byte *table; /* no cmap selected: return identity */ if (font->cmapsubtable <= 0) return code; table = font->data + font->cmapsubtable; switch (u16(table)) { case 0: /* Apple standard 1-to-1 mapping. */ { int i, length = u16(&table[2]) - 6; if (length < 0 || length > 256) return gs_error_invalidfont; for (i=0;i<length;i++) { if (table[6 + i] == code) return i; } } return 0; case 4: /* Microsoft/Adobe segmented mapping. */ { int segCount2 = u16(table + 6); byte *endCount = table + 14; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; int i2; if (segCount2 < 3 || segCount2 > 65535) return gs_error_invalidfont; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; int i2; if (segCount2 < 3 || segCount2 > 65535) return gs_error_invalidfont; for (i2 = 0; i2 < segCount2 - 3; i2 += 2) if (roff == 0) { glyph = (i + delta) & 0xffff; } else { glyph = u16(idRangeOffset + i2 + roff + ((i - start) << 1)); } if (glyph == code) { return i; } } } if (roff == 0) { glyph = (i + delta) & 0xffff; } else { glyph = u16(idRangeOffset + i2 + roff + ((i - start) << 1)); } if (glyph == code) { return i; ch = u16(&table[10 + (i * 2)]); if (ch == code) return (firstCode + i); } } return 0; case 10: /* Trimmed array (like 6) */ { unsigned int ch, i, length = u32(&table[20]); int firstCode = u32(&table[16]); for (i=0;i<length;i++) { ch = u16(&table[10 + (i * 2)]); if (ch == code) return (firstCode + i); } } return 0; case 12: /* Segmented coverage. (like 4) */ { unsigned int nGroups = u32(&table[12]); int Group; for (Group=0;Group<nGroups;Group++) { int startCharCode = u32(&table[16 + (Group * 12)]); int endCharCode = u32(&table[16 + (Group * 12) + 4]); int startGlyphCode = u32(&table[16 + (Group * 12) + 8]); if (code >= startGlyphCode && code <= (startGlyphCode + (endCharCode - startCharCode))) { return startGlyphCode + (code - startCharCode); } } } return 0; case 2: /* High-byte mapping through table. */ case 8: /* Mixed 16-bit and 32-bit coverage (like 2) */ default: gs_warn1("unknown cmap format: %d\n", u16(table)); return 0; } 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 URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { UriBool firstItem = URI_TRUE; int ampersandLen = 0; /* increased to 1 from second item on */ URI_CHAR * write = dest; /* Subtract terminator */ if (dest == NULL) { *charsRequired = 0; } else { maxChars--; } while (queryList != NULL) { const URI_CHAR * const key = queryList->key; const URI_CHAR * const value = queryList->value; const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3); const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key); const int keyRequiredChars = worstCase * keyLen; const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value); const int valueRequiredChars = worstCase * valueLen; if (dest == NULL) { (*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL) ? 0 : 1 + valueRequiredChars); if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } } else { if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy key */ if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } else { write[0] = _UT('&'); write++; } write = URI_FUNC(EscapeEx)(key, key + keyLen, write, spaceToPlus, normalizeBreaks); if (value != NULL) { if ((write - dest) + 1 + valueRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy value */ write[0] = _UT('='); write++; write = URI_FUNC(EscapeEx)(value, value + valueLen, write, spaceToPlus, normalizeBreaks); } } queryList = queryList->next; } if (dest != NULL) { write[0] = _UT('\0'); if (charsWritten != NULL) { *charsWritten = (int)(write - dest) + 1; /* .. for terminator */ } } return URI_SUCCESS; } CWE ID: CWE-190 Target: 1 Example 2: Code: size_t IGraphicBufferProducer::QueueBufferInput::getFlattenedSize() const { return sizeof(timestamp) + sizeof(isAutoTimestamp) + sizeof(dataSpace) + sizeof(crop) + sizeof(scalingMode) + sizeof(transform) + sizeof(stickyTransform) + sizeof(async) + fence->getFlattenedSize() + surfaceDamage.getFlattenedSize(); } 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: ModuleExport size_t RegisterJPEGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char description[] = "Joint Photographic Experts Group JFIF format"; *version='\0'; #if defined(JPEG_LIB_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION); #endif entry=SetMagickInfo("JPE"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPS"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PJPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } 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 MemoryInstrumentation::GetVmRegionsForHeapProfiler( RequestGlobalDumpCallback callback) { const auto& coordinator = GetCoordinatorBindingForCurrentThread(); coordinator->GetVmRegionsForHeapProfiler(callback); } CWE ID: CWE-269 Target: 1 Example 2: Code: static int is_ascii_string(char* s, int len) { int ret = 1, i = 0; for(i = 0; i < len; i++) { if ( !isascii( s[i] ) ) { ret = 0; break; } } return ret; } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int read_request(int fd, debugger_request_t* out_request) { ucred cr; socklen_t len = sizeof(cr); int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len); if (status != 0) { ALOGE("cannot get credentials"); return -1; } ALOGV("reading tid"); fcntl(fd, F_SETFL, O_NONBLOCK); pollfd pollfds[1]; pollfds[0].fd = fd; pollfds[0].events = POLLIN; pollfds[0].revents = 0; status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000)); if (status != 1) { ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid); return -1; } debugger_msg_t msg; memset(&msg, 0, sizeof(msg)); status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg))); if (status < 0) { ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid); return -1; } if (status != sizeof(debugger_msg_t)) { ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid); return -1; } out_request->action = static_cast<debugger_action_t>(msg.action); out_request->tid = msg.tid; out_request->pid = cr.pid; out_request->uid = cr.uid; out_request->gid = cr.gid; out_request->abort_msg_address = msg.abort_msg_address; out_request->original_si_code = msg.original_si_code; if (msg.action == DEBUGGER_ACTION_CRASH) { char buf[64]; struct stat s; snprintf(buf, sizeof buf, "/proc/%d/task/%d", out_request->pid, out_request->tid); if (stat(buf, &s)) { ALOGE("tid %d does not exist in pid %d. ignoring debug request\n", out_request->tid, out_request->pid); return -1; } } else if (cr.uid == 0 || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) { status = get_process_info(out_request->tid, &out_request->pid, &out_request->uid, &out_request->gid); if (status < 0) { ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid); return -1; } if (!selinux_action_allowed(fd, out_request)) return -1; } else { return -1; } return 0; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int jpg_validate(jas_stream_t *in) { uchar buf[JPG_MAGICLEN]; int i; int n; assert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN); /* Read the validation data (i.e., the data used for detecting the format). */ if ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) { return -1; } /* Put the validation data back onto the stream, so that the stream position will not be changed. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Did we read enough data? */ if (n < JPG_MAGICLEN) { return -1; } /* Does this look like JPEG? */ if (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) { return -1; } return 0; } CWE ID: CWE-190 Target: 1 Example 2: Code: void Dispatcher::UpdateContentCapabilities(ScriptContext* context) { APIPermissionSet permissions; for (const auto& extension : *RendererExtensionRegistry::Get()->GetMainThreadExtensionSet()) { const ContentCapabilitiesInfo& info = ContentCapabilitiesInfo::Get(extension.get()); if (info.url_patterns.MatchesURL(context->url())) { APIPermissionSet new_permissions; APIPermissionSet::Union(permissions, info.permissions, &new_permissions); permissions = new_permissions; } } context->set_content_capabilities(permissions); } 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: void OxideQQuickWebViewPrivate::attachContextSignals( OxideQQuickWebContextPrivate* context) { Q_Q(OxideQQuickWebView); if (!context) { return; } QObject::connect(context, SIGNAL(destroyed()), q, SLOT(contextDestroyed())); QObject::connect(context, SIGNAL(constructed()), q, SLOT(contextConstructed())); } 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: bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices, uint32 close_types) { if (indices.empty()) return true; bool retval = true; std::vector<TabContentsWrapper*> tabs; for (size_t i = 0; i < indices.size(); ++i) tabs.push_back(GetContentsAt(indices[i])); if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) { std::map<RenderProcessHost*, size_t> processes; for (size_t i = 0; i < indices.size(); ++i) { if (!delegate_->CanCloseContentsAt(indices[i])) { retval = false; continue; } TabContentsWrapper* detached_contents = GetContentsAt(indices[i]); RenderProcessHost* process = detached_contents->tab_contents()->GetRenderProcessHost(); std::map<RenderProcessHost*, size_t>::iterator iter = processes.find(process); if (iter == processes.end()) { processes[process] = 1; } else { iter->second++; } } for (std::map<RenderProcessHost*, size_t>::iterator iter = processes.begin(); iter != processes.end(); ++iter) { iter->first->FastShutdownForPageCount(iter->second); } } for (size_t i = 0; i < tabs.size(); ++i) { TabContentsWrapper* detached_contents = tabs[i]; int index = GetIndexOfTabContents(detached_contents); if (index == kNoTab) continue; detached_contents->tab_contents()->OnCloseStarted(); if (!delegate_->CanCloseContentsAt(index)) { retval = false; continue; } if (!detached_contents->tab_contents()->closed_by_user_gesture()) { detached_contents->tab_contents()->set_closed_by_user_gesture( close_types & CLOSE_USER_GESTURE); } if (delegate_->RunUnloadListenerBeforeClosing(detached_contents)) { retval = false; continue; } InternalCloseTab(detached_contents, index, (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0); } return retval; } CWE ID: CWE-20 Target: 1 Example 2: Code: static void Ins_DEPTH( INS_ARG ) { args[0] = CUR.top; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void nfs4_opendata_free(struct kref *kref) { struct nfs4_opendata *p = container_of(kref, struct nfs4_opendata, kref); struct super_block *sb = p->dentry->d_sb; nfs_free_seqid(p->o_arg.seqid); if (p->state != NULL) nfs4_put_open_state(p->state); nfs4_put_state_owner(p->owner); dput(p->dir); dput(p->dentry); nfs_sb_deactive(sb); nfs_fattr_free_names(&p->f_attr); kfree(p); } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void NormalPageArena::promptlyFreeObject(HeapObjectHeader* header) { ASSERT(!getThreadState()->sweepForbidden()); ASSERT(header->checkHeader()); Address address = reinterpret_cast<Address>(header); Address payload = header->payload(); size_t size = header->size(); size_t payloadSize = header->payloadSize(); ASSERT(size > 0); ASSERT(pageFromObject(address) == findPageFromAddress(address)); { ThreadState::SweepForbiddenScope forbiddenScope(getThreadState()); header->finalize(payload, payloadSize); if (address + size == m_currentAllocationPoint) { m_currentAllocationPoint = address; setRemainingAllocationSize(m_remainingAllocationSize + size); SET_MEMORY_INACCESSIBLE(address, size); return; } SET_MEMORY_INACCESSIBLE(payload, payloadSize); header->markPromptlyFreed(); } m_promptlyFreedSize += size; } CWE ID: CWE-119 Target: 1 Example 2: Code: int ip_mc_output(struct sk_buff *skb) { struct sock *sk = skb->sk; struct rtable *rt = skb_rtable(skb); struct net_device *dev = rt->dst.dev; /* * If the indicated interface is up and running, send the packet. */ IP_UPD_PO_STATS(dev_net(dev), IPSTATS_MIB_OUT, skb->len); skb->dev = dev; skb->protocol = htons(ETH_P_IP); /* * Multicasts are looped back for other local users */ if (rt->rt_flags&RTCF_MULTICAST) { if (sk_mc_loop(sk) #ifdef CONFIG_IP_MROUTE /* Small optimization: do not loopback not local frames, which returned after forwarding; they will be dropped by ip_mr_input in any case. Note, that local frames are looped back to be delivered to local recipients. This check is duplicated in ip_mr_input at the moment. */ && ((rt->rt_flags & RTCF_LOCAL) || !(IPCB(skb)->flags & IPSKB_FORWARDED)) #endif ) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); if (newskb) NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, newskb, NULL, newskb->dev, ip_dev_loopback_xmit); } /* Multicasts with ttl 0 must not go beyond the host */ if (ip_hdr(skb)->ttl == 0) { kfree_skb(skb); return 0; } } if (rt->rt_flags&RTCF_BROADCAST) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); if (newskb) NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, newskb, NULL, newskb->dev, ip_dev_loopback_xmit); } return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING, skb, NULL, skb->dev, ip_finish_output, !(IPCB(skb)->flags & IPSKB_REROUTED)); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void nfs4_open_confirm_release(void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state *state = NULL; /* If this request hasn't been cancelled, do nothing */ if (data->cancelled == 0) goto out_free; /* In case of error, no cleanup! */ if (!data->rpc_done) goto out_free; state = nfs4_opendata_to_nfs4_state(data); if (!IS_ERR(state)) nfs4_close_state(&data->path, state, data->o_arg.open_flags); out_free: nfs4_opendata_put(data); } 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 reflectStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); Element* impl = V8Element::toImpl(holder); V8StringResource<> cppValue = v8Value; if (!cppValue.prepare()) return; impl->setAttribute(HTMLNames::reflectstringattributeAttr, cppValue); } CWE ID: CWE-189 Target: 1 Example 2: Code: static void tcp_ecn_create_request(struct request_sock *req, const struct sk_buff *skb, const struct sock *listen_sk, const struct dst_entry *dst) { const struct tcphdr *th = tcp_hdr(skb); const struct net *net = sock_net(listen_sk); bool th_ecn = th->ece && th->cwr; bool ect, ecn_ok; u32 ecn_ok_dst; if (!th_ecn) return; ect = !INET_ECN_is_not_ect(TCP_SKB_CB(skb)->ip_dsfield); ecn_ok_dst = dst_feature(dst, DST_FEATURE_ECN_MASK); ecn_ok = net->ipv4.sysctl_tcp_ecn || ecn_ok_dst; if ((!ect && ecn_ok) || tcp_ca_needs_ecn(listen_sk) || (ecn_ok_dst & DST_FEATURE_ECN_CA)) inet_rsk(req)->ecn_ok = 1; } 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 SVGDocumentExtensions::removePendingSVGFontFaceElementsForRemoval() { m_pendingSVGFontFaceElementsForRemoval.clear(); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void *sock_poll_thread(void *arg) { struct pollfd pfds[MAX_POLL]; memset(pfds, 0, sizeof(pfds)); int h = (intptr_t)arg; for(;;) { prepare_poll_fds(h, pfds); int ret = poll(pfds, ts[h].poll_count, -1); if(ret == -1) { APPL_TRACE_ERROR("poll ret -1, exit the thread, errno:%d, err:%s", errno, strerror(errno)); break; } if(ret != 0) { int need_process_data_fd = TRUE; if(pfds[0].revents) //cmd fd always is the first one { asrt(pfds[0].fd == ts[h].cmd_fdr); if(!process_cmd_sock(h)) { APPL_TRACE_DEBUG("h:%d, process_cmd_sock return false, exit...", h); break; } if(ret == 1) need_process_data_fd = FALSE; else ret--; //exclude the cmd fd } if(need_process_data_fd) process_data_sock(h, pfds, ret); } else {APPL_TRACE_DEBUG("no data, select ret: %d", ret)}; } ts[h].thread_id = -1; APPL_TRACE_DEBUG("socket poll thread exiting, h:%d", h); return 0; } CWE ID: CWE-284 Target: 1 Example 2: Code: CSPSourceTest() : csp(ContentSecurityPolicy::create()) { } 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: GDataFileError GDataFileSystem::AddNewDirectory( const FilePath& directory_path, base::Value* entry_value) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!entry_value) return GDATA_FILE_ERROR_FAILED; scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::CreateFrom(*entry_value)); if (!doc_entry.get()) return GDATA_FILE_ERROR_FAILED; GDataEntry* entry = directory_service_->FindEntryByPathSync(directory_path); if (!entry) return GDATA_FILE_ERROR_FAILED; GDataDirectory* parent_dir = entry->AsGDataDirectory(); if (!parent_dir) return GDATA_FILE_ERROR_FAILED; GDataEntry* new_entry = GDataEntry::FromDocumentEntry( NULL, doc_entry.get(), directory_service_.get()); if (!new_entry) return GDATA_FILE_ERROR_FAILED; parent_dir->AddEntry(new_entry); OnDirectoryChanged(directory_path); return GDATA_FILE_OK; } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SimulateOnBufferCreated(int buffer_id, const base::SharedMemory& shm) { auto handle = base::SharedMemory::DuplicateHandle(shm.handle()); video_capture_impl_->OnBufferCreated( buffer_id, mojo::WrapSharedMemoryHandle(handle, shm.mapped_size(), true /* read_only */)); } CWE ID: CWE-787 Target: 1 Example 2: Code: static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb) { struct sock *sk = d->owner; if (!sk) return; atomic_add(skb->len, &sk->sk_rmem_alloc); skb_queue_tail(&sk->sk_receive_queue, skb); sk->sk_data_ready(sk); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) rfcomm_dlc_throttle(d); } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void MarkingVisitor::ConservativelyMarkHeader(HeapObjectHeader* header) { const GCInfo* gc_info = ThreadHeap::GcInfo(header->GcInfoIndex()); if (gc_info->HasVTable() && !VTableInitialized(header->Payload())) { MarkHeaderNoTracing(header); #if DCHECK_IS_ON() DCHECK(IsUninitializedMemory(header->Payload(), header->PayloadSize())); #endif } else { MarkHeader(header, gc_info->trace_); } } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ExtensionBookmarksTest() : client_(NULL), model_(NULL), node_(NULL), folder_(NULL) {} CWE ID: CWE-399 Target: 1 Example 2: Code: xmlBufGrow(xmlBufPtr buf, int len) { size_t ret; if ((buf == NULL) || (len < 0)) return(-1); if (len == 0) return(0); ret = xmlBufGrowInternal(buf, len); if (buf->error != 0) return(-1); return((int) ret); } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } CWE ID: CWE-404 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: gs_heap_alloc_bytes(gs_memory_t * mem, uint size, client_name_t cname) { gs_malloc_memory_t *mmem = (gs_malloc_memory_t *) mem; byte *ptr = 0; #ifdef DEBUG const char *msg; static const char *const ok_msg = "OK"; # define set_msg(str) (msg = (str)) #else # define set_msg(str) DO_NOTHING #endif /* Exclusive acces so our decisions and changes are 'atomic' */ if (mmem->monitor) gx_monitor_enter(mmem->monitor); if (size > mmem->limit - sizeof(gs_malloc_block_t)) { /* Definitely too large to allocate; also avoids overflow. */ set_msg("exceeded limit"); } else { uint added = size + sizeof(gs_malloc_block_t); if (mmem->limit - added < mmem->used) set_msg("exceeded limit"); else if ((ptr = (byte *) Memento_label(malloc(added), cname)) == 0) set_msg("failed"); else { gs_malloc_block_t *bp = (gs_malloc_block_t *) ptr; /* * We would like to check that malloc aligns blocks at least as * strictly as the compiler (as defined by ARCH_ALIGN_MEMORY_MOD). * However, Microsoft VC 6 does not satisfy this requirement. * See gsmemory.h for more explanation. */ set_msg(ok_msg); if (mmem->allocated) mmem->allocated->prev = bp; bp->next = mmem->allocated; bp->prev = 0; bp->size = size; bp->type = &st_bytes; bp->cname = cname; mmem->allocated = bp; ptr = (byte *) (bp + 1); mmem->used += size + sizeof(gs_malloc_block_t); if (mmem->used > mmem->max_used) mmem->max_used = mmem->used; } } if (mmem->monitor) gx_monitor_leave(mmem->monitor); /* Done with exclusive access */ /* We don't want to 'fill' under mutex to keep the window smaller */ if (ptr) gs_alloc_fill(ptr, gs_alloc_fill_alloc, size); #ifdef DEBUG if (gs_debug_c('a') || msg != ok_msg) dmlprintf6(mem, "[a+]gs_malloc(%s)(%u) = 0x%lx: %s, used=%ld, max=%ld\n", client_name_string(cname), size, (ulong) ptr, msg, mmem->used, mmem->max_used); #endif return ptr; #undef set_msg } CWE ID: CWE-189 Target: 1 Example 2: Code: SearchCandidate(LayoutObject* layoutObject, float distance) : candidateLayoutObject(layoutObject) , candidateDistance(distance) { } 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 ssize_t cuse_read_iter(struct kiocb *kiocb, struct iov_iter *to) { struct fuse_io_priv io = { .async = 0, .file = kiocb->ki_filp }; loff_t pos = 0; return fuse_direct_io(&io, to, &pos, FUSE_DIO_CUSE); } 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 RecordDailyContentLengthHistograms( int64 original_length, int64 received_length, int64 original_length_with_data_reduction_enabled, int64 received_length_with_data_reduction_enabled, int64 original_length_via_data_reduction_proxy, int64 received_length_via_data_reduction_proxy) { if (original_length <= 0 || received_length <= 0) return; UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength", original_length >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength", received_length >> 10); int percent = 0; if (original_length > received_length) { percent = (100 * (original_length - received_length)) / original_length; } UMA_HISTOGRAM_PERCENTAGE("Net.DailyContentSavingPercent", percent); if (original_length_with_data_reduction_enabled <= 0 || received_length_with_data_reduction_enabled <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_DataReductionProxyEnabled", original_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled", received_length_with_data_reduction_enabled >> 10); int percent_data_reduction_proxy_enabled = 0; if (original_length_with_data_reduction_enabled > received_length_with_data_reduction_enabled) { percent_data_reduction_proxy_enabled = 100 * (original_length_with_data_reduction_enabled - received_length_with_data_reduction_enabled) / original_length_with_data_reduction_enabled; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_DataReductionProxyEnabled", percent_data_reduction_proxy_enabled); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled", (100 * received_length_with_data_reduction_enabled) / received_length); if (original_length_via_data_reduction_proxy <= 0 || received_length_via_data_reduction_proxy <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_ViaDataReductionProxy", original_length_via_data_reduction_proxy >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_ViaDataReductionProxy", received_length_via_data_reduction_proxy >> 10); int percent_via_data_reduction_proxy = 0; if (original_length_via_data_reduction_proxy > received_length_via_data_reduction_proxy) { percent_via_data_reduction_proxy = 100 * (original_length_via_data_reduction_proxy - received_length_via_data_reduction_proxy) / original_length_via_data_reduction_proxy; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_ViaDataReductionProxy", percent_via_data_reduction_proxy); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_ViaDataReductionProxy", (100 * received_length_via_data_reduction_proxy) / received_length); } CWE ID: CWE-416 Target: 1 Example 2: Code: void MessageLoopForUI::Attach() { static_cast<MessagePumpUIApplication*>(pump_.get())->Attach(this); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: append_utf8_value (const unsigned char *value, size_t length, struct stringbuf *sb) { unsigned char tmp[6]; const unsigned char *s; size_t n; int i, nmore; if (length && (*value == ' ' || *value == '#')) { tmp[0] = '\\'; tmp[1] = *value; put_stringbuf_mem (sb, tmp, 2); value++; length--; } if (length && value[length-1] == ' ') { tmp[0] = '\\'; tmp[1] = ' '; put_stringbuf_mem (sb, tmp, 2); length--; } /* FIXME: check that the invalid encoding handling is correct */ for (s=value, n=0;;) { for (value = s; n < length && !(*s & 0x80); n++, s++) for (value = s; n < length && !(*s & 0x80); n++, s++) ; append_quoted (sb, value, s-value, 0); if (n==length) return; /* ready */ assert ((*s & 0x80)); if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */ nmore = 1; else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */ nmore = 2; else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */ nmore = 3; else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */ nmore = 4; else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */ nmore = 5; else /* invalid encoding */ nmore = 5; /* we will reduce the check length anyway */ if (n+nmore > length) nmore = length - n; /* oops, encoding to short */ tmp[0] = *s++; n++; for (i=1; i <= nmore; i++) { if ( (*s & 0xc0) != 0x80) break; /* invalid encoding - stop */ tmp[i] = *s++; n++; } put_stringbuf_mem (sb, tmp, i); } } 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 ssize_t n_tty_write(struct tty_struct *tty, struct file *file, const unsigned char *buf, size_t nr) { const unsigned char *b = buf; DECLARE_WAITQUEUE(wait, current); int c; ssize_t retval = 0; /* Job control check -- must be done at start (POSIX.1 7.1.1.4). */ if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) { retval = tty_check_change(tty); if (retval) return retval; } down_read(&tty->termios_rwsem); /* Write out any echoed characters that are still pending */ process_echoes(tty); add_wait_queue(&tty->write_wait, &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (signal_pending(current)) { retval = -ERESTARTSYS; break; } if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) { retval = -EIO; break; } if (O_OPOST(tty)) { while (nr > 0) { ssize_t num = process_output_block(tty, b, nr); if (num < 0) { if (num == -EAGAIN) break; retval = num; goto break_out; } b += num; nr -= num; if (nr == 0) break; c = *b; if (process_output(c, tty) < 0) break; b++; nr--; } if (tty->ops->flush_chars) tty->ops->flush_chars(tty); } else { while (nr > 0) { c = tty->ops->write(tty, b, nr); if (c < 0) { retval = c; goto break_out; } if (!c) break; b += c; nr -= c; } } if (!nr) break; if (file->f_flags & O_NONBLOCK) { retval = -EAGAIN; break; } up_read(&tty->termios_rwsem); schedule(); down_read(&tty->termios_rwsem); } break_out: __set_current_state(TASK_RUNNING); remove_wait_queue(&tty->write_wait, &wait); if (b - buf != nr && tty->fasync) set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); up_read(&tty->termios_rwsem); return (b - buf) ? b - buf : retval; } CWE ID: CWE-362 Target: 1 Example 2: Code: static void corsSettingAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); String resultValue = imp->fastGetAttribute(HTMLNames::corssettingattributeAttr); if (resultValue.isNull()) { ; } else if (resultValue.isEmpty()) { resultValue = "anonymous"; } else if (equalIgnoringCase(resultValue, "anonymous")) { resultValue = "anonymous"; } else if (equalIgnoringCase(resultValue, "use-credentials")) { resultValue = "use-credentials"; } else { resultValue = "anonymous"; } v8SetReturnValueString(info, resultValue, info.GetIsolate()); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AutofillManager::OnHidePopup() { if (!IsAutofillEnabled()) return; autocomplete_history_manager_->CancelPendingQuery(); client_->HideAutofillPopup(); } 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 char *print_number( cJSON *item ) { char *str; double f, f2; int64_t i; str = (char*) cJSON_malloc( 64 ); if ( str ) { f = item->valuefloat; i = f; f2 = i; if ( f2 == f && item->valueint >= LLONG_MIN && item->valueint <= LLONG_MAX ) sprintf( str, "%lld", (long long) item->valueint ); else sprintf( str, "%g", item->valuefloat ); } return str; } CWE ID: CWE-119 Target: 1 Example 2: Code: xmlSAXParseDoc(xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery) { xmlDocPtr ret; xmlParserCtxtPtr ctxt; xmlSAXHandlerPtr oldsax = NULL; if (cur == NULL) return(NULL); ctxt = xmlCreateDocParserCtxt(cur); if (ctxt == NULL) return(NULL); if (sax != NULL) { oldsax = ctxt->sax; ctxt->sax = sax; ctxt->userData = NULL; } xmlDetectSAX2(ctxt); xmlParseDocument(ctxt); if ((ctxt->wellFormed) || recovery) ret = ctxt->myDoc; else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if (sax != NULL) ctxt->sax = oldsax; xmlFreeParserCtxt(ctxt); return(ret); } CWE ID: CWE-611 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Document::removeFormAssociation(Element* element) { auto it = m_associatedFormControls.find(element); if (it == m_associatedFormControls.end()) return; m_associatedFormControls.remove(it); if (m_associatedFormControls.isEmpty()) m_didAssociateFormControlsTimer.stop(); } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void copyTrespass( short * /* dst */, const int *const * /* src */, unsigned /* nSamples */, unsigned /* nChannels */) { TRESPASS(); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int nl80211_join_mesh(struct sk_buff *skb, struct genl_info *info) { struct cfg80211_registered_device *rdev = info->user_ptr[0]; struct net_device *dev = info->user_ptr[1]; struct mesh_config cfg; struct mesh_setup setup; int err; /* start with default */ memcpy(&cfg, &default_mesh_config, sizeof(cfg)); memcpy(&setup, &default_mesh_setup, sizeof(setup)); if (info->attrs[NL80211_ATTR_MESH_CONFIG]) { /* and parse parameters if given */ err = nl80211_parse_mesh_config(info, &cfg, NULL); if (err) return err; } if (!info->attrs[NL80211_ATTR_MESH_ID] || !nla_len(info->attrs[NL80211_ATTR_MESH_ID])) return -EINVAL; setup.mesh_id = nla_data(info->attrs[NL80211_ATTR_MESH_ID]); setup.mesh_id_len = nla_len(info->attrs[NL80211_ATTR_MESH_ID]); if (info->attrs[NL80211_ATTR_MESH_SETUP]) { /* parse additional setup parameters if given */ err = nl80211_parse_mesh_setup(info, &setup); if (err) return err; } return cfg80211_join_mesh(rdev, dev, &setup, &cfg); } 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: lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */ 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 LayerWebKitThread::setNeedsCommit() { if (m_owner) m_owner->notifySyncRequired(); } CWE ID: CWE-20 Target: 1 Example 2: Code: static int protocol_client_init(VncState *vs, uint8_t *data, size_t len) { char buf[1024]; VncShareMode mode; int size; mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE; switch (vs->vd->share_policy) { case VNC_SHARE_POLICY_IGNORE: /* * Ignore the shared flag. Nothing to do here. * * Doesn't conform to the rfb spec but is traditional qemu * behavior, thus left here as option for compatibility * reasons. */ break; case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE: /* * Policy: Allow clients ask for exclusive access. * * Implementation: When a client asks for exclusive access, * disconnect all others. Shared connects are allowed as long * as no exclusive connection exists. * * This is how the rfb spec suggests to handle the shared flag. */ if (mode == VNC_SHARE_MODE_EXCLUSIVE) { VncState *client; QTAILQ_FOREACH(client, &vs->vd->clients, next) { if (vs == client) { continue; } if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE && client->share_mode != VNC_SHARE_MODE_SHARED) { continue; } vnc_disconnect_start(client); } } if (mode == VNC_SHARE_MODE_SHARED) { if (vs->vd->num_exclusive > 0) { vnc_disconnect_start(vs); return 0; } } break; case VNC_SHARE_POLICY_FORCE_SHARED: /* * Policy: Shared connects only. * Implementation: Disallow clients asking for exclusive access. * * Useful for shared desktop sessions where you don't want * someone forgetting to say -shared when running the vnc * client disconnect everybody else. */ if (mode == VNC_SHARE_MODE_EXCLUSIVE) { vnc_disconnect_start(vs); return 0; } break; } vnc_set_share_mode(vs, mode); vs->client_width = pixman_image_get_width(vs->vd->server); vs->client_height = pixman_image_get_height(vs->vd->server); vnc_write_u16(vs, vs->client_width); vnc_write_u16(vs, vs->client_height); pixel_format_message(vs); if (qemu_name) size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name); else size = snprintf(buf, sizeof(buf), "QEMU"); vnc_write_u32(vs, size); vnc_write(vs, buf, size); vnc_flush(vs); vnc_client_cache_auth(vs); vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED); vnc_read_when(vs, protocol_client_msg, 1); 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: int GetZoomPercent(const content::WebContents* contents, bool* enable_plus, bool* enable_minus) { int percent = zoom::ZoomController::FromWebContents(contents)->GetZoomPercent(); *enable_plus = percent < contents->GetMaximumZoomPercent(); *enable_minus = percent > contents->GetMinimumZoomPercent(); return percent; } 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: png_get_uint_16(png_bytep buf) { png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) + (png_uint_16)(*(buf + 1))); return (i); } CWE ID: CWE-119 Target: 1 Example 2: Code: CJSON_PUBLIC(void) cJSON_Minify(char *json) { unsigned char *into = (unsigned char*)json; if (json == NULL) { return; } while (*json) { if (*json == ' ') { json++; } else if (*json == '\t') { /* Whitespace characters. */ json++; } else if (*json == '\r') { json++; } else if (*json=='\n') { json++; } else if ((*json == '/') && (json[1] == '/')) { /* double-slash comments, to end of line. */ while (*json && (*json != '\n')) { json++; } } else if ((*json == '/') && (json[1] == '*')) { /* multiline comments. */ while (*json && !((*json == '*') && (json[1] == '/'))) { json++; } json += 2; } else if (*json == '\"') { /* string literals, which are \" sensitive. */ *into++ = (unsigned char)*json++; while (*json && (*json != '\"')) { if (*json == '\\') { *into++ = (unsigned char)*json++; } *into++ = (unsigned char)*json++; } *into++ = (unsigned char)*json++; } else { /* All other characters. */ *into++ = (unsigned char)*json++; } } /* and null-terminate. */ *into = '\0'; } CWE ID: CWE-754 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObject, BOOL ignoreOpenFiles) { PEXTENSION extension = deviceObject->DeviceExtension; NTSTATUS ntStatus; HANDLE volumeHandle; PFILE_OBJECT volumeFileObject; Dump ("UnmountDevice %d\n", extension->nDosDriveNo); ntStatus = TCOpenFsVolume (extension, &volumeHandle, &volumeFileObject); if (NT_SUCCESS (ntStatus)) { int dismountRetry; if (IsOSAtLeast (WIN_7) && !extension->bReadOnly) { NTFS_VOLUME_DATA_BUFFER ntfsData; if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) DriverUnloadDisabled = TRUE; } ntStatus = TCFsctlCall (volumeFileObject, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0); Dump ("FSCTL_LOCK_VOLUME returned %X\n", ntStatus); if (!NT_SUCCESS (ntStatus) && !ignoreOpenFiles) { TCCloseFsVolume (volumeHandle, volumeFileObject); return ERR_FILES_OPEN; } for (dismountRetry = 0; dismountRetry < 200; ++dismountRetry) { ntStatus = TCFsctlCall (volumeFileObject, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0); Dump ("FSCTL_DISMOUNT_VOLUME returned %X\n", ntStatus); if (NT_SUCCESS (ntStatus) || ntStatus == STATUS_VOLUME_DISMOUNTED) break; if (!ignoreOpenFiles) { TCCloseFsVolume (volumeHandle, volumeFileObject); return ERR_FILES_OPEN; } TCSleep (100); } } else { if (!ignoreOpenFiles) return ERR_FILES_OPEN; else volumeHandle = NULL; } if (extension->bMountManager) MountManagerUnmount (extension->nDosDriveNo); RemoveDriveLink (extension->nDosDriveNo); extension->bShuttingDown = TRUE; ntStatus = IoAcquireRemoveLock (&extension->Queue.RemoveLock, NULL); ASSERT (NT_SUCCESS (ntStatus)); IoReleaseRemoveLockAndWait (&extension->Queue.RemoveLock, NULL); if (volumeHandle != NULL) TCCloseFsVolume (volumeHandle, volumeFileObject); if (unmountRequest) { PCRYPTO_INFO cryptoInfo = ((PEXTENSION) deviceObject->DeviceExtension)->cryptoInfo; unmountRequest->HiddenVolumeProtectionTriggered = (cryptoInfo->bProtectHiddenVolume && cryptoInfo->bHiddenVolProtectionAction); } TCDeleteDeviceObject (deviceObject, (PEXTENSION) deviceObject->DeviceExtension); return 0; } CWE ID: CWE-119 Output:
0