prompt
stringlengths
799
20.4k
output
int64
0
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ElementsUploadDataStreamTest::FileChangedHelper( const base::FilePath& file_path, const base::Time& time, bool error_expected) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(base::MakeUnique<UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time)); TestCompletionCallback init_callback; std::unique_ptr<UploadDataStream> stream( new ElementsUploadDataStream(std::move(element_readers), 0)); ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()), IsError(ERR_IO_PENDING)); int error_code = init_callback.WaitForResult(); if (error_expected) ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED)); else ASSERT_THAT(error_code, IsOk()); } CWE ID: CWE-311 Target: 1 Example 2: Code: dest_get_scanline_wide (pixman_iter_t *iter, const uint32_t *mask) { bits_image_t * image = &iter->image->bits; int x = iter->x; int y = iter->y; int width = iter->width; argb_t * buffer = (argb_t *)iter->buffer; image->fetch_scanline_float ( image, x, y, width, (uint32_t *)buffer, mask); if (image->common.alpha_map) { argb_t *alpha; if ((alpha = malloc (width * sizeof (argb_t)))) { int i; x -= image->common.alpha_origin_x; y -= image->common.alpha_origin_y; image->common.alpha_map->fetch_scanline_float ( image->common.alpha_map, x, y, width, (uint32_t *)alpha, mask); for (i = 0; i < width; ++i) buffer[i].a = alpha[i].a; free (alpha); } } return iter->buffer; } 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: PHP_FUNCTION(xml_set_object) { xml_parser *parser; zval *pind, *mythis; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ro", &pind, &mythis) == FAILURE) { return; } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); /* please leave this commented - or ask [email protected] before doing it (again) */ if (parser->object) { zval_ptr_dtor(&parser->object); } /* please leave this commented - or ask [email protected] before doing it (again) */ /* #ifdef ZEND_ENGINE_2 zval_add_ref(&parser->object); #endif */ ALLOC_ZVAL(parser->object); MAKE_COPY_ZVAL(&mythis, parser->object); RETVAL_TRUE; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode) { if (file->f_flags & O_DSYNC) return 0; if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE)) return 1; if (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL || (inode->i_flock->fl_start == 0 && inode->i_flock->fl_end == OFFSET_MAX && inode->i_flock->fl_type != F_RDLCK))) return 1; return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int cma_modify_qp_rtr(struct rdma_id_private *id_priv, struct rdma_conn_param *conn_param) { struct ib_qp_attr qp_attr; int qp_attr_mask, ret; union ib_gid sgid; mutex_lock(&id_priv->qp_mutex); if (!id_priv->id.qp) { ret = 0; goto out; } /* Need to update QP attributes from default values. */ qp_attr.qp_state = IB_QPS_INIT; ret = rdma_init_qp_attr(&id_priv->id, &qp_attr, &qp_attr_mask); if (ret) goto out; ret = ib_modify_qp(id_priv->id.qp, &qp_attr, qp_attr_mask); if (ret) goto out; qp_attr.qp_state = IB_QPS_RTR; ret = rdma_init_qp_attr(&id_priv->id, &qp_attr, &qp_attr_mask); if (ret) goto out; ret = ib_query_gid(id_priv->id.device, id_priv->id.port_num, qp_attr.ah_attr.grh.sgid_index, &sgid); if (ret) goto out; if (rdma_node_get_transport(id_priv->cma_dev->device->node_type) == RDMA_TRANSPORT_IB && rdma_port_get_link_layer(id_priv->id.device, id_priv->id.port_num) == IB_LINK_LAYER_ETHERNET) { ret = rdma_addr_find_smac_by_sgid(&sgid, qp_attr.smac, NULL); if (ret) goto out; } if (conn_param) qp_attr.max_dest_rd_atomic = conn_param->responder_resources; ret = ib_modify_qp(id_priv->id.qp, &qp_attr, qp_attr_mask); out: mutex_unlock(&id_priv->qp_mutex); return ret; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vrend_destroy_sampler_view_object(void *obj_ptr) { struct vrend_sampler_view *samp = obj_ptr; vrend_sampler_view_reference(&samp, NULL); } CWE ID: CWE-772 Output:
0
Here are some example code snippets. Analyze the following 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 CleanUp(DownloadId id) { MockDownloadFile* file = download_file_factory_->GetExistingFile(id); ASSERT_TRUE(file != NULL); EXPECT_CALL(*file, Cancel()); download_file_manager_->CancelDownload(id); EXPECT_TRUE(NULL == download_file_manager_->GetDownloadFile(id)); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *time) { jas_iccputuint16(out, time->year); jas_iccputuint16(out, time->month); jas_iccputuint16(out, time->day); jas_iccputuint16(out, time->hour); jas_iccputuint16(out, time->min); jas_iccputuint16(out, time->sec); return 0; } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool PluginInfoMessageFilter::Context::FindEnabledPlugin( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, ChromeViewHostMsg_GetPluginInfo_Status* status, WebPluginInfo* plugin, std::string* actual_mime_type, scoped_ptr<PluginMetadata>* plugin_metadata) const { bool allow_wildcard = true; std::vector<WebPluginInfo> matching_plugins; std::vector<std::string> mime_types; PluginService::GetInstance()->GetPluginInfoArray( url, mime_type, allow_wildcard, &matching_plugins, &mime_types); if (matching_plugins.empty()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound; return false; } content::PluginServiceFilter* filter = PluginService::GetInstance()->GetFilter(); size_t i = 0; for (; i < matching_plugins.size(); ++i) { if (!filter || filter->IsPluginEnabled(render_process_id_, render_view_id, resource_context_, url, top_origin_url, &matching_plugins[i])) { break; } } bool enabled = i < matching_plugins.size(); if (!enabled) { i = 0; status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled; } *plugin = matching_plugins[i]; *actual_mime_type = mime_types[i]; if (plugin_metadata) *plugin_metadata = PluginFinder::GetInstance()->GetPluginMetadata(*plugin); return enabled; } CWE ID: CWE-287 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool ExecuteTranspose(LocalFrame& frame, Event*, EditorCommandSource, const String&) { frame.GetEditor().Transpose(); return true; } CWE ID: Target: 1 Example 2: Code: static struct cm_timewait_info * cm_create_timewait_info(__be32 local_id) { struct cm_timewait_info *timewait_info; timewait_info = kzalloc(sizeof *timewait_info, GFP_KERNEL); if (!timewait_info) return ERR_PTR(-ENOMEM); timewait_info->work.local_id = local_id; INIT_DELAYED_WORK(&timewait_info->work.work, cm_work_handler); timewait_info->work.cm_event.event = IB_CM_TIMEWAIT_EXIT; return timewait_info; } 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 SendStatus(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { std::string response = "HTTP/1.1 200 OK\r\n" "Content-Length:2\r\n\r\n" "ok"; mg_write(connection, response.data(), response.length()); } 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 ExtensionInstallDialogView::InitView() { int left_column_width = (prompt_->ShouldShowPermissions() || prompt_->GetRetainedFileCount() > 0) ? kPermissionsLeftColumnWidth : kNoPermissionsLeftColumnWidth; if (is_external_install()) left_column_width = kExternalInstallLeftColumnWidth; int column_set_id = 0; views::GridLayout* layout = CreateLayout(left_column_width, column_set_id); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); if (prompt_->has_webstore_data()) { layout->StartRow(0, column_set_id); views::View* rating = new views::View(); rating->SetLayoutManager(new views::BoxLayout( views::BoxLayout::kHorizontal, 0, 0, 0)); layout->AddView(rating); prompt_->AppendRatingStars(AddResourceIcon, rating); const gfx::FontList& small_font_list = rb.GetFontList(ui::ResourceBundle::SmallFont); views::Label* rating_count = new views::Label(prompt_->GetRatingCount(), small_font_list); rating_count->SetBorder(views::Border::CreateEmptyBorder(0, 2, 0, 0)); rating->AddChildView(rating_count); layout->StartRow(0, column_set_id); views::Label* user_count = new views::Label(prompt_->GetUserCount(), small_font_list); user_count->SetAutoColorReadabilityEnabled(false); user_count->SetEnabledColor(SK_ColorGRAY); layout->AddView(user_count); layout->StartRow(0, column_set_id); views::Link* store_link = new views::Link( l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_STORE_LINK)); store_link->SetFontList(small_font_list); store_link->set_listener(this); layout->AddView(store_link); if (prompt_->ShouldShowPermissions()) { layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); layout->StartRow(0, column_set_id); layout->AddView(new views::Separator(views::Separator::HORIZONTAL), 3, 1, views::GridLayout::FILL, views::GridLayout::FILL); } } int content_width = left_column_width + views::kPanelHorizMargin + kIconSize; CustomScrollableView* scrollable = new CustomScrollableView(); views::GridLayout* scroll_layout = new views::GridLayout(scrollable); scrollable->SetLayoutManager(scroll_layout); views::ColumnSet* scrollable_column_set = scroll_layout->AddColumnSet(column_set_id); int scrollable_width = prompt_->has_webstore_data() ? content_width : left_column_width; scrollable_column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, // no resizing views::GridLayout::USE_PREF, scrollable_width, scrollable_width); int padding_width = content_width + views::kButtonHEdgeMarginNew - scrollable_width; scrollable_column_set->AddPaddingColumn(0, padding_width); layout->StartRow(0, column_set_id); scroll_view_ = new views::ScrollView(); scroll_view_->set_hide_horizontal_scrollbar(true); scroll_view_->SetContents(scrollable); layout->AddView(scroll_view_, 4, 1); if (is_bundle_install()) { BundleInstaller::ItemList items = prompt_->bundle()->GetItemsWithState( BundleInstaller::Item::STATE_PENDING); scroll_layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing); for (const BundleInstaller::Item& item : items) { scroll_layout->StartRow(0, column_set_id); views::Label* extension_label = new views::Label(item.GetNameForDisplay()); extension_label->SetMultiLine(true); extension_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); extension_label->SizeToFit( scrollable_width - kSmallIconSize - kSmallIconPadding); gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(item.icon); scroll_layout->AddView(new IconedView(extension_label, image)); } scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); } if (prompt_->ShouldShowPermissions()) { bool has_permissions = prompt_->GetPermissionCount( ExtensionInstallPrompt::PermissionsType::ALL_PERMISSIONS) > 0; if (has_permissions) { AddPermissions( scroll_layout, rb, column_set_id, scrollable_width, ExtensionInstallPrompt::PermissionsType::REGULAR_PERMISSIONS); AddPermissions( scroll_layout, rb, column_set_id, scrollable_width, ExtensionInstallPrompt::PermissionsType::WITHHELD_PERMISSIONS); } else { scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); scroll_layout->StartRow(0, column_set_id); views::Label* permission_label = new views::Label( l10n_util::GetStringUTF16(IDS_EXTENSION_NO_SPECIAL_PERMISSIONS)); permission_label->SetMultiLine(true); permission_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); permission_label->SizeToFit(scrollable_width); scroll_layout->AddView(permission_label); } } if (prompt_->GetRetainedFileCount()) { scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); scroll_layout->StartRow(0, column_set_id); views::Label* retained_files_header = new views::Label(prompt_->GetRetainedFilesHeading()); retained_files_header->SetMultiLine(true); retained_files_header->SetHorizontalAlignment(gfx::ALIGN_LEFT); retained_files_header->SizeToFit(scrollable_width); scroll_layout->AddView(retained_files_header); scroll_layout->StartRow(0, column_set_id); PermissionDetails details; for (size_t i = 0; i < prompt_->GetRetainedFileCount(); ++i) { details.push_back(prompt_->GetRetainedFile(i)); } ExpandableContainerView* issue_advice_view = new ExpandableContainerView(this, base::string16(), details, scrollable_width, false); scroll_layout->AddView(issue_advice_view); } if (prompt_->GetRetainedDeviceCount()) { scroll_layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); scroll_layout->StartRow(0, column_set_id); views::Label* retained_devices_header = new views::Label(prompt_->GetRetainedDevicesHeading()); retained_devices_header->SetMultiLine(true); retained_devices_header->SetHorizontalAlignment(gfx::ALIGN_LEFT); retained_devices_header->SizeToFit(scrollable_width); scroll_layout->AddView(retained_devices_header); scroll_layout->StartRow(0, column_set_id); PermissionDetails details; for (size_t i = 0; i < prompt_->GetRetainedDeviceCount(); ++i) { details.push_back(prompt_->GetRetainedDeviceMessageString(i)); } ExpandableContainerView* issue_advice_view = new ExpandableContainerView(this, base::string16(), details, scrollable_width, false); scroll_layout->AddView(issue_advice_view); } DCHECK(prompt_->type() >= 0); UMA_HISTOGRAM_ENUMERATION("Extensions.InstallPrompt.Type", prompt_->type(), ExtensionInstallPrompt::NUM_PROMPT_TYPES); scroll_view_->ClipHeightTo( 0, std::min(kScrollViewMaxHeight, scrollable->GetPreferredSize().height())); dialog_size_ = gfx::Size( content_width + 2 * views::kButtonHEdgeMarginNew, container_->GetPreferredSize().height()); std::string event_name = ExperienceSamplingEvent::kExtensionInstallDialog; event_name.append( ExtensionInstallPrompt::PromptTypeToString(prompt_->type())); sampling_event_ = ExperienceSamplingEvent::Create(event_name); } CWE ID: CWE-17 Target: 1 Example 2: Code: static int tomoyo_audit_mount_log(struct tomoyo_request_info *r) { const char *dev = r->param.mount.dev->name; const char *dir = r->param.mount.dir->name; const char *type = r->param.mount.type->name; const unsigned long flags = r->param.mount.flags; if (r->granted) return 0; if (!strcmp(type, TOMOYO_MOUNT_REMOUNT_KEYWORD)) tomoyo_warn_log(r, "mount -o remount %s 0x%lX", dir, flags); else if (!strcmp(type, TOMOYO_MOUNT_BIND_KEYWORD) || !strcmp(type, TOMOYO_MOUNT_MOVE_KEYWORD)) tomoyo_warn_log(r, "mount %s %s %s 0x%lX", type, dev, dir, flags); else if (!strcmp(type, TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD) || !strcmp(type, TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD) || !strcmp(type, TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD) || !strcmp(type, TOMOYO_MOUNT_MAKE_SHARED_KEYWORD)) tomoyo_warn_log(r, "mount %s %s 0x%lX", type, dir, flags); else tomoyo_warn_log(r, "mount -t %s %s %s 0x%lX", type, dev, dir, flags); return tomoyo_supervisor(r, TOMOYO_KEYWORD_ALLOW_MOUNT "%s %s %s 0x%lX\n", tomoyo_pattern(r->param.mount.dev), tomoyo_pattern(r->param.mount.dir), type, flags); } 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 cliOutputGenericHelp(void) { sds version = cliVersion(); printf( "redis-cli %s\n" "To get help about Redis commands type:\n" " \"help @<group>\" to get a list of commands in <group>\n" " \"help <command>\" for help on <command>\n" " \"help <tab>\" to get a list of possible help topics\n" " \"quit\" to exit\n" "\n" "To set redis-cli preferences:\n" " \":set hints\" enable online hints\n" " \":set nohints\" disable online hints\n" "Set your preferences in ~/.redisclirc\n", version ); sdsfree(version); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AppCacheDatabase::ReadCacheRecord( const sql::Statement& statement, CacheRecord* record) { record->cache_id = statement.ColumnInt64(0); record->group_id = statement.ColumnInt64(1); record->online_wildcard = statement.ColumnBool(2); record->update_time = base::Time::FromInternalValue(statement.ColumnInt64(3)); record->cache_size = statement.ColumnInt64(4); } CWE ID: CWE-200 Target: 1 Example 2: Code: void CompleteSavingAsArchiveCreationFailed() { DCHECK(mock_saving_); mock_saving_ = false; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(save_page_callback_), SavePageResult::ARCHIVE_CREATION_FAILED, 0)); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int cma_modify_qp_err(struct rdma_id_private *id_priv) { struct ib_qp_attr qp_attr; int ret; mutex_lock(&id_priv->qp_mutex); if (!id_priv->id.qp) { ret = 0; goto out; } qp_attr.qp_state = IB_QPS_ERR; ret = ib_modify_qp(id_priv->id.qp, &qp_attr, IB_QP_STATE); out: mutex_unlock(&id_priv->qp_mutex); return ret; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int myrecvfrom6(int sockfd, void *buf, size_t *buflen, int flags, struct in6_addr *addr, uint32_t *ifindex) { struct sockaddr_in6 sin6; unsigned char cbuf[CMSG_SPACE(sizeof(struct in6_pktinfo))]; struct iovec iovec; struct msghdr msghdr; struct cmsghdr *cmsghdr; ssize_t len; iovec.iov_len = *buflen; iovec.iov_base = buf; memset(&msghdr, 0, sizeof(msghdr)); msghdr.msg_name = &sin6; msghdr.msg_namelen = sizeof(sin6); msghdr.msg_iov = &iovec; msghdr.msg_iovlen = 1; msghdr.msg_control = cbuf; msghdr.msg_controllen = sizeof(cbuf); len = recvmsg(sockfd, &msghdr, flags); if (len == -1) return -errno; *buflen = len; /* Set ifindex to scope_id now. But since scope_id gets not * set by kernel for linklocal addresses, use pktinfo to obtain that * value right after. */ *ifindex = sin6.sin6_scope_id; for (cmsghdr = CMSG_FIRSTHDR(&msghdr); cmsghdr; cmsghdr = CMSG_NXTHDR(&msghdr, cmsghdr)) { if (cmsghdr->cmsg_level == IPPROTO_IPV6 && cmsghdr->cmsg_type == IPV6_PKTINFO && cmsghdr->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) { struct in6_pktinfo *pktinfo; pktinfo = (struct in6_pktinfo *) CMSG_DATA(cmsghdr); *ifindex = pktinfo->ipi6_ifindex; } } *addr = sin6.sin6_addr; return 0; } CWE ID: CWE-284 Target: 1 Example 2: Code: static void tcp_v6_restore_cb(struct sk_buff *skb) { /* We need to move header back to the beginning if xfrm6_policy_check() * and tcp_v6_fill_cb() are going to be called again. * ip6_datagram_recv_specific_ctl() also expects IP6CB to be there. */ memmove(IP6CB(skb), &TCP_SKB_CB(skb)->header.h6, sizeof(struct inet6_skb_parm)); } 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: struct socket *tun_get_socket(struct file *file) { struct tun_file *tfile; if (file->f_op != &tun_fops) return ERR_PTR(-EINVAL); tfile = file->private_data; if (!tfile) return ERR_PTR(-EBADFD); return &tfile->socket; } 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 inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags, struct rt6_info *rt) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { struct frag_hdr fhdr; skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr, rt); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); } return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } CWE ID: CWE-264 Target: 1 Example 2: Code: static struct llc_sap_state_trans *llc_find_sap_trans(struct llc_sap *sap, struct sk_buff *skb) { int i = 0; struct llc_sap_state_trans *rc = NULL; struct llc_sap_state_trans **next_trans; struct llc_sap_state *curr_state = &llc_sap_state_table[sap->state - 1]; /* * Search thru events for this state until list exhausted or until * its obvious the event is not valid for the current state */ for (next_trans = curr_state->transitions; next_trans[i]->ev; i++) if (!next_trans[i]->ev(sap, skb)) { rc = next_trans[i]; /* got event match; return it */ break; } return rc; } 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: vrrp_native_ipv6_handler(__attribute__((unused)) vector_t *strvec) { vrrp_t *vrrp = LIST_TAIL_DATA(vrrp_data->vrrp); if (vrrp->family == AF_INET) { report_config_error(CONFIG_GENERAL_ERROR,"(%s) Cannot specify native_ipv6 with IPv4 addresses", vrrp->iname); return; } vrrp->family = AF_INET6; vrrp->version = VRRP_VERSION_3; } CWE ID: CWE-59 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int attach_recursive_mnt(struct mount *source_mnt, struct mount *dest_mnt, struct mountpoint *dest_mp, struct path *parent_path) { HLIST_HEAD(tree_list); struct mount *child, *p; struct hlist_node *n; int err; if (IS_MNT_SHARED(dest_mnt)) { err = invent_group_ids(source_mnt, true); if (err) goto out; err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list); lock_mount_hash(); if (err) goto out_cleanup_ids; for (p = source_mnt; p; p = next_mnt(p, source_mnt)) set_mnt_shared(p); } else { lock_mount_hash(); } if (parent_path) { detach_mnt(source_mnt, parent_path); attach_mnt(source_mnt, dest_mnt, dest_mp); touch_mnt_namespace(source_mnt->mnt_ns); } else { mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt); commit_tree(source_mnt, NULL); } hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) { struct mount *q; hlist_del_init(&child->mnt_hash); q = __lookup_mnt_last(&child->mnt_parent->mnt, child->mnt_mountpoint); commit_tree(child, q); } unlock_mount_hash(); return 0; out_cleanup_ids: while (!hlist_empty(&tree_list)) { child = hlist_entry(tree_list.first, struct mount, mnt_hash); umount_tree(child, UMOUNT_SYNC); } unlock_mount_hash(); cleanup_group_ids(source_mnt, NULL); out: return err; } CWE ID: CWE-400 Target: 1 Example 2: Code: static bool HasAccessorsImpl(JSObject* holder, FixedArrayBase* backing_store) { DisallowHeapAllocation no_gc; SeededNumberDictionary* dict = SeededNumberDictionary::cast(backing_store); if (!dict->requires_slow_elements()) return false; int capacity = dict->Capacity(); Isolate* isolate = dict->GetIsolate(); for (int i = 0; i < capacity; i++) { Object* key = dict->KeyAt(i); if (!dict->IsKey(isolate, key)) continue; DCHECK(!dict->IsDeleted(i)); PropertyDetails details = dict->DetailsAt(i); if (details.kind() == kAccessor) return true; } return false; } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SupervisedUserService::AddPermissionRequestInternal( const CreatePermissionRequestCallback& create_request, SuccessCallback callback, size_t index) { size_t next_index = FindEnabledPermissionRequestCreator(index); if (next_index >= permissions_creators_.size()) { std::move(callback).Run(false); return; } create_request.Run( permissions_creators_[next_index].get(), base::BindOnce(&SupervisedUserService::OnPermissionRequestIssued, weak_ptr_factory_.GetWeakPtr(), create_request, std::move(callback), next_index)); } 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: Blob::Blob(const KURL& srcURL, const String& type, long long size) : m_type(type) , m_size(size) { ScriptWrappable::init(this); m_internalURL = BlobURL::createInternalURL(); ThreadableBlobRegistry::registerBlobURL(0, m_internalURL, srcURL); } CWE ID: Target: 1 Example 2: Code: static inline void VectorReciprocal(const DDSVector4 value, DDSVector4 *destination) { destination->x = 1.0f / value.x; destination->y = 1.0f / value.y; destination->z = 1.0f / value.z; destination->w = 1.0f / value.w; } 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 user_ta_dump_state(struct tee_ta_ctx *ctx) { struct user_ta_ctx *utc = to_user_ta_ctx(ctx); struct vm_region *r; char flags[7] = { '\0', }; char desc[13]; size_t n = 0; EMSG_RAW(" arch: %s load address: %#" PRIxVA " ctx-idr: %d", utc->is_32bit ? "arm" : "aarch64", utc->load_addr, utc->vm_info->asid); EMSG_RAW(" stack: 0x%" PRIxVA " %zu", utc->stack_addr, utc->mobj_stack->size); TAILQ_FOREACH(r, &utc->vm_info->regions, link) { paddr_t pa = 0; if (r->mobj) mobj_get_pa(r->mobj, r->offset, 0, &pa); mattr_perm_to_str(flags, sizeof(flags), r->attr); describe_region(utc, r->va, r->size, desc, sizeof(desc)); EMSG_RAW(" region %zu: va %#" PRIxVA " pa %#" PRIxPA " size %#zx flags %s %s", n, r->va, pa, r->size, flags, desc); n++; } show_elfs(utc); } 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 GaiaOAuthClient::Core::FetchUserInfoAndInvokeCallback() { request_.reset(new UrlFetcher( GURL(provider_info_.user_info_url), UrlFetcher::GET)); request_->SetRequestContext(request_context_getter_); request_->SetHeader("Authorization", "Bearer " + access_token_); request_->Start( base::Bind(&GaiaOAuthClient::Core::OnUserInfoFetchComplete, this)); } CWE ID: CWE-399 Target: 1 Example 2: Code: size_t sc_right_trim(u8 *buf, size_t len) { size_t i; if (!buf) return 0; if (len > 0) { for(i = len-1; i > 0; i--) { if(!isprint(buf[i])) { buf[i] = '\0'; len--; continue; } break; } } return len; } 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: int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { int result = -1; if (!a || !b || a->type != b->type) return -1; switch (a->type) { case V_ASN1_OBJECT: result = OBJ_cmp(a->value.object, b->value.object); break; case V_ASN1_BOOLEAN: result = a->value.boolean - b->value.boolean; break; case V_ASN1_NULL: result = 0; /* They do not have content. */ break; case V_ASN1_INTEGER: case V_ASN1_NEG_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_NEG_ENUMERATED: case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: default: result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr, (ASN1_STRING *)b->value.ptr); break; } return result; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name) { int i,n=0,len,nid, first, use_bn; BIGNUM *bl; unsigned long l; const unsigned char *p; char tbuf[DECIMAL_SIZE(i)+DECIMAL_SIZE(l)+2]; if ((a == NULL) || (a->data == NULL)) { buf[0]='\0'; return(0); } if (!no_name && (nid=OBJ_obj2nid(a)) != NID_undef) { s=OBJ_nid2ln(nid); if (s == NULL) s=OBJ_nid2sn(nid); if (s) { if (buf) BUF_strlcpy(buf,s,buf_len); n=strlen(s); return n; } } len=a->length; p=a->data; first = 1; bl = NULL; while (len > 0) { l=0; use_bn = 0; for (;;) { unsigned char c = *p++; len--; if ((len == 0) && (c & 0x80)) goto err; if (use_bn) { if (!BN_add_word(bl, c & 0x7f)) goto err; } else l |= c & 0x7f; if (!(c & 0x80)) break; if (!use_bn && (l > (ULONG_MAX >> 7L))) { if (!bl && !(bl = BN_new())) goto err; if (!BN_set_word(bl, l)) goto err; use_bn = 1; } if (use_bn) { if (!BN_lshift(bl, bl, 7)) goto err; } else l<<=7L; } if (first) { first = 0; if (l >= 80) { i = 2; if (use_bn) { if (!BN_sub_word(bl, 80)) goto err; } else l -= 80; } else { i=(int)(l/40); i=(int)(l/40); l-=(long)(i*40); } if (buf && (buf_len > 0)) { *buf++ = i + '0'; buf_len--; } n++; if (use_bn) { char *bndec; bndec = BN_bn2dec(bl); if (!bndec) goto err; i = strlen(bndec); if (buf) i = strlen(bndec); if (buf) { if (buf_len > 0) { *buf++ = '.'; buf_len--; } BUF_strlcpy(buf,bndec,buf_len); buf_len = 0; } else { buf+=i; buf_len-=i; } } n++; n += i; OPENSSL_free(bndec); } else { BIO_snprintf(tbuf,sizeof tbuf,".%lu",l); i=strlen(tbuf); if (buf && (buf_len > 0)) { BUF_strlcpy(buf,tbuf,buf_len); if (i > buf_len) { buf += buf_len; buf_len = 0; } else { buf+=i; buf_len-=i; } } n+=i; l=0; } } if (bl) BN_free(bl); return n; err: if (bl) BN_free(bl); return -1; } CWE ID: CWE-200 Target: 1 Example 2: Code: void PasswordInputType::OnDetachWithLayoutObject() { GetElement().GetDocument().DecrementPasswordCount(); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int set_port_feature(struct usb_device *hdev, int port1, int feature) { return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0), USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1, NULL, 0, 1000); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_akcipher rakcipher; strlcpy(rakcipher.type, "akcipher", sizeof(rakcipher.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER, sizeof(struct crypto_report_akcipher), &rakcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } CWE ID: Target: 1 Example 2: Code: static int stream_pri_cmp(int sid1, int sid2, void *ctx) { h2_session *session = ctx; nghttp2_stream *s1, *s2; s1 = nghttp2_session_find_stream(session->ngh2, sid1); s2 = nghttp2_session_find_stream(session->ngh2, sid2); if (s1 == s2) { return 0; } else if (!s1) { return 1; } else if (!s2) { return -1; } return spri_cmp(sid1, s1, sid2, s2, session); } 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: long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void sas_eh_finish_cmd(struct scsi_cmnd *cmd) { struct sas_ha_struct *sas_ha = SHOST_TO_SAS_HA(cmd->device->host); struct sas_task *task = TO_SAS_TASK(cmd); /* At this point, we only get called following an actual abort * of the task, so we should be guaranteed not to be racing with * any completions from the LLD. Task is freed after this. */ sas_end_task(cmd, task); /* now finish the command and move it on to the error * handler done list, this also takes it off the * error handler pending list. */ scsi_eh_finish_cmd(cmd, &sas_ha->eh_done_q); } CWE ID: Target: 1 Example 2: Code: char *strstr_m(const char *src, const char *findstr) { smb_ucs2_t *p; smb_ucs2_t *src_w, *find_w; const char *s; char *s2; char *retp; size_t converted_size, findstr_len = 0; TALLOC_CTX *frame; /* Only set up in the iconv case */ /* for correctness */ if (!findstr[0]) { return discard_const_p(char, src); } /* Samba does single character findstr calls a *lot*. */ if (findstr[1] == '\0') return strchr_m(src, *findstr); /* We optimise for the ascii case, knowing that all our supported multi-byte character sets are ascii-compatible (ie. they match for the first 128 chars) */ for (s = src; *s && !(((unsigned char)s[0]) & 0x80); s++) { if (*s == *findstr) { if (!findstr_len) findstr_len = strlen(findstr); if (strncmp(s, findstr, findstr_len) == 0) { return discard_const_p(char, s); } } } if (!*s) return NULL; #if 1 /* def BROKEN_UNICODE_COMPOSE_CHARACTERS */ /* 'make check' fails unless we do this */ /* With compose characters we must restart from the beginning. JRA. */ s = src; #endif frame = talloc_stackframe(); if (!push_ucs2_talloc(frame, &src_w, src, &converted_size)) { DBG_WARNING("src malloc fail\n"); TALLOC_FREE(frame); return NULL; } if (!push_ucs2_talloc(frame, &find_w, findstr, &converted_size)) { DBG_WARNING("find malloc fail\n"); TALLOC_FREE(frame); return NULL; } p = strstr_w(src_w, find_w); if (!p) { TALLOC_FREE(frame); return NULL; } *p = 0; if (!pull_ucs2_talloc(frame, &s2, src_w, &converted_size)) { TALLOC_FREE(frame); DEBUG(0,("strstr_m: dest malloc fail\n")); return NULL; } retp = discard_const_p(char, (s+strlen(s2))); TALLOC_FREE(frame); return retp; } 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: explicit IncrementalMarkingScope(ThreadState* thread_state) : IncrementalMarkingScopeBase(thread_state), gc_forbidden_scope_(thread_state), marking_worklist_(heap_.GetMarkingWorklist()), not_fully_constructed_worklist_( heap_.GetNotFullyConstructedWorklist()) { thread_state_->SetGCPhase(ThreadState::GCPhase::kMarking); ThreadState::AtomicPauseScope atomic_pause_scope_(thread_state_); EXPECT_TRUE(marking_worklist_->IsGlobalEmpty()); EXPECT_TRUE(not_fully_constructed_worklist_->IsGlobalEmpty()); thread_state->EnableIncrementalMarkingBarrier(); thread_state->current_gc_data_.visitor = MarkingVisitor::Create(thread_state, MarkingVisitor::kGlobalMarking); } 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 void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags) { if ((ctx->clockid == CLOCK_REALTIME || ctx->clockid == CLOCK_REALTIME_ALARM) && (flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) { if (!ctx->might_cancel) { ctx->might_cancel = true; spin_lock(&cancel_lock); list_add_rcu(&ctx->clist, &cancel_list); spin_unlock(&cancel_lock); } } else if (ctx->might_cancel) { timerfd_remove_cancel(ctx); } } CWE ID: CWE-416 Target: 1 Example 2: Code: static void nfs4_close_done(struct rpc_task *task, void *data) { struct nfs4_closedata *calldata = data; struct nfs4_state *state = calldata->state; struct nfs_server *server = NFS_SERVER(calldata->inode); dprintk("%s: begin!\n", __func__); if (!nfs4_sequence_done(task, &calldata->res.seq_res)) return; /* hmm. we are done with the inode, and in the process of freeing * the state_owner. we keep this around to process errors */ switch (task->tk_status) { case 0: if (calldata->roc) pnfs_roc_set_barrier(state->inode, calldata->roc_barrier); nfs_set_open_stateid(state, &calldata->res.stateid, 0); renew_lease(server, calldata->timestamp); nfs4_close_clear_stateid_flags(state, calldata->arg.fmode); break; case -NFS4ERR_STALE_STATEID: case -NFS4ERR_OLD_STATEID: case -NFS4ERR_BAD_STATEID: case -NFS4ERR_EXPIRED: if (calldata->arg.fmode == 0) break; default: if (nfs4_async_handle_error(task, server, state) == -EAGAIN) rpc_restart_call_prepare(task); } nfs_release_seqid(calldata->arg.seqid); nfs_refresh_inode(calldata->inode, calldata->res.fattr); dprintk("%s: done, ret = %d!\n", __func__, task->tk_status); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ServiceWorkerContextCore::OnReportConsoleMessage( ServiceWorkerVersion* version, blink::mojom::ConsoleMessageSource source, blink::mojom::ConsoleMessageLevel message_level, const base::string16& message, int line_number, const GURL& source_url) { DCHECK_CURRENTLY_ON(BrowserThread::IO); const bool is_builtin_component = HasWebUIScheme(source_url); LogConsoleMessage(ConsoleMessageLevelToLogSeverity(message_level), message, line_number, is_builtin_component, wrapper_->is_incognito(), base::UTF8ToUTF16(source_url.spec())); observer_list_->Notify( FROM_HERE, &ServiceWorkerContextCoreObserver::OnReportConsoleMessage, version->version_id(), ConsoleMessage(source, message_level, message, line_number, source_url)); } 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: int main() { gdImagePtr im; char *buffer; size_t size; size = read_test_file(&buffer, "heap_overflow.tga"); im = gdImageCreateFromTgaPtr(size, (void *) buffer); gdTestAssert(im == NULL); free(buffer); return gdNumFailures(); } CWE ID: CWE-125 Target: 1 Example 2: Code: void CloseSource(size_t handle) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return; if (mp4->mediafp) fclose(mp4->mediafp), mp4->mediafp = NULL; if (mp4->metasizes) free(mp4->metasizes), mp4->metasizes = 0; if (mp4->metaoffsets) free(mp4->metaoffsets), mp4->metaoffsets = 0; free(mp4); } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebSocketJob::OnCloseSpdyStream() { spdy_websocket_stream_.reset(); OnClose(socket_); } 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: OMX_ERRORTYPE omx_video::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { DEBUG_PRINT_LOW("FTB: buffer->pBuffer[%p]", buffer->pBuffer); if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: FTB in Invalid State"); return OMX_ErrorInvalidState; } if (buffer == NULL ||(buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Invalid buffer or size"); return OMX_ErrorBadParameter; } if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->OMX Version Invalid"); return OMX_ErrorVersionMismatch; } if (buffer->nOutputPortIndex != (OMX_U32)PORT_INDEX_OUT) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Bad port index"); return OMX_ErrorBadPortIndex; } if (!m_sOutPortDef.bEnabled) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->port is disabled"); return OMX_ErrorIncorrectStateOperation; } post_event((unsigned long) hComp, (unsigned long)buffer,OMX_COMPONENT_GENERATE_FTB); return OMX_ErrorNone; } CWE ID: Target: 1 Example 2: Code: brcmf_cfg80211_change_beacon(struct wiphy *wiphy, struct net_device *ndev, struct cfg80211_beacon_data *info) { struct brcmf_if *ifp = netdev_priv(ndev); s32 err; brcmf_dbg(TRACE, "Enter\n"); err = brcmf_config_ap_mgmt_ie(ifp->vif, info); return err; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void aio_nr_sub(unsigned nr) { spin_lock(&aio_nr_lock); if (WARN_ON(aio_nr - nr > aio_nr)) aio_nr = 0; else aio_nr -= nr; spin_unlock(&aio_nr_lock); } 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: HeapObjectHeader* NormalPage::findHeaderFromAddress(Address address) { if (address < payload()) return nullptr; if (!m_objectStartBitMapComputed) populateObjectStartBitMap(); size_t objectOffset = address - payload(); size_t objectStartNumber = objectOffset / allocationGranularity; size_t mapIndex = objectStartNumber / 8; ASSERT(mapIndex < objectStartBitMapSize); size_t bit = objectStartNumber & 7; uint8_t byte = m_objectStartBitMap[mapIndex] & ((1 << (bit + 1)) - 1); while (!byte) { ASSERT(mapIndex > 0); byte = m_objectStartBitMap[--mapIndex]; } int leadingZeroes = numberOfLeadingZeroes(byte); objectStartNumber = (mapIndex * 8) + 7 - leadingZeroes; objectOffset = objectStartNumber * allocationGranularity; Address objectAddress = objectOffset + payload(); HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(objectAddress); if (header->isFree()) return nullptr; ASSERT(header->checkHeader()); return header; } CWE ID: CWE-119 Target: 1 Example 2: Code: void InspectorPageAgent::SearchContentAfterResourcesContentLoaded( const String& frame_id, const String& url, const String& query, bool case_sensitive, bool is_regex, std::unique_ptr<SearchInResourceCallback> callback) { LocalFrame* frame = IdentifiersFactory::FrameById(inspected_frames_, frame_id); if (!frame) { callback->sendFailure(Response::Error("No frame for given id found")); return; } String content; bool base64_encoded; if (!InspectorPageAgent::CachedResourceContent( CachedResource(frame, KURL(kParsedURLString, url), inspector_resource_content_loader_), &content, &base64_encoded)) { callback->sendFailure(Response::Error("No resource with given URL found")); return; } auto matches = v8_session_->searchInTextByLines( ToV8InspectorStringView(content), ToV8InspectorStringView(query), case_sensitive, is_regex); auto results = protocol::Array< v8_inspector::protocol::Debugger::API::SearchMatch>::create(); for (size_t i = 0; i < matches.size(); ++i) results->addItem(std::move(matches[i])); callback->sendSuccess(std::move(results)); } 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: email_open_implementation( const char * final_args[]) { FILE *mailerstream; pid_t pid; int pipefds[2]; param_functions *p_funcs = NULL; /* The gist of this code is to exec a mailer whose stdin is dup2'ed onto the write end of a pipe. The parent gets the fdopen'ed read end so it looks like a FILE*. The child goes out of its way to set its real uid to condor and prop up the environment so that any mail that gets sent from the condor daemons ends up as comming from the condor account instead of superuser. On some OS'es, the child cannot write to the logs even though the mailer process is ruid condor. So I turned off logging in the child. I have no clue why this behaviour happens. -pete 04/14/2000 */ if (pipe(pipefds) < 0) { dprintf(D_ALWAYS, "Could not open email pipe!\n"); return NULL; } dprintf(D_FULLDEBUG, "Forking Mailer process...\n"); if ((pid = fork()) < 0) { dprintf(D_ALWAYS, "Could not fork email process!\n"); return NULL; } else if (pid > 0) /* parent */ { /* SIGCLD, SIGPIPE are ignored elsewhere in the code.... */ /* close read end of pipe */ close(pipefds[0]); mailerstream = fdopen(pipefds[1], EMAIL_POPEN_FLAGS); if (mailerstream == NULL) { dprintf(D_ALWAYS, "Could not open email FILE*: %s\n", strerror(errno)); return NULL; } return mailerstream; } else /* child mailer process */ { static char pe_logname[256]; /* Sorry, putenv wants it this way */ static char pe_user[256]; const char *condor_name; int i; /* Disable any EXCEPT_Cleanup code installed by the parent process. Otherwise, for example, in the master, any call to EXCEPT in the following code will cause us to kill the master's children. */ _EXCEPT_Cleanup = NULL; /* XXX This must be the FIRST thing in this block of code. For some reason, at least on IRIX65, this forked process will not be able to open the shadow lock file, or be able to use dprintf or do any sort of logging--even if the ruid hasn't changed. I do not know why and this should be investigated. So for now, I've turned off logging for this child process. Thankfully it is a short piece of code before the exec. -pete 03-05-2000 */ Termlog = 1; p_funcs = get_param_functions(); dprintf_config(get_mySubSystemName(), p_funcs); /* this is a simple daemon that if it needs to stat . should be able to. You might not be able to if the shadow's cwd is in the user dir somewhere and not readable by the Condor Account. */ chdir("/"); umask(0); /* Change my userid permanently to "condor" */ /* WARNING This code must happen before the close/dup operation. */ set_condor_priv_final(); /* close write end of pipe */ close(pipefds[1]); /* connect the write end of the pipe to the stdin of the mailer */ if (dup2(pipefds[0], STDIN_FILENO) < 0) { /* I hope this EXCEPT gets recorded somewhere */ EXCEPT("EMAIL PROCESS: Could not connect stdin to child!\n"); } /* close all other unneeded file descriptors including stdout and stderr, just leave the stdin open to this process. */ for(i = 0; i < sysconf(_SC_OPEN_MAX); i++) { if (i != pipefds[0] && i != STDIN_FILENO) { (void)close(i); } } /* prop up the environment with goodies to get the Mailer to do the right thing */ condor_name = get_condor_username(); /* Should be snprintf() but we don't have it for all platforms */ sprintf(pe_logname,"LOGNAME=%s", condor_name); if (putenv(pe_logname) != 0) { EXCEPT("EMAIL PROCESS: Unable to insert LOGNAME=%s into " " environment correctly: %s\n", pe_logname, strerror(errno)); } /* Should be snprintf() but we don't have it for all platforms */ sprintf(pe_user,"USER=%s", condor_name); if( putenv(pe_user) != 0) { /* I hope this EXCEPT gets recorded somewhere */ EXCEPT("EMAIL PROCESS: Unable to insert USER=%s into " " environment correctly: %s\n", pe_user, strerror(errno)); } /* invoke the mailer */ execvp(final_args[0], const_cast<char *const*>(final_args) ); /* I hope this EXCEPT gets recorded somewhere */ EXCEPT("EMAIL PROCESS: Could not exec mailer using '%s' with command " "'%s' because of error: %s.", "/bin/sh", (final_args[0]==NULL)?"(null)":final_args[0], strerror(errno)); } /* for completeness */ return NULL; } CWE ID: CWE-134 Output:
0
Here are some example code snippets. Analyze the following 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 RemoveProcessIdFromGlobalMap(int32_t process_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); GetProcessIdToFilterMap()->erase(process_id); } CWE ID: CWE-362 Target: 1 Example 2: Code: SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms, unsigned int *nbytes, struct kvec *iov, int n_vec) { int rc = 0; struct smb2_write_req *req = NULL; struct smb2_write_rsp *rsp = NULL; int resp_buftype; struct kvec rsp_iov; int flags = 0; *nbytes = 0; if (n_vec < 1) return rc; rc = small_smb2_init(SMB2_WRITE, io_parms->tcon, (void **) &req); if (rc) return rc; if (io_parms->tcon->ses->server == NULL) return -ECONNABORTED; if (encryption_required(io_parms->tcon)) flags |= CIFS_TRANSFORM_REQ; req->hdr.sync_hdr.ProcessId = cpu_to_le32(io_parms->pid); req->PersistentFileId = io_parms->persistent_fid; req->VolatileFileId = io_parms->volatile_fid; req->WriteChannelInfoOffset = 0; req->WriteChannelInfoLength = 0; req->Channel = 0; req->Length = cpu_to_le32(io_parms->length); req->Offset = cpu_to_le64(io_parms->offset); /* 4 for rfc1002 length field */ req->DataOffset = cpu_to_le16( offsetof(struct smb2_write_req, Buffer) - 4); req->RemainingBytes = 0; iov[0].iov_base = (char *)req; /* 4 for rfc1002 length field and 1 for Buffer */ iov[0].iov_len = get_rfc1002_length(req) + 4 - 1; /* length of entire message including data to be written */ inc_rfc1001_len(req, io_parms->length - 1 /* Buffer */); rc = SendReceive2(xid, io_parms->tcon->ses, iov, n_vec + 1, &resp_buftype, flags, &rsp_iov); cifs_small_buf_release(req); rsp = (struct smb2_write_rsp *)rsp_iov.iov_base; if (rc) { cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE); cifs_dbg(VFS, "Send error in write = %d\n", rc); } else *nbytes = le32_to_cpu(rsp->DataLength); free_rsp_buf(resp_buftype, rsp); return rc; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void Sp_lastIndexOf(js_State *J) { const char *haystack = checkstring(J, 0); const char *needle = js_tostring(J, 1); int pos = js_isdefined(J, 2) ? js_tointeger(J, 2) : (int)strlen(haystack); int len = strlen(needle); int k = 0, last = -1; Rune rune; while (*haystack && k <= pos) { if (!strncmp(haystack, needle, len)) last = k; haystack += chartorune(&rune, haystack); ++k; } js_pushnumber(J, last); } CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SPL_METHOD(SplFileObject, __construct) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_bool use_include_path = 0; char *p1, *p2; char *tmp_path; int tmp_path_len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->u.file.open_mode_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|sbr!", &intern->file_name, &intern->file_name_len, &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (intern->u.file.open_mode == NULL) { intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) { tmp_path_len = strlen(intern->u.file.stream->orig_path); if (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) { tmp_path_len--; } tmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len); p1 = strrchr(tmp_path, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(tmp_path, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path; } else { intern->_path_len = 0; } efree(tmp_path); intern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplTempFileObject::__construct([int max_memory]) CWE ID: CWE-190 Target: 1 Example 2: Code: static void pl022_write(void *opaque, hwaddr offset, uint64_t value, unsigned size) { PL022State *s = (PL022State *)opaque; switch (offset) { case 0x00: /* CR0 */ s->cr0 = value; /* Clock rate and format are ignored. */ s->bitmask = (1 << ((value & 15) + 1)) - 1; break; case 0x04: /* CR1 */ s->cr1 = value; if ((s->cr1 & (PL022_CR1_MS | PL022_CR1_SSE)) == (PL022_CR1_MS | PL022_CR1_SSE)) { BADF("SPI slave mode not implemented\n"); } pl022_xfer(s); break; case 0x08: /* DR */ if (s->tx_fifo_len < 8) { DPRINTF("TX %02x\n", (unsigned)value); s->tx_fifo[s->tx_fifo_head] = value & s->bitmask; s->tx_fifo_head = (s->tx_fifo_head + 1) & 7; s->tx_fifo_len++; pl022_xfer(s); } break; case 0x10: /* CPSR */ /* Prescaler. Ignored. */ s->cpsr = value & 0xff; break; case 0x14: /* IMSC */ s->im = value; pl022_update(s); break; case 0x20: /* DMACR */ if (value) { qemu_log_mask(LOG_UNIMP, "pl022: DMA not implemented\n"); } break; default: qemu_log_mask(LOG_GUEST_ERROR, "pl022_write: Bad offset %x\n", (int)offset); } } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long SeekHead::Parse() { IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = m_start; const long long stop = m_start + m_size; int entry_count = 0; int void_element_count = 0; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x0DBB) // SeekEntry ID ++entry_count; else if (id == 0x6C) // Void ID ++void_element_count; pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); m_entries = new (std::nothrow) Entry[entry_count]; if (m_entries == NULL) return -1; m_void_elements = new (std::nothrow) VoidElement[void_element_count]; if (m_void_elements == NULL) return -1; Entry* pEntry = m_entries; VoidElement* pVoidElement = m_void_elements; pos = m_start; while (pos < stop) { const long long idpos = pos; long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x0DBB) { // SeekEntry ID if (ParseEntry(pReader, pos, size, pEntry)) { Entry& e = *pEntry++; e.element_start = idpos; e.element_size = (pos + size) - idpos; } } else if (id == 0x6C) { // Void ID VoidElement& e = *pVoidElement++; e.element_start = idpos; e.element_size = (pos + size) - idpos; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries); assert(count_ >= 0); assert(count_ <= entry_count); m_entry_count = static_cast<int>(count_); count_ = ptrdiff_t(pVoidElement - m_void_elements); assert(count_ >= 0); assert(count_ <= void_element_count); m_void_element_count = static_cast<int>(count_); return 0; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool Cues::DoneParsing() const { const long long stop = m_start + m_size; return (m_pos >= stop); } CWE ID: CWE-119 Target: 1 Example 2: Code: double Document::timerAlignmentInterval() const { Page* p = page(); if (!p) return ScriptExecutionContext::timerAlignmentInterval(); return p->settings()->domTimerAlignmentInterval(); } 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 _ext4_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int flags) { struct ext4_map_blocks map; int ret = 0; if (ext4_has_inline_data(inode)) return -ERANGE; map.m_lblk = iblock; map.m_len = bh->b_size >> inode->i_blkbits; ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map, flags); if (ret > 0) { map_bh(bh, inode->i_sb, map.m_pblk); ext4_update_bh_state(bh, map.m_flags); bh->b_size = inode->i_sb->s_blocksize * map.m_len; ret = 0; } return ret; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DirectoryEntrySync::removeRecursively(ExceptionState& exceptionState) { RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create(); m_fileSystem->removeRecursively(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); } CWE ID: CWE-119 Target: 1 Example 2: Code: void Splash::setStrokeAlpha(SplashCoord alpha) { state->strokeAlpha = alpha; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool InputType::IsInRange(const String& value) const { if (!IsSteppable()) return false; const Decimal numeric_value = ParseToNumberOrNaN(value); if (!numeric_value.IsFinite()) return true; StepRange step_range(CreateStepRange(kRejectAny)); return step_range.HasRangeLimitations() && numeric_value >= step_range.Minimum() && numeric_value <= step_range.Maximum(); } 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: my_object_finalize (GObject *object) { MyObject *mobject = MY_OBJECT (object); g_free (mobject->this_is_a_string); (G_OBJECT_CLASS (my_object_parent_class)->finalize) (object); } CWE ID: CWE-264 Target: 1 Example 2: Code: TPM_RC tpm_session_start_auth_with_params(TSS2_SYS_CONTEXT *sapi_context, SESSION **session, TPMI_DH_OBJECT tpmKey, TPM2B_MAX_BUFFER *salt, TPMI_DH_ENTITY bind, TPM2B_AUTH *bindAuth, TPM2B_NONCE *nonceCaller, TPM2B_ENCRYPTED_SECRET *encryptedSalt, TPM_SE sessionType, TPMT_SYM_DEF *symmetric, TPMI_ALG_HASH algId ) { TPM_RC rval; SESSION_LIST_ENTRY *sessionEntry; rval = AddSession( &sessionEntry ); if( rval == TSS2_RC_SUCCESS ) { *session = &sessionEntry->session; (*session)->bind = bind; (*session)->tpmKey = tpmKey; memcpy( &(*session)->nonceOlder.b, &nonceCaller->b, sizeof(nonceCaller->b)); memcpy( &(*session)->encryptedSalt.b, &encryptedSalt->b, sizeof(encryptedSalt->b)); (*session)->sessionType = sessionType; (*session)->symmetric.algorithm = symmetric->algorithm; (*session)->symmetric.keyBits.sym = symmetric->keyBits.sym; (*session)->symmetric.mode.sym = symmetric->mode.sym; (*session)->authHash = algId; if( bindAuth == 0 ) { (*session)->authValueBind.b.size = 0; } else { memcpy( &( (*session)->authValueBind.b ), &( bindAuth->b ), sizeof(bindAuth->b)); } if( (*session)->tpmKey == TPM_RH_NULL ) { (*session)->salt.t.size = 0; } else { memcpy( &(*session)->salt.b, &salt->b, sizeof(salt->b)); } if( (*session)->bind == TPM_RH_NULL ) (*session)->authValueBind.t.size = 0; rval = StartAuthSession(sapi_context, *session ); } else { DeleteSession( *session ); } return( rval ); } CWE ID: CWE-522 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 u64 do_task_delta_exec(struct task_struct *p, struct rq *rq) { u64 ns = 0; if (task_current(rq, p)) { update_rq_clock(rq); ns = rq->clock_task - p->se.exec_start; if ((s64)ns < 0) ns = 0; } return ns; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: apprentice_load(struct magic_set *ms, const char *fn, int action) { int errs = 0; uint32_t i, j; size_t files = 0, maxfiles = 0; char **filearr = NULL; struct stat st; struct magic_map *map; struct magic_entry_set mset[MAGIC_SETS]; php_stream *dir; php_stream_dirent d; TSRMLS_FETCH(); memset(mset, 0, sizeof(mset)); ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */ if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) { file_oomem(ms, sizeof(*map)); return NULL; } /* print silly verbose header for USG compat. */ if (action == FILE_CHECK) (void)fprintf(stderr, "%s\n", usg_hdr); /* load directory or file */ /* FIXME: Read file names and sort them to prevent non-determinism. See Debian bug #488562. */ if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) { int mflen; char mfn[MAXPATHLEN]; dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL); if (!dir) { errs++; goto out; } while (php_stream_readdir(dir, &d)) { if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) { file_oomem(ms, strlen(fn) + strlen(d.d_name) + 2); errs++; php_stream_closedir(dir); goto out; } if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) { continue; } if (files >= maxfiles) { size_t mlen; maxfiles = (maxfiles + 1) * 2; mlen = maxfiles * sizeof(*filearr); if ((filearr = CAST(char **, erealloc(filearr, mlen))) == NULL) { file_oomem(ms, mlen); efree(mfn); php_stream_closedir(dir); errs++; goto out; goto out; } } filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen); } php_stream_closedir(dir); qsort(filearr, files, sizeof(*filearr), cmpstrp); for (i = 0; i < files; i++) { load_1(ms, action, filearr[i], &errs, mset); efree(filearr[i]); } efree(filearr); } else load_1(ms, action, fn, &errs, mset); if (errs) goto out; for (j = 0; j < MAGIC_SETS; j++) { /* Set types of tests */ for (i = 0; i < mset[j].count; ) { if (mset[j].me[i].mp->cont_level != 0) { i++; continue; } i = set_text_binary(ms, mset[j].me, mset[j].count, i); } qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me), apprentice_sort); /* * Make sure that any level 0 "default" line is last * (if one exists). */ set_last_default(ms, mset[j].me, mset[j].count); /* coalesce per file arrays into a single one */ if (coalesce_entries(ms, mset[j].me, mset[j].count, &map->magic[j], &map->nmagic[j]) == -1) { errs++; goto out; } } out: for (j = 0; j < MAGIC_SETS; j++) magic_entry_free(mset[j].me, mset[j].count); if (errs) { for (j = 0; j < MAGIC_SETS; j++) { if (map->magic[j]) efree(map->magic[j]); } efree(map); return NULL; } return map; } CWE ID: CWE-17 Target: 1 Example 2: Code: void DevToolsWindow::ToggleDevToolsWindow( content::WebContents* inspected_web_contents, bool force_open, const DevToolsToggleAction& action, const std::string& settings) { scoped_refptr<DevToolsAgentHost> agent( DevToolsAgentHost::GetOrCreateFor(inspected_web_contents)); DevToolsWindow* window = FindDevToolsWindow(agent.get()); bool do_open = force_open; if (!window) { Profile* profile = Profile::FromBrowserContext( inspected_web_contents->GetBrowserContext()); base::RecordAction(base::UserMetricsAction("DevTools_InspectRenderer")); std::string panel = ""; switch (action.type()) { case DevToolsToggleAction::kInspect: case DevToolsToggleAction::kShowElementsPanel: panel = "elements"; break; case DevToolsToggleAction::kShowConsolePanel: panel = "console"; break; case DevToolsToggleAction::kShow: case DevToolsToggleAction::kToggle: case DevToolsToggleAction::kReveal: case DevToolsToggleAction::kNoOp: break; } window = Create(profile, inspected_web_contents, kFrontendDefault, std::string(), true, settings, panel); if (!window) return; window->bindings_->AttachTo(agent.get()); do_open = true; } window->UpdateBrowserToolbar(); if (!window->is_docked_ || do_open) window->ScheduleShow(action); else window->CloseWindow(); } CWE ID: CWE-668 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int main(int argc, char *argv[]) { p_fm_config_conx_hdlt hdl; int instance = 0; fm_mgr_config_errno_t res; char *rem_addr = NULL; char *community = "public"; char Opts[256]; int arg; char *command; int i; /* Get options at the command line (overide default values) */ strcpy(Opts, "i:d:h-"); while ((arg = getopt(argc, argv, Opts)) != EOF) { switch (arg) { case 'h': case '-': usage(argv[0]); return(0); case 'i': instance = atol(optarg); break; case 'd': rem_addr = optarg; break; default: usage(argv[0]); return(-1); } } if(optind >= argc){ fprintf(stderr, "Command required\n"); usage(argv[0]); return -1; } command = argv[optind++]; printf("Connecting to %s FM instance %d\n", (rem_addr==NULL) ? "LOCAL":rem_addr, instance); if((res = fm_mgr_config_init(&hdl,instance, rem_addr, community)) != FM_CONF_OK) { fprintf(stderr, "Failed to initialize the client handle: %d\n", res); goto die_clean; } if((res = fm_mgr_config_connect(hdl)) != FM_CONF_OK) { fprintf(stderr, "Failed to connect: (%d) %s\n",res,fm_mgr_get_error_str(res)); goto die_clean; } for(i=0;i<commandListLen;i++){ if(strcmp(command,commandList[i].name) == 0){ return commandList[i].cmdPtr(hdl, commandList[i].mgr, (argc - optind), &argv[optind]); } } fprintf(stderr, "Command (%s) is not valid\n",command); usage(argv[0]); res = -1; die_clean: if (hdl) free(hdl); return res; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int recv_msg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t buf_len, int flags) { struct sock *sk = sock->sk; struct tipc_port *tport = tipc_sk_port(sk); struct sk_buff *buf; struct tipc_msg *msg; long timeout; unsigned int sz; u32 err; int res; /* Catch invalid receive requests */ if (unlikely(!buf_len)) return -EINVAL; lock_sock(sk); if (unlikely(sock->state == SS_UNCONNECTED)) { res = -ENOTCONN; goto exit; } /* will be updated in set_orig_addr() if needed */ m->msg_namelen = 0; timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); restart: /* Look for a message in receive queue; wait if necessary */ while (skb_queue_empty(&sk->sk_receive_queue)) { if (sock->state == SS_DISCONNECTING) { res = -ENOTCONN; goto exit; } if (timeout <= 0L) { res = timeout ? timeout : -EWOULDBLOCK; goto exit; } release_sock(sk); timeout = wait_event_interruptible_timeout(*sk_sleep(sk), tipc_rx_ready(sock), timeout); lock_sock(sk); } /* Look at first message in receive queue */ buf = skb_peek(&sk->sk_receive_queue); msg = buf_msg(buf); sz = msg_data_sz(msg); err = msg_errcode(msg); /* Discard an empty non-errored message & try again */ if ((!sz) && (!err)) { advance_rx_queue(sk); goto restart; } /* Capture sender's address (optional) */ set_orig_addr(m, msg); /* Capture ancillary data (optional) */ res = anc_data_recv(m, msg, tport); if (res) goto exit; /* Capture message data (if valid) & compute return value (always) */ if (!err) { if (unlikely(buf_len < sz)) { sz = buf_len; m->msg_flags |= MSG_TRUNC; } res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg), m->msg_iov, sz); if (res) goto exit; res = sz; } else { if ((sock->state == SS_READY) || ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)) res = 0; else res = -ECONNRESET; } /* Consume received message (optional) */ if (likely(!(flags & MSG_PEEK))) { if ((sock->state != SS_READY) && (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN)) tipc_acknowledge(tport->ref, tport->conn_unacked); advance_rx_queue(sk); } exit: release_sock(sk); return res; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int rl2_read_packet(AVFormatContext *s, AVPacket *pkt) { Rl2DemuxContext *rl2 = s->priv_data; AVIOContext *pb = s->pb; AVIndexEntry *sample = NULL; int i; int ret = 0; int stream_id = -1; int64_t pos = INT64_MAX; /** check if there is a valid video or audio entry that can be used */ for(i=0; i<s->nb_streams; i++){ if(rl2->index_pos[i] < s->streams[i]->nb_index_entries && s->streams[i]->index_entries[ rl2->index_pos[i] ].pos < pos){ sample = &s->streams[i]->index_entries[ rl2->index_pos[i] ]; pos= sample->pos; stream_id= i; } } if(stream_id == -1) return AVERROR_EOF; ++rl2->index_pos[stream_id]; /** position the stream (will probably be there anyway) */ avio_seek(pb, sample->pos, SEEK_SET); /** fill the packet */ ret = av_get_packet(pb, pkt, sample->size); if(ret != sample->size){ av_packet_unref(pkt); return AVERROR(EIO); } pkt->stream_index = stream_id; pkt->pts = sample->timestamp; return ret; } CWE ID: CWE-834 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 RenderingHelper::Clear() { suppress_swap_to_display_ = false; width_ = 0; height_ = 0; texture_id_to_surface_index_.clear(); message_loop_ = NULL; egl_display_ = EGL_NO_DISPLAY; egl_context_ = EGL_NO_CONTEXT; egl_surfaces_.clear(); PlatformUnInitialize(); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY *pkey = ktri->pkey; unsigned char *ek = NULL; size_t eklen; int ret = 0; CMS_EncryptedContentInfo *ec; ec = cms->d.envelopedData->encryptedContentInfo; CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY); return 0; return 0; } CWE ID: CWE-311 Target: 1 Example 2: Code: void Browser::UpdateCommandsForTabState() { TabContents* current_tab = GetSelectedTabContents(); TabContentsWrapper* current_tab_wrapper = GetSelectedTabContentsWrapper(); if (!current_tab || !current_tab_wrapper) // May be NULL during tab restore. return; NavigationController& nc = current_tab->controller(); command_updater_.UpdateCommandEnabled(IDC_BACK, nc.CanGoBack()); command_updater_.UpdateCommandEnabled(IDC_FORWARD, nc.CanGoForward()); command_updater_.UpdateCommandEnabled(IDC_RELOAD, CanReloadContents(current_tab)); command_updater_.UpdateCommandEnabled(IDC_RELOAD_IGNORING_CACHE, CanReloadContents(current_tab)); bool non_app_window = !(type() & TYPE_APP); command_updater_.UpdateCommandEnabled(IDC_DUPLICATE_TAB, non_app_window && CanDuplicateContentsAt(active_index())); window_->SetStarredState(current_tab_wrapper->is_starred()); command_updater_.UpdateCommandEnabled(IDC_VIEW_SOURCE, current_tab->controller().CanViewSource()); command_updater_.UpdateCommandEnabled(IDC_EMAIL_PAGE_LOCATION, current_tab->ShouldDisplayURL() && current_tab->GetURL().is_valid()); NavigationEntry* active_entry = nc.GetActiveEntry(); bool is_chrome_internal = (active_entry ? active_entry->url().SchemeIs(chrome::kChromeUIScheme) : false); command_updater_.UpdateCommandEnabled(IDC_ENCODING_MENU, !is_chrome_internal && SavePackage::IsSavableContents( current_tab->contents_mime_type())); #if !defined(OS_MACOSX) command_updater_.UpdateCommandEnabled(IDC_CREATE_SHORTCUTS, web_app::IsValidUrl(current_tab->GetURL())); #endif UpdateCommandsForContentRestrictionState(); UpdateCommandsForBookmarkEditing(); } 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: unsigned long ossl_statem_client_max_message_size(SSL *s) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { case TLS_ST_CR_SRVR_HELLO: return SERVER_HELLO_MAX_LENGTH; case DTLS_ST_CR_HELLO_VERIFY_REQUEST: return HELLO_VERIFY_REQUEST_MAX_LENGTH; case TLS_ST_CR_CERT: return s->max_cert_list; case TLS_ST_CR_CERT_STATUS: return SSL3_RT_MAX_PLAIN_LENGTH; case TLS_ST_CR_KEY_EXCH: return SERVER_KEY_EXCH_MAX_LENGTH; case TLS_ST_CR_CERT_REQ: /* * Set to s->max_cert_list for compatibility with previous releases. In * practice these messages can get quite long if servers are configured * to provide a long list of acceptable CAs */ return s->max_cert_list; case TLS_ST_CR_SRVR_DONE: return SERVER_HELLO_DONE_MAX_LENGTH; case TLS_ST_CR_CHANGE: if (s->version == DTLS1_BAD_VER) return 3; return CCS_MAX_LENGTH; case TLS_ST_CR_SESSION_TICKET: return SSL3_RT_MAX_PLAIN_LENGTH; case TLS_ST_CR_FINISHED: return FINISHED_MAX_LENGTH; default: /* Shouldn't happen */ break; } return 0; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool PermissionsContainsFunction::RunImpl() { scoped_ptr<Contains::Params> params(Contains::Params::Create(*args_)); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, &error_); if (!permissions.get()) return false; results_ = Contains::Results::Create( GetExtension()->GetActivePermissions()->Contains(*permissions)); return true; } CWE ID: CWE-264 Target: 1 Example 2: Code: const char* DismissalTypeToString(Document::PageDismissalType dismissal_type) { switch (dismissal_type) { case Document::kBeforeUnloadDismissal: return "beforeunload"; case Document::kPageHideDismissal: return "pagehide"; case Document::kUnloadVisibilityChangeDismissal: return "visibilitychange"; case Document::kUnloadDismissal: return "unload"; case Document::kNoDismissal: NOTREACHED(); } NOTREACHED(); return ""; } 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: status_t AMRSource::read( MediaBuffer **out, const ReadOptions *options) { *out = NULL; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options && options->getSeekTo(&seekTimeUs, &mode)) { size_t size; int64_t seekFrame = seekTimeUs / 20000ll; // 20ms per frame. mCurrentTimeUs = seekFrame * 20000ll; size_t index = seekFrame < 0 ? 0 : seekFrame / 50; if (index >= mOffsetTableLength) { index = mOffsetTableLength - 1; } mOffset = mOffsetTable[index] + (mIsWide ? 9 : 6); for (size_t i = 0; i< seekFrame - index * 50; i++) { status_t err; if ((err = getFrameSizeByOffset(mDataSource, mOffset, mIsWide, &size)) != OK) { return err; } mOffset += size; } } uint8_t header; ssize_t n = mDataSource->readAt(mOffset, &header, 1); if (n < 1) { return ERROR_END_OF_STREAM; } if (header & 0x83) { ALOGE("padding bits must be 0, header is 0x%02x", header); return ERROR_MALFORMED; } unsigned FT = (header >> 3) & 0x0f; size_t frameSize = getFrameSize(mIsWide, FT); if (frameSize == 0) { return ERROR_MALFORMED; } MediaBuffer *buffer; status_t err = mGroup->acquire_buffer(&buffer); if (err != OK) { return err; } n = mDataSource->readAt(mOffset, buffer->data(), frameSize); if (n != (ssize_t)frameSize) { buffer->release(); buffer = NULL; if (n < 0) { return ERROR_IO; } else { mOffset += n; return ERROR_END_OF_STREAM; } } buffer->set_range(0, frameSize); buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs); buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); mOffset += frameSize; mCurrentTimeUs += 20000; // Each frame is 20ms *out = buffer; return OK; } 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: NetworkChangeNotifierMac::NetworkChangeNotifierMac() : NetworkChangeNotifier(NetworkChangeCalculatorParamsMac()), connection_type_(CONNECTION_UNKNOWN), connection_type_initialized_(false), initial_connection_type_cv_(&connection_type_lock_), forwarder_(this), dns_config_service_thread_(base::MakeUnique<DnsConfigServiceThread>()) { config_watcher_ = base::MakeUnique<NetworkConfigWatcherMac>(&forwarder_); dns_config_service_thread_->StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); } CWE ID: CWE-311 Target: 1 Example 2: Code: void av_register_codec_parser(AVCodecParser *parser) { do { parser->next = av_first_parser; } while (parser->next != avpriv_atomic_ptr_cas((void * volatile *)&av_first_parser, parser->next, parser)); } 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 RunAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); uint32_t max_error = 0; int64_t total_error = 0; const int count_test_block = 10000; for (int i = 0; i < count_test_block; ++i) { DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block, test_temp_block, pitch_)); REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1u, max_error) << "Error: 4x4 FHT/IHT has an individual round trip error > 1"; EXPECT_GE(count_test_block , total_error) << "Error: 4x4 FHT/IHT has average round trip error > 1 per block"; } 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: cifs_iovec_write(struct file *file, const struct iovec *iov, unsigned long nr_segs, loff_t *poffset) { unsigned long nr_pages, i; size_t copied, len, cur_len; ssize_t total_written = 0; loff_t offset; struct iov_iter it; struct cifsFileInfo *open_file; struct cifs_tcon *tcon; struct cifs_sb_info *cifs_sb; struct cifs_writedata *wdata, *tmp; struct list_head wdata_list; int rc; pid_t pid; len = iov_length(iov, nr_segs); if (!len) return 0; rc = generic_write_checks(file, poffset, &len, 0); if (rc) return rc; INIT_LIST_HEAD(&wdata_list); cifs_sb = CIFS_SB(file->f_path.dentry->d_sb); open_file = file->private_data; tcon = tlink_tcon(open_file->tlink); if (!tcon->ses->server->ops->async_writev) return -ENOSYS; offset = *poffset; if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RWPIDFORWARD) pid = open_file->pid; else pid = current->tgid; iov_iter_init(&it, iov, nr_segs, len, 0); do { size_t save_len; nr_pages = get_numpages(cifs_sb->wsize, len, &cur_len); wdata = cifs_writedata_alloc(nr_pages, cifs_uncached_writev_complete); if (!wdata) { rc = -ENOMEM; break; } rc = cifs_write_allocate_pages(wdata->pages, nr_pages); if (rc) { kfree(wdata); break; } save_len = cur_len; for (i = 0; i < nr_pages; i++) { copied = min_t(const size_t, cur_len, PAGE_SIZE); copied = iov_iter_copy_from_user(wdata->pages[i], &it, 0, copied); cur_len -= copied; iov_iter_advance(&it, copied); } cur_len = save_len - cur_len; wdata->sync_mode = WB_SYNC_ALL; wdata->nr_pages = nr_pages; wdata->offset = (__u64)offset; wdata->cfile = cifsFileInfo_get(open_file); wdata->pid = pid; wdata->bytes = cur_len; wdata->pagesz = PAGE_SIZE; wdata->tailsz = cur_len - ((nr_pages - 1) * PAGE_SIZE); rc = cifs_uncached_retry_writev(wdata); if (rc) { kref_put(&wdata->refcount, cifs_uncached_writedata_release); break; } list_add_tail(&wdata->list, &wdata_list); offset += cur_len; len -= cur_len; } while (len > 0); /* * If at least one write was successfully sent, then discard any rc * value from the later writes. If the other write succeeds, then * we'll end up returning whatever was written. If it fails, then * we'll get a new rc value from that. */ if (!list_empty(&wdata_list)) rc = 0; /* * Wait for and collect replies for any successful sends in order of * increasing offset. Once an error is hit or we get a fatal signal * while waiting, then return without waiting for any more replies. */ restart_loop: list_for_each_entry_safe(wdata, tmp, &wdata_list, list) { if (!rc) { /* FIXME: freezable too? */ rc = wait_for_completion_killable(&wdata->done); if (rc) rc = -EINTR; else if (wdata->result) rc = wdata->result; else total_written += wdata->bytes; /* resend call if it's a retryable error */ if (rc == -EAGAIN) { rc = cifs_uncached_retry_writev(wdata); goto restart_loop; } } list_del_init(&wdata->list); kref_put(&wdata->refcount, cifs_uncached_writedata_release); } if (total_written > 0) *poffset += total_written; cifs_stats_bytes_written(tcon, total_written); return total_written ? total_written : (ssize_t)rc; } CWE ID: CWE-119 Target: 1 Example 2: Code: MagickExport PixelPacket *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; PixelPacket *magick_restrict pixels; RectangleInfo region; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((PixelPacket *) NULL); assert(cache_info->signature == MagickSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((PixelPacket *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((PixelPacket *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((PixelPacket *) NULL); /* Return pixel cache. */ region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,&region, (image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ? MagickTrue : MagickFalse,nexus_info,exception); return(pixels); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vmx_load_host_state(struct vcpu_vmx *vmx) { preempt_disable(); __vmx_load_host_state(vmx); preempt_enable(); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline void removeElementPreservingChildren(PassRefPtr<DocumentFragment> fragment, HTMLElement* element) { ExceptionCode ignoredExceptionCode; RefPtr<Node> nextChild; for (RefPtr<Node> child = element->firstChild(); child; child = nextChild) { nextChild = child->nextSibling(); element->removeChild(child.get(), ignoredExceptionCode); ASSERT(!ignoredExceptionCode); fragment->insertBefore(child, element, ignoredExceptionCode); ASSERT(!ignoredExceptionCode); } fragment->removeChild(element, ignoredExceptionCode); ASSERT(!ignoredExceptionCode); } CWE ID: CWE-264 Target: 1 Example 2: Code: void NavigationControllerImpl::FinishRestore(int selected_index, RestoreType type) { DCHECK(selected_index >= 0 && selected_index < GetEntryCount()); ConfigureEntriesForRestore(&entries_, type); last_committed_entry_index_ = selected_index; } 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: OMX_ERRORTYPE SoftAVC::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *)params; if (bitRate->nPortIndex != 1) { return OMX_ErrorUndefined; } bitRate->eControlRate = OMX_Video_ControlRateVariable; bitRate->nTargetBitrate = mBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE *avcParams = (OMX_VIDEO_PARAM_AVCTYPE *)params; if (avcParams->nPortIndex != 1) { return OMX_ErrorUndefined; } OMX_VIDEO_AVCLEVELTYPE omxLevel = OMX_VIDEO_AVCLevel41; if (OMX_ErrorNone != ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) { return OMX_ErrorUndefined; } avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline; avcParams->eLevel = omxLevel; avcParams->nRefFrames = 1; avcParams->bUseHadamard = OMX_TRUE; avcParams->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP | OMX_VIDEO_PictureTypeB); avcParams->nRefIdx10ActiveMinus1 = 0; avcParams->nRefIdx11ActiveMinus1 = 0; avcParams->bWeightedPPrediction = OMX_FALSE; avcParams->bconstIpred = OMX_FALSE; avcParams->bDirect8x8Inference = OMX_FALSE; avcParams->bDirectSpatialTemporal = OMX_FALSE; avcParams->nCabacInitIdc = 0; return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalGetParameter(index, params); } } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int test_sqr(BIO *bp, BN_CTX *ctx) { BIGNUM a,c,d,e; int i; BN_init(&a); BN_init(&c); BN_init(&d); BN_init(&e); for (i=0; i<num0; i++) { BN_bntest_rand(&a,40+i*10,0,0); a.neg=rand_neg(); BN_sqr(&c,&a,ctx); if (bp != NULL) { if (!results) { BN_print(bp,&a); BIO_puts(bp," * "); BN_print(bp,&a); BIO_puts(bp," - "); } BN_print(bp,&c); BIO_puts(bp,"\n"); } BN_div(&d,&e,&c,&a,ctx); BN_sub(&d,&d,&a); if(!BN_is_zero(&d) || !BN_is_zero(&e)) { fprintf(stderr,"Square test failed!\n"); return 0; } } BN_free(&a); BN_free(&c); BN_free(&d); BN_free(&e); return(1); } CWE ID: CWE-310 Target: 1 Example 2: Code: static void vmxnet3_set_variable_mac(VMXNET3State *s, uint32_t h, uint32_t l) { s->conf.macaddr.a[0] = VMXNET3_GET_BYTE(l, 0); s->conf.macaddr.a[1] = VMXNET3_GET_BYTE(l, 1); s->conf.macaddr.a[2] = VMXNET3_GET_BYTE(l, 2); s->conf.macaddr.a[3] = VMXNET3_GET_BYTE(l, 3); s->conf.macaddr.a[4] = VMXNET3_GET_BYTE(h, 0); s->conf.macaddr.a[5] = VMXNET3_GET_BYTE(h, 1); VMW_CFPRN("Variable MAC: " MAC_FMT, MAC_ARG(s->conf.macaddr.a)); qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool VaapiJpegDecoder::Initialize(const base::RepeatingClosure& error_uma_cb) { vaapi_wrapper_ = VaapiWrapper::Create(VaapiWrapper::kDecode, VAProfileJPEGBaseline, error_uma_cb); if (!vaapi_wrapper_) { VLOGF(1) << "Failed initializing VAAPI"; return false; } return true; } 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: static ssize_t out_write(struct audio_stream_out *stream, const void* buffer, size_t bytes) { struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream; int sent; DEBUG("write %zu bytes (fd %d)", bytes, out->common.audio_fd); pthread_mutex_lock(&out->common.lock); if (out->common.state == AUDIO_A2DP_STATE_SUSPENDED) { DEBUG("stream suspended"); pthread_mutex_unlock(&out->common.lock); return -1; } /* only allow autostarting if we are in stopped or standby */ if ((out->common.state == AUDIO_A2DP_STATE_STOPPED) || (out->common.state == AUDIO_A2DP_STATE_STANDBY)) { if (start_audio_datapath(&out->common) < 0) { /* emulate time this write represents to avoid very fast write failures during transition periods or remote suspend */ int us_delay = calc_audiotime(out->common.cfg, bytes); DEBUG("emulate a2dp write delay (%d us)", us_delay); usleep(us_delay); pthread_mutex_unlock(&out->common.lock); return -1; } } else if (out->common.state != AUDIO_A2DP_STATE_STARTED) { ERROR("stream not in stopped or standby"); pthread_mutex_unlock(&out->common.lock); return -1; } pthread_mutex_unlock(&out->common.lock); sent = skt_write(out->common.audio_fd, buffer, bytes); if (sent == -1) { skt_disconnect(out->common.audio_fd); out->common.audio_fd = AUDIO_SKT_DISCONNECTED; if (out->common.state != AUDIO_A2DP_STATE_SUSPENDED) out->common.state = AUDIO_A2DP_STATE_STOPPED; else ERROR("write failed : stream suspended, avoid resetting state"); } else { const size_t frames = bytes / audio_stream_out_frame_size(stream); out->frames_rendered += frames; out->frames_presented += frames; } DEBUG("wrote %d bytes out of %zu bytes", sent, bytes); return sent; } CWE ID: CWE-284 Target: 1 Example 2: Code: static int get_moov_size(AVFormatContext *s) { int ret; AVIOContext *moov_buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&moov_buf)) < 0) return ret; if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0) return ret; return ffio_close_null_buf(moov_buf); } 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: struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) { struct tcp_options_received tcp_opt; struct inet_request_sock *ireq; struct tcp_request_sock *treq; struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); __u32 cookie = ntohl(th->ack_seq) - 1; struct sock *ret = sk; struct request_sock *req; int mss; struct dst_entry *dst; __u8 rcv_wscale; if (!sysctl_tcp_syncookies || !th->ack || th->rst) goto out; if (tcp_synq_no_recent_overflow(sk)) goto out; mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie); if (mss == 0) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED); goto out; } NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV); /* check for timestamp cookie support */ memset(&tcp_opt, 0, sizeof(tcp_opt)); tcp_parse_options(skb, &tcp_opt, 0, NULL); if (!cookie_timestamp_decode(&tcp_opt)) goto out; ret = NULL; req = inet_reqsk_alloc(&tcp6_request_sock_ops, sk, false); if (!req) goto out; ireq = inet_rsk(req); treq = tcp_rsk(req); treq->tfo_listener = false; if (security_inet_conn_request(sk, skb, req)) goto out_free; req->mss = mss; ireq->ir_rmt_port = th->source; ireq->ir_num = ntohs(th->dest); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); ireq->ir_mark = inet_request_mark(sk, skb); req->num_retrans = 0; ireq->snd_wscale = tcp_opt.snd_wscale; ireq->sack_ok = tcp_opt.sack_ok; ireq->wscale_ok = tcp_opt.wscale_ok; ireq->tstamp_ok = tcp_opt.saw_tstamp; req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0; treq->snt_synack.v64 = 0; treq->rcv_isn = ntohl(th->seq) - 1; treq->snt_isn = cookie; /* * We need to lookup the dst_entry to get the correct window size. * This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten * me if there is a preferred way. */ { struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(&fl6, np->opt, &final); fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = ireq->ir_mark; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = inet_sk(sk)->inet_sport; security_req_classify_flow(req, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) goto out_free; } req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW); tcp_select_initial_window(tcp_full_space(sk), req->mss, &req->rsk_rcv_wnd, &req->rsk_window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst); ret = tcp_get_cookie_sock(sk, skb, req, dst); out: return ret; out_free: reqsk_free(req); return NULL; } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WebGraphicsContext3DCommandBufferImpl::reshape(int width, int height) { cached_width_ = width; cached_height_ = height; gl_->ResizeCHROMIUM(width, height); #ifdef FLIP_FRAMEBUFFER_VERTICALLY scanline_.reset(new uint8[width * 4]); #endif // FLIP_FRAMEBUFFER_VERTICALLY } CWE ID: CWE-119 Target: 1 Example 2: Code: static struct page *new_page(struct page *page, unsigned long start, int **x) { return NULL; } CWE ID: CWE-388 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: size_t cac_list_meter(const void *el) { return sizeof(cac_object_t); } 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 size_t _php_mb_regex_get_option_string(char *str, size_t len, OnigOptionType option, OnigSyntaxType *syntax) { size_t len_left = len; size_t len_req = 0; char *p = str; char c; if ((option & ONIG_OPTION_IGNORECASE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'i'; } ++len_req; } if ((option & ONIG_OPTION_EXTEND) != 0) { if (len_left > 0) { --len_left; *(p++) = 'x'; } ++len_req; } if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) == (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) { if (len_left > 0) { --len_left; *(p++) = 'p'; } ++len_req; } else { if ((option & ONIG_OPTION_MULTILINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'm'; } ++len_req; } if ((option & ONIG_OPTION_SINGLELINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 's'; } ++len_req; } } if ((option & ONIG_OPTION_FIND_LONGEST) != 0) { if (len_left > 0) { --len_left; *(p++) = 'l'; } ++len_req; } if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) { if (len_left > 0) { --len_left; *(p++) = 'n'; } ++len_req; } c = 0; if (syntax == ONIG_SYNTAX_JAVA) { c = 'j'; } else if (syntax == ONIG_SYNTAX_GNU_REGEX) { c = 'u'; } else if (syntax == ONIG_SYNTAX_GREP) { c = 'g'; } else if (syntax == ONIG_SYNTAX_EMACS) { c = 'c'; } else if (syntax == ONIG_SYNTAX_RUBY) { c = 'r'; } else if (syntax == ONIG_SYNTAX_PERL) { c = 'z'; } else if (syntax == ONIG_SYNTAX_POSIX_BASIC) { c = 'b'; } else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) { c = 'd'; } if (c != 0) { if (len_left > 0) { --len_left; *(p++) = c; } ++len_req; } if (len_left > 0) { --len_left; *(p++) = '\0'; } ++len_req; if (len < len_req) { return len_req; } return 0; } CWE ID: CWE-415 Target: 1 Example 2: Code: void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id) { ui::AXTreeUpdate<AXContentNodeData> response; RendererAccessibility::SnapshotAccessibilityTree(this, &response); Send(new AccessibilityHostMsg_SnapshotResponse( routing_id_, callback_id, response)); } 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 inet6_destroy_sock(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct ipv6_txoptions *opt; /* Release rx options */ skb = xchg(&np->pktoptions, NULL); if (skb) kfree_skb(skb); skb = xchg(&np->rxpmtu, NULL); if (skb) kfree_skb(skb); /* Free flowlabels */ fl6_free_socklist(sk); /* Free tx options */ opt = xchg(&np->opt, NULL); if (opt) sock_kfree_s(sk, opt, opt->tot_len); } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, size_t mincodes, size_t numcodes, unsigned maxbitlen) { unsigned error = 0; while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/ tree->maxbitlen = maxbitlen; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ tree->lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned)); if(!tree->lengths) return 83; /*alloc fail*/ /*initialize all lengths to 0*/ memset(tree->lengths, 0, numcodes * sizeof(unsigned)); error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); if(!error) error = HuffmanTree_makeFromLengths2(tree); return error; } CWE ID: CWE-772 Target: 1 Example 2: Code: cmsBool Type_ViewingConditions_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems) { cmsICCViewingConditions* sc = (cmsICCViewingConditions* ) Ptr; if (!_cmsWriteXYZNumber(io, &sc ->IlluminantXYZ)) return FALSE; if (!_cmsWriteXYZNumber(io, &sc ->SurroundXYZ)) return FALSE; if (!_cmsWriteUInt32Number(io, sc ->IlluminantType)) return FALSE; return TRUE; cmsUNUSED_PARAMETER(nItems); cmsUNUSED_PARAMETER(self); } 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: AP_DECLARE(int) ap_process_request_internal(request_rec *r) { int file_req = (r->main && r->filename); int access_status; core_dir_config *d; /* Ignore embedded %2F's in path for proxy requests */ if (!r->proxyreq && r->parsed_uri.path) { d = ap_get_core_module_config(r->per_dir_config); if (d->allow_encoded_slashes) { access_status = ap_unescape_url_keep2f(r->parsed_uri.path, d->decode_encoded_slashes); } else { access_status = ap_unescape_url(r->parsed_uri.path); } if (access_status) { if (access_status == HTTP_NOT_FOUND) { if (! d->allow_encoded_slashes) { ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00026) "found %%2f (encoded '/') in URI " "(decoded='%s'), returning 404", r->parsed_uri.path); } } return access_status; } } ap_getparents(r->uri); /* OK --- shrinking transformations... */ /* All file subrequests are a huge pain... they cannot bubble through the * next several steps. Only file subrequests are allowed an empty uri, * otherwise let translate_name kill the request. */ if (!file_req) { if ((access_status = ap_location_walk(r))) { return access_status; } if ((access_status = ap_if_walk(r))) { return access_status; } /* Don't set per-dir loglevel if LogLevelOverride is set */ if (!r->connection->log) { d = ap_get_core_module_config(r->per_dir_config); if (d->log) r->log = d->log; } if ((access_status = ap_run_translate_name(r))) { return decl_die(access_status, "translate", r); } } /* Reset to the server default config prior to running map_to_storage */ r->per_dir_config = r->server->lookup_defaults; if ((access_status = ap_run_map_to_storage(r))) { /* This request wasn't in storage (e.g. TRACE) */ return access_status; } /* Rerun the location walk, which overrides any map_to_storage config. */ if ((access_status = ap_location_walk(r))) { return access_status; } if ((access_status = ap_if_walk(r))) { return access_status; } /* Don't set per-dir loglevel if LogLevelOverride is set */ if (!r->connection->log) { d = ap_get_core_module_config(r->per_dir_config); if (d->log) r->log = d->log; } if ((access_status = ap_run_post_perdir_config(r))) { return access_status; } /* Only on the main request! */ if (r->main == NULL) { if ((access_status = ap_run_header_parser(r))) { return access_status; } } /* Skip authn/authz if the parent or prior request passed the authn/authz, * and that configuration didn't change (this requires optimized _walk() * functions in map_to_storage that use the same merge results given * identical input.) If the config changes, we must re-auth. */ if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) { r->user = r->prev->user; r->ap_auth_type = r->prev->ap_auth_type; } else if (r->main && (r->main->per_dir_config == r->per_dir_config)) { r->user = r->main->user; r->ap_auth_type = r->main->ap_auth_type; } else { switch (ap_satisfies(r)) { case SATISFY_ALL: case SATISFY_NOSPEC: if ((access_status = ap_run_access_checker(r)) != OK) { return decl_die(access_status, "check access (with Satisfy All)", r); } access_status = ap_run_access_checker_ex(r); if (access_status == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker_ex hook: %s", r->uri); } else if (access_status != DECLINED) { return decl_die(access_status, "check access", r); } else { if ((access_status = ap_run_check_user_id(r)) != OK) { return decl_die(access_status, "check user", r); } if (r->user == NULL) { /* don't let buggy authn module crash us in authz */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00027) "No authentication done but request not " "allowed without authentication for %s. " "Authentication not configured?", r->uri); access_status = HTTP_INTERNAL_SERVER_ERROR; return decl_die(access_status, "check user", r); } if ((access_status = ap_run_auth_checker(r)) != OK) { return decl_die(access_status, "check authorization", r); } } break; case SATISFY_ANY: if ((access_status = ap_run_access_checker(r)) == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker hook and 'Satisfy any': %s", r->uri); break; } access_status = ap_run_access_checker_ex(r); if (access_status == OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "request authorized without authentication by " "access_checker_ex hook: %s", r->uri); } else if (access_status != DECLINED) { return decl_die(access_status, "check access", r); } else { if ((access_status = ap_run_check_user_id(r)) != OK) { return decl_die(access_status, "check user", r); } if (r->user == NULL) { /* don't let buggy authn module crash us in authz */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00028) "No authentication done but request not " "allowed without authentication for %s. " "Authentication not configured?", r->uri); access_status = HTTP_INTERNAL_SERVER_ERROR; return decl_die(access_status, "check user", r); } if ((access_status = ap_run_auth_checker(r)) != OK) { return decl_die(access_status, "check authorization", r); } } break; } } /* XXX Must make certain the ap_run_type_checker short circuits mime * in mod-proxy for r->proxyreq && r->parsed_uri.scheme * && !strcmp(r->parsed_uri.scheme, "http") */ if ((access_status = ap_run_type_checker(r)) != OK) { return decl_die(access_status, "find types", r); } if ((access_status = ap_run_fixups(r)) != OK) { ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "fixups hook gave %d: %s", access_status, r->uri); return access_status; } return OK; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg) { unsigned char *buffer; unsigned int *dest; int x, y; ImageStream *imgStr; Guchar *pix; int i; double *ctm; QMatrix matrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); if (maskColors) { for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); for (x = 0; x < width; x++) { for (i = 0; i < colorMap->getNumPixelComps(); ++i) { if (pix[i] < maskColors[2*i] * 255|| pix[i] > maskColors[2*i+1] * 255) { *dest = *dest | 0xff000000; break; } } pix += colorMap->getNumPixelComps(); dest++; } } m_image = new QImage(buffer, width, height, QImage::Format_ARGB32); } else { for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } m_image = new QImage(buffer, width, height, QImage::Format_RGB32); } if (m_image == NULL || m_image->isNull()) { qDebug() << "Null image"; delete imgStr; return; } ctm = state->getCTM(); matrix.setMatrix(ctm[0] / width, ctm[1] / width, -ctm[2] / height, -ctm[3] / height, ctm[2] + ctm[4], ctm[3] + ctm[5]); m_painter->setMatrix(matrix, true); m_painter->drawImage( QPoint(0,0), *m_image ); delete m_image; m_image = 0; free (buffer); delete imgStr; } CWE ID: CWE-189 Target: 1 Example 2: Code: static int mac80211_hwsim_change_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum nl80211_iftype newtype, bool newp2p) { newtype = ieee80211_iftype_p2p(newtype, newp2p); wiphy_dbg(hw->wiphy, "%s (old type=%d, new type=%d, mac_addr=%pM)\n", __func__, ieee80211_vif_type_p2p(vif), newtype, vif->addr); hwsim_check_magic(vif); /* * interface may change from non-AP to AP in * which case this needs to be set up again */ vif->cab_queue = 0; return 0; } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int fill_note_info(struct elfhdr *elf, int phdrs, struct elf_note_info *info, long signr, struct pt_regs *regs) { struct list_head *t; if (!elf_note_info_init(info)) return 0; if (signr) { struct core_thread *ct; struct elf_thread_status *ets; for (ct = current->mm->core_state->dumper.next; ct; ct = ct->next) { ets = kzalloc(sizeof(*ets), GFP_KERNEL); if (!ets) return 0; ets->thread = ct->task; list_add(&ets->list, &info->thread_list); } list_for_each(t, &info->thread_list) { int sz; ets = list_entry(t, struct elf_thread_status, list); sz = elf_dump_thread_status(signr, ets); info->thread_status_size += sz; } } /* now collect the dump for the current */ memset(info->prstatus, 0, sizeof(*info->prstatus)); fill_prstatus(info->prstatus, current, signr); elf_core_copy_regs(&info->prstatus->pr_reg, regs); /* Set up header */ fill_elf_header(elf, phdrs, ELF_ARCH, ELF_CORE_EFLAGS, ELF_OSABI); /* * Set up the notes in similar form to SVR4 core dumps made * with info from their /proc. */ fill_note(info->notes + 0, "CORE", NT_PRSTATUS, sizeof(*info->prstatus), info->prstatus); fill_psinfo(info->psinfo, current->group_leader, current->mm); fill_note(info->notes + 1, "CORE", NT_PRPSINFO, sizeof(*info->psinfo), info->psinfo); info->numnote = 2; fill_auxv_note(&info->notes[info->numnote++], current->mm); /* Try to dump the FPU. */ info->prstatus->pr_fpvalid = elf_core_copy_task_fpregs(current, regs, info->fpu); if (info->prstatus->pr_fpvalid) fill_note(info->notes + info->numnote++, "CORE", NT_PRFPREG, sizeof(*info->fpu), info->fpu); #ifdef ELF_CORE_COPY_XFPREGS if (elf_core_copy_task_xfpregs(current, info->xfpu)) fill_note(info->notes + info->numnote++, "LINUX", ELF_CORE_XFPREG_TYPE, sizeof(*info->xfpu), info->xfpu); #endif return 1; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_METHOD(Phar, offsetUnset) { char *fname, *error; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return; } if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate entry after copy on write */ entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } } CWE ID: CWE-20 Target: 1 Example 2: Code: int bdrv_parse_cache_flags(const char *mode, int *flags) { *flags &= ~BDRV_O_CACHE_MASK; if (!strcmp(mode, "off") || !strcmp(mode, "none")) { *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB; } else if (!strcmp(mode, "directsync")) { *flags |= BDRV_O_NOCACHE; } else if (!strcmp(mode, "writeback")) { *flags |= BDRV_O_CACHE_WB; } else if (!strcmp(mode, "unsafe")) { *flags |= BDRV_O_CACHE_WB; *flags |= BDRV_O_NO_FLUSH; } else if (!strcmp(mode, "writethrough")) { /* this is the default */ } else { return -1; } return 0; } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ResourceFetcher::didInitializeResourceLoader(ResourceLoader* loader) { if (!m_document) return; if (!m_loaders) m_loaders = adoptPtr(new ResourceLoaderSet()); ASSERT(!m_loaders->contains(loader)); m_loaders->add(loader); } 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: image_transform_png_set_palette_to_rgb_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_palette_to_rgb(pp); this->next->set(this->next, that, pp, pi); } CWE ID: Target: 1 Example 2: Code: void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo( const blink::WebMouseEvent& mouse_event, const ui::LatencyInfo& latency) { TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent", "x", mouse_event.PositionInWidget().x, "y", mouse_event.PositionInWidget().y); DCHECK_GE(mouse_event.GetType(), blink::WebInputEvent::kMouseTypeFirst); DCHECK_LE(mouse_event.GetType(), blink::WebInputEvent::kMouseTypeLast); for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) { if (mouse_event_callbacks_[i].Run(mouse_event)) return; } if (ShouldDropInputEvents()) return; if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event)) return; MouseEventWithLatencyInfo mouse_with_latency(mouse_event, latency); DispatchInputEventWithLatencyInfo(mouse_event, &mouse_with_latency.latency); input_router_->SendMouseEvent(mouse_with_latency); } 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: TIFFFdOpen(int fd, const char* name, const char* mode) { TIFF* tif; tif = TIFFClientOpen(name, mode, (thandle_t) fd, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); if (tif) tif->tif_fd = fd; return (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: rdpdr_process(STREAM s) { uint32 handle; uint16 vmin; uint16 component; uint16 pakid; logger(Protocol, Debug, "rdpdr_process()"); /* hexdump(s->p, s->end - s->p); */ in_uint16(s, component); in_uint16(s, pakid); if (component == RDPDR_CTYP_CORE) { switch (pakid) { case PAKID_CORE_DEVICE_IOREQUEST: rdpdr_process_irp(s); break; case PAKID_CORE_SERVER_ANNOUNCE: /* DR_CORE_SERVER_ANNOUNCE_REQ */ in_uint8s(s, 2); /* skip versionMajor */ in_uint16_le(s, vmin); /* VersionMinor */ in_uint32_le(s, g_client_id); /* ClientID */ /* The RDP client is responsibility to provide a random client id if server version is < 12 */ if (vmin < 0x000c) g_client_id = 0x815ed39d; /* IP address (use 127.0.0.1) 0x815ed39d */ g_epoch++; #if WITH_SCARD /* * We need to release all SCARD contexts to end all * current transactions and pending calls */ scard_release_all_contexts(); /* * According to [MS-RDPEFS] 3.2.5.1.2: * * If this packet appears after a sequence of other packets, * it is a signal that the server has reconnected to a new session * and the whole sequence has been reset. The client MUST treat * this packet as the beginning of a new sequence. * The client MUST also cancel all outstanding requests and release * previous references to all devices. * * If any problem arises in the future, please, pay attention to the * "If this packet appears after a sequence of other packets" part * */ #endif rdpdr_send_client_announce_reply(); rdpdr_send_client_name_request(); break; case PAKID_CORE_CLIENTID_CONFIRM: rdpdr_send_client_device_list_announce(); break; case PAKID_CORE_DEVICE_REPLY: in_uint32(s, handle); logger(Protocol, Debug, "rdpdr_process(), server connected to resource %d", handle); break; case PAKID_CORE_SERVER_CAPABILITY: rdpdr_send_client_capability_response(); break; default: logger(Protocol, Debug, "rdpdr_process(), pakid 0x%x of component 0x%x", pakid, component); break; } } else if (component == RDPDR_CTYP_PRN) { if (pakid == PAKID_PRN_CACHE_DATA) printercache_process(s); } else logger(Protocol, Warning, "rdpdr_process(), unhandled component 0x%x", component); } CWE ID: CWE-119 Target: 1 Example 2: Code: void GpuVideoDecodeAccelerator::OnDestroy() { DCHECK(video_decode_accelerator_.get()); video_decode_accelerator_->Destroy(); } 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 svm_vcpu_run(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX]; svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP]; svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP]; /* * A vmexit emulation is required before the vcpu can be executed * again. */ if (unlikely(svm->nested.exit_required)) return; pre_svm_run(svm); sync_lapic_to_cr8(vcpu); svm->vmcb->save.cr2 = vcpu->arch.cr2; clgi(); local_irq_enable(); asm volatile ( "push %%" _ASM_BP "; \n\t" "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t" "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t" "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t" "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t" "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t" "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t" #ifdef CONFIG_X86_64 "mov %c[r8](%[svm]), %%r8 \n\t" "mov %c[r9](%[svm]), %%r9 \n\t" "mov %c[r10](%[svm]), %%r10 \n\t" "mov %c[r11](%[svm]), %%r11 \n\t" "mov %c[r12](%[svm]), %%r12 \n\t" "mov %c[r13](%[svm]), %%r13 \n\t" "mov %c[r14](%[svm]), %%r14 \n\t" "mov %c[r15](%[svm]), %%r15 \n\t" #endif /* Enter guest mode */ "push %%" _ASM_AX " \n\t" "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t" __ex(SVM_VMLOAD) "\n\t" __ex(SVM_VMRUN) "\n\t" __ex(SVM_VMSAVE) "\n\t" "pop %%" _ASM_AX " \n\t" /* Save guest registers, load host registers */ "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t" "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t" "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t" "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t" "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t" "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t" #ifdef CONFIG_X86_64 "mov %%r8, %c[r8](%[svm]) \n\t" "mov %%r9, %c[r9](%[svm]) \n\t" "mov %%r10, %c[r10](%[svm]) \n\t" "mov %%r11, %c[r11](%[svm]) \n\t" "mov %%r12, %c[r12](%[svm]) \n\t" "mov %%r13, %c[r13](%[svm]) \n\t" "mov %%r14, %c[r14](%[svm]) \n\t" "mov %%r15, %c[r15](%[svm]) \n\t" #endif "pop %%" _ASM_BP : : [svm]"a"(svm), [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)), [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])), [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])), [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])), [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])), [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])), [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP])) #ifdef CONFIG_X86_64 , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])), [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])), [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])), [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])), [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])), [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])), [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])), [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15])) #endif : "cc", "memory" #ifdef CONFIG_X86_64 , "rbx", "rcx", "rdx", "rsi", "rdi" , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15" #else , "ebx", "ecx", "edx", "esi", "edi" #endif ); #ifdef CONFIG_X86_64 wrmsrl(MSR_GS_BASE, svm->host.gs_base); #else loadsegment(fs, svm->host.fs); #ifndef CONFIG_X86_32_LAZY_GS loadsegment(gs, svm->host.gs); #endif #endif reload_tss(vcpu); local_irq_disable(); vcpu->arch.cr2 = svm->vmcb->save.cr2; vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax; vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp; vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip; trace_kvm_exit(svm->vmcb->control.exit_code, vcpu, KVM_ISA_SVM); if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI)) kvm_before_handle_nmi(&svm->vcpu); stgi(); /* Any pending NMI will happen here */ if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI)) kvm_after_handle_nmi(&svm->vcpu); sync_cr8_to_lapic(vcpu); svm->next_rip = 0; svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING; /* if exit due to PF check for async PF */ if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) svm->apf_reason = kvm_read_and_reset_pf_reason(); if (npt_enabled) { vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR); vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR); } /* * We need to handle MC intercepts here before the vcpu has a chance to * change the physical cpu */ if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + MC_VECTOR)) svm_handle_mce(svm); mark_all_clean(svm->vmcb); } 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 DebuggerAttachFunction::RunAsync() { scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); if (!InitAgentHost()) return false; if (!DevToolsHttpHandler::IsSupportedProtocolVersion( params->required_version)) { error_ = ErrorUtils::FormatErrorMessage( keys::kProtocolVersionNotSupportedError, params->required_version); return false; } if (agent_host_->IsAttached()) { FormatErrorMessage(keys::kAlreadyAttachedError); return false; } infobars::InfoBar* infobar = NULL; if (!CommandLine::ForCurrentProcess()-> HasSwitch(switches::kSilentDebuggerExtensionAPI)) { infobar = ExtensionDevToolsInfoBarDelegate::Create( agent_host_->GetRenderViewHost(), GetExtension()->name()); if (!infobar) { error_ = ErrorUtils::FormatErrorMessage( keys::kSilentDebuggingRequired, switches::kSilentDebuggerExtensionAPI); return false; } } new ExtensionDevToolsClientHost(GetProfile(), agent_host_.get(), GetExtension()->id(), GetExtension()->name(), debuggee_, infobar); SendResponse(true); return true; } CWE ID: CWE-264 Target: 1 Example 2: Code: png_push_read_sig(png_structp png_ptr, png_infop info_ptr) { png_size_t num_checked = png_ptr->sig_bytes, num_to_check = 8 - num_checked; if (png_ptr->buffer_size < num_to_check) { num_to_check = png_ptr->buffer_size; } png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]), num_to_check); png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes + num_to_check); if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check)) { if (num_checked < 4 && png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4)) png_error(png_ptr, "Not a PNG file"); else png_error(png_ptr, "PNG file corrupted by ASCII conversion"); } else { if (png_ptr->sig_bytes >= 8) { png_ptr->process_mode = PNG_READ_CHUNK_MODE; } } } 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: EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionRemoveEventListener(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestEventTarget::s_info)) return throwVMTypeError(exec); JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info); TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); impl->removeEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)).get(), exec->argument(2).toBoolean(exec)); return JSValue::encode(jsUndefined()); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ext4_fill_flex_info(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_group_desc *gdp = NULL; ext4_group_t flex_group_count; ext4_group_t flex_group; int groups_per_flex = 0; size_t size; int i; sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { sbi->s_log_groups_per_flex = 0; return 1; } /* We allocate both existing and potentially added groups */ flex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) + ((le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) + 1) << EXT4_DESC_PER_BLOCK_BITS(sb))) / groups_per_flex; size = flex_group_count * sizeof(struct flex_groups); sbi->s_flex_groups = ext4_kvzalloc(size, GFP_KERNEL); if (sbi->s_flex_groups == NULL) { ext4_msg(sb, KERN_ERR, "not enough memory for %u flex groups", flex_group_count); goto failed; } for (i = 0; i < sbi->s_groups_count; i++) { gdp = ext4_get_group_desc(sb, i, NULL); flex_group = ext4_flex_group(sbi, i); atomic_add(ext4_free_inodes_count(sb, gdp), &sbi->s_flex_groups[flex_group].free_inodes); atomic_add(ext4_free_group_clusters(sb, gdp), &sbi->s_flex_groups[flex_group].free_clusters); atomic_add(ext4_used_dirs_count(sb, gdp), &sbi->s_flex_groups[flex_group].used_dirs); } return 1; failed: return 0; } CWE ID: CWE-189 Target: 1 Example 2: Code: void tty_ldisc_deinit(struct tty_struct *tty) { tty_ldisc_put(tty->ldisc); tty->ldisc = NULL; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: png_read_rows(png_structp png_ptr, png_bytepp row, png_bytepp display_row, png_uint_32 num_rows) { png_uint_32 i; png_bytepp rp; png_bytepp dp; png_debug(1, "in png_read_rows"); if (png_ptr == NULL) return; rp = row; dp = display_row; if (rp != NULL && dp != NULL) for (i = 0; i < num_rows; i++) { png_bytep rptr = *rp++; png_bytep dptr = *dp++; png_read_row(png_ptr, rptr, dptr); } else if (rp != NULL) for (i = 0; i < num_rows; i++) { png_bytep rptr = *rp; png_read_row(png_ptr, rptr, png_bytep_NULL); rp++; } else if (dp != NULL) for (i = 0; i < num_rows; i++) { png_bytep dptr = *dp; png_read_row(png_ptr, png_bytep_NULL, dptr); dp++; } } 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(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } CWE ID: CWE-190 Target: 1 Example 2: Code: size_t Parcel::getGlobalAllocSize() { pthread_mutex_lock(&gParcelGlobalAllocSizeLock); size_t size = gParcelGlobalAllocSize; pthread_mutex_unlock(&gParcelGlobalAllocSizeLock); return size; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void nfs4_open_prepare(struct rpc_task *task, void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state_owner *sp = data->owner; if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0) return; /* * Check if we still need to send an OPEN call, or if we can use * a delegation instead. */ if (data->state != NULL) { struct nfs_delegation *delegation; if (can_open_cached(data->state, data->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL))) goto out_no_action; rcu_read_lock(); delegation = rcu_dereference(NFS_I(data->state->inode)->delegation); if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) { rcu_read_unlock(); goto out_no_action; } rcu_read_unlock(); } /* Update sequence id. */ data->o_arg.id = sp->so_owner_id.id; data->o_arg.clientid = sp->so_client->cl_clientid; if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) { task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR]; nfs_copy_fh(&data->o_res.fh, data->o_arg.fh); } data->timestamp = jiffies; rpc_call_start(task); return; out_no_action: task->tk_action = NULL; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FlushImeConfig() { if (!initialized_successfully_) return; bool active_input_methods_are_changed = false; InputMethodConfigRequests::iterator iter = pending_config_requests_.begin(); while (iter != pending_config_requests_.end()) { const std::string& section = iter->first.first; const std::string& config_name = iter->first.second; ImeConfigValue& value = iter->second; if (config_name == language_prefs::kPreloadEnginesConfigName && !tentative_current_input_method_id_.empty()) { std::vector<std::string>::iterator engine_iter = std::find( value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_); if (engine_iter != value.string_list_value.end()) { std::rotate(value.string_list_value.begin(), engine_iter, // this becomes the new first element value.string_list_value.end()); } else { LOG(WARNING) << tentative_current_input_method_id_ << " is not in preload_engines: " << value.ToString(); } tentative_current_input_method_id_.erase(); } if (chromeos::SetImeConfig(input_method_status_connection_, section.c_str(), config_name.c_str(), value)) { if (config_name == language_prefs::kPreloadEnginesConfigName) { active_input_methods_are_changed = true; VLOG(1) << "Updated preload_engines: " << value.ToString(); } pending_config_requests_.erase(iter++); } else { break; } } if (active_input_methods_are_changed) { const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_, ActiveInputMethodsChanged(this, current_input_method_, num_active_input_methods)); } } CWE ID: CWE-399 Target: 1 Example 2: Code: static ssize_t ucma_disconnect(struct ucma_file *file, const char __user *inbuf, int in_len, int out_len) { struct rdma_ucm_disconnect cmd; struct ucma_context *ctx; int ret; if (copy_from_user(&cmd, inbuf, sizeof(cmd))) return -EFAULT; ctx = ucma_get_ctx(file, cmd.id); if (IS_ERR(ctx)) return PTR_ERR(ctx); ret = rdma_disconnect(ctx->cm_id); ucma_put_ctx(ctx); return ret; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; } zval_add_ref(&object); return (zend_object_iterator*)iterator; } CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void buf_to_pages(const void *buf, size_t buflen, struct page **pages, unsigned int *pgbase) { const void *p = buf; *pgbase = offset_in_page(buf); p -= *pgbase; while (p < buf + buflen) { *(pages++) = virt_to_page(p); p += PAGE_CACHE_SIZE; } } CWE ID: CWE-189 Target: 1 Example 2: Code: void OnResetModalDialogEvent(gfx::NativeViewId containing_window) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (modal_dialog_event_map_.count(containing_window)) modal_dialog_event_map_[containing_window].event->Reset(); } 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: long long BlockGroup::GetPrevTimeCode() const { return m_prev; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void hid_input_field(struct hid_device *hid, struct hid_field *field, __u8 *data, int interrupt) { unsigned n; unsigned count = field->report_count; unsigned offset = field->report_offset; unsigned size = field->report_size; __s32 min = field->logical_minimum; __s32 max = field->logical_maximum; __s32 *value; value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC); if (!value) return; for (n = 0; n < count; n++) { value[n] = min < 0 ? snto32(hid_field_extract(hid, data, offset + n * size, size), size) : hid_field_extract(hid, data, offset + n * size, size); /* Ignore report if ErrorRollOver */ if (!(field->flags & HID_MAIN_ITEM_VARIABLE) && value[n] >= min && value[n] <= max && field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1) goto exit; } for (n = 0; n < count; n++) { if (HID_MAIN_ITEM_VARIABLE & field->flags) { hid_process_event(hid, field, &field->usage[n], value[n], interrupt); continue; } if (field->value[n] >= min && field->value[n] <= max && field->usage[field->value[n] - min].hid && search(value, field->value[n], count)) hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt); if (value[n] >= min && value[n] <= max && field->usage[value[n] - min].hid && search(field->value, value[n], count)) hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt); } memcpy(field->value, value, count * sizeof(__s32)); exit: kfree(value); } CWE ID: CWE-125 Target: 1 Example 2: Code: static int xtea_setkey(struct crypto_tfm *tfm, const u8 *in_key, unsigned int key_len) { struct xtea_ctx *ctx = crypto_tfm_ctx(tfm); const __le32 *key = (const __le32 *)in_key; ctx->KEY[0] = le32_to_cpu(key[0]); ctx->KEY[1] = le32_to_cpu(key[1]); ctx->KEY[2] = le32_to_cpu(key[2]); ctx->KEY[3] = le32_to_cpu(key[3]); return 0; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void mntput_no_expire(struct mount *mnt) { rcu_read_lock(); mnt_add_count(mnt, -1); if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */ rcu_read_unlock(); return; } lock_mount_hash(); if (mnt_get_count(mnt)) { rcu_read_unlock(); unlock_mount_hash(); return; } if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) { rcu_read_unlock(); unlock_mount_hash(); return; } mnt->mnt.mnt_flags |= MNT_DOOMED; rcu_read_unlock(); list_del(&mnt->mnt_instance); unlock_mount_hash(); if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) { struct task_struct *task = current; if (likely(!(task->flags & PF_KTHREAD))) { init_task_work(&mnt->mnt_rcu, __cleanup_mnt); if (!task_work_add(task, &mnt->mnt_rcu, true)) return; } if (llist_add(&mnt->mnt_llist, &delayed_mntput_list)) schedule_delayed_work(&delayed_mntput_work, 1); return; } cleanup_mnt(mnt); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (1 << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (1 << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } CWE ID: CWE-125 Target: 1 Example 2: Code: int __sys_sendto(int fd, void __user *buff, size_t len, unsigned int flags, struct sockaddr __user *addr, int addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; err = import_single_range(WRITE, buff, len, &iov, &msg.msg_iter); if (unlikely(err)) return err; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_name = NULL; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg); out_put: fput_light(sock->file, fput_needed); out: return err; } 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 char* allocFromUTF16(const char16_t* in, size_t len) { if (len == 0) return getEmptyString(); const ssize_t bytes = utf16_to_utf8_length(in, len); if (bytes < 0) { return getEmptyString(); } SharedBuffer* buf = SharedBuffer::alloc(bytes+1); ALOG_ASSERT(buf, "Unable to allocate shared buffer"); if (!buf) { return getEmptyString(); } char* str = (char*)buf->data(); utf16_to_utf8(in, len, str); return str; } 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: MojoResult UnwrapSharedMemoryHandle(ScopedSharedBufferHandle handle, base::SharedMemoryHandle* memory_handle, size_t* size, bool* read_only) { if (!handle.is_valid()) return MOJO_RESULT_INVALID_ARGUMENT; MojoPlatformHandle platform_handle; platform_handle.struct_size = sizeof(MojoPlatformHandle); MojoPlatformSharedBufferHandleFlags flags; size_t num_bytes; MojoSharedBufferGuid mojo_guid; MojoResult result = MojoUnwrapPlatformSharedBufferHandle( handle.release().value(), &platform_handle, &num_bytes, &mojo_guid, &flags); if (result != MOJO_RESULT_OK) return result; if (size) *size = num_bytes; if (read_only) *read_only = flags & MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_READ_ONLY; base::UnguessableToken guid = base::UnguessableToken::Deserialize(mojo_guid.high, mojo_guid.low); #if defined(OS_MACOSX) && !defined(OS_IOS) DCHECK_EQ(platform_handle.type, MOJO_PLATFORM_HANDLE_TYPE_MACH_PORT); *memory_handle = base::SharedMemoryHandle( static_cast<mach_port_t>(platform_handle.value), num_bytes, guid); #elif defined(OS_FUCHSIA) DCHECK_EQ(platform_handle.type, MOJO_PLATFORM_HANDLE_TYPE_FUCHSIA_HANDLE); *memory_handle = base::SharedMemoryHandle( static_cast<zx_handle_t>(platform_handle.value), num_bytes, guid); #elif defined(OS_POSIX) DCHECK_EQ(platform_handle.type, MOJO_PLATFORM_HANDLE_TYPE_FILE_DESCRIPTOR); *memory_handle = base::SharedMemoryHandle( base::FileDescriptor(static_cast<int>(platform_handle.value), false), num_bytes, guid); #elif defined(OS_WIN) DCHECK_EQ(platform_handle.type, MOJO_PLATFORM_HANDLE_TYPE_WINDOWS_HANDLE); *memory_handle = base::SharedMemoryHandle( reinterpret_cast<HANDLE>(platform_handle.value), num_bytes, guid); #endif return MOJO_RESULT_OK; } CWE ID: CWE-787 Target: 1 Example 2: Code: static int nfs4_xdr_dec_open_noattr(struct rpc_rqst *rqstp, __be32 *p, struct nfs_openres *res) { struct xdr_stream xdr; struct compound_hdr hdr; int status; xdr_init_decode(&xdr, &rqstp->rq_rcv_buf, p); status = decode_compound_hdr(&xdr, &hdr); if (status) goto out; status = decode_putfh(&xdr); if (status) goto out; status = decode_open(&xdr, res); if (status) goto out; decode_getfattr(&xdr, res->f_attr, res->server); out: return status; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virDomainAbortJob(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainAbortJob) { int ret; ret = conn->driver->domainAbortJob(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } 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: static int bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); } if(rctx->topdown) { iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); } rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; } CWE ID: CWE-787 Target: 1 Example 2: Code: check_end (const char *p) { if (!p) return false; while (c_isspace (*p)) ++p; if (!*p || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T') || ((p[0] == '+' || p[0] == '-') && c_isdigit (p[1]))) return true; else return false; } 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: GF_Box *elst_New() { ISOM_DECL_BOX_ALLOC(GF_EditListBox, GF_ISOM_BOX_TYPE_ELST); tmp->entryList = gf_list_new(); if (!tmp->entryList) { gf_free(tmp); return NULL; } return (GF_Box *)tmp; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = cur_regs(env); struct bpf_reg_state *reg = regs + regno; int size, err = 0; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; /* alignment checks will add in reg->off themselves */ err = check_ptr_alignment(env, reg, off, size); if (err) return err; /* for access checks, reg->off is just part of off */ off += reg->off; if (reg->type == PTR_TO_MAP_VALUE) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into map\n", value_regno); return -EACCES; } err = check_map_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = SCALAR_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into ctx\n", value_regno); return -EACCES; } /* ctx accesses must be at a fixed offset, so that we can * determine what type of data were returned. */ if (reg->off) { verbose(env, "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n", regno, reg->off, off - reg->off); return -EACCES; } if (!tnum_is_const(reg->var_off) || reg->var_off.value) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable ctx access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } err = check_ctx_access(env, insn_idx, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { /* ctx access returns either a scalar, or a * PTR_TO_PACKET[_META,_END]. In the latter * case, we know the offset is zero. */ if (reg_type == SCALAR_VALUE) mark_reg_unknown(env, regs, value_regno); else mark_reg_known_zero(env, regs, value_regno); regs[value_regno].id = 0; regs[value_regno].off = 0; regs[value_regno].range = 0; regs[value_regno].type = reg_type; } } else if (reg->type == PTR_TO_STACK) { /* stack accesses must be at a fixed offset, so that we can * determine what type of data were returned. * See check_stack_read(). */ if (!tnum_is_const(reg->var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); verbose(env, "variable stack access var_off=%s off=%d size=%d", tn_buf, off, size); return -EACCES; } off += reg->var_off.value; if (off >= 0 || off < -MAX_BPF_STACK) { verbose(env, "invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (t == BPF_WRITE) err = check_stack_write(env, state, off, size, value_regno); else err = check_stack_read(env, state, off, size, value_regno); } else if (reg_is_pkt_pointer(reg)) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose(env, "cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose(env, "R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size, false); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown(env, regs, value_regno); } else { verbose(env, "R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && regs[value_regno].type == SCALAR_VALUE) { /* b/h/w load zero-extends, mark upper bits as known 0 */ regs[value_regno].var_off = tnum_cast(regs[value_regno].var_off, size); __update_reg_bounds(&regs[value_regno]); } return err; } CWE ID: CWE-119 Target: 1 Example 2: Code: ProcRenderQueryPictIndexValues(ClientPtr client) { PictFormatPtr pFormat; int rc, num; int rlength; int i; REQUEST(xRenderQueryPictIndexValuesReq); xRenderQueryPictIndexValuesReply *reply; xIndexValue *values; REQUEST_AT_LEAST_SIZE(xRenderQueryPictIndexValuesReq); rc = dixLookupResourceByType((void **) &pFormat, stuff->format, PictFormatType, client, DixReadAccess); if (rc != Success) return rc; if (pFormat->type != PictTypeIndexed) { client->errorValue = stuff->format; return BadMatch; } num = pFormat->index.nvalues; rlength = (sizeof(xRenderQueryPictIndexValuesReply) + num * sizeof(xIndexValue)); reply = (xRenderQueryPictIndexValuesReply *) calloc(1, rlength); if (!reply) return BadAlloc; reply->type = X_Reply; reply->sequenceNumber = client->sequence; reply->length = bytes_to_int32(rlength - sizeof(xGenericReply)); reply->numIndexValues = num; values = (xIndexValue *) (reply + 1); memcpy(reply + 1, pFormat->index.pValues, num * sizeof(xIndexValue)); if (client->swapped) { for (i = 0; i < num; i++) { swapl(&values[i].pixel); swaps(&values[i].red); swaps(&values[i].green); swaps(&values[i].blue); swaps(&values[i].alpha); } swaps(&reply->sequenceNumber); swapl(&reply->length); swapl(&reply->numIndexValues); } WriteToClient(client, rlength, reply); free(reply); return Success; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; unsigned char *byteptr = wpmd->data; wpc->version_five = 1; // just having this block signals version 5.0 wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0; if (wpc->channel_reordering) { free (wpc->channel_reordering); wpc->channel_reordering = NULL; } if (bytecnt) { wpc->file_format = *byteptr++; wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++; bytecnt -= 2; if (bytecnt) { int nchans, i; wpc->channel_layout = (int32_t) *byteptr++ << 16; bytecnt--; if (bytecnt) { wpc->channel_layout += nchans = *byteptr++; bytecnt--; if (bytecnt) { if (bytecnt > nchans) return FALSE; wpc->channel_reordering = malloc (nchans); if (wpc->channel_reordering) { for (i = 0; i < nchans; ++i) if (bytecnt) { wpc->channel_reordering [i] = *byteptr++; bytecnt--; } else wpc->channel_reordering [i] = i; } } } else wpc->channel_layout += wpc->config.num_channels; } } return TRUE; } CWE ID: CWE-125 Target: 1 Example 2: Code: void ff_put_pixels8x8_c(uint8_t *dst, uint8_t *src, ptrdiff_t stride) { put_pixels8_8_c(dst, src, stride, 8); } 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 bool svc_rdma_prealloc_maps(struct svcxprt_rdma *xprt) { unsigned int i; /* One for each receive buffer on this connection. */ i = xprt->sc_max_requests; while (i--) { struct svc_rdma_req_map *map; map = alloc_req_map(GFP_KERNEL); if (!map) { dprintk("svcrdma: No memory for request map\n"); return false; } list_add(&map->free, &xprt->sc_maps); } return true; } 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: v8::Handle<v8::Value> V8TestSerializedScriptValueInterface::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestSerializedScriptValueInterface.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 2) return V8Proxy::throwNotEnoughArgumentsError(); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, hello, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); MessagePortArray messagePortArrayTransferList; ArrayBufferArray arrayBufferArrayTransferList; if (args.Length() > 2) { if (!extractTransferables(args[2], messagePortArrayTransferList, arrayBufferArrayTransferList)) return V8Proxy::throwTypeError("Could not extract transferables"); } bool dataDidThrow = false; RefPtr<SerializedScriptValue> data = SerializedScriptValue::create(args[1], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate()); if (dataDidThrow) return v8::Undefined(); RefPtr<TestSerializedScriptValueInterface> impl = TestSerializedScriptValueInterface::create(hello, data, messagePortArrayTransferList); v8::Handle<v8::Object> wrapper = args.Holder(); V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get()); V8DOMWrapper::setJSWrapperForDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate()); return args.Holder(); } CWE ID: Target: 1 Example 2: Code: void HTMLMediaElement::scheduleNotifyPlaying() { scheduleEvent(EventTypeNames::playing); scheduleResolvePlayPromises(); } 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: Error* Automation::CheckAlertsSupported() { return CheckVersion( 768, 0, "Alerts are not supported for this version of Chrome"); } 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: ZSTD_encodeSequences_body( void* dst, size_t dstCapacity, FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, seqDef const* sequences, size_t nbSeq, int longOffsets) { BIT_CStream_t blockStream; FSE_CState_t stateMatchLength; FSE_CState_t stateOffsetBits; FSE_CState_t stateLitLength; CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */ /* first symbols */ FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]); FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]); FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]); BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); if (longOffsets) { U32 const ofBits = ofCodeTable[nbSeq-1]; int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits); BIT_flushBits(&blockStream); } BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits, ofBits - extraBits); } else { BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]); } BIT_flushBits(&blockStream); { size_t n; for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */ BYTE const llCode = llCodeTable[n]; BYTE const ofCode = ofCodeTable[n]; BYTE const mlCode = mlCodeTable[n]; U32 const llBits = LL_bits[llCode]; U32 const ofBits = ofCode; U32 const mlBits = ML_bits[mlCode]; DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u", sequences[n].litLength, sequences[n].matchLength + MINMATCH, sequences[n].offset); /* 32b*/ /* 64b*/ /* (7)*/ /* (7)*/ FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */ FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */ if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/ FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */ if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog))) BIT_flushBits(&blockStream); /* (7)*/ BIT_addBits(&blockStream, sequences[n].litLength, llBits); if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[n].matchLength, mlBits); if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream); if (longOffsets) { int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[n].offset, extraBits); BIT_flushBits(&blockStream); /* (7)*/ } BIT_addBits(&blockStream, sequences[n].offset >> extraBits, ofBits - extraBits); /* 31 */ } else { BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */ } BIT_flushBits(&blockStream); /* (7)*/ } } DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog); FSE_flushCState(&blockStream, &stateMatchLength); DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog); FSE_flushCState(&blockStream, &stateOffsetBits); DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog); FSE_flushCState(&blockStream, &stateLitLength); { size_t const streamSize = BIT_closeCStream(&blockStream); if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */ return streamSize; } } CWE ID: CWE-362 Target: 1 Example 2: Code: ofputil_pull_ofp11_buckets(struct ofpbuf *msg, size_t buckets_length, enum ofp_version version, struct ovs_list *buckets) { struct ofp11_bucket *ob; uint32_t bucket_id = 0; ovs_list_init(buckets); while (buckets_length > 0) { struct ofputil_bucket *bucket; struct ofpbuf ofpacts; enum ofperr error; size_t ob_len; ob = (buckets_length >= sizeof *ob ? ofpbuf_try_pull(msg, sizeof *ob) : NULL); if (!ob) { VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %"PRIuSIZE" leftover bytes", buckets_length); ofputil_bucket_list_destroy(buckets); return OFPERR_OFPGMFC_BAD_BUCKET; } ob_len = ntohs(ob->len); if (ob_len < sizeof *ob) { VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length " "%"PRIuSIZE" is not valid", ob_len); ofputil_bucket_list_destroy(buckets); return OFPERR_OFPGMFC_BAD_BUCKET; } else if (ob_len > buckets_length) { VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length " "%"PRIuSIZE" exceeds remaining buckets data size %"PRIuSIZE, ob_len, buckets_length); ofputil_bucket_list_destroy(buckets); return OFPERR_OFPGMFC_BAD_BUCKET; } buckets_length -= ob_len; ofpbuf_init(&ofpacts, 0); error = ofpacts_pull_openflow_actions(msg, ob_len - sizeof *ob, version, NULL, NULL, &ofpacts); if (error) { ofpbuf_uninit(&ofpacts); ofputil_bucket_list_destroy(buckets); return error; } bucket = xzalloc(sizeof *bucket); bucket->weight = ntohs(ob->weight); error = ofputil_port_from_ofp11(ob->watch_port, &bucket->watch_port); if (error) { ofpbuf_uninit(&ofpacts); ofputil_bucket_list_destroy(buckets); free(bucket); return OFPERR_OFPGMFC_BAD_WATCH; } bucket->watch_group = ntohl(ob->watch_group); bucket->bucket_id = bucket_id++; bucket->ofpacts = ofpbuf_steal_data(&ofpacts); bucket->ofpacts_len = ofpacts.size; ovs_list_push_back(buckets, &bucket->list_node); } return 0; } CWE ID: CWE-617 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ikev2_parent_inI2outR2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inI2outR2: calculating g^{xy}, sending R2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inI2outR2_tail(pcrc, r); if ( e > STF_FAIL) { /* we do not send a notify because we are the initiator that could be responding to an error notification */ int v2_notify_num = e - STF_FAIL; DBG_log( "ikev2_parent_inI2outR2_tail returned STF_FAIL with %s", enum_name(&ikev2_notify_names, v2_notify_num)); } else if ( e != STF_OK) { DBG_log("ikev2_parent_inI2outR2_tail returned %s", enum_name(&stfstatus_name, e)); } if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); passert(GLOBALS_ARE_RESET()); } 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: OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() { CHECK(mHandle != NULL); memset(mHandle, 0, sizeof(tagvideoEncControls)); CHECK(mEncParams != NULL); memset(mEncParams, 0, sizeof(tagvideoEncOptions)); if (!PVGetDefaultEncOption(mEncParams, 0)) { ALOGE("Failed to get default encoding parameters"); return OMX_ErrorUndefined; } mEncParams->encMode = mEncodeMode; mEncParams->encWidth[0] = mWidth; mEncParams->encHeight[0] = mHeight; mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format mEncParams->rcType = VBR_1; mEncParams->vbvDelay = 5.0f; mEncParams->profile_level = CORE_PROFILE_LEVEL2; mEncParams->packetSize = 32; mEncParams->rvlcEnable = PV_OFF; mEncParams->numLayers = 1; mEncParams->timeIncRes = 1000; mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate; mEncParams->bitRate[0] = mBitrate; mEncParams->iQuant[0] = 15; mEncParams->pQuant[0] = 12; mEncParams->quantType[0] = 0; mEncParams->noFrameSkipped = PV_OFF; if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) { free(mInputFrameData); mInputFrameData = (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1); CHECK(mInputFrameData != NULL); } if (mWidth % 16 != 0 || mHeight % 16 != 0) { ALOGE("Video frame size %dx%d must be a multiple of 16", mWidth, mHeight); return OMX_ErrorBadParameter; } if (mIDRFrameRefreshIntervalInSec < 0) { mEncParams->intraPeriod = -1; } else if (mIDRFrameRefreshIntervalInSec == 0) { mEncParams->intraPeriod = 1; // All I frames } else { mEncParams->intraPeriod = (mIDRFrameRefreshIntervalInSec * mFramerate) >> 16; } mEncParams->numIntraMB = 0; mEncParams->sceneDetect = PV_ON; mEncParams->searchRange = 16; mEncParams->mv8x8Enable = PV_OFF; mEncParams->gobHeaderInterval = 0; mEncParams->useACPred = PV_ON; mEncParams->intraDCVlcTh = 0; return OMX_ErrorNone; } CWE ID: CWE-119 Target: 1 Example 2: Code: void SplashOutputDev::clearModRegion() { splash->clearModRegion(); } 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: process_remove_identity(SocketEntry *e, int version) { size_t blen; int r, success = 0; struct sshkey *key = NULL; u_char *blob; #ifdef WITH_SSH1 u_int bits; #endif /* WITH_SSH1 */ switch (version) { #ifdef WITH_SSH1 case 1: if ((key = sshkey_new(KEY_RSA1)) == NULL) { error("%s: sshkey_new failed", __func__); return; } if ((r = sshbuf_get_u32(e->request, &bits)) != 0 || (r = sshbuf_get_bignum1(e->request, key->rsa->e)) != 0 || (r = sshbuf_get_bignum1(e->request, key->rsa->n)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); if (bits != sshkey_size(key)) logit("Warning: identity keysize mismatch: " "actual %u, announced %u", sshkey_size(key), bits); break; #endif /* WITH_SSH1 */ case 2: if ((r = sshbuf_get_string(e->request, &blob, &blen)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); if ((r = sshkey_from_blob(blob, blen, &key)) != 0) error("%s: sshkey_from_blob failed: %s", __func__, ssh_err(r)); free(blob); break; } if (key != NULL) { Identity *id = lookup_identity(key, version); if (id != NULL) { /* * We have this key. Free the old key. Since we * don't want to leave empty slots in the middle of * the array, we actually free the key there and move * all the entries between the empty slot and the end * of the array. */ Idtab *tab = idtab_lookup(version); if (tab->nentries < 1) fatal("process_remove_identity: " "internal error: tab->nentries %d", tab->nentries); TAILQ_REMOVE(&tab->idlist, id, next); free_identity(id); tab->nentries--; success = 1; } sshkey_free(key); } send_status(e, success); } CWE ID: CWE-426 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FrameSelection::MoveCaretSelection(const IntPoint& point) { DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); Element* const editable = ComputeVisibleSelectionInDOMTree().RootEditableElement(); if (!editable) return; const VisiblePosition position = VisiblePositionForContentsPoint(point, GetFrame()); SelectionInDOMTree::Builder builder; builder.SetIsDirectional(GetSelectionInDOMTree().IsDirectional()); builder.SetIsHandleVisible(true); if (position.IsNotNull()) builder.Collapse(position.ToPositionWithAffinity()); SetSelection(builder.Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetSetSelectionBy(SetSelectionBy::kUser) .Build()); } CWE ID: CWE-119 Target: 1 Example 2: Code: ExtensionInstallDialogView::ExtensionInstallDialogView( Profile* profile, content::PageNavigator* navigator, ExtensionInstallPrompt::Delegate* delegate, scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) : profile_(profile), navigator_(navigator), delegate_(delegate), prompt_(prompt), container_(NULL), scroll_view_(NULL), handled_result_(false) { InitView(); } CWE ID: CWE-17 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SetVisibleFalseAndQueueSwapPromise() { layer_tree_host()->SetVisible(false); std::unique_ptr<SwapPromise> swap_promise( new TestSwapPromise(&swap_promise_result_)); layer_tree_host()->GetSwapPromiseManager()->QueueSwapPromise( std::move(swap_promise)); } CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree() { ASSERT(!m_isDestroyingShadowSubtree); m_isDestroyingShadowSubtree = true; if (SpinButtonElement* element = spinButtonElement()) element->removeSpinButtonOwner(); if (ClearButtonElement* element = clearButtonElement()) element->removeClearButtonOwner(); if (DateTimeEditElement* element = dateTimeEditElement()) element->removeEditControlOwner(); if (PickerIndicatorElement* element = pickerIndicatorElement()) element->removePickerIndicatorOwner(); if (element()->focused()) element()->focus(); BaseDateAndTimeInputType::destroyShadowSubtree(); m_isDestroyingShadowSubtree = false; } CWE ID: CWE-399 Target: 1 Example 2: Code: inline v8::Handle<v8::Value> DialogHandler::returnValue() const { if (m_dialogContext.IsEmpty()) return v8::Undefined(); v8::Context::Scope scope(m_dialogContext); v8::Handle<v8::Value> returnValue = m_dialogContext->Global()->Get(v8::String::NewSymbol("returnValue")); if (returnValue.IsEmpty()) return v8::Undefined(); return returnValue; } 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: set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, "w"); if (!fp) { if (name) flog(LOG_ERR, "failed to set %s (%u) for %s: %s", name, val, iface, strerror(errno)); return -1; } fprintf(fp, "%u", val); fclose(fp); return 0; } CWE ID: CWE-22 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; } CWE ID: Target: 1 Example 2: Code: void SoftAACEncoder::onQueueFilled(OMX_U32 portIndex) { if (mSignalledError) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (!mSentCodecSpecificData) { if (outQueue.empty()) { return; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; outHeader->nFilledLen = sizeof(mAudioSpecificConfigData); outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG; uint8_t *out = outHeader->pBuffer + outHeader->nOffset; memcpy(out, mAudioSpecificConfigData, sizeof(mAudioSpecificConfigData)); #if 0 ALOGI("sending codec specific data."); hexdump(out, sizeof(mAudioSpecificConfigData)); #endif outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); mSentCodecSpecificData = true; } size_t numBytesPerInputFrame = mNumChannels * kNumSamplesPerFrame * sizeof(int16_t); for (;;) { while (mInputSize < numBytesPerInputFrame) { if (mSawInputEOS || inQueue.empty()) { return; } BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; const void *inData = inHeader->pBuffer + inHeader->nOffset; size_t copy = numBytesPerInputFrame - mInputSize; if (copy > inHeader->nFilledLen) { copy = inHeader->nFilledLen; } if (mInputFrame == NULL) { mInputFrame = new int16_t[kNumSamplesPerFrame * mNumChannels]; } if (mInputSize == 0) { mInputTimeUs = inHeader->nTimeStamp; } memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy); mInputSize += copy; inHeader->nOffset += copy; inHeader->nFilledLen -= copy; inHeader->nTimeStamp += (copy * 1000000ll / mSampleRate) / (mNumChannels * sizeof(int16_t)); if (inHeader->nFilledLen == 0) { if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { ALOGV("saw input EOS"); mSawInputEOS = true; memset((uint8_t *)mInputFrame + mInputSize, 0, numBytesPerInputFrame - mInputSize); mInputSize = numBytesPerInputFrame; } inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inData = NULL; inHeader = NULL; inInfo = NULL; } } if (outQueue.empty()) { return; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; VO_CODECBUFFER inputData; memset(&inputData, 0, sizeof(inputData)); inputData.Buffer = (unsigned char *)mInputFrame; inputData.Length = numBytesPerInputFrame; CHECK(VO_ERR_NONE == mApiHandle->SetInputData(mEncoderHandle, &inputData)); VO_CODECBUFFER outputData; memset(&outputData, 0, sizeof(outputData)); VO_AUDIO_OUTPUTINFO outputInfo; memset(&outputInfo, 0, sizeof(outputInfo)); uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset; size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset; VO_U32 ret = VO_ERR_NONE; size_t nOutputBytes = 0; do { outputData.Buffer = outPtr; outputData.Length = outAvailable - nOutputBytes; ret = mApiHandle->GetOutputData( mEncoderHandle, &outputData, &outputInfo); if (ret == VO_ERR_NONE) { outPtr += outputData.Length; nOutputBytes += outputData.Length; } } while (ret != VO_ERR_INPUT_BUFFER_SMALL); outHeader->nFilledLen = nOutputBytes; outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME; if (mSawInputEOS) { outHeader->nFlags = OMX_BUFFERFLAG_EOS; } outHeader->nTimeStamp = mInputTimeUs; #if 0 ALOGI("sending %d bytes of data (time = %lld us, flags = 0x%08lx)", nOutputBytes, mInputTimeUs, outHeader->nFlags); hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen); #endif outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); outHeader = NULL; outInfo = NULL; mInputSize = 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: keepalived_free_realloc_common(void *buffer, size_t size, const char *file, const char *function, int line, bool is_realloc) { unsigned long check; MEMCHECK *entry, *entry2, *le; MEMCHECK search = {.ptr = buffer}; /* If nullpointer remember */ if (buffer == NULL) { entry = get_free_alloc_entry(); entry->ptr = NULL; entry->size = size; entry->file = file; entry->func = function; entry->line = line; entry->type = !size ? FREE_NULL : REALLOC_NULL; if (!is_realloc) fprintf(log_op, "%s%-7s%9s, %9s, %4s at %s, %3d, %s\n", format_time(), "free", "ERROR", "NULL", "", file, line, function); else fprintf(log_op, "%s%-7s%9s, %9s, %4zu at %s, %3d, %s%s\n", format_time(), "realloc", "ERROR", "NULL", size, file, line, function, size ? " *** converted to malloc" : ""); __set_bit(MEM_ERR_DETECT_BIT, &debug); list_add_tail(&entry->l, &bad_list); return !size ? NULL : keepalived_malloc(size, file, function, line); } entry = rb_search(&alloc_list, &search, t, memcheck_ptr_cmp); /* Not found */ if (!entry) { entry = get_free_alloc_entry(); entry->ptr = buffer; entry->size = size; entry->file = file; entry->func = function; entry->line = line; entry->type = !size ? FREE_NOT_ALLOC : REALLOC_NOT_ALLOC; entry->seq_num = seq_num++; if (!is_realloc) fprintf(log_op, "%s%-7s%9s, %9p, at %s, %3d, %s - not found\n", format_time(), "free", "ERROR", buffer, file, line, function); else fprintf(log_op, "%s%-7s%9s, %9p, %4zu at %s, %3d, %s - not found\n", format_time(), "realloc", "ERROR", buffer, size, file, line, function); __set_bit(MEM_ERR_DETECT_BIT, &debug); list_for_each_entry_reverse(le, &free_list, l) { if (le->ptr == buffer && le->type == LAST_FREE) { fprintf (log_op, "%11s-> pointer last released at [%3d:%3d], at %s, %3d, %s\n", "", le->seq_num, number_alloc_list, le->file, le->line, le->func); entry->type = !size ? DOUBLE_FREE : REALLOC_DOUBLE_FREE; break; } }; list_add_tail(&entry->l, &bad_list); return NULL; } check = entry->size + CHECK_VAL; if (*(unsigned long *)((char *)buffer + entry->size) != check) { entry2 = get_free_alloc_entry(); *entry2 = *entry; entry2->type = OVERRUN; list_add_tail(&entry2->l, &bad_list); fprintf(log_op, "%s%s corrupt, buffer overrun [%3d:%3d], %9p, %4zu at %s, %3d, %s\n", format_time(), !is_realloc ? "free" : "realloc", entry->seq_num, number_alloc_list, buffer, entry->size, file, line, function); dump_buffer(entry->ptr, entry->size + sizeof (check), log_op, TIME_STR_LEN); fprintf(log_op, "%*sCheck_sum\n", TIME_STR_LEN, ""); dump_buffer((char *) &check, sizeof(check), log_op, TIME_STR_LEN); __set_bit(MEM_ERR_DETECT_BIT, &debug); } mem_allocated -= entry->size; if (!size) { free(buffer); if (is_realloc) { fprintf(log_op, "%s%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9s, %4s at %s, %3d, %s\n", format_time(), "realloc", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, "made free", "", file, line, function); /* Record bad realloc */ entry2 = get_free_alloc_entry(); *entry2 = *entry; entry2->type = REALLOC_ZERO_SIZE; entry2->file = file; entry2->line = line; entry2->func = function; list_add_tail(&entry2->l, &bad_list); } else fprintf(log_op, "%s%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9s, %4s at %s, %3d, %s\n", format_time(), "free", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, "NULL", "", file, line, function); #ifdef _MEM_CHECK_LOG_ if (__test_bit(MEM_CHECK_LOG_BIT, &debug)) log_message(LOG_INFO, "%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s", is_realloc ? "realloc" : "free", entry->seq_num, number_alloc_list, buffer, entry->size, file, line, function); #endif entry->file = file; entry->line = line; entry->func = function; entry->type = LAST_FREE; rb_erase(&entry->t, &alloc_list); list_add_tail(&entry->l, &free_list); free_list_size++; number_alloc_list--; return NULL; } buffer = realloc(buffer, size + sizeof (unsigned long)); mem_allocated += size; if (mem_allocated > max_mem_allocated) max_mem_allocated = mem_allocated; fprintf(log_op, "%srealloc[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9p, %4zu at %s, %3d, %s\n", format_time(), entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, buffer, size, file, line, function); #ifdef _MEM_CHECK_LOG_ if (__test_bit(MEM_CHECK_LOG_BIT, &debug)) log_message(LOG_INFO, "realloc[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9p, %4zu at %s, %3d, %s", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, buffer, size, file, line, function); #endif *(unsigned long *) ((char *) buffer + size) = size + CHECK_VAL; if (entry->ptr != buffer) { rb_erase(&entry->t, &alloc_list); entry->ptr = buffer; rb_insert_sort(&alloc_list, entry, t, memcheck_ptr_cmp); } else entry->ptr = buffer; entry->size = size; entry->file = file; entry->line = line; entry->func = function; num_reallocs++; return buffer; } CWE ID: CWE-59 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: RenderThread::~RenderThread() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); if (web_database_observer_impl_.get()) web_database_observer_impl_->WaitForAllDatabasesToClose(); RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; RemoveFilter(vc_manager_->video_capture_message_filter()); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_.get()) file_thread_->Stop(); if (webkit_client_.get()) WebKit::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) PluginChannelBase::CleanupChannels(); if (RenderProcessImpl::InProcessPlugins()) CoUninitialize(); #endif } CWE ID: CWE-20 Target: 1 Example 2: Code: int bdrv_create_file(const char* filename, QEMUOptionParameter *options, Error **errp) { BlockDriver *drv; Error *local_err = NULL; int ret; drv = bdrv_find_protocol(filename, true); if (drv == NULL) { error_setg(errp, "Could not find protocol for file '%s'", filename); return -ENOENT; } ret = bdrv_create(drv, filename, options, &local_err); if (local_err) { error_propagate(errp, local_err); } return ret; } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GLES2DecoderPassthroughImpl::BindPendingImagesForSamplers() { for (TexturePendingBinding& pending : textures_pending_binding_) BindOnePendingImage(pending.target, pending.texture.get()); textures_pending_binding_.clear(); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; struct crypto_blkcipher *tfm = desc->tfm; struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm); int err; blkcipher_walk_init(&walk, dst, src, nbytes); err = blkcipher_walk_virt_block(desc, &walk, 64); salsa20_ivsetup(ctx, walk.iv); if (likely(walk.nbytes == nbytes)) { salsa20_encrypt_bytes(ctx, walk.src.virt.addr, walk.dst.virt.addr, nbytes); return blkcipher_walk_done(desc, &walk, 0); } while (walk.nbytes >= 64) { salsa20_encrypt_bytes(ctx, walk.src.virt.addr, walk.dst.virt.addr, walk.nbytes - (walk.nbytes % 64)); err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64); } if (walk.nbytes) { salsa20_encrypt_bytes(ctx, walk.src.virt.addr, walk.dst.virt.addr, walk.nbytes); err = blkcipher_walk_done(desc, &walk, 0); } return err; } CWE ID: CWE-20 Target: 1 Example 2: Code: void Document::fullScreenChangeDelayTimerFired(Timer<Document>*) { RefPtr<Document> protectDocument(this); Deque<RefPtr<Node> > changeQueue; m_fullScreenChangeEventTargetQueue.swap(changeQueue); Deque<RefPtr<Node> > errorQueue; m_fullScreenErrorEventTargetQueue.swap(errorQueue); while (!changeQueue.isEmpty()) { RefPtr<Node> node = changeQueue.takeFirst(); if (!node) node = documentElement(); if (!node) continue; if (!contains(node.get()) && !node->inDocument()) changeQueue.append(documentElement()); node->dispatchEvent(Event::create(eventNames().webkitfullscreenchangeEvent, true, false)); } while (!errorQueue.isEmpty()) { RefPtr<Node> node = errorQueue.takeFirst(); if (!node) node = documentElement(); if (!node) continue; if (!contains(node.get()) && !node->inDocument()) errorQueue.append(documentElement()); node->dispatchEvent(Event::create(eventNames().webkitfullscreenerrorEvent, true, false)); } } 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 UsbDeviceImpl::OnPathAccessRequestComplete(const OpenCallback& callback, bool success) { if (success) { blocking_task_runner_->PostTask( FROM_HERE, base::Bind(&UsbDeviceImpl::OpenOnBlockingThread, this, callback)); } else { chromeos::PermissionBrokerClient* client = chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient(); DCHECK(client) << "Could not get permission broker client."; client->OpenPath( device_path_, base::Bind(&UsbDeviceImpl::OnOpenRequestComplete, this, callback)); } } 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: int ssl_get_prev_session(SSL *s, unsigned char *session_id, int len, const unsigned char *limit) { /* This is used only by servers. */ SSL_SESSION *ret = NULL; int fatal = 0; int try_session_cache = 1; #ifndef OPENSSL_NO_TLSEXT int r; #endif if (session_id + len > limit) { fatal = 1; goto err; } if (len == 0) try_session_cache = 0; #ifndef OPENSSL_NO_TLSEXT /* sets s->tlsext_ticket_expected */ r = tls1_process_ticket(s, session_id, len, limit, &ret); switch (r) { case -1: /* Error during processing */ fatal = 1; goto err; case 0: /* No ticket found */ case 1: /* Zero length ticket found */ break; /* Ok to carry on processing session id. */ case 2: /* Ticket found but not decrypted. */ case 3: /* Ticket decrypted, *ret has been set. */ try_session_cache = 0; break; default: abort(); } #endif if (try_session_cache && ret == NULL && !(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) { SSL_SESSION data; data.ssl_version = s->version; data.session_id_length = len; if (len == 0) return 0; memcpy(data.session_id, session_id, len); CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX); ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data); if (ret != NULL) { /* don't allow other threads to steal it: */ CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION); } CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); if (ret == NULL) s->session_ctx->stats.sess_miss++; } if (try_session_cache && ret == NULL && s->session_ctx->get_session_cb != NULL) { int copy = 1; if ((ret = s->session_ctx->get_session_cb(s, session_id, len, &copy))) { s->session_ctx->stats.sess_cb_hit++; /* * Increment reference count now if the session callback asks us * to do so (note that if the session structures returned by the * callback are shared between threads, it must handle the * reference count itself [i.e. copy == 0], or things won't be * thread-safe). */ if (copy) CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION); /* * Add the externally cached session to the internal cache as * well if and only if we are supposed to. */ if (! (s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE)) /* * The following should not return 1, otherwise, things are * very strange */ SSL_CTX_add_session(s->session_ctx, ret); } } if (ret == NULL) goto err; /* Now ret is non-NULL and we own one of its reference counts. */ if (ret->sid_ctx_length != s->sid_ctx_length || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) { /* * We have the session requested by the client, but we don't want to * use it in this context. */ goto err; /* treat like cache miss */ } if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) { /* * We can't be sure if this session is being used out of context, * which is especially important for SSL_VERIFY_PEER. The application * should have used SSL[_CTX]_set_session_id_context. For this error * case, we generate an error instead of treating the event like a * cache miss (otherwise it would be easy for applications to * effectively disable the session cache by accident without anyone * noticing). */ SSLerr(SSL_F_SSL_GET_PREV_SESSION, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED); fatal = 1; goto err; } if (ret->cipher == NULL) { unsigned char buf[5], *p; unsigned long l; p = buf; l = ret->cipher_id; l2n(l, p); if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR) ret->cipher = ssl_get_cipher_by_char(s, &(buf[2])); else ret->cipher = ssl_get_cipher_by_char(s, &(buf[1])); if (ret->cipher == NULL) goto err; } if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */ s->session_ctx->stats.sess_timeout++; if (try_session_cache) { /* session was from the cache, so remove it */ SSL_CTX_remove_session(s->session_ctx, ret); } goto err; } s->session_ctx->stats.sess_hit++; if (s->session != NULL) SSL_SESSION_free(s->session); s->session = ret; s->verify_result = s->session->verify_result; return 1; err: if (ret != NULL) { SSL_SESSION_free(ret); #ifndef OPENSSL_NO_TLSEXT if (!try_session_cache) { /* * The session was from a ticket, so we should issue a ticket for * the new session */ s->tlsext_ticket_expected = 1; } #endif } if (fatal) return -1; else return 0; } CWE ID: CWE-190 Target: 1 Example 2: Code: encode_POP_MPLS(const struct ofpact_pop_mpls *pop_mpls, enum ofp_version ofp_version, struct ofpbuf *out) { put_OFPAT_POP_MPLS(out, ofp_version, pop_mpls->ethertype); } 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 gdImageColorAllocateAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; int ct = (-1); if (im->trueColor) { return gdTrueColorAlpha(r, g, b, a); } for (i = 0; i < im->colorsTotal; i++) { if (im->open[i]) { ct = i; break; } } if (ct == (-1)) { ct = im->colorsTotal; if (ct == gdMaxColors) { return -1; } im->colorsTotal++; } im->red[ct] = r; im->green[ct] = g; im->blue[ct] = b; im->alpha[ct] = a; im->open[ct] = 0; return ct; } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device; /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ if (!scsi_block_when_processing_errors(sdev)) return -ENODEV; if (sdev->host->hostt->compat_ioctl) { int ret; ret = sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg); return ret; } /* * Let the static ioctl translation table take care of it. */ return -ENOIOCTLCMD; } CWE ID: CWE-264 Target: 1 Example 2: Code: void ChromePluginServiceFilter::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); switch (type) { case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: { int render_process_id = content::Source<content::RenderProcessHost>(source).ptr()->GetID(); base::AutoLock auto_lock(lock_); plugin_details_.erase(render_process_id); break; } case chrome::NOTIFICATION_PLUGIN_ENABLE_STATUS_CHANGED: { Profile* profile = content::Source<Profile>(source).ptr(); PluginService::GetInstance()->PurgePluginListCache(profile, false); if (profile && profile->HasOffTheRecordProfile()) { PluginService::GetInstance()->PurgePluginListCache( profile->GetOffTheRecordProfile(), false); } break; } default: { NOTREACHED(); } } } CWE ID: CWE-287 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int swp_handler(struct pt_regs *regs, unsigned int instr) { unsigned int address, destreg, data, type; unsigned int res = 0; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, regs->ARM_pc); if (current->pid != previous_pid) { pr_debug("\"%s\" (%ld) uses deprecated SWP{B} instruction\n", current->comm, (unsigned long)current->pid); previous_pid = current->pid; } address = regs->uregs[EXTRACT_REG_NUM(instr, RN_OFFSET)]; data = regs->uregs[EXTRACT_REG_NUM(instr, RT2_OFFSET)]; destreg = EXTRACT_REG_NUM(instr, RT_OFFSET); type = instr & TYPE_SWPB; pr_debug("addr in r%d->0x%08x, dest is r%d, source in r%d->0x%08x)\n", EXTRACT_REG_NUM(instr, RN_OFFSET), address, destreg, EXTRACT_REG_NUM(instr, RT2_OFFSET), data); /* Check access in reasonable access range for both SWP and SWPB */ if (!access_ok(VERIFY_WRITE, (address & ~3), 4)) { pr_debug("SWP{B} emulation: access to %p not allowed!\n", (void *)address); res = -EFAULT; } else { res = emulate_swpX(address, &data, type); } if (res == 0) { /* * On successful emulation, revert the adjustment to the PC * made in kernel/traps.c in order to resume execution at the * instruction following the SWP{B}. */ regs->ARM_pc += 4; regs->uregs[destreg] = data; } else if (res == -EFAULT) { /* * Memory errors do not mean emulation failed. * Set up signal info to return SEGV, then return OK */ set_segfault(regs, address); } return 0; } 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: H264PictureToVaapiDecodeSurface(const scoped_refptr<H264Picture>& pic) { VaapiH264Picture* vaapi_pic = pic->AsVaapiH264Picture(); CHECK(vaapi_pic); return vaapi_pic->dec_surface(); } CWE ID: CWE-362 Target: 1 Example 2: Code: static void limitedWithEmptyMissingInvalidAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectPythonV8Internal::limitedWithEmptyMissingInvalidAttributeAttributeGetter(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: void GLES2Implementation::RestoreArrayBuffer(bool restore) { if (restore) { helper_->BindBuffer(GL_ARRAY_BUFFER, bound_array_buffer_); } } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline void set_socket_blocking(int s, int blocking) { int opts; opts = fcntl(s, F_GETFL); if (opts<0) APPL_TRACE_ERROR("set blocking (%s)", strerror(errno)); if(blocking) opts &= ~O_NONBLOCK; else opts |= O_NONBLOCK; if (fcntl(s, F_SETFL, opts) < 0) APPL_TRACE_ERROR("set blocking (%s)", strerror(errno)); } CWE ID: CWE-284 Target: 1 Example 2: Code: int V8Debugger::getGroupId(v8::Local<v8::Context> context) { v8::Local<v8::Value> data = context->GetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex)); if (data.IsEmpty() || !data->IsString()) return 0; String16 dataString = toProtocolString(data.As<v8::String>()); if (dataString.isEmpty()) return 0; size_t commaPos = dataString.find(","); if (commaPos == String16::kNotFound) return 0; return dataString.substring(0, commaPos).toInteger(); } CWE ID: CWE-79 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ipv6_parse_hopopts(struct sk_buff *skb) { struct inet6_skb_parm *opt = IP6CB(skb); /* * skb_network_header(skb) is equal to skb->data, and * skb_network_header_len(skb) is always equal to * sizeof(struct ipv6hdr) by definition of * hop-by-hop options. */ if (!pskb_may_pull(skb, sizeof(struct ipv6hdr) + 8) || !pskb_may_pull(skb, (sizeof(struct ipv6hdr) + ((skb_transport_header(skb)[1] + 1) << 3)))) { kfree_skb(skb); return -1; } opt->flags |= IP6SKB_HOPBYHOP; if (ip6_parse_tlv(tlvprochopopt_lst, skb)) { skb->transport_header += (skb_transport_header(skb)[1] + 1) << 3; opt = IP6CB(skb); opt->nhoff = sizeof(struct ipv6hdr); return 1; } return -1; } 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: pgp_enumerate_blob(sc_card_t *card, pgp_blob_t *blob) { const u8 *in; int r; if (blob->files != NULL) return SC_SUCCESS; if ((r = pgp_read_blob(card, blob)) < 0) return r; in = blob->data; while ((int) blob->len > (in - blob->data)) { unsigned int cla, tag, tmptag; size_t len; const u8 *data = in; pgp_blob_t *new; r = sc_asn1_read_tag(&data, blob->len - (in - blob->data), &cla, &tag, &len); if (r < 0 || data == NULL) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unexpected end of contents\n"); return SC_ERROR_OBJECT_NOT_VALID; } /* undo ASN1's split of tag & class */ for (tmptag = tag; tmptag > 0x0FF; tmptag >>= 8) { cla <<= 8; } tag |= cla; /* Awful hack for composite DOs that have * a TLV with the DO's id encompassing the * entire blob. Example: Yubikey Neo */ if (tag == blob->id) { in = data; continue; } /* create fake file system hierarchy by * using constructed DOs as DF */ if ((new = pgp_new_blob(card, blob, tag, sc_file_new())) == NULL) return SC_ERROR_OUT_OF_MEMORY; pgp_set_blob(new, data, len); in = data + len; } return SC_SUCCESS; } CWE ID: CWE-125 Target: 1 Example 2: Code: int dtls1_read_failed(SSL *s, int code) { if ( code > 0) { fprintf( stderr, "invalid state reached %s:%d", __FILE__, __LINE__); return 1; } if (!dtls1_is_timer_expired(s)) { /* not a timeout, none of our business, let higher layers handle this. in fact it's probably an error */ return code; } #ifndef OPENSSL_NO_HEARTBEATS if (!SSL_in_init(s) && !s->tlsext_hb_pending) /* done, no need to send a retransmit */ #else if (!SSL_in_init(s)) /* done, no need to send a retransmit */ #endif { BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ); return code; } #if 0 /* for now, each alert contains only one record number */ item = pqueue_peek(state->rcvd_records); if ( item ) { /* send an alert immediately for all the missing records */ } else #endif #if 0 /* no more alert sending, just retransmit the last set of messages */ if ( state->timeout.read_timeouts >= DTLS1_TMO_READ_COUNT) ssl3_send_alert(s,SSL3_AL_WARNING, DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); #endif return dtls1_handle_timeout(s); } 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 Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ image->storage_class=PseudoClass; if (image->columns == 0) image->columns=2592; if (image->rows == 0) image->rows=3508; image->depth=8; if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Monochrome colormap. */ image->colormap[0].red=QuantumRange; image->colormap[0].green=QuantumRange; image->colormap[0].blue=QuantumRange; image->colormap[1].red=(Quantum) 0; image->colormap[1].green=(Quantum) 0; image->colormap[1].blue=(Quantum) 0; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=HuffmanDecodeImage(image); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } 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 PlatformSensorProviderWin::SensorReaderCreated( mojom::SensorType type, mojo::ScopedSharedBufferMapping mapping, const CreateSensorCallback& callback, std::unique_ptr<PlatformSensorReaderWin> sensor_reader) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!sensor_reader) { callback.Run(nullptr); return; } scoped_refptr<PlatformSensor> sensor = new PlatformSensorWin( type, std::move(mapping), this, sensor_thread_->task_runner(), std::move(sensor_reader)); callback.Run(sensor); } CWE ID: CWE-732 Target: 1 Example 2: Code: static int burl_normalize_2F_to_slash (buffer *b, int qs, int flags) { /*("%2F" must already have been uppercased during normalization)*/ const char * const s = b->ptr; const int used = qs < 0 ? (int)buffer_string_length(b) : qs; for (int i = 0; i < used; ++i) { if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { return (flags & HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE) ? burl_normalize_2F_to_slash_fix(b, qs, i) : -2; /*(flags & HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT)*/ } } return qs; } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int ret; int copylen; ret = -EOPNOTSUPP; if (m->msg_flags&MSG_OOB) goto read_error; skb = skb_recv_datagram(sk, flags, 0 , &ret); if (!skb) goto read_error; copylen = skb->len; if (len < copylen) { m->msg_flags |= MSG_TRUNC; copylen = len; } ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen); if (ret) goto out_free; ret = (flags & MSG_TRUNC) ? skb->len : copylen; out_free: skb_free_datagram(sk, skb); caif_check_flow_release(sk); return ret; read_error: return ret; } 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: int ipmi_destroy_user(struct ipmi_user *user) { _ipmi_destroy_user(user); cleanup_srcu_struct(&user->release_barrier); kref_put(&user->refcount, free_user); return 0; } CWE ID: CWE-416 Target: 1 Example 2: Code: static Handle<Object> GetImpl(Isolate* isolate, FixedArrayBase* backing_store, uint32_t entry) { return BackingStore::get(BackingStore::cast(backing_store), entry); } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(mcrypt_cfb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int misaligned_fpu_store(struct pt_regs *regs, __u32 opcode, int displacement_not_indexed, int width_shift, int do_paired_load) { /* Return -1 for a fault, 0 for OK */ int error; int srcreg; __u64 address; error = generate_and_check_address(regs, opcode, displacement_not_indexed, width_shift, &address); if (error < 0) { return error; } perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, address); srcreg = (opcode >> 4) & 0x3f; if (user_mode(regs)) { __u64 buffer; /* Initialise these to NaNs. */ __u32 buflo=0xffffffffUL, bufhi=0xffffffffUL; if (!access_ok(VERIFY_WRITE, (unsigned long) address, 1UL<<width_shift)) { return -1; } /* 'current' may be the current owner of the FPU state, so context switch the registers into memory so they can be indexed by register number. */ if (last_task_used_math == current) { enable_fpu(); save_fpu(current); disable_fpu(); last_task_used_math = NULL; regs->sr |= SR_FD; } switch (width_shift) { case 2: buflo = current->thread.xstate->hardfpu.fp_regs[srcreg]; break; case 3: if (do_paired_load) { buflo = current->thread.xstate->hardfpu.fp_regs[srcreg]; bufhi = current->thread.xstate->hardfpu.fp_regs[srcreg+1]; } else { #if defined(CONFIG_CPU_LITTLE_ENDIAN) bufhi = current->thread.xstate->hardfpu.fp_regs[srcreg]; buflo = current->thread.xstate->hardfpu.fp_regs[srcreg+1]; #else buflo = current->thread.xstate->hardfpu.fp_regs[srcreg]; bufhi = current->thread.xstate->hardfpu.fp_regs[srcreg+1]; #endif } break; default: printk("Unexpected width_shift %d in misaligned_fpu_store, PC=%08lx\n", width_shift, (unsigned long) regs->pc); break; } *(__u32*) &buffer = buflo; *(1 + (__u32*) &buffer) = bufhi; if (__copy_user((void *)(int)address, &buffer, (1 << width_shift)) > 0) { return -1; /* fault */ } return 0; } else { die ("Misaligned FPU load inside kernel", regs, 0); return -1; } } CWE ID: CWE-399 Target: 1 Example 2: Code: adisplay_clear( ADisplay display ) { grBitmap* bit = display->bitmap; int pitch = bit->pitch; if ( pitch < 0 ) pitch = -pitch; if ( bit->mode == gr_pixel_mode_gray ) memset( bit->buffer, display->back_color.value, pitch * bit->rows ); else { unsigned char* p = bit->buffer; int i, j; for ( i = 0; i < bit->rows; i++ ) { for ( j = 0; j < bit->width; j++ ) memcpy( p + 3 * j, display->back_color.chroma, 3 ); p += pitch; } } } 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: init_sg(void) { int rc; if (scatter_elem_sz < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = scatter_elem_sz; } if (def_reserved_size >= 0) sg_big_buff = def_reserved_size; else def_reserved_size = sg_big_buff; rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS, "sg"); if (rc) return rc; sg_sysfs_class = class_create(THIS_MODULE, "scsi_generic"); if ( IS_ERR(sg_sysfs_class) ) { rc = PTR_ERR(sg_sysfs_class); goto err_out; } sg_sysfs_valid = 1; rc = scsi_register_interface(&sg_interface); if (0 == rc) { #ifdef CONFIG_SCSI_PROC_FS sg_proc_init(); #endif /* CONFIG_SCSI_PROC_FS */ return 0; } class_destroy(sg_sysfs_class); err_out: unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS); return rc; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); } CWE ID: CWE-190 Target: 1 Example 2: Code: static struct xfrm_state *xfrm_user_state_lookup(struct net *net, struct xfrm_usersa_id *p, struct nlattr **attrs, int *errp) { struct xfrm_state *x = NULL; struct xfrm_mark m; int err; u32 mark = xfrm_mark_get(attrs, &m); if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) { err = -ESRCH; x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family); } else { xfrm_address_t *saddr = NULL; verify_one_addr(attrs, XFRMA_SRCADDR, &saddr); if (!saddr) { err = -EINVAL; goto out; } err = -ESRCH; x = xfrm_state_lookup_byaddr(net, mark, &p->daddr, saddr, p->proto, p->family); } out: if (!x && errp) *errp = err; return x; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int em_sysexit(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; int usermode; u16 cs_sel = 0, ss_sel = 0; /* inject #GP if in real mode or Virtual 8086 mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_gp(ctxt, 0); setup_syscalls_segments(ctxt, &cs, &ss); if ((ctxt->rex_prefix & 0x8) != 0x0) usermode = X86EMUL_MODE_PROT64; else usermode = X86EMUL_MODE_PROT32; cs.dpl = 3; ss.dpl = 3; ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (usermode) { case X86EMUL_MODE_PROT32: cs_sel = (u16)(msr_data + 16); if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); ss_sel = (u16)(msr_data + 24); break; case X86EMUL_MODE_PROT64: cs_sel = (u16)(msr_data + 32); if (msr_data == 0x0) return emulate_gp(ctxt, 0); ss_sel = cs_sel + 8; cs.d = 0; cs.l = 1; break; } cs_sel |= SELECTOR_RPL_MASK; ss_sel |= SELECTOR_RPL_MASK; ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ctxt->_eip = reg_read(ctxt, VCPU_REGS_RDX); *reg_write(ctxt, VCPU_REGS_RSP) = reg_read(ctxt, VCPU_REGS_RCX); return X86EMUL_CONTINUE; } 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 kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot) { gfn_t gfn, end_gfn; pfn_t pfn; int r = 0; struct iommu_domain *domain = kvm->arch.iommu_domain; int flags; /* check if iommu exists and in use */ if (!domain) return 0; gfn = slot->base_gfn; end_gfn = gfn + slot->npages; flags = IOMMU_READ; if (!(slot->flags & KVM_MEM_READONLY)) flags |= IOMMU_WRITE; if (!kvm->arch.iommu_noncoherent) flags |= IOMMU_CACHE; while (gfn < end_gfn) { unsigned long page_size; /* Check if already mapped */ if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) { gfn += 1; continue; } /* Get the page size we could use to map */ page_size = kvm_host_page_size(kvm, gfn); /* Make sure the page_size does not exceed the memslot */ while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn) page_size >>= 1; /* Make sure gfn is aligned to the page size we want to map */ while ((gfn << PAGE_SHIFT) & (page_size - 1)) page_size >>= 1; /* Make sure hva is aligned to the page size we want to map */ while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1)) page_size >>= 1; /* * Pin all pages we are about to map in memory. This is * important because we unmap and unpin in 4kb steps later. */ pfn = kvm_pin_pages(slot, gfn, page_size); if (is_error_noslot_pfn(pfn)) { gfn += 1; continue; } /* Map into IO address space */ r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn), page_size, flags); if (r) { printk(KERN_ERR "kvm_iommu_map_address:" "iommu failed to map pfn=%llx\n", pfn); goto unmap_pages; } gfn += page_size >> PAGE_SHIFT; } return 0; unmap_pages: kvm_iommu_put_pages(kvm, slot->base_gfn, gfn); return r; } CWE ID: CWE-189 Target: 1 Example 2: Code: R_API ut64 r_bin_java_class_cp_calc_size(RBinJavaCPTypeObj *obj) { ut64 size = 0; size += 1; size += 2; return size; } 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 OomInterventionTabHelper::StartDetectionInRenderer() { auto* config = OomInterventionConfig::GetInstance(); bool renderer_pause_enabled = config->is_renderer_pause_enabled(); bool navigate_ads_enabled = config->is_navigate_ads_enabled(); if ((renderer_pause_enabled || navigate_ads_enabled) && decider_) { DCHECK(!web_contents()->GetBrowserContext()->IsOffTheRecord()); const std::string& host = web_contents()->GetVisibleURL().host(); if (!decider_->CanTriggerIntervention(host)) { renderer_pause_enabled = false; navigate_ads_enabled = false; } } content::RenderFrameHost* main_frame = web_contents()->GetMainFrame(); DCHECK(main_frame); content::RenderProcessHost* render_process_host = main_frame->GetProcess(); DCHECK(render_process_host); content::BindInterface(render_process_host, mojo::MakeRequest(&intervention_)); DCHECK(!binding_.is_bound()); blink::mojom::OomInterventionHostPtr host; binding_.Bind(mojo::MakeRequest(&host)); blink::mojom::DetectionArgsPtr detection_args = config->GetRendererOomDetectionArgs(); intervention_->StartDetection(std::move(host), std::move(detection_args), renderer_pause_enabled, navigate_ads_enabled); } 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 Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { const char *section_name = ""; const char *link_section_name = ""; char *end = NULL; Elf_(Shdr) *link_shdr = NULL; ut8 dfs[sizeof (Elf_(Verdef))] = {0}; Sdb *sdb; int cnt, i; if (shdr->sh_link > bin->ehdr.e_shnum) { return false; } link_shdr = &bin->shdr[shdr->sh_link]; if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) { return false; } Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char)); if (!defs) { return false; } if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!defs) { bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n"); return NULL; } sdb = sdb_new0 (); end = (char *)defs + shdr->sh_size; sdb_set (sdb, "section_name", section_name, 0); sdb_num_set (sdb, "entries", shdr->sh_info, 0); sdb_num_set (sdb, "addr", shdr->sh_addr, 0); sdb_num_set (sdb, "offset", shdr->sh_offset, 0); sdb_num_set (sdb, "link", shdr->sh_link, 0); sdb_set (sdb, "link_section_name", link_section_name, 0); for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) { Sdb *sdb_verdef = sdb_new0 (); char *vstart = ((char*)defs) + i; char key[32] = {0}; Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart; Elf_(Verdaux) aux = {0}; int j = 0; int isum = 0; r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef))); verdef->vd_version = READ16 (dfs, j) verdef->vd_flags = READ16 (dfs, j) verdef->vd_ndx = READ16 (dfs, j) verdef->vd_cnt = READ16 (dfs, j) verdef->vd_hash = READ32 (dfs, j) verdef->vd_aux = READ32 (dfs, j) verdef->vd_next = READ32 (dfs, j) int vdaux = verdef->vd_aux; if (vdaux < 1) { sdb_free (sdb_verdef); goto out_error; } vstart += vdaux; if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); goto out_error; } j = 0; aux.vda_name = READ32 (vstart, j) aux.vda_next = READ32 (vstart, j) isum = i + verdef->vd_aux; if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); goto out_error; } sdb_num_set (sdb_verdef, "idx", i, 0); sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0); sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0); sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0); sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0); sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0); for (j = 1; j < verdef->vd_cnt; ++j) { int k; Sdb *sdb_parent = sdb_new0 (); isum += aux.vda_next; vstart += aux.vda_next; if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } k = 0; aux.vda_name = READ32 (vstart, k) aux.vda_next = READ32 (vstart, k) if (aux.vda_name > bin->dynstr_size) { sdb_free (sdb_verdef); sdb_free (sdb_parent); goto out_error; } sdb_num_set (sdb_parent, "idx", isum, 0); sdb_num_set (sdb_parent, "parent", j, 0); sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0); snprintf (key, sizeof (key), "parent%d", j - 1); sdb_ns_set (sdb_verdef, key, sdb_parent); } snprintf (key, sizeof (key), "verdef%d", cnt); sdb_ns_set (sdb, key, sdb_verdef); if (!verdef->vd_next) { sdb_free (sdb_verdef); goto out_error; } if ((st32)verdef->vd_next < 1) { eprintf ("Warning: Invalid vd_next in the ELF version\n"); break; } i += verdef->vd_next; } free (defs); return sdb; out_error: free (defs); sdb_free (sdb); return NULL; } CWE ID: CWE-476 Target: 1 Example 2: Code: unsigned long do_mremap(unsigned long addr, unsigned long old_len, unsigned long new_len, unsigned long flags, unsigned long new_addr) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; unsigned long ret = -EINVAL; unsigned long charged = 0; if (flags & ~(MREMAP_FIXED | MREMAP_MAYMOVE)) goto out; if (addr & ~PAGE_MASK) goto out; old_len = PAGE_ALIGN(old_len); new_len = PAGE_ALIGN(new_len); /* * We allow a zero old-len as a special case * for DOS-emu "duplicate shm area" thing. But * a zero new-len is nonsensical. */ if (!new_len) goto out; if (flags & MREMAP_FIXED) { if (flags & MREMAP_MAYMOVE) ret = mremap_to(addr, old_len, new_addr, new_len); goto out; } /* * Always allow a shrinking remap: that just unmaps * the unnecessary pages.. * do_munmap does all the needed commit accounting */ if (old_len >= new_len) { ret = do_munmap(mm, addr+new_len, old_len - new_len); if (ret && old_len != new_len) goto out; ret = addr; goto out; } /* * Ok, we need to grow.. */ vma = vma_to_resize(addr, old_len, new_len, &charged); if (IS_ERR(vma)) { ret = PTR_ERR(vma); goto out; } /* old_len exactly to the end of the area.. */ if (old_len == vma->vm_end - addr) { /* can we just expand the current mapping? */ if (vma_expandable(vma, new_len - old_len)) { int pages = (new_len - old_len) >> PAGE_SHIFT; if (vma_adjust(vma, vma->vm_start, addr + new_len, vma->vm_pgoff, NULL)) { ret = -ENOMEM; goto out; } mm->total_vm += pages; vm_stat_account(mm, vma->vm_flags, vma->vm_file, pages); if (vma->vm_flags & VM_LOCKED) { mm->locked_vm += pages; mlock_vma_pages_range(vma, addr + old_len, addr + new_len); } ret = addr; goto out; } } /* * We weren't able to just expand or shrink the area, * we need to create a new one and move it.. */ ret = -ENOMEM; if (flags & MREMAP_MAYMOVE) { unsigned long map_flags = 0; if (vma->vm_flags & VM_MAYSHARE) map_flags |= MAP_SHARED; new_addr = get_unmapped_area(vma->vm_file, 0, new_len, vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT), map_flags); if (new_addr & ~PAGE_MASK) { ret = new_addr; goto out; } ret = security_file_mmap(NULL, 0, 0, 0, new_addr, 1); if (ret) goto out; ret = move_vma(vma, addr, old_len, new_len, new_addr); } out: if (ret & ~PAGE_MASK) vm_unacct_memory(charged); return ret; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: modifier_init(png_modifier *pm) { memset(pm, 0, sizeof *pm); store_init(&pm->this); pm->modifications = NULL; pm->state = modifier_start; pm->sbitlow = 1U; pm->ngammas = 0; pm->ngamma_tests = 0; pm->gammas = 0; pm->current_gamma = 0; pm->encodings = 0; pm->nencodings = 0; pm->current_encoding = 0; pm->encoding_counter = 0; pm->encoding_ignored = 0; pm->repeat = 0; pm->test_uses_encoding = 0; pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0; pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0; pm->maxcalcG = 0; pm->limit = 4E-3; pm->log8 = pm->log16 = 0; /* Means 'off' */ pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0; pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0; pm->error_indexed = 0; pm->use_update_info = 0; pm->interlace_type = PNG_INTERLACE_NONE; pm->test_standard = 0; pm->test_size = 0; pm->test_transform = 0; pm->use_input_precision = 0; pm->use_input_precision_sbit = 0; pm->use_input_precision_16to8 = 0; pm->calculations_use_input_precision = 0; pm->assume_16_bit_calculations = 0; pm->test_gamma_threshold = 0; pm->test_gamma_transform = 0; pm->test_gamma_sbit = 0; pm->test_gamma_scale16 = 0; pm->test_gamma_background = 0; pm->test_gamma_alpha_mode = 0; pm->test_gamma_expand16 = 0; pm->test_exhaustive = 0; pm->log = 0; /* Rely on the memset for all the other fields - there are no pointers */ } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SVGDocumentExtensions::startAnimations() { WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> > timeContainers; timeContainers.appendRange(m_timeContainers.begin(), m_timeContainers.end()); WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> >::iterator end = timeContainers.end(); for (WillBeHeapVector<RefPtrWillBeMember<SVGSVGElement> >::iterator itr = timeContainers.begin(); itr != end; ++itr) (*itr)->timeContainer()->begin(); } CWE ID: Target: 1 Example 2: Code: status_t OMXCodec::setAACFormat( int32_t numChannels, int32_t sampleRate, int32_t bitRate, int32_t aacProfile, bool isADTS) { if (numChannels > 2) { ALOGW("Number of channels: (%d) \n", numChannels); } if (mIsEncoder) { if (isADTS) { return -EINVAL; } setRawAudioFormat(kPortIndexInput, sampleRate, numChannels); OMX_AUDIO_PARAM_PORTFORMATTYPE format; InitOMXParams(&format); format.nPortIndex = kPortIndexOutput; format.nIndex = 0; status_t err = OMX_ErrorNone; while (OMX_ErrorNone == err) { CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat, &format, sizeof(format)), (status_t)OK); if (format.eEncoding == OMX_AUDIO_CodingAAC) { break; } format.nIndex++; } CHECK_EQ((status_t)OK, err); CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat, &format, sizeof(format)), (status_t)OK); OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = kPortIndexOutput; CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)), (status_t)OK); def.format.audio.bFlagErrorConcealment = OMX_TRUE; def.format.audio.eEncoding = OMX_AUDIO_CodingAAC; CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)), (status_t)OK); OMX_AUDIO_PARAM_AACPROFILETYPE profile; InitOMXParams(&profile); profile.nPortIndex = kPortIndexOutput; CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)), (status_t)OK); profile.nChannels = numChannels; profile.eChannelMode = (numChannels == 1? OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo); profile.nSampleRate = sampleRate; profile.nBitRate = bitRate; profile.nAudioBandWidth = 0; profile.nFrameLength = 0; profile.nAACtools = OMX_AUDIO_AACToolAll; profile.nAACERtools = OMX_AUDIO_AACERNone; profile.eAACProfile = (OMX_AUDIO_AACPROFILETYPE) aacProfile; profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; err = mOMX->setParameter(mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed " "(err = %d)", err); return err; } } else { OMX_AUDIO_PARAM_AACPROFILETYPE profile; InitOMXParams(&profile); profile.nPortIndex = kPortIndexInput; status_t err = mOMX->getParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); CHECK_EQ(err, (status_t)OK); profile.nChannels = numChannels; profile.nSampleRate = sampleRate; profile.eAACStreamFormat = isADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF; err = mOMX->setParameter( mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile)); if (err != OK) { CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed " "(err = %d)", err); return err; } } return OK; } CWE ID: CWE-284 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal) { HEVCLocalContext *lc = s->HEVClc; GetBitContext *gb = &lc->gb; int ctb_addr_ts, ret; *gb = nal->gb; s->nal_unit_type = nal->type; s->temporal_id = nal->temporal_id; switch (s->nal_unit_type) { case HEVC_NAL_VPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps, s->apply_defdispwin); if (ret < 0) goto fail; break; case HEVC_NAL_PPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SEI_PREFIX: case HEVC_NAL_SEI_SUFFIX: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sei(gb, s->avctx, &s->sei, &s->ps, s->nal_unit_type); if (ret < 0) goto fail; break; case HEVC_NAL_TRAIL_R: case HEVC_NAL_TRAIL_N: case HEVC_NAL_TSA_N: case HEVC_NAL_TSA_R: case HEVC_NAL_STSA_N: case HEVC_NAL_STSA_R: case HEVC_NAL_BLA_W_LP: case HEVC_NAL_BLA_W_RADL: case HEVC_NAL_BLA_N_LP: case HEVC_NAL_IDR_W_RADL: case HEVC_NAL_IDR_N_LP: case HEVC_NAL_CRA_NUT: case HEVC_NAL_RADL_N: case HEVC_NAL_RADL_R: case HEVC_NAL_RASL_N: case HEVC_NAL_RASL_R: ret = hls_slice_header(s); if (ret < 0) return ret; if ( (s->avctx->skip_frame >= AVDISCARD_BIDIR && s->sh.slice_type == HEVC_SLICE_B) || (s->avctx->skip_frame >= AVDISCARD_NONINTRA && s->sh.slice_type != HEVC_SLICE_I) || (s->avctx->skip_frame >= AVDISCARD_NONKEY && !IS_IRAP(s))) { break; } if (s->sh.first_slice_in_pic_flag) { if (s->ref) { av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n"); goto fail; } if (s->max_ra == INT_MAX) { if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) { s->max_ra = s->poc; } else { if (IS_IDR(s)) s->max_ra = INT_MIN; } } if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) && s->poc <= s->max_ra) { s->is_decoded = 0; break; } else { if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra) s->max_ra = INT_MIN; } s->overlap ++; ret = hevc_frame_start(s); if (ret < 0) return ret; } else if (!s->ref) { av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n"); goto fail; } if (s->nal_unit_type != s->first_nal_type) { av_log(s->avctx, AV_LOG_ERROR, "Non-matching NAL types of the VCL NALUs: %d %d\n", s->first_nal_type, s->nal_unit_type); return AVERROR_INVALIDDATA; } if (!s->sh.dependent_slice_segment_flag && s->sh.slice_type != HEVC_SLICE_I) { ret = ff_hevc_slice_rpl(s); if (ret < 0) { av_log(s->avctx, AV_LOG_WARNING, "Error constructing the reference lists for the current slice.\n"); goto fail; } } if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) { ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0); if (ret < 0) goto fail; } if (s->avctx->hwaccel) { ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } else { if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0) ctb_addr_ts = hls_slice_data_wpp(s, nal); else ctb_addr_ts = hls_slice_data(s); if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) { s->is_decoded = 1; } if (ctb_addr_ts < 0) { ret = ctb_addr_ts; goto fail; } } break; case HEVC_NAL_EOS_NUT: case HEVC_NAL_EOB_NUT: s->seq_decode = (s->seq_decode + 1) & 0xff; s->max_ra = INT_MAX; break; case HEVC_NAL_AUD: case HEVC_NAL_FD_NUT: break; default: av_log(s->avctx, AV_LOG_INFO, "Skipping NAL unit %d\n", s->nal_unit_type); } return 0; fail: if (s->avctx->err_recognition & AV_EF_EXPLODE) return ret; return 0; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { xmlElementContentPtr ret = NULL, cur = NULL, n; const xmlChar *elem = NULL; GROW; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { SKIP(7); SKIP_BLANKS; SHRINK; if (RAW == ')') { if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); if (RAW == '*') { ret->ocur = XML_ELEMENT_CONTENT_MULT; NEXT; } return(ret); } if ((RAW == '(') || (RAW == '|')) { ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); } while (RAW == '|') { NEXT; if (elem == NULL) { ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (ret == NULL) return(NULL); ret->c1 = cur; if (cur != NULL) cur->parent = ret; cur = ret; } else { n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (n == NULL) return(NULL); n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (n->c1 != NULL) n->c1->parent = n; cur->c2 = n; if (n != NULL) n->parent = cur; cur = n; } SKIP_BLANKS; elem = xmlParseName(ctxt); if (elem == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseElementMixedContentDecl : Name expected\n"); xmlFreeDocElementContent(ctxt->myDoc, cur); return(NULL); } SKIP_BLANKS; GROW; } if ((RAW == ')') && (NXT(1) == '*')) { if (elem != NULL) { cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (cur->c2 != NULL) cur->c2->parent = cur; } if (ret != NULL) ret->ocur = XML_ELEMENT_CONTENT_MULT; if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } SKIP(2); } else { xmlFreeDocElementContent(ctxt->myDoc, ret); xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL); return(NULL); } } else { xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL); } return(ret); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void fb_set_logocmap(struct fb_info *info, const struct linux_logo *logo) { struct fb_cmap palette_cmap; u16 palette_green[16]; u16 palette_blue[16]; u16 palette_red[16]; int i, j, n; const unsigned char *clut = logo->clut; palette_cmap.start = 0; palette_cmap.len = 16; palette_cmap.red = palette_red; palette_cmap.green = palette_green; palette_cmap.blue = palette_blue; palette_cmap.transp = NULL; for (i = 0; i < logo->clutsize; i += n) { n = logo->clutsize - i; /* palette_cmap provides space for only 16 colors at once */ if (n > 16) n = 16; palette_cmap.start = 32 + i; palette_cmap.len = n; for (j = 0; j < n; ++j) { palette_cmap.red[j] = clut[0] << 8 | clut[0]; palette_cmap.green[j] = clut[1] << 8 | clut[1]; palette_cmap.blue[j] = clut[2] << 8 | clut[2]; clut += 3; } fb_set_cmap(&palette_cmap, info); } } 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 ssize_t map_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos, int cap_setid, struct uid_gid_map *map, struct uid_gid_map *parent_map) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; struct uid_gid_map new_map; unsigned idx; struct uid_gid_extent *extent = NULL; unsigned long page = 0; char *kbuf, *pos, *next_line; ssize_t ret = -EINVAL; /* * The id_map_mutex serializes all writes to any given map. * * Any map is only ever written once. * * An id map fits within 1 cache line on most architectures. * * On read nothing needs to be done unless you are on an * architecture with a crazy cache coherency model like alpha. * * There is a one time data dependency between reading the * count of the extents and the values of the extents. The * desired behavior is to see the values of the extents that * were written before the count of the extents. * * To achieve this smp_wmb() is used on guarantee the write * order and smp_read_barrier_depends() is guaranteed that we * don't have crazy architectures returning stale data. * */ mutex_lock(&id_map_mutex); ret = -EPERM; /* Only allow one successful write to the map */ if (map->nr_extents != 0) goto out; /* Require the appropriate privilege CAP_SETUID or CAP_SETGID * over the user namespace in order to set the id mapping. */ if (cap_valid(cap_setid) && !ns_capable(ns, cap_setid)) goto out; /* Get a buffer */ ret = -ENOMEM; page = __get_free_page(GFP_TEMPORARY); kbuf = (char *) page; if (!page) goto out; /* Only allow <= page size writes at the beginning of the file */ ret = -EINVAL; if ((*ppos != 0) || (count >= PAGE_SIZE)) goto out; /* Slurp in the user data */ ret = -EFAULT; if (copy_from_user(kbuf, buf, count)) goto out; kbuf[count] = '\0'; /* Parse the user data */ ret = -EINVAL; pos = kbuf; new_map.nr_extents = 0; for (;pos; pos = next_line) { extent = &new_map.extent[new_map.nr_extents]; /* Find the end of line and ensure I don't look past it */ next_line = strchr(pos, '\n'); if (next_line) { *next_line = '\0'; next_line++; if (*next_line == '\0') next_line = NULL; } pos = skip_spaces(pos); extent->first = simple_strtoul(pos, &pos, 10); if (!isspace(*pos)) goto out; pos = skip_spaces(pos); extent->lower_first = simple_strtoul(pos, &pos, 10); if (!isspace(*pos)) goto out; pos = skip_spaces(pos); extent->count = simple_strtoul(pos, &pos, 10); if (*pos && !isspace(*pos)) goto out; /* Verify there is not trailing junk on the line */ pos = skip_spaces(pos); if (*pos != '\0') goto out; /* Verify we have been given valid starting values */ if ((extent->first == (u32) -1) || (extent->lower_first == (u32) -1 )) goto out; /* Verify count is not zero and does not cause the extent to wrap */ if ((extent->first + extent->count) <= extent->first) goto out; if ((extent->lower_first + extent->count) <= extent->lower_first) goto out; /* Do the ranges in extent overlap any previous extents? */ if (mappings_overlap(&new_map, extent)) goto out; new_map.nr_extents++; /* Fail if the file contains too many extents */ if ((new_map.nr_extents == UID_GID_MAP_MAX_EXTENTS) && (next_line != NULL)) goto out; } /* Be very certaint the new map actually exists */ if (new_map.nr_extents == 0) goto out; ret = -EPERM; /* Validate the user is allowed to use user id's mapped to. */ if (!new_idmap_permitted(ns, cap_setid, &new_map)) goto out; /* Map the lower ids from the parent user namespace to the * kernel global id space. */ for (idx = 0; idx < new_map.nr_extents; idx++) { u32 lower_first; extent = &new_map.extent[idx]; lower_first = map_id_range_down(parent_map, extent->lower_first, extent->count); /* Fail if we can not map the specified extent to * the kernel global id space. */ if (lower_first == (u32) -1) goto out; extent->lower_first = lower_first; } /* Install the map */ memcpy(map->extent, new_map.extent, new_map.nr_extents*sizeof(new_map.extent[0])); smp_wmb(); map->nr_extents = new_map.nr_extents; *ppos = count; ret = count; out: mutex_unlock(&id_map_mutex); if (page) free_page(page); return ret; } 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: EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len) { int ok = 0; EC_KEY *ret = NULL; EC_PRIVATEKEY *priv_key = NULL; if ((priv_key = EC_PRIVATEKEY_new()) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); return NULL; } if ((priv_key = d2i_EC_PRIVATEKEY(&priv_key, in, len)) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); EC_PRIVATEKEY_free(priv_key); return NULL; } if (a == NULL || *a == NULL) { if ((ret = EC_KEY_new()) == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_MALLOC_FAILURE); goto err; } if (a) *a = ret; } else ret = *a; ret = *a; if (priv_key->parameters) { if (ret->group) EC_GROUP_clear_free(ret->group); ret->group = ec_asn1_pkparameters2group(priv_key->parameters); } if (ret->group == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } ret->version = priv_key->version; if (priv_key->privateKey) { ret->priv_key = BN_bin2bn(M_ASN1_STRING_data(priv_key->privateKey), M_ASN1_STRING_length(priv_key->privateKey), ret->priv_key); if (ret->priv_key == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_BN_LIB); goto err; } } else { ECerr(EC_F_D2I_ECPRIVATEKEY, EC_R_MISSING_PRIVATE_KEY); goto err; } if (priv_key->publicKey) { const unsigned char *pub_oct; size_t pub_oct_len; if (ret->pub_key) EC_POINT_clear_free(ret->pub_key); ret->pub_key = EC_POINT_new(ret->group); if (ret->pub_key == NULL) { ECerr(EC_F_D2I_ECPRIVATEKEY, ERR_R_EC_LIB); goto err; } pub_oct = M_ASN1_STRING_data(priv_key->publicKey); pub_oct_len = M_ASN1_STRING_length(priv_key->publicKey); /* save the point conversion form */ ret->conv_form = (point_conversion_form_t) (pub_oct[0] & ~0x01); if (!EC_POINT_oct2point(ret->group, ret->pub_key, pub_oct, pub_oct_len, NULL)) { } } ok = 1; err: if (!ok) { if (ret) EC_KEY_free(ret); ret = NULL; } if (priv_key) EC_PRIVATEKEY_free(priv_key); return (ret); } CWE ID: Target: 1 Example 2: Code: static uint8_t msix_pending_mask(int vector) { return 1 << (vector % 8); } 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 encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct blkcipher_walk walk; struct crypto_blkcipher *tfm = desc->tfm; struct salsa20_ctx *ctx = crypto_blkcipher_ctx(tfm); int err; blkcipher_walk_init(&walk, dst, src, nbytes); err = blkcipher_walk_virt_block(desc, &walk, 64); salsa20_ivsetup(ctx, walk.iv); if (likely(walk.nbytes == nbytes)) { salsa20_encrypt_bytes(ctx, walk.dst.virt.addr, walk.src.virt.addr, nbytes); return blkcipher_walk_done(desc, &walk, 0); } while (walk.nbytes >= 64) { salsa20_encrypt_bytes(ctx, walk.dst.virt.addr, walk.src.virt.addr, walk.nbytes - (walk.nbytes % 64)); err = blkcipher_walk_done(desc, &walk, walk.nbytes % 64); } if (walk.nbytes) { salsa20_encrypt_bytes(ctx, walk.dst.virt.addr, walk.src.virt.addr, walk.nbytes); err = blkcipher_walk_done(desc, &walk, 0); } return err; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int generate_key(DH *dh) { int ok = 0; int generate_new_key = 0; unsigned l; BN_CTX *ctx; BN_MONT_CTX *mont = NULL; BIGNUM *pub_key = NULL, *priv_key = NULL; ctx = BN_CTX_new(); if (ctx == NULL) goto err; generate_new_key = 1; } else CWE ID: CWE-320 Target: 1 Example 2: Code: fst_rx_config(struct fst_port_info *port) { int i; int pi; unsigned int offset; unsigned long flags; struct fst_card_info *card; pi = port->index; card = port->card; spin_lock_irqsave(&card->card_lock, flags); for (i = 0; i < NUM_RX_BUFFER; i++) { offset = BUF_OFFSET(rxBuffer[pi][i][0]); FST_WRW(card, rxDescrRing[pi][i].ladr, (u16) offset); FST_WRB(card, rxDescrRing[pi][i].hadr, (u8) (offset >> 16)); FST_WRW(card, rxDescrRing[pi][i].bcnt, cnv_bcnt(LEN_RX_BUFFER)); FST_WRW(card, rxDescrRing[pi][i].mcnt, LEN_RX_BUFFER); FST_WRB(card, rxDescrRing[pi][i].bits, DMA_OWN); } port->rxpos = 0; spin_unlock_irqrestore(&card->card_lock, flags); } 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: PHP_MINFO_FUNCTION(bcmath) { php_info_print_table_start(); php_info_print_table_row(2, "BCMath support", "enabled"); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } CWE ID: CWE-125 Target: 1 Example 2: Code: static void Free_CursivePos( HB_GPOS_SubTable* st ) { HB_UShort n, count; HB_CursivePos* cp = &st->cursive; HB_EntryExitRecord* eer; if ( cp->EntryExitRecord ) { count = cp->EntryExitCount; eer = cp->EntryExitRecord; for ( n = 0; n < count; n++ ) { Free_Anchor( &eer[n].EntryAnchor ); Free_Anchor( &eer[n].ExitAnchor ); } FREE( eer ); } _HB_OPEN_Free_Coverage( &cp->Coverage ); } 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: swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc) { uint32* wp = (uint32*) cp0; tmsize_t wc = cc / 4; TIFFSwabArrayOfLong(wp, wc); horAcc32(tif, cp0, cc); } 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 SpeechRecognitionManagerImpl::RecognitionAllowedCallback(int session_id, bool ask_user, bool is_allowed) { DCHECK_CURRENTLY_ON(BrowserThread::IO); auto iter = sessions_.find(session_id); if (iter == sessions_.end()) return; Session* session = iter->second.get(); if (session->abort_requested) return; if (ask_user) { SpeechRecognitionSessionContext& context = session->context; context.label = media_stream_manager_->MakeMediaAccessRequest( context.render_process_id, context.render_frame_id, session_id, StreamControls(true, false), context.security_origin, base::BindOnce( &SpeechRecognitionManagerImpl::MediaRequestPermissionCallback, weak_factory_.GetWeakPtr(), session_id)); return; } if (is_allowed) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&SpeechRecognitionManagerImpl::DispatchEvent, weak_factory_.GetWeakPtr(), session_id, EVENT_START)); } else { OnRecognitionError( session_id, blink::mojom::SpeechRecognitionError( blink::mojom::SpeechRecognitionErrorCode::kNotAllowed, blink::mojom::SpeechAudioErrorDetails::kNone)); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&SpeechRecognitionManagerImpl::DispatchEvent, weak_factory_.GetWeakPtr(), session_id, EVENT_ABORT)); } } CWE ID: CWE-189 Target: 1 Example 2: Code: void ServiceWorkerContextCore::UnregisterServiceWorker( const GURL& scope, UnregistrationCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); job_coordinator_->Unregister( scope, base::BindOnce(&ServiceWorkerContextCore::UnregistrationComplete, AsWeakPtr(), scope, std::move(callback))); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int btreeOverwriteContent( MemPage *pPage, /* MemPage on which writing will occur */ u8 *pDest, /* Pointer to the place to start writing */ const BtreePayload *pX, /* Source of data to write */ int iOffset, /* Offset of first byte to write */ int iAmt /* Number of bytes to be written */ ){ int nData = pX->nData - iOffset; if( nData<=0 ){ /* Overwritting with zeros */ int i; for(i=0; i<iAmt && pDest[i]==0; i++){} if( i<iAmt ){ int rc = sqlite3PagerWrite(pPage->pDbPage); if( rc ) return rc; memset(pDest + i, 0, iAmt - i); } }else{ if( nData<iAmt ){ /* Mixed read data and zeros at the end. Make a recursive call ** to write the zeros then fall through to write the real data */ int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData, iAmt-nData); if( rc ) return rc; iAmt = nData; } if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){ int rc = sqlite3PagerWrite(pPage->pDbPage); if( rc ) return rc; /* In a corrupt database, it is possible for the source and destination ** buffers to overlap. This is harmless since the database is already ** corrupt but it does cause valgrind and ASAN warnings. So use ** memmove(). */ memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt); } } return SQLITE_OK; } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void registerStreamURLTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().registerStreamURL(blobRegistryContext->url, blobRegistryContext->type); } CWE ID: Target: 1 Example 2: Code: void DomOperationObserver::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_DOM_OPERATION_RESPONSE) { content::Details<DomOperationNotificationDetails> dom_op_details(details); if (dom_op_details->automation_id == automation_id_) OnDomOperationCompleted(dom_op_details->json); } else if (type == chrome::NOTIFICATION_APP_MODAL_DIALOG_SHOWN) { OnModalDialogShown(); } else { DCHECK_EQ(chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, type); WebContents* web_contents = content::Source<WebContents>(source).ptr(); if (web_contents) { TabSpecificContentSettings* tab_content_settings = TabSpecificContentSettings::FromWebContents(web_contents); if (tab_content_settings && tab_content_settings->IsContentBlocked( CONTENT_SETTINGS_TYPE_JAVASCRIPT)) OnJavascriptBlocked(); } } } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool DateTimeFieldElement::supportsFocus() const { return true; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline bool elementCanUseSimpleDefaultStyle(Element* e) { return isHTMLHtmlElement(e) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || isHTMLAnchorElement(e); } CWE ID: CWE-399 Target: 1 Example 2: Code: void red_client_semi_seamless_migrate_complete(RedClient *client) { RingItem *link; pthread_mutex_lock(&client->lock); if (!client->during_target_migrate || client->seamless_migrate) { spice_error("unexpected"); pthread_mutex_unlock(&client->lock); return; } client->during_target_migrate = FALSE; RING_FOREACH(link, &client->channels) { RedChannelClient *rcc = SPICE_CONTAINEROF(link, RedChannelClient, client_link); if (rcc->latency_monitor.timer) { red_channel_client_start_ping_timer(rcc, PING_TEST_IDLE_NET_TIMEOUT_MS); } } pthread_mutex_unlock(&client->lock); reds_on_client_semi_seamless_migrate_complete(client); } 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 RenderWidgetHostViewAura::UnlockMouse() { event_handler_->UnlockMouse(); } 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: GDataEntry::GDataEntry(GDataDirectory* parent, GDataDirectoryService* directory_service) : directory_service_(directory_service), deleted_(false) { SetParent(parent); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void DSA_get0_pqg(const DSA *d, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g) { *p = d->p; *q = d->q; *g = d->g; } 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: read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval) /* Read an unsigned decimal integer from the PPM file */ /* Swallows one trailing character after the integer */ /* Note that on a 16-bit-int machine, only values up to 64k can be read. */ /* This should not be a problem in practice. */ { register int ch; register unsigned int val; /* Skip any leading whitespace */ do { ch = pbm_getc(infile); if (ch == EOF) ERREXIT(cinfo, JERR_INPUT_EOF); } while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'); if (ch < '0' || ch > '9') ERREXIT(cinfo, JERR_PPM_NONNUMERIC); val = ch - '0'; while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') { val *= 10; val += ch - '0'; } if (val > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); return val; } 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: long long AudioTrack::GetBitDepth() const { return m_bitDepth; } CWE ID: CWE-119 Target: 1 Example 2: Code: event_sched_out(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { u64 tstamp = perf_event_time(event); u64 delta; WARN_ON_ONCE(event->ctx != ctx); lockdep_assert_held(&ctx->lock); /* * An event which could not be activated because of * filter mismatch still needs to have its timings * maintained, otherwise bogus information is return * via read() for time_enabled, time_running: */ if (event->state == PERF_EVENT_STATE_INACTIVE && !event_filter_match(event)) { delta = tstamp - event->tstamp_stopped; event->tstamp_running += delta; event->tstamp_stopped = tstamp; } if (event->state != PERF_EVENT_STATE_ACTIVE) return; perf_pmu_disable(event->pmu); event->tstamp_stopped = tstamp; event->pmu->del(event, 0); event->oncpu = -1; event->state = PERF_EVENT_STATE_INACTIVE; if (event->pending_disable) { event->pending_disable = 0; event->state = PERF_EVENT_STATE_OFF; } if (!is_software_event(event)) cpuctx->active_oncpu--; if (!--ctx->nr_active) perf_event_ctx_deactivate(ctx); if (event->attr.freq && event->attr.sample_freq) ctx->nr_freq--; if (event->attr.exclusive || !cpuctx->active_oncpu) cpuctx->exclusive = 0; perf_pmu_enable(event->pmu); } 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 Image *ReadOneDJVUImage(LoadContext* lc,const int pagenum, const ImageInfo *image_info,ExceptionInfo *exception) { ddjvu_page_type_t type; ddjvu_pageinfo_t info; ddjvu_message_t *message; Image *image; int logging; int tag; /* so, we know that the page is there! Get its dimension, and */ /* Read one DJVU image */ image = lc->image; /* register PixelPacket *q; */ logging=LogMagickEvent(CoderEvent,GetMagickModule(), " enter ReadOneDJVUImage()"); (void) logging; #if DEBUG printf("==== Loading the page %d\n", pagenum); #endif lc->page = ddjvu_page_create_by_pageno(lc->document, pagenum); /* 0? */ /* pump data untill the page is ready for rendering. */ tag=(-1); do { while ((message = ddjvu_message_peek(lc->context))) { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } /* fixme: maybe exit? */ /* if (lc->error) break; */ message = pump_data_until_message(lc,image); if (message) do { tag=process_message(message); if (tag == 0) break; ddjvu_message_pop(lc->context); } while ((message = ddjvu_message_peek(lc->context))); } while (!ddjvu_page_decoding_done(lc->page)); ddjvu_document_get_pageinfo(lc->document, pagenum, &info); image->x_resolution = (float) info.dpi; image->y_resolution =(float) info.dpi; if (image_info->density != (char *) NULL) { int flags; GeometryInfo geometry_info; /* Set rendering resolution. */ flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; info.width=(int) (info.width*image->x_resolution/info.dpi); info.height=(int) (info.height*image->y_resolution/info.dpi); info.dpi=(int) MagickMax(image->x_resolution,image->y_resolution); } type = ddjvu_page_get_type(lc->page); /* double -> float! */ /* image->gamma = (float)ddjvu_page_get_gamma(lc->page); */ /* mmc: set image->depth */ /* mmc: This from the type */ image->columns=(size_t) info.width; image->rows=(size_t) info.height; /* mmc: bitonal should be palettized, and compressed! */ if (type == DDJVU_PAGETYPE_BITONAL){ image->colorspace = GRAYColorspace; image->storage_class = PseudoClass; image->depth = 8UL; /* i only support that? */ image->colors= 2; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } else { image->colorspace = RGBColorspace; image->storage_class = DirectClass; /* fixme: MAGICKCORE_QUANTUM_DEPTH ?*/ image->depth = 8UL; /* i only support that? */ image->matte = MagickTrue; /* is this useful? */ } #if DEBUG printf("now filling %.20g x %.20g\n",(double) image->columns,(double) image->rows); #endif #if 1 /* per_line */ /* q = QueueAuthenticPixels(image,0,0,image->columns,image->rows); */ get_page_image(lc, lc->page, 0, 0, info.width, info.height, image_info); #else int i; for (i = 0;i< image->rows; i++) { printf("%d\n",i); q = QueueAuthenticPixels(image,0,i,image->columns,1); get_page_line(lc, i, quantum_info); SyncAuthenticPixels(image); } #endif /* per_line */ #if DEBUG printf("END: finished filling %.20g x %.20g\n",(double) image->columns, (double) image->rows); #endif if (!image->ping) SyncImage(image); /* indexes=GetAuthenticIndexQueue(image); */ /* mmc: ??? Convert PNM pixels to runlength-encoded MIFF packets. */ /* image->colors = */ /* how is the line padding / stride? */ if (lc->page) { ddjvu_page_release(lc->page); lc->page = NULL; } /* image->page.y=mng_info->y_off[mng_info->object_id]; */ if (tag == 0) image=DestroyImage(image); return image; /* end of reading one DJVU page/image */ } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ChromeContentRendererClient::ShouldFork(WebFrame* frame, const GURL& url, bool is_initial_navigation, bool* send_referrer) { DCHECK(!frame->parent()); if (prerender_dispatcher_.get() && prerender_dispatcher_->IsPrerenderURL(url)) return true; const ExtensionSet* extensions = extension_dispatcher_->extensions(); const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension( *extensions, ExtensionURLInfo(url)); bool is_extension_url = !!new_url_extension; if (CrossesExtensionExtents(frame, url, *extensions, is_extension_url, is_initial_navigation)) { *send_referrer = true; const Extension* extension = extension_dispatcher_->extensions()->GetExtensionOrAppByURL( ExtensionURLInfo(url)); if (extension && extension->is_app()) { UMA_HISTOGRAM_ENUMERATION( extension_misc::kAppLaunchHistogram, extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); } return true; } if (frame->top()->document().url() == url) { if (is_extension_url != extension_dispatcher_->is_extension_process()) return true; } if (url.SchemeIs(kChromeUIScheme)) return true; return false; } CWE ID: CWE-264 Target: 1 Example 2: Code: link_heap_page(mrb_gc *gc, mrb_heap_page *page) { page->next = gc->heaps; if (gc->heaps) gc->heaps->prev = page; gc->heaps = page; } 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: transit_free (struct transit *transit) { if (transit->val) XFREE (MTYPE_TRANSIT_VAL, transit->val); XFREE (MTYPE_TRANSIT, transit); } 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: newEntry(struct rx_call *call, char aname[], afs_int32 flag, afs_int32 oid, afs_int32 *aid, afs_int32 *cid) { afs_int32 code; struct ubik_trans *tt; int admin; char cname[PR_MAXNAMELEN]; stolower(aname); code = Initdb(); if (code) return code; code = ubik_BeginTrans(dbase, UBIK_WRITETRANS, &tt); if (code) return code; code = ubik_SetLock(tt, 1, 1, LOCKWRITE); if (code) ABORT_WITH(tt, code); code = read_DbHeader(tt); if (code) ABORT_WITH(tt, code); /* this is for cross-cell self registration. It is not added in the * SPR_INewEntry because we want self-registration to only do * automatic id assignment. */ code = WhoIsThisWithName(call, tt, cid, cname); if (code != 2) { /* 2 specifies that this is a foreign cell request */ if (code) ABORT_WITH(tt, PRPERM); admin = IsAMemberOf(tt, *cid, SYSADMINID); } else { admin = ((!restricted && !strcmp(aname, cname))) || IsAMemberOf(tt, *cid, SYSADMINID); oid = *cid = SYSADMINID; } if (!CreateOK(tt, *cid, oid, flag, admin)) ABORT_WITH(tt, PRPERM); if (code) return code; return PRSUCCESS; } CWE ID: CWE-284 Target: 1 Example 2: Code: static long jas_iccpowi(int x, int n) { long y; y = 1; while (--n >= 0) y *= x; return y; } 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: image_transform_default_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) UNUSED(bit_depth) this->next = *that; *that = this; return 1; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ReleaseAccelerator(ui::KeyboardCode keycode, bool shift_pressed, bool ctrl_pressed, bool alt_pressed) : ui::Accelerator(keycode, shift_pressed, ctrl_pressed, alt_pressed) { set_type(ui::ET_KEY_RELEASED); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void stream_int_chk_snd(struct stream_interface *si) { struct channel *ob = si->ob; DPRINTF(stderr, "%s: si=%p, si->state=%d ib->flags=%08x ob->flags=%08x\n", __FUNCTION__, si, si->state, si->ib->flags, si->ob->flags); if (unlikely(si->state != SI_ST_EST || (si->ob->flags & CF_SHUTW))) return; if (!(si->flags & SI_FL_WAIT_DATA) || /* not waiting for data */ channel_is_empty(ob)) /* called with nothing to send ! */ return; /* Otherwise there are remaining data to be sent in the buffer, * so we tell the handler. */ si->flags &= ~SI_FL_WAIT_DATA; if (!tick_isset(ob->wex)) ob->wex = tick_add_ifset(now_ms, ob->wto); if (!(si->flags & SI_FL_DONT_WAKE) && si->owner) task_wakeup(si->owner, TASK_WOKEN_IO); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased) { if (paintingDisabled()) return; if (numPoints <= 1) return; SkPath path; if (!isPathSkiaSafe(getCTM(), path)) return; setPathFromConvexPoints(&path, numPoints, points); if (antialiased) platformContext()->clipPathAntiAliased(path); else platformContext()->canvas()->clipPath(path); } CWE ID: CWE-19 Output:
0
Here are some example code snippets. Analyze the following 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 inode_owner_or_capable(const struct inode *inode) { if (uid_eq(current_fsuid(), inode->i_uid)) return true; if (inode_capable(inode, CAP_FOWNER)) return true; return false; } CWE ID: CWE-264 Target: 1 Example 2: Code: int fscrypt_has_permitted_context(struct inode *parent, struct inode *child) { struct fscrypt_info *parent_ci, *child_ci; int res; if ((parent == NULL) || (child == NULL)) { printk(KERN_ERR "parent %p child %p\n", parent, child); BUG_ON(1); } /* no restrictions if the parent directory is not encrypted */ if (!parent->i_sb->s_cop->is_encrypted(parent)) return 1; /* if the child directory is not encrypted, this is always a problem */ if (!parent->i_sb->s_cop->is_encrypted(child)) return 0; res = fscrypt_get_encryption_info(parent); if (res) return 0; res = fscrypt_get_encryption_info(child); if (res) return 0; parent_ci = parent->i_crypt_info; child_ci = child->i_crypt_info; if (!parent_ci && !child_ci) return 1; if (!parent_ci || !child_ci) return 0; return (memcmp(parent_ci->ci_master_key, child_ci->ci_master_key, FS_KEY_DESCRIPTOR_SIZE) == 0 && (parent_ci->ci_data_mode == child_ci->ci_data_mode) && (parent_ci->ci_filename_mode == child_ci->ci_filename_mode) && (parent_ci->ci_flags == child_ci->ci_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: PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); } CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "nivaead"); snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } CWE ID: CWE-310 Target: 1 Example 2: Code: static void ctdb_listen_event(struct event_context *ev, struct fd_event *fde, uint16_t flags, void *private_data) { struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context); struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data, struct ctdb_tcp); ctdb_sock_addr addr; socklen_t len; int fd, nodeid; struct ctdb_incoming *in; int one = 1; const char *incoming_node; memset(&addr, 0, sizeof(addr)); len = sizeof(addr); fd = accept(ctcp->listen_fd, (struct sockaddr *)&addr, &len); if (fd == -1) return; incoming_node = ctdb_addr_to_str(&addr); nodeid = ctdb_ip_to_nodeid(ctdb, incoming_node); if (nodeid == -1) { DEBUG(DEBUG_ERR, ("Refused connection from unknown node %s\n", incoming_node)); close(fd); return; } in = talloc_zero(ctcp, struct ctdb_incoming); in->fd = fd; in->ctdb = ctdb; set_nonblocking(in->fd); set_close_on_exec(in->fd); DEBUG(DEBUG_DEBUG, (__location__ " Created SOCKET FD:%d to incoming ctdb connection\n", fd)); setsockopt(in->fd,SOL_SOCKET,SO_KEEPALIVE,(char *)&one,sizeof(one)); in->queue = ctdb_queue_setup(ctdb, in, in->fd, CTDB_TCP_ALIGNMENT, ctdb_tcp_read_cb, in, "ctdbd-%s", incoming_node); } 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 security_get_bools(int *len, char ***names, int **values) { int i, rc; read_lock(&policy_rwlock); *names = NULL; *values = NULL; rc = 0; *len = policydb.p_bools.nprim; if (!*len) goto out; rc = -ENOMEM; *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC); if (!*names) goto err; rc = -ENOMEM; *values = kcalloc(*len, sizeof(int), GFP_ATOMIC); if (!*values) goto err; for (i = 0; i < *len; i++) { size_t name_len; (*values)[i] = policydb.bool_val_to_struct[i]->state; name_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1; rc = -ENOMEM; (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC); if (!(*names)[i]) goto err; strncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len); (*names)[i][name_len - 1] = 0; } rc = 0; out: read_unlock(&policy_rwlock); return rc; err: if (*names) { for (i = 0; i < *len; i++) kfree((*names)[i]); } kfree(*values); goto out; } 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: PHP_FUNCTION(stream_resolve_include_path) { char *filename, *resolved_path; int filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename, &filename_len) == FAILURE) { return; } resolved_path = zend_resolve_path(filename, filename_len TSRMLS_CC); if (resolved_path) { RETURN_STRING(resolved_path, 0); } RETURN_FALSE; } CWE ID: CWE-254 Target: 1 Example 2: Code: bool HTMLInputElement::isTextFormControlKeyboardFocusable(KeyboardEvent* event) const { return HTMLTextFormControlElement::isKeyboardFocusable(event); } 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 void key_alloc_serial(struct key *key) { struct rb_node *parent, **p; struct key *xkey; /* propose a random serial number and look for a hole for it in the * serial number tree */ do { get_random_bytes(&key->serial, sizeof(key->serial)); key->serial >>= 1; /* negative numbers are not permitted */ } while (key->serial < 3); spin_lock(&key_serial_lock); attempt_insertion: parent = NULL; p = &key_serial_tree.rb_node; while (*p) { parent = *p; xkey = rb_entry(parent, struct key, serial_node); if (key->serial < xkey->serial) p = &(*p)->rb_left; else if (key->serial > xkey->serial) p = &(*p)->rb_right; else goto serial_exists; } /* we've found a suitable hole - arrange for this key to occupy it */ rb_link_node(&key->serial_node, parent, p); rb_insert_color(&key->serial_node, &key_serial_tree); spin_unlock(&key_serial_lock); return; /* we found a key with the proposed serial number - walk the tree from * that point looking for the next unused serial number */ serial_exists: for (;;) { key->serial++; if (key->serial < 3) { key->serial = 3; goto attempt_insertion; } parent = rb_next(parent); if (!parent) goto attempt_insertion; xkey = rb_entry(parent, struct key, serial_node); if (key->serial < xkey->serial) goto attempt_insertion; } } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int er_supported(ERContext *s) { if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice || !s->cur_pic.f || s->cur_pic.field_picture || s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO ) return 0; return 1; } CWE ID: CWE-617 Target: 1 Example 2: Code: void OxideQQuickWebView::inputMethodEvent(QInputMethodEvent* event) { Q_D(OxideQQuickWebView); QQuickItem::inputMethodEvent(event); d->contents_view_->handleInputMethodEvent(event); } 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 registerURL(const char* url, const char* file, const char* mimeType) { registerMockedURLLoad(KURL(m_baseUrl, url), WebString::fromUTF8(file), m_folder, WebString::fromUTF8(mimeType)); } 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: uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, const QString &body, const QStringList &actions, const QVariantMap &hints, int timeout) { uint partOf = 0; const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString(); const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString(); const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool(); if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) { partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt(); } qDebug() << "Currrent active notifications:" << m_activeNotifications; qDebug() << "Guessing partOf as:" << partOf; qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf; QString _body; if (partOf > 0) { const QString source = QStringLiteral("notification %1").arg(partOf); Plasma::DataContainer *container = containerForSource(source); if (container) { _body = container->data()[QStringLiteral("body")].toString(); if (_body != body) { _body.append("\n").append(body); } else { _body = body; } replaces_id = partOf; CloseNotification(partOf); } } uint id = replaces_id ? replaces_id : m_nextId++; if (m_alwaysReplaceAppsList.contains(app_name)) { if (m_notificationsFromReplaceableApp.contains(app_name)) { id = m_notificationsFromReplaceableApp.value(app_name); } else { m_notificationsFromReplaceableApp.insert(app_name, id); } } QString appname_str = app_name; if (appname_str.isEmpty()) { appname_str = i18n("Unknown Application"); } bool isPersistent = timeout == 0; const int AVERAGE_WORD_LENGTH = 6; const int WORD_PER_MINUTE = 250; int count = summary.length() + body.length(); timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE; timeout = 2000 + qMax(timeout, 3000); } CWE ID: CWE-200 Target: 1 Example 2: Code: static u32 cdc_ncm_check_rx_max(struct usbnet *dev, u32 new_rx) { struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0]; u32 val, max, min; /* clamp new_rx to sane values */ min = USB_CDC_NCM_NTB_MIN_IN_SIZE; max = min_t(u32, CDC_NCM_NTB_MAX_SIZE_RX, le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize)); /* dwNtbInMaxSize spec violation? Use MIN size for both limits */ if (max < min) { dev_warn(&dev->intf->dev, "dwNtbInMaxSize=%u is too small. Using %u\n", le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize), min); max = min; } val = clamp_t(u32, new_rx, min, max); if (val != new_rx) dev_dbg(&dev->intf->dev, "rx_max must be in the [%u, %u] range\n", min, max); return 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: static int snd_hrtimer_start(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); hrtimer_cancel(&stime->hrt); hrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution), HRTIMER_MODE_REL); atomic_set(&stime->running, 1); return 0; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ProcRenderAddGlyphs (ClientPtr client) { GlyphSetPtr glyphSet; REQUEST(xRenderAddGlyphsReq); GlyphNewRec glyphsLocal[NLOCALGLYPH]; GlyphNewPtr glyphsBase, glyphs, glyph_new; int remain, nglyphs; CARD32 *gids; xGlyphInfo *gi; CARD8 *bits; unsigned int size; int err; int i, screen; PicturePtr pSrc = NULL, pDst = NULL; PixmapPtr pSrcPix = NULL, pDstPix = NULL; CARD32 component_alpha; REQUEST_AT_LEAST_SIZE(xRenderAddGlyphsReq); err = dixLookupResourceByType((pointer *)&glyphSet, stuff->glyphset, GlyphSetType, client, DixAddAccess); if (err != Success) { client->errorValue = stuff->glyphset; return err; } err = BadAlloc; nglyphs = stuff->nglyphs; if (nglyphs > UINT32_MAX / sizeof(GlyphNewRec)) return BadAlloc; component_alpha = NeedsComponent (glyphSet->format->format); if (nglyphs <= NLOCALGLYPH) { memset (glyphsLocal, 0, sizeof (glyphsLocal)); glyphsBase = glyphsLocal; } else { glyphsBase = (GlyphNewPtr)calloc(nglyphs, sizeof (GlyphNewRec)); if (!glyphsBase) return BadAlloc; } remain = (client->req_len << 2) - sizeof (xRenderAddGlyphsReq); glyphs = glyphsBase; gids = (CARD32 *) (stuff + 1); gi = (xGlyphInfo *) (gids + nglyphs); bits = (CARD8 *) (gi + nglyphs); remain -= (sizeof (CARD32) + sizeof (xGlyphInfo)) * nglyphs; for (i = 0; i < nglyphs; i++) { size_t padded_width; size = gi[i].height * padded_width; if (remain < size) break; err = HashGlyph (&gi[i], bits, size, glyph_new->sha1); if (err) goto bail; glyph_new->glyph = FindGlyphByHash (glyph_new->sha1, glyphSet->fdepth); if (glyph_new->glyph && glyph_new->glyph != DeletedGlyph) { glyph_new->found = TRUE; } else { GlyphPtr glyph; glyph_new->found = FALSE; glyph_new->glyph = glyph = AllocateGlyph (&gi[i], glyphSet->fdepth); if (! glyph) { err = BadAlloc; goto bail; } for (screen = 0; screen < screenInfo.numScreens; screen++) { int width = gi[i].width; int height = gi[i].height; int depth = glyphSet->format->depth; ScreenPtr pScreen; int error; /* Skip work if it's invisibly small anyway */ if (!width || !height) break; pScreen = screenInfo.screens[screen]; pSrcPix = GetScratchPixmapHeader (pScreen, width, height, depth, depth, -1, bits); if (! pSrcPix) { err = BadAlloc; goto bail; } pSrc = CreatePicture (0, &pSrcPix->drawable, glyphSet->format, 0, NULL, serverClient, &error); if (! pSrc) { err = BadAlloc; goto bail; } pDstPix = (pScreen->CreatePixmap) (pScreen, width, height, depth, CREATE_PIXMAP_USAGE_GLYPH_PICTURE); if (!pDstPix) { err = BadAlloc; goto bail; } GlyphPicture (glyph)[screen] = pDst = CreatePicture (0, &pDstPix->drawable, glyphSet->format, CPComponentAlpha, &component_alpha, serverClient, &error); /* The picture takes a reference to the pixmap, so we drop ours. */ (pScreen->DestroyPixmap) (pDstPix); pDstPix = NULL; if (! pDst) { err = BadAlloc; goto bail; } CompositePicture (PictOpSrc, pSrc, None, pDst, 0, 0, 0, 0, 0, 0, width, height); FreePicture ((pointer) pSrc, 0); pSrc = NULL; FreeScratchPixmapHeader (pSrcPix); pSrcPix = NULL; } memcpy (glyph_new->glyph->sha1, glyph_new->sha1, 20); } glyph_new->id = gids[i]; if (size & 3) size += 4 - (size & 3); bits += size; remain -= size; } if (remain || i < nglyphs) { err = BadLength; goto bail; } if (!ResizeGlyphSet (glyphSet, nglyphs)) { err = BadAlloc; goto bail; } for (i = 0; i < nglyphs; i++) AddGlyph (glyphSet, glyphs[i].glyph, glyphs[i].id); if (glyphsBase != glyphsLocal) free(glyphsBase); return Success; bail: if (pSrc) FreePicture ((pointer) pSrc, 0); if (pSrcPix) FreeScratchPixmapHeader (pSrcPix); for (i = 0; i < nglyphs; i++) if (glyphs[i].glyph && ! glyphs[i].found) free(glyphs[i].glyph); if (glyphsBase != glyphsLocal) free(glyphsBase); return err; } CWE ID: CWE-20 Target: 1 Example 2: Code: void LayerTreeHostImpl::ActivateSyncTree() { if (pending_tree_) { TRACE_EVENT_ASYNC_END0("cc", "PendingTree:waiting", pending_tree_.get()); DCHECK(pending_tree_duration_timer_); pending_tree_duration_timer_.reset(); pending_tree_->ProcessUIResourceRequestQueue(); if (pending_tree_->needs_full_tree_sync()) { TreeSynchronizer::SynchronizeTrees(pending_tree_.get(), active_tree_.get()); } if (active_tree_->property_trees()->changed) { if (pending_tree_->property_trees()->sequence_number == active_tree_->property_trees()->sequence_number) active_tree_->property_trees()->PushChangeTrackingTo( pending_tree_->property_trees()); else active_tree_->MoveChangeTrackingToLayers(); } active_tree_->property_trees()->PushOpacityIfNeeded( pending_tree_->property_trees()); TreeSynchronizer::PushLayerProperties(pending_tree(), active_tree()); pending_tree_->PushPropertiesTo(active_tree_.get()); if (!pending_tree_->LayerListIsEmpty()) pending_tree_->property_trees()->ResetAllChangeTracking(); DCHECK(!recycle_tree_); pending_tree_.swap(recycle_tree_); ActivateAnimations(); Mutate(CurrentBeginFrameArgs().frame_time); } else { active_tree_->ProcessUIResourceRequestQueue(); } UpdateViewportContainerSizes(); active_tree_->DidBecomeActive(); client_->RenewTreePriority(); if (!active_tree_->picture_layers().empty()) DidModifyTilePriorities(); tile_manager_.DidActivateSyncTree(); client_->OnCanDrawStateChanged(CanDraw()); client_->DidActivateSyncTree(); if (!tree_activation_callback_.is_null()) tree_activation_callback_.Run(); std::unique_ptr<PendingPageScaleAnimation> pending_page_scale_animation = active_tree_->TakePendingPageScaleAnimation(); if (pending_page_scale_animation) { StartPageScaleAnimation(pending_page_scale_animation->target_offset, pending_page_scale_animation->use_anchor, pending_page_scale_animation->scale, pending_page_scale_animation->duration); } UpdateRootLayerStateForSynchronousInputHandler(); } 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 linuxOvercommitMemoryValue(void) { FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); char buf[64]; if (!fp) return -1; if (fgets(buf,64,fp) == NULL) { fclose(fp); return -1; } fclose(fp); return atoi(buf); } 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: static int ati_remote2_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(interface); struct usb_host_interface *alt = interface->cur_altsetting; struct ati_remote2 *ar2; int r; if (alt->desc.bInterfaceNumber) return -ENODEV; ar2 = kzalloc(sizeof (struct ati_remote2), GFP_KERNEL); if (!ar2) return -ENOMEM; ar2->udev = udev; ar2->intf[0] = interface; ar2->ep[0] = &alt->endpoint[0].desc; ar2->intf[1] = usb_ifnum_to_if(udev, 1); r = usb_driver_claim_interface(&ati_remote2_driver, ar2->intf[1], ar2); if (r) goto fail1; alt = ar2->intf[1]->cur_altsetting; ar2->ep[1] = &alt->endpoint[0].desc; r = ati_remote2_urb_init(ar2); if (r) goto fail2; ar2->channel_mask = channel_mask; ar2->mode_mask = mode_mask; r = ati_remote2_setup(ar2, ar2->channel_mask); if (r) goto fail2; usb_make_path(udev, ar2->phys, sizeof(ar2->phys)); strlcat(ar2->phys, "/input0", sizeof(ar2->phys)); strlcat(ar2->name, "ATI Remote Wonder II", sizeof(ar2->name)); r = sysfs_create_group(&udev->dev.kobj, &ati_remote2_attr_group); if (r) goto fail2; r = ati_remote2_input_init(ar2); if (r) goto fail3; usb_set_intfdata(interface, ar2); interface->needs_remote_wakeup = 1; return 0; fail3: sysfs_remove_group(&udev->dev.kobj, &ati_remote2_attr_group); fail2: ati_remote2_urb_cleanup(ar2); usb_driver_release_interface(&ati_remote2_driver, ar2->intf[1]); fail1: kfree(ar2); return r; } CWE ID: Target: 1 Example 2: Code: void SVGElement::UpdateRelativeLengthsInformation( bool client_has_relative_lengths, SVGElement* client_element) { DCHECK(client_element); for (Node& current_node : NodeTraversal::InclusiveAncestorsOf(*this)) { if (!current_node.isConnected()) return; } for (Node& current_node : NodeTraversal::InclusiveAncestorsOf(*this)) { if (!current_node.IsSVGElement()) break; SVGElement& current_element = ToSVGElement(current_node); #if DCHECK_IS_ON() DCHECK(!current_element.in_relative_length_clients_invalidation_); #endif bool had_relative_lengths = current_element.HasRelativeLengths(); if (client_has_relative_lengths) current_element.elements_with_relative_lengths_.insert(client_element); else current_element.elements_with_relative_lengths_.erase(client_element); if (had_relative_lengths == current_element.HasRelativeLengths()) return; client_element = &current_element; client_has_relative_lengths = client_element->HasRelativeLengths(); } if (auto* svg = ToSVGSVGElementOrNull(*client_element)) { SVGDocumentExtensions& svg_extensions = GetDocument().AccessSVGExtensions(); if (client_element->HasRelativeLengths()) svg_extensions.AddSVGRootWithRelativeLengthDescendents(svg); else svg_extensions.RemoveSVGRootWithRelativeLengthDescendents(svg); } } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: pushBuffer(Buffer *buf) { Buffer *b; #ifdef USE_IMAGE deleteImage(Currentbuf); #endif if (clear_buffer) tmpClearBuffer(Currentbuf); if (Firstbuf == Currentbuf) { buf->nextBuffer = Firstbuf; Firstbuf = Currentbuf = buf; } else if ((b = prevBuffer(Firstbuf, Currentbuf)) != NULL) { b->nextBuffer = buf; buf->nextBuffer = Currentbuf; Currentbuf = buf; } #ifdef USE_BUFINFO saveBufferInfo(); #endif } CWE ID: CWE-59 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = calloc(1, sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = malloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = malloc(strlen("Unknown") + 1); strcpy(pdf->name, "Unknown"); } return pdf; } CWE ID: CWE-787 Target: 1 Example 2: Code: static int walk_component(struct nameidata *nd, int flags) { struct path path; struct inode *inode; unsigned seq; int err; /* * "." and ".." are special - ".." especially so because it has * to be able to know about the current root directory and * parent relationships. */ if (unlikely(nd->last_type != LAST_NORM)) { err = handle_dots(nd, nd->last_type); if (!(flags & WALK_MORE) && nd->depth) put_link(nd); return err; } err = lookup_fast(nd, &path, &inode, &seq); if (unlikely(err <= 0)) { if (err < 0) return err; path.dentry = lookup_slow(&nd->last, nd->path.dentry, nd->flags); if (IS_ERR(path.dentry)) return PTR_ERR(path.dentry); path.mnt = nd->path.mnt; err = follow_managed(&path, nd); if (unlikely(err < 0)) return err; if (unlikely(d_is_negative(path.dentry))) { path_to_nameidata(&path, nd); return -ENOENT; } seq = 0; /* we are already out of RCU mode */ inode = d_backing_inode(path.dentry); } return step_into(nd, &path, flags, inode, seq); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int handle_vmptrld(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); gva_t gva; gpa_t vmptr; struct x86_exception e; u32 exec_control; if (!nested_vmx_check_permission(vcpu)) return 1; if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION), vmcs_read32(VMX_INSTRUCTION_INFO), &gva)) return 1; if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr, sizeof(vmptr), &e)) { kvm_inject_page_fault(vcpu, &e); return 1; } if (!IS_ALIGNED(vmptr, PAGE_SIZE)) { nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS); skip_emulated_instruction(vcpu); return 1; } if (vmx->nested.current_vmptr != vmptr) { struct vmcs12 *new_vmcs12; struct page *page; page = nested_get_page(vcpu, vmptr); if (page == NULL) { nested_vmx_failInvalid(vcpu); skip_emulated_instruction(vcpu); return 1; } new_vmcs12 = kmap(page); if (new_vmcs12->revision_id != VMCS12_REVISION) { kunmap(page); nested_release_page_clean(page); nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID); skip_emulated_instruction(vcpu); return 1; } if (vmx->nested.current_vmptr != -1ull) nested_release_vmcs12(vmx); vmx->nested.current_vmptr = vmptr; vmx->nested.current_vmcs12 = new_vmcs12; vmx->nested.current_vmcs12_page = page; if (enable_shadow_vmcs) { exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); exec_control |= SECONDARY_EXEC_SHADOW_VMCS; vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); vmcs_write64(VMCS_LINK_POINTER, __pa(vmx->nested.current_shadow_vmcs)); vmx->nested.sync_shadow_vmcs = true; } } nested_vmx_succeed(vcpu); skip_emulated_instruction(vcpu); return 1; } 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: htmlInitParserCtxt(htmlParserCtxtPtr ctxt) { htmlSAXHandler *sax; if (ctxt == NULL) return(-1); memset(ctxt, 0, sizeof(htmlParserCtxt)); ctxt->dict = xmlDictCreate(); if (ctxt->dict == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); return(-1); } sax = (htmlSAXHandler *) xmlMalloc(sizeof(htmlSAXHandler)); if (sax == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); return(-1); } else memset(sax, 0, sizeof(htmlSAXHandler)); /* Allocate the Input stack */ ctxt->inputTab = (htmlParserInputPtr *) xmlMalloc(5 * sizeof(htmlParserInputPtr)); if (ctxt->inputTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->inputNr = 0; ctxt->inputMax = 5; ctxt->input = NULL; ctxt->version = NULL; ctxt->encoding = NULL; ctxt->standalone = -1; ctxt->instate = XML_PARSER_START; /* Allocate the Node stack */ ctxt->nodeTab = (htmlNodePtr *) xmlMalloc(10 * sizeof(htmlNodePtr)); if (ctxt->nodeTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->nodeNr = 0; ctxt->nodeMax = 10; ctxt->node = NULL; /* Allocate the Name stack */ ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *)); if (ctxt->nameTab == NULL) { htmlErrMemory(NULL, "htmlInitParserCtxt: out of memory\n"); ctxt->nameNr = 0; ctxt->nameMax = 0; ctxt->name = NULL; ctxt->nodeNr = 0; ctxt->nodeMax = 0; ctxt->node = NULL; ctxt->inputNr = 0; ctxt->inputMax = 0; ctxt->input = NULL; return(-1); } ctxt->nameNr = 0; ctxt->nameMax = 10; ctxt->name = NULL; ctxt->nodeInfoTab = NULL; ctxt->nodeInfoNr = 0; ctxt->nodeInfoMax = 0; if (sax == NULL) ctxt->sax = (xmlSAXHandlerPtr) &htmlDefaultSAXHandler; else { ctxt->sax = sax; memcpy(sax, &htmlDefaultSAXHandler, sizeof(xmlSAXHandlerV1)); } ctxt->userData = ctxt; ctxt->myDoc = NULL; ctxt->wellFormed = 1; ctxt->replaceEntities = 0; ctxt->linenumbers = xmlLineNumbersDefaultValue; ctxt->html = 1; ctxt->vctxt.finishDtd = XML_CTXT_FINISH_DTD_0; ctxt->vctxt.userData = ctxt; ctxt->vctxt.error = xmlParserValidityError; ctxt->vctxt.warning = xmlParserValidityWarning; ctxt->record_info = 0; ctxt->validate = 0; ctxt->nbChars = 0; ctxt->checkIndex = 0; ctxt->catalogs = NULL; xmlInitNodeInfoSeq(&ctxt->node_seq); return(0); } CWE ID: CWE-787 Target: 1 Example 2: Code: jpc_ppxstab_t *jpc_ppxstab_create() { jpc_ppxstab_t *tab; if (!(tab = jas_malloc(sizeof(jpc_ppxstab_t)))) { return 0; } tab->numents = 0; tab->maxents = 0; tab->ents = 0; return tab; } 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 __videobuf_mmap_mapper(struct videobuf_queue *q, struct vm_area_struct *vma) { struct videbuf_vmalloc_memory *mem; struct videobuf_mapping *map; unsigned int first; int retval; unsigned long offset = vma->vm_pgoff << PAGE_SHIFT; if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED)) return -EINVAL; /* look for first buffer to map */ for (first = 0; first < VIDEO_MAX_FRAME; first++) { if (NULL == q->bufs[first]) continue; if (V4L2_MEMORY_MMAP != q->bufs[first]->memory) continue; if (q->bufs[first]->boff == offset) break; } if (VIDEO_MAX_FRAME == first) { dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n", (vma->vm_pgoff << PAGE_SHIFT)); return -EINVAL; } /* create mapping + update buffer list */ map = q->bufs[first]->map = kmalloc(sizeof(struct videobuf_mapping),GFP_KERNEL); if (NULL == map) return -ENOMEM; map->start = vma->vm_start; map->end = vma->vm_end; map->q = q; q->bufs[first]->baddr = vma->vm_start; vma->vm_ops = &videobuf_vm_ops; vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED; vma->vm_private_data = map; mem=q->bufs[first]->priv; BUG_ON (!mem); MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM); /* Try to remap memory */ retval=remap_vmalloc_range(vma, mem->vmalloc,0); if (retval<0) { dprintk(1,"mmap: postponing remap_vmalloc_range\n"); mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL); if (!mem->vma) { kfree(map); q->bufs[first]->map=NULL; return -ENOMEM; } memcpy(mem->vma,vma,sizeof(*vma)); } dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n", map,q,vma->vm_start,vma->vm_end, (long int) q->bufs[first]->bsize, vma->vm_pgoff,first); videobuf_vm_open(vma); return (0); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void ConvertLoopSequence(ModSample &smp, STPLoopList &loopList) { if(!smp.HasSampleData() || loopList.size() < 2) return; ModSample newSmp = smp; newSmp.nLength = 0; newSmp.pSample = nullptr; size_t numLoops = loopList.size(); for(size_t i = 0; i < numLoops; i++) { STPLoopInfo &info = loopList[i]; if((newSmp.nLength + info.loopLength > MAX_SAMPLE_LENGTH) || (info.loopLength > MAX_SAMPLE_LENGTH) || (info.loopStart + info.loopLength > smp.nLength)) { numLoops = i; break; } newSmp.nLength += info.loopLength; } if(!newSmp.AllocateSample()) { return; } SmpLength start = 0; for(size_t i = 0; i < numLoops; i++) { STPLoopInfo &info = loopList[i]; memcpy(newSmp.pSample8 + start, smp.pSample8 + info.loopStart, info.loopLength); info.loopStart = start; if(i > 0 && i <= mpt::size(newSmp.cues)) { newSmp.cues[i - 1] = start; } start += info.loopLength; } smp.FreeSample(); smp = newSmp; smp.nLoopStart = 0; smp.nLoopEnd = smp.nLength; smp.uFlags.set(CHN_LOOP); } CWE ID: CWE-125 Target: 1 Example 2: Code: static void add_8x8basis_c(int16_t rem[64], int16_t basis[64], int scale){ int i; for(i=0; i<8*8; i++){ rem[i] += (basis[i]*scale + (1<<(BASIS_SHIFT - RECON_SHIFT-1)))>>(BASIS_SHIFT - RECON_SHIFT); } } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int gc (lua_State *L) { struct ssh_userdata *sshu = NULL; sshu = (struct ssh_userdata *) nseU_checkudata(L, 1, SSH2_UDATA, "ssh2"); if (!sshu) { return 0; } if (sshu) { if (sshu->session != NULL) { if (libssh2_session_free(sshu->session) < 0) { } sshu->session = NULL; } } #ifdef WIN32 closesocket(sshu->sp[0]); closesocket(sshu->sp[1]); #else close(sshu->sp[0]); close(sshu->sp[1]); #endif return 0; } CWE ID: CWE-415 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(locale_get_display_region) { get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } CWE ID: CWE-125 Target: 1 Example 2: Code: static void png_filter_row(PNGDSPContext *dsp, uint8_t *dst, int filter_type, uint8_t *src, uint8_t *last, int size, int bpp) { int i, p, r, g, b, a; switch (filter_type) { case PNG_FILTER_VALUE_NONE: memcpy(dst, src, size); break; case PNG_FILTER_VALUE_SUB: for (i = 0; i < bpp; i++) dst[i] = src[i]; if (bpp == 4) { p = *(int *)dst; for (; i < size; i += bpp) { unsigned s = *(int *)(src + i); p = ((s & 0x7f7f7f7f) + (p & 0x7f7f7f7f)) ^ ((s ^ p) & 0x80808080); *(int *)(dst + i) = p; } } else { #define OP_SUB(x, s, l) ((x) + (s)) UNROLL_FILTER(OP_SUB); } break; case PNG_FILTER_VALUE_UP: dsp->add_bytes_l2(dst, src, last, size); break; case PNG_FILTER_VALUE_AVG: for (i = 0; i < bpp; i++) { p = (last[i] >> 1); dst[i] = p + src[i]; } #define OP_AVG(x, s, l) (((((x) + (l)) >> 1) + (s)) & 0xff) UNROLL_FILTER(OP_AVG); break; case PNG_FILTER_VALUE_PAETH: for (i = 0; i < bpp; i++) { p = last[i]; dst[i] = p + src[i]; } if (bpp > 2 && size > 4) { /* would write off the end of the array if we let it process * the last pixel with bpp=3 */ int w = (bpp & 3) ? size - 3 : size; if (w > i) { dsp->add_paeth_prediction(dst + i, src + i, last + i, size - i, bpp); i = w; } } ff_add_png_paeth_prediction(dst + i, src + i, last + i, size - i, bpp); break; } } 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: bool CSPSource::schemeMatches(const KURL& url) const { if (m_scheme.isEmpty()) return m_policy->protocolMatchesSelf(url); return equalIgnoringCase(url.protocol(), m_scheme); } 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: png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn) { #endif /* PNG_USER_MEM_SUPPORTED */ #ifdef PNG_SETJMP_SUPPORTED volatile #endif png_structp png_ptr; #ifdef PNG_SETJMP_SUPPORTED #ifdef USE_FAR_KEYWORD jmp_buf jmpbuf; #endif #endif int i; png_debug(1, "in png_create_write_struct"); #ifdef PNG_USER_MEM_SUPPORTED png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG, (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr); #else png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); #endif /* PNG_USER_MEM_SUPPORTED */ if (png_ptr == NULL) return (NULL); /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif #ifdef PNG_SETJMP_SUPPORTED #ifdef USE_FAR_KEYWORD if (setjmp(jmpbuf)) #else if (setjmp(png_ptr->jmpbuf)) #endif { png_free(png_ptr, png_ptr->zbuf); png_ptr->zbuf = NULL; #ifdef PNG_USER_MEM_SUPPORTED png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn, (png_voidp)mem_ptr); #else png_destroy_struct((png_voidp)png_ptr); #endif return (NULL); } #ifdef USE_FAR_KEYWORD png_memcpy(png_ptr->jmpbuf, jmpbuf, png_sizeof(jmp_buf)); #endif #endif #ifdef PNG_USER_MEM_SUPPORTED png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn); #endif /* PNG_USER_MEM_SUPPORTED */ png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn); if (user_png_ver != NULL) { int found_dots = 0; i = -1; do { i++; if (user_png_ver[i] != PNG_LIBPNG_VER_STRING[i]) png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; if (user_png_ver[i] == '.') found_dots++; } while (found_dots < 2 && user_png_ver[i] != 0 && PNG_LIBPNG_VER_STRING[i] != 0); } else png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH) { /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so * we must recompile any applications that use any older library version. * For versions after libpng 1.0, we will be compatible, so we need * only check the first digit. */ if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] || (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) || (user_png_ver[0] == '0' && user_png_ver[2] < '9')) { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char msg[80]; if (user_png_ver) { png_snprintf(msg, 80, "Application was compiled with png.h from libpng-%.20s", user_png_ver); png_warning(png_ptr, msg); } png_snprintf(msg, 80, "Application is running with png.c from libpng-%.20s", png_libpng_ver); png_warning(png_ptr, msg); #endif #ifdef PNG_ERROR_NUMBERS_SUPPORTED png_ptr->flags = 0; #endif png_error(png_ptr, "Incompatible libpng version in application and library"); } } /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL, png_flush_ptr_NULL); #ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT, 1, png_doublep_NULL, png_doublep_NULL); #endif #ifdef PNG_SETJMP_SUPPORTED /* Applications that neglect to set up their own setjmp() and then * encounter a png_error() will longjmp here. Since the jmpbuf is * then meaningless we abort instead of returning. */ #ifdef USE_FAR_KEYWORD if (setjmp(jmpbuf)) PNG_ABORT(); png_memcpy(png_ptr->jmpbuf, jmpbuf, png_sizeof(jmp_buf)); #else if (setjmp(png_ptr->jmpbuf)) PNG_ABORT(); #endif #endif return (png_ptr); } CWE ID: CWE-119 Target: 1 Example 2: Code: Ins_SCANTYPE( TT_ExecContext exc, FT_Long* args ) { if ( args[0] >= 0 ) exc->GS.scan_type = (FT_Int)args[0] & 0xFFFF; } 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: TabContentsWrapper* Browser::AddSelectedTabWithURL( const GURL& url, PageTransition::Type transition) { browser::NavigateParams params(this, url, transition); params.disposition = NEW_FOREGROUND_TAB; browser::Navigate(&params); return params.target_contents; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AwFeatureListCreator::SetUpFieldTrials() { auto* metrics_client = AwMetricsServiceClient::GetInstance(); DCHECK(!field_trial_list_); field_trial_list_ = std::make_unique<base::FieldTrialList>( metrics_client->CreateLowEntropyProvider()); std::unique_ptr<variations::SeedResponse> seed = GetAndClearJavaSeed(); base::Time null_time; base::Time seed_date = seed ? base::Time::FromJavaTime(seed->date) : null_time; variations::UIStringOverrider ui_string_overrider; client_ = std::make_unique<AwVariationsServiceClient>(); auto seed_store = std::make_unique<variations::VariationsSeedStore>( local_state_.get(), /*initial_seed=*/std::move(seed), /*on_initial_seed_stored=*/base::DoNothing()); if (!seed_date.is_null()) seed_store->RecordLastFetchTime(seed_date); variations_field_trial_creator_ = std::make_unique<variations::VariationsFieldTrialCreator>( local_state_.get(), client_.get(), std::move(seed_store), ui_string_overrider); variations_field_trial_creator_->OverrideVariationsPlatform( variations::Study::PLATFORM_ANDROID_WEBVIEW); std::set<std::string> unforceable_field_trials; variations::SafeSeedManager ignored_safe_seed_manager(true, local_state_.get()); variations_field_trial_creator_->SetupFieldTrials( cc::switches::kEnableGpuBenchmarking, switches::kEnableFeatures, switches::kDisableFeatures, unforceable_field_trials, std::vector<std::string>(), content::GetSwitchDependentFeatureOverrides( *base::CommandLine::ForCurrentProcess()), /*low_entropy_provider=*/nullptr, std::make_unique<base::FeatureList>(), aw_field_trials_.get(), &ignored_safe_seed_manager); } CWE ID: CWE-20 Target: 1 Example 2: Code: register_CE(struct archive_read *a, int32_t location, struct file_info *file) { struct iso9660 *iso9660; struct read_ce_queue *heap; struct read_ce_req *p; uint64_t offset, parent_offset; int hole, parent; iso9660 = (struct iso9660 *)(a->format->data); offset = ((uint64_t)location) * (uint64_t)iso9660->logical_block_size; if (((file->mode & AE_IFMT) == AE_IFREG && offset >= file->offset) || offset < iso9660->current_position || (((uint64_t)file->ce_offset) + file->ce_size) > (uint64_t)iso9660->logical_block_size || offset + file->ce_offset + file->ce_size > iso9660->volume_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid parameter in SUSP \"CE\" extension"); return (ARCHIVE_FATAL); } /* Expand our CE list as necessary. */ heap = &(iso9660->read_ce_req); if (heap->cnt >= heap->allocated) { int new_size; if (heap->allocated < 16) new_size = 16; else new_size = heap->allocated * 2; /* Overflow might keep us from growing the list. */ if (new_size <= heap->allocated) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } p = calloc(new_size, sizeof(p[0])); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } if (heap->reqs != NULL) { memcpy(p, heap->reqs, heap->cnt * sizeof(*p)); free(heap->reqs); } heap->reqs = p; heap->allocated = new_size; } /* * Start with hole at end, walk it up tree to find insertion point. */ hole = heap->cnt++; while (hole > 0) { parent = (hole - 1)/2; parent_offset = heap->reqs[parent].offset; if (offset >= parent_offset) { heap->reqs[hole].offset = offset; heap->reqs[hole].file = file; return (ARCHIVE_OK); } /* Move parent into hole <==> move hole up tree. */ heap->reqs[hole] = heap->reqs[parent]; hole = parent; } heap->reqs[0].offset = offset; heap->reqs[0].file = file; return (ARCHIVE_OK); } 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: hash_rehash( hashtable* ht, FT_Memory memory ) { hashnode* obp = ht->table, *bp, *nbp; int i, sz = ht->size; FT_Error error = BDF_Err_Ok; ht->size <<= 1; ht->limit = ht->size / 3; if ( FT_NEW_ARRAY( ht->table, ht->size ) ) goto Exit; for ( i = 0, bp = obp; i < sz; i++, bp++ ) { if ( *bp ) { nbp = hash_bucket( (*bp)->key, ht ); *nbp = *bp; } } FT_FREE( obp ); Exit: return error; } 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: dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree, guint8 *drep _U_, char **data, int hf_name) { gint len, remaining; char *text; if (offset % 2) offset += 2 - (offset % 2); /* Get remaining data in buffer as a string */ remaining = tvb_captured_length_remaining(tvb, offset); if (remaining <= 0) { if (data) *data = g_strdup(""); return offset; } text = tvb_get_string_enc(NULL, tvb, offset, remaining, ENC_UTF_16|ENC_LITTLE_ENDIAN); len = (int)strlen(text); proto_tree_add_string(tree, hf_name, tvb, offset, len * 2, text); if (data) *data = text; else g_free(text); return offset + (len + 1) * 2; } CWE ID: CWE-399 Target: 1 Example 2: Code: FrameView::~FrameView() { if (m_postLayoutTasksTimer.isActive()) m_postLayoutTasksTimer.stop(); if (m_didScrollTimer.isActive()) m_didScrollTimer.stop(); removeFromAXObjectCache(); resetScrollbars(); ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar()); ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar()); setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow. setHasVerticalScrollbar(false); ASSERT(!m_scrollCorner); ASSERT(m_frame); ASSERT(m_frame->view() != this || !m_frame->contentRenderer()); HTMLFrameOwnerElement* ownerElement = m_frame->deprecatedLocalOwner(); if (ownerElement && ownerElement->ownedWidget() == this) ownerElement->setWidget(nullptr); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: std::string GetDMToken() { std::string dm_token = *GetTestingDMToken(); #if !defined(OS_CHROMEOS) if (dm_token.empty() && policy::ChromeBrowserCloudManagementController::IsEnabled()) { dm_token = policy::BrowserDMTokenStorage::Get()->RetrieveDMToken(); } #endif return dm_token; } 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: tt_cmap8_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_Byte* is32; FT_UInt32 length; FT_UInt32 num_groups; if ( table + 16 + 8192 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); if ( table + length > valid->limit || length < 8208 ) FT_INVALID_TOO_SHORT; is32 = table + 12; p = is32 + 8192; /* skip `is32' array */ num_groups = TT_NEXT_ULONG( p ); if ( p + num_groups * 12 > valid->limit ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ { FT_UInt32 n, start, end, start_id, count, last = 0; for ( n = 0; n < num_groups; n++ ) { FT_UInt hi, lo; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; count = (FT_UInt32)( end - start + 1 ); if ( start & ~0xFFFFU ) { /* start_hi != 0; check that is32[i] is 1 for each i in */ /* the `hi' and `lo' of the range [start..end] */ for ( ; count > 0; count--, start++ ) { hi = (FT_UInt)( start >> 16 ); lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 ) FT_INVALID_DATA; if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 ) FT_INVALID_DATA; } } else { /* start_hi == 0; check that is32[i] is 0 for each i in */ /* the range [start..end] */ /* end_hi cannot be != 0! */ if ( end & ~0xFFFFU ) FT_INVALID_DATA; for ( ; count > 0; count--, start++ ) { lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 ) FT_INVALID_DATA; } } } last = end; } } return SFNT_Err_Ok; } CWE ID: CWE-189 Target: 1 Example 2: Code: static void __exit pkcs7_key_cleanup(void) { unregister_key_type(&key_type_pkcs7); } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version) { zval **oid, **value, **type; char *a1, *a2, *a3, *a4, *a5, *a6, *a7; int a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len; zend_bool use_orignames = 0, suffix_keys = 0; long timeout = SNMP_DEFAULT_TIMEOUT; long retries = SNMP_DEFAULT_RETRIES; int argc = ZEND_NUM_ARGS(); struct objid_query objid_query; php_snmp_session *session; int session_less_mode = (getThis() == NULL); php_snmp_object *snmp_object; php_snmp_object glob_snmp_object; objid_query.max_repetitions = -1; objid_query.non_repeaters = 0; objid_query.valueretrieval = SNMP_G(valueretrieval); objid_query.oid_increasing_check = TRUE; if (session_less_mode) { if (version == SNMP_VERSION_3) { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } else { /* SNMP_CMD_GET * SNMP_CMD_GETNEXT * SNMP_CMD_WALK */ if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } } else { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "ssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } else { /* SNMP_CMD_GET * SNMP_CMD_GETNEXT * SNMP_CMD_WALK */ if (zend_parse_parameters(argc TSRMLS_CC, "ssZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } } } else { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "ZZZ", &oid, &type, &value) == FAILURE) { RETURN_FALSE; } } else if (st & SNMP_CMD_WALK) { if (zend_parse_parameters(argc TSRMLS_CC, "Z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) { RETURN_FALSE; } if (suffix_keys) { st |= SNMP_USE_SUFFIX_AS_KEYS; } } else if (st & SNMP_CMD_GET) { if (zend_parse_parameters(argc TSRMLS_CC, "Z|b", &oid, &use_orignames) == FAILURE) { RETURN_FALSE; } if (use_orignames) { st |= SNMP_ORIGINAL_NAMES_AS_KEYS; } } else { /* SNMP_CMD_GETNEXT */ if (zend_parse_parameters(argc TSRMLS_CC, "Z", &oid) == FAILURE) { RETURN_FALSE; } } } if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value TSRMLS_CC)) { RETURN_FALSE; } if (session_less_mode) { if (netsnmp_session_init(&session, version, a1, a2, timeout, retries TSRMLS_CC)) { efree(objid_query.vars); netsnmp_session_free(&session); RETURN_FALSE; } if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL TSRMLS_CC)) { efree(objid_query.vars); netsnmp_session_free(&session); /* Warning message sent already, just bail out */ RETURN_FALSE; } } else { zval *object = getThis(); snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); session = snmp_object->session; if (!session) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid or uninitialized SNMP object"); efree(objid_query.vars); RETURN_FALSE; } if (snmp_object->max_oids > 0) { objid_query.step = snmp_object->max_oids; if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */ objid_query.max_repetitions = snmp_object->max_oids; } } objid_query.oid_increasing_check = snmp_object->oid_increasing_check; objid_query.valueretrieval = snmp_object->valueretrieval; glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print); glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print); glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format); } if (objid_query.max_repetitions < 0) { objid_query.max_repetitions = 20; /* provide correct default value */ } php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query); efree(objid_query.vars); if (session_less_mode) { netsnmp_session_free(&session); } else { netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print); netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format); } } 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: int drm_mode_dirtyfb_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_clip_rect __user *clips_ptr; struct drm_clip_rect *clips = NULL; struct drm_mode_fb_dirty_cmd *r = data; struct drm_mode_object *obj; struct drm_framebuffer *fb; unsigned flags; int num_clips; int ret = 0; if (!drm_core_check_feature(dev, DRIVER_MODESET)) return -EINVAL; mutex_lock(&dev->mode_config.mutex); obj = drm_mode_object_find(dev, r->fb_id, DRM_MODE_OBJECT_FB); if (!obj) { DRM_ERROR("invalid framebuffer id\n"); ret = -EINVAL; goto out_err1; } fb = obj_to_fb(obj); num_clips = r->num_clips; clips_ptr = (struct drm_clip_rect *)(unsigned long)r->clips_ptr; if (!num_clips != !clips_ptr) { ret = -EINVAL; goto out_err1; } flags = DRM_MODE_FB_DIRTY_FLAGS & r->flags; /* If userspace annotates copy, clips must come in pairs */ if (flags & DRM_MODE_FB_DIRTY_ANNOTATE_COPY && (num_clips % 2)) { ret = -EINVAL; goto out_err1; } if (num_clips && clips_ptr) { clips = kzalloc(num_clips * sizeof(*clips), GFP_KERNEL); if (!clips) { ret = -ENOMEM; goto out_err1; } ret = copy_from_user(clips, clips_ptr, num_clips * sizeof(*clips)); if (ret) { ret = -EFAULT; goto out_err2; } } if (fb->funcs->dirty) { ret = fb->funcs->dirty(fb, file_priv, flags, r->color, clips, num_clips); } else { ret = -ENOSYS; goto out_err2; } out_err2: kfree(clips); out_err1: mutex_unlock(&dev->mode_config.mutex); return ret; } CWE ID: CWE-189 Target: 1 Example 2: Code: static int btrfs_real_readdir(struct file *filp, void *dirent, filldir_t filldir) { struct inode *inode = filp->f_dentry->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_item *item; struct btrfs_dir_item *di; struct btrfs_key key; struct btrfs_key found_key; struct btrfs_path *path; struct list_head ins_list; struct list_head del_list; int ret; struct extent_buffer *leaf; int slot; unsigned char d_type; int over = 0; u32 di_cur; u32 di_total; u32 di_len; int key_type = BTRFS_DIR_INDEX_KEY; char tmp_name[32]; char *name_ptr; int name_len; int is_curr = 0; /* filp->f_pos points to the current index? */ /* FIXME, use a real flag for deciding about the key type */ if (root->fs_info->tree_root == root) key_type = BTRFS_DIR_ITEM_KEY; /* special case for "." */ if (filp->f_pos == 0) { over = filldir(dirent, ".", 1, filp->f_pos, btrfs_ino(inode), DT_DIR); if (over) return 0; filp->f_pos = 1; } /* special case for .., just use the back ref */ if (filp->f_pos == 1) { u64 pino = parent_ino(filp->f_path.dentry); over = filldir(dirent, "..", 2, filp->f_pos, pino, DT_DIR); if (over) return 0; filp->f_pos = 2; } path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = 1; if (key_type == BTRFS_DIR_INDEX_KEY) { INIT_LIST_HEAD(&ins_list); INIT_LIST_HEAD(&del_list); btrfs_get_delayed_items(inode, &ins_list, &del_list); } btrfs_set_key_type(&key, key_type); key.offset = filp->f_pos; key.objectid = btrfs_ino(inode); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto err; while (1) { leaf = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) goto err; else if (ret > 0) break; continue; } item = btrfs_item_nr(leaf, slot); btrfs_item_key_to_cpu(leaf, &found_key, slot); if (found_key.objectid != key.objectid) break; if (btrfs_key_type(&found_key) != key_type) break; if (found_key.offset < filp->f_pos) goto next; if (key_type == BTRFS_DIR_INDEX_KEY && btrfs_should_delete_dir_index(&del_list, found_key.offset)) goto next; filp->f_pos = found_key.offset; is_curr = 1; di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item); di_cur = 0; di_total = btrfs_item_size(leaf, item); while (di_cur < di_total) { struct btrfs_key location; if (verify_dir_item(root, leaf, di)) break; name_len = btrfs_dir_name_len(leaf, di); if (name_len <= sizeof(tmp_name)) { name_ptr = tmp_name; } else { name_ptr = kmalloc(name_len, GFP_NOFS); if (!name_ptr) { ret = -ENOMEM; goto err; } } read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1), name_len); d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)]; btrfs_dir_item_key_to_cpu(leaf, di, &location); /* is this a reference to our own snapshot? If so * skip it. * * In contrast to old kernels, we insert the snapshot's * dir item and dir index after it has been created, so * we won't find a reference to our own snapshot. We * still keep the following code for backward * compatibility. */ if (location.type == BTRFS_ROOT_ITEM_KEY && location.objectid == root->root_key.objectid) { over = 0; goto skip; } over = filldir(dirent, name_ptr, name_len, found_key.offset, location.objectid, d_type); skip: if (name_ptr != tmp_name) kfree(name_ptr); if (over) goto nopos; di_len = btrfs_dir_name_len(leaf, di) + btrfs_dir_data_len(leaf, di) + sizeof(*di); di_cur += di_len; di = (struct btrfs_dir_item *)((char *)di + di_len); } next: path->slots[0]++; } if (key_type == BTRFS_DIR_INDEX_KEY) { if (is_curr) filp->f_pos++; ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir, &ins_list); if (ret) goto nopos; } /* Reached end of directory/root. Bump pos past the last item. */ if (key_type == BTRFS_DIR_INDEX_KEY) /* * 32-bit glibc will use getdents64, but then strtol - * so the last number we can serve is this. */ filp->f_pos = 0x7fffffff; else filp->f_pos++; nopos: ret = 0; err: if (key_type == BTRFS_DIR_INDEX_KEY) btrfs_put_delayed_items(&ins_list, &del_list); btrfs_free_path(path); return ret; } CWE ID: CWE-310 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: IndexedDBCursor::~IndexedDBCursor() { Close(); } 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: status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; } CWE ID: CWE-119 Target: 1 Example 2: Code: struct jv_parser* jv_parser_new(int flags) { struct jv_parser* p = jv_mem_alloc(sizeof(struct jv_parser)); parser_init(p, flags); p->flags = flags; return p; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static vm_fault_t hugetlb_no_page(struct mm_struct *mm, struct vm_area_struct *vma, struct address_space *mapping, pgoff_t idx, unsigned long address, pte_t *ptep, unsigned int flags) { struct hstate *h = hstate_vma(vma); vm_fault_t ret = VM_FAULT_SIGBUS; int anon_rmap = 0; unsigned long size; struct page *page; pte_t new_pte; spinlock_t *ptl; unsigned long haddr = address & huge_page_mask(h); bool new_page = false; /* * Currently, we are forced to kill the process in the event the * original mapper has unmapped pages from the child due to a failed * COW. Warn that such a situation has occurred as it may not be obvious */ if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) { pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n", current->pid); return ret; } /* * Use page lock to guard against racing truncation * before we get page_table_lock. */ retry: page = find_lock_page(mapping, idx); if (!page) { size = i_size_read(mapping->host) >> huge_page_shift(h); if (idx >= size) goto out; /* * Check for page in userfault range */ if (userfaultfd_missing(vma)) { u32 hash; struct vm_fault vmf = { .vma = vma, .address = haddr, .flags = flags, /* * Hard to debug if it ends up being * used by a callee that assumes * something about the other * uninitialized fields... same as in * memory.c */ }; /* * hugetlb_fault_mutex must be dropped before * handling userfault. Reacquire after handling * fault to make calling code simpler. */ hash = hugetlb_fault_mutex_hash(h, mm, vma, mapping, idx, haddr); mutex_unlock(&hugetlb_fault_mutex_table[hash]); ret = handle_userfault(&vmf, VM_UFFD_MISSING); mutex_lock(&hugetlb_fault_mutex_table[hash]); goto out; } page = alloc_huge_page(vma, haddr, 0); if (IS_ERR(page)) { ret = vmf_error(PTR_ERR(page)); goto out; } clear_huge_page(page, address, pages_per_huge_page(h)); __SetPageUptodate(page); new_page = true; if (vma->vm_flags & VM_MAYSHARE) { int err = huge_add_to_page_cache(page, mapping, idx); if (err) { put_page(page); if (err == -EEXIST) goto retry; goto out; } } else { lock_page(page); if (unlikely(anon_vma_prepare(vma))) { ret = VM_FAULT_OOM; goto backout_unlocked; } anon_rmap = 1; } } else { /* * If memory error occurs between mmap() and fault, some process * don't have hwpoisoned swap entry for errored virtual address. * So we need to block hugepage fault by PG_hwpoison bit check. */ if (unlikely(PageHWPoison(page))) { ret = VM_FAULT_HWPOISON | VM_FAULT_SET_HINDEX(hstate_index(h)); goto backout_unlocked; } } /* * If we are going to COW a private mapping later, we examine the * pending reservations for this page now. This will ensure that * any allocations necessary to record that reservation occur outside * the spinlock. */ if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { if (vma_needs_reservation(h, vma, haddr) < 0) { ret = VM_FAULT_OOM; goto backout_unlocked; } /* Just decrements count, does not deallocate */ vma_end_reservation(h, vma, haddr); } ptl = huge_pte_lock(h, mm, ptep); size = i_size_read(mapping->host) >> huge_page_shift(h); if (idx >= size) goto backout; ret = 0; if (!huge_pte_none(huge_ptep_get(ptep))) goto backout; if (anon_rmap) { ClearPagePrivate(page); hugepage_add_new_anon_rmap(page, vma, haddr); } else page_dup_rmap(page, true); new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE) && (vma->vm_flags & VM_SHARED))); set_huge_pte_at(mm, haddr, ptep, new_pte); hugetlb_count_add(pages_per_huge_page(h), mm); if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { /* Optimization, do the COW without a second fault */ ret = hugetlb_cow(mm, vma, address, ptep, page, ptl); } spin_unlock(ptl); /* * Only make newly allocated pages active. Existing pages found * in the pagecache could be !page_huge_active() if they have been * isolated for migration. */ if (new_page) set_page_huge_active(page); unlock_page(page); out: return ret; backout: spin_unlock(ptl); backout_unlocked: unlock_page(page); restore_reserve_on_error(h, vma, haddr, page); put_page(page); goto out; } 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: virtual void AddObserver(Observer* observer) { if (!observers_.size()) { observer->FirstObserverIsAdded(this); } observers_.AddObserver(observer); } CWE ID: CWE-399 Target: 1 Example 2: Code: kwsfree (kwset_t kwset) { obstack_free (&kwset->obstack, NULL); free (kwset); } 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: PasswordStoreLoginsChangedObserver::PasswordStoreLoginsChangedObserver( AutomationProvider* automation, IPC::Message* reply_message, PasswordStoreChange::Type expected_type, const std::string& result_key) : automation_(automation->AsWeakPtr()), reply_message_(reply_message), expected_type_(expected_type), result_key_(result_key), done_event_(false, false) { AddRef(); } CWE ID: CWE-20 Output:
0