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 PropertyTreeManager::SetupRootTransformNode() { cc::TransformTree& transform_tree = property_trees_.transform_tree; transform_tree.clear(); property_trees_.element_id_to_transform_node_index.clear(); cc::TransformNode& transform_node = *transform_tree.Node( transform_tree.Insert(cc::TransformNode(), kRealRootNodeId)); DCHECK_EQ(transform_node.id, kSecondaryRootNodeId); transform_node.source_node_id = transform_node.parent_id; float device_scale_factor = root_layer_->layer_tree_host()->device_scale_factor(); gfx::Transform to_screen; to_screen.Scale(device_scale_factor, device_scale_factor); transform_tree.SetToScreen(kRealRootNodeId, to_screen); gfx::Transform from_screen; bool invertible = to_screen.GetInverse(&from_screen); DCHECK(invertible); transform_tree.SetFromScreen(kRealRootNodeId, from_screen); transform_tree.set_needs_update(true); transform_node_map_.Set(TransformPaintPropertyNode::Root(), transform_node.id); root_layer_->SetTransformTreeIndex(transform_node.id); } CWE ID: Target: 1 Example 2: Code: static void TIFFReadDirEntryCheckedByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value) { (void) tif; *value=*(uint8*)(&direntry->tdir_offset); } 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 FakePlatformSensorProvider::CreateSensorInternal( mojom::SensorType type, mojo::ScopedSharedBufferMapping mapping, const CreateSensorCallback& callback) { DCHECK(type >= mojom::SensorType::FIRST && type <= mojom::SensorType::LAST); auto sensor = base::MakeRefCounted<FakePlatformSensor>(type, std::move(mapping), this); DoCreateSensorInternal(type, std::move(sensor), callback); } CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xfs_attr3_leaf_flipflags( struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf1; struct xfs_attr_leafblock *leaf2; struct xfs_attr_leaf_entry *entry1; struct xfs_attr_leaf_entry *entry2; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_buf *bp1; struct xfs_buf *bp2; int error; #ifdef DEBUG struct xfs_attr3_icleaf_hdr ichdr1; struct xfs_attr3_icleaf_hdr ichdr2; xfs_attr_leaf_name_local_t *name_loc; int namelen1, namelen2; char *name1, *name2; #endif /* DEBUG */ trace_xfs_attr_leaf_flipflags(args); /* * Read the block containing the "old" attr */ error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp1); if (error) return error; /* * Read the block containing the "new" attr, if it is different */ if (args->blkno2 != args->blkno) { error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno2, -1, &bp2); if (error) return error; } else { bp2 = bp1; } leaf1 = bp1->b_addr; entry1 = &xfs_attr3_leaf_entryp(leaf1)[args->index]; leaf2 = bp2->b_addr; entry2 = &xfs_attr3_leaf_entryp(leaf2)[args->index2]; #ifdef DEBUG xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1); ASSERT(args->index < ichdr1.count); ASSERT(args->index >= 0); xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2); ASSERT(args->index2 < ichdr2.count); ASSERT(args->index2 >= 0); if (entry1->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf1, args->index); namelen1 = name_loc->namelen; name1 = (char *)name_loc->nameval; } else { name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index); namelen1 = name_rmt->namelen; name1 = (char *)name_rmt->name; } if (entry2->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf2, args->index2); namelen2 = name_loc->namelen; name2 = (char *)name_loc->nameval; } else { name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2); namelen2 = name_rmt->namelen; name2 = (char *)name_rmt->name; } ASSERT(be32_to_cpu(entry1->hashval) == be32_to_cpu(entry2->hashval)); ASSERT(namelen1 == namelen2); ASSERT(memcmp(name1, name2, namelen1) == 0); #endif /* DEBUG */ ASSERT(entry1->flags & XFS_ATTR_INCOMPLETE); ASSERT((entry2->flags & XFS_ATTR_INCOMPLETE) == 0); entry1->flags &= ~XFS_ATTR_INCOMPLETE; xfs_trans_log_buf(args->trans, bp1, XFS_DA_LOGRANGE(leaf1, entry1, sizeof(*entry1))); if (args->rmtblkno) { ASSERT((entry1->flags & XFS_ATTR_LOCAL) == 0); name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index); name_rmt->valueblk = cpu_to_be32(args->rmtblkno); name_rmt->valuelen = cpu_to_be32(args->valuelen); xfs_trans_log_buf(args->trans, bp1, XFS_DA_LOGRANGE(leaf1, name_rmt, sizeof(*name_rmt))); } entry2->flags |= XFS_ATTR_INCOMPLETE; xfs_trans_log_buf(args->trans, bp2, XFS_DA_LOGRANGE(leaf2, entry2, sizeof(*entry2))); if ((entry2->flags & XFS_ATTR_LOCAL) == 0) { name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2); name_rmt->valueblk = 0; name_rmt->valuelen = 0; xfs_trans_log_buf(args->trans, bp2, XFS_DA_LOGRANGE(leaf2, name_rmt, sizeof(*name_rmt))); } /* * Commit the flag value change and start the next trans in series. */ error = xfs_trans_roll(&args->trans, args->dp); return error; } CWE ID: CWE-19 Target: 1 Example 2: Code: Text* FrameSelectionTest::AppendTextNode(const String& data) { Text* text = GetDocument().createTextNode(data); GetDocument().body()->AppendChild(text); return text; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int exfat_mount(struct exfat* ef, const char* spec, const char* options) { int rc; enum exfat_mode mode; exfat_tzset(); memset(ef, 0, sizeof(struct exfat)); parse_options(ef, options); if (match_option(options, "ro")) mode = EXFAT_MODE_RO; else if (match_option(options, "ro_fallback")) mode = EXFAT_MODE_ANY; else mode = EXFAT_MODE_RW; ef->dev = exfat_open(spec, mode); if (ef->dev == NULL) return -EIO; if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO) { if (mode == EXFAT_MODE_ANY) ef->ro = -1; else ef->ro = 1; } ef->sb = malloc(sizeof(struct exfat_super_block)); if (ef->sb == NULL) { exfat_close(ef->dev); exfat_error("failed to allocate memory for the super block"); return -ENOMEM; } memset(ef->sb, 0, sizeof(struct exfat_super_block)); if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to read boot sector"); return -EIO; } if (memcmp(ef->sb->oem_name, "EXFAT ", 8) != 0) { exfat_close(ef->dev); free(ef->sb); exfat_error("exFAT file system is not found"); return -EIO; } ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb)); if (ef->zero_cluster == NULL) { exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate zero sector"); return -ENOMEM; } /* use zero_cluster as a temporary buffer for VBR checksum verification */ if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb))) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb)); if (ef->sb->version.major != 1 || ef->sb->version.minor != 0) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported exFAT version: %hhu.%hhu", ef->sb->version.major, ef->sb->version.minor); free(ef->sb); return -EIO; } if (ef->sb->fat_count != 1) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("unsupported FAT count: %hhu", ef->sb->fat_count); free(ef->sb); return -EIO; } /* officially exFAT supports cluster size up to 32 MB */ if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error("too big cluster size: 2^%d", (int) ef->sb->sector_bits + (int) ef->sb->spc_bits); free(ef->sb); return -EIO; } if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) > exfat_get_size(ef->dev)) { /* this can cause I/O errors later but we don't fail mounting to let user rescue data */ exfat_warn("file system is larger than underlying device: " "%"PRIu64" > %"PRIu64, le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb), exfat_get_size(ef->dev)); } ef->root = malloc(sizeof(struct exfat_node)); if (ef->root == NULL) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); exfat_error("failed to allocate root node"); return -ENOMEM; } memset(ef->root, 0, sizeof(struct exfat_node)); ef->root->flags = EXFAT_ATTRIB_DIR; ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster); ef->root->fptr_cluster = ef->root->start_cluster; ef->root->name[0] = cpu_to_le16('\0'); ef->root->size = rootdir_size(ef); if (ef->root->size == 0) { free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } /* exFAT does not have time attributes for the root directory */ ef->root->mtime = 0; ef->root->atime = 0; /* always keep at least 1 reference to the root node */ exfat_get_node(ef->root); rc = exfat_cache_directory(ef, ef->root); if (rc != 0) goto error; if (ef->upcase == NULL) { exfat_error("upcase table is not found"); goto error; } if (ef->cmap.chunk == NULL) { exfat_error("clusters bitmap is not found"); goto error; } if (prepare_super_block(ef) != 0) goto error; return 0; error: exfat_put_node(ef, ef->root); exfat_reset_cache(ef); free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } 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: ContentEncoding::ContentCompression::~ContentCompression() { delete [] settings; } CWE ID: CWE-119 Target: 1 Example 2: Code: void Browser::URLStarredChanged(content::WebContents* web_contents, bool starred) { if (web_contents == chrome::GetActiveWebContents(this)) window_->SetStarredState(starred); } 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: blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider( blink::WebLocalFrame* frame) { DCHECK(!frame_ || frame_ == frame); DCHECK(frame->dataSource()); if (!ChildThreadImpl::current()) return NULL; // May be null in some tests. ServiceWorkerNetworkProvider* provider = ServiceWorkerNetworkProvider::FromDocumentState( DocumentState::FromDataSource(frame->dataSource())); DCHECK(provider); return new WebServiceWorkerProviderImpl( ChildThreadImpl::current()->thread_safe_sender(), provider->context()); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RegisterOptimizationHintsComponent(ComponentUpdateService* cus, PrefService* profile_prefs) { if (!previews::params::IsOptimizationHintsEnabled()) { return; } bool data_saver_enabled = base::CommandLine::ForCurrentProcess()->HasSwitch( data_reduction_proxy::switches::kEnableDataReductionProxy) || (profile_prefs && profile_prefs->GetBoolean( data_reduction_proxy::prefs::kDataSaverEnabled)); if (!data_saver_enabled) return; auto installer = base::MakeRefCounted<ComponentInstaller>( std::make_unique<OptimizationHintsComponentInstallerPolicy>()); installer->Register(cus, base::OnceClosure()); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool AppCacheDatabase::FindOnlineWhiteListForCache( int64_t cache_id, std::vector<OnlineWhiteListRecord>* records) { DCHECK(records && records->empty()); if (!LazyOpen(kDontCreate)) return false; static const char kSql[] = "SELECT cache_id, namespace_url, is_pattern FROM OnlineWhiteLists" " WHERE cache_id = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, cache_id); while (statement.Step()) { records->push_back(OnlineWhiteListRecord()); this->ReadOnlineWhiteListRecord(statement, &records->back()); DCHECK(records->back().cache_id == cache_id); } return statement.Succeeded(); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int trigger_fpga_config(void) { int ret = 0, init_l; /* approx 10ms */ u32 timeout = 10000; /* make sure the FPGA_can access the EEPROM */ toggle_fpga_eeprom_bus(false); /* assert CONF_SEL_L to be able to drive FPGA_PROG_L */ qrio_gpio_direction_output(GPIO_A, CONF_SEL_L, 0); /* trigger the config start */ qrio_gpio_direction_output(GPIO_A, FPGA_PROG_L, 0); /* small delay for INIT_L line */ udelay(10); /* wait for FPGA_INIT to be asserted */ do { init_l = qrio_get_gpio(GPIO_A, FPGA_INIT_L); if (timeout-- == 0) { printf("FPGA_INIT timeout\n"); ret = -EFAULT; break; } udelay(10); } while (init_l); /* deassert FPGA_PROG, config should start */ qrio_set_gpio(GPIO_A, FPGA_PROG_L, 1); return ret; } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int fscrypt_setup_filename(struct inode *dir, const struct qstr *iname, int lookup, struct fscrypt_name *fname) { int ret = 0, bigname = 0; memset(fname, 0, sizeof(struct fscrypt_name)); fname->usr_fname = iname; if (!dir->i_sb->s_cop->is_encrypted(dir) || fscrypt_is_dot_dotdot(iname)) { fname->disk_name.name = (unsigned char *)iname->name; fname->disk_name.len = iname->len; return 0; } ret = fscrypt_get_crypt_info(dir); if (ret && ret != -EOPNOTSUPP) return ret; if (dir->i_crypt_info) { ret = fscrypt_fname_alloc_buffer(dir, iname->len, &fname->crypto_buf); if (ret) return ret; ret = fname_encrypt(dir, iname, &fname->crypto_buf); if (ret) goto errout; fname->disk_name.name = fname->crypto_buf.name; fname->disk_name.len = fname->crypto_buf.len; return 0; } if (!lookup) return -ENOKEY; /* * We don't have the key and we are doing a lookup; decode the * user-supplied name */ if (iname->name[0] == '_') bigname = 1; if ((bigname && (iname->len != 33)) || (!bigname && (iname->len > 43))) return -ENOENT; fname->crypto_buf.name = kmalloc(32, GFP_KERNEL); if (fname->crypto_buf.name == NULL) return -ENOMEM; ret = digest_decode(iname->name + bigname, iname->len - bigname, fname->crypto_buf.name); if (ret < 0) { ret = -ENOENT; goto errout; } fname->crypto_buf.len = ret; if (bigname) { memcpy(&fname->hash, fname->crypto_buf.name, 4); memcpy(&fname->minor_hash, fname->crypto_buf.name + 4, 4); } else { fname->disk_name.name = fname->crypto_buf.name; fname->disk_name.len = fname->crypto_buf.len; } return 0; errout: fscrypt_fname_free_buffer(&fname->crypto_buf); return ret; } CWE ID: CWE-416 Target: 1 Example 2: Code: std::string caption() { return caption_; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void KeyboardOverlayHandler::GetInputMethodId(const ListValue* args) { chromeos::input_method::InputMethodManager* manager = chromeos::input_method::InputMethodManager::GetInstance(); const chromeos::input_method::InputMethodDescriptor& descriptor = manager->current_input_method(); StringValue param(descriptor.id()); web_ui_->CallJavascriptFunction("initKeyboardOverlayId", param); } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct ipddp_route __user *rt = ifr->ifr_data; struct ipddp_route rcp, rcp2, *rp; if(!capable(CAP_NET_ADMIN)) return -EPERM; if(copy_from_user(&rcp, rt, sizeof(rcp))) return -EFAULT; switch(cmd) { case SIOCADDIPDDPRT: return ipddp_create(&rcp); case SIOCFINDIPDDPRT: spin_lock_bh(&ipddp_route_lock); rp = __ipddp_find_route(&rcp); if (rp) memcpy(&rcp2, rp, sizeof(rcp2)); spin_unlock_bh(&ipddp_route_lock); if (rp) { if (copy_to_user(rt, &rcp2, sizeof(struct ipddp_route))) return -EFAULT; return 0; } else return -ENOENT; case SIOCDELIPDDPRT: return ipddp_delete(&rcp); default: return -EINVAL; } } CWE ID: CWE-200 Target: 1 Example 2: Code: static int strict_blocks_to_sectors(const char *buf, sector_t *sectors) { unsigned long long blocks; sector_t new; if (kstrtoull(buf, 10, &blocks) < 0) return -EINVAL; if (blocks & 1ULL << (8 * sizeof(blocks) - 1)) return -EINVAL; /* sector conversion overflow */ new = blocks * 2; if (new != blocks * 2) return -EINVAL; /* unsigned long long to sector_t overflow */ *sectors = new; return 0; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int extract_status_code(char *buffer, size_t size) { char *buf_code; char *begin; char *end = buffer + size; size_t inc = 0; int code; /* Allocate the room */ buf_code = (char *)MALLOC(10); /* Status-Code extraction */ while (buffer < end && *buffer++ != ' ') ; begin = buffer; while (buffer < end && *buffer++ != ' ') inc++; strncat(buf_code, begin, inc); code = atoi(buf_code); FREE(buf_code); return code; } 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 CloudPolicyController::StopAutoRetry() { scheduler_->CancelDelayedWork(); backend_.reset(); } CWE ID: CWE-399 Target: 1 Example 2: Code: static inline unsigned int gcm_remain(unsigned int len) { len &= 0xfU; return len ? 16 - len : 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: void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size, int32 id_request, IPC::Message* reply_message) { TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateTransferBuffer"); if (command_buffer_.get()) { int32 id = command_buffer_->CreateTransferBuffer(size, id_request); GpuCommandBufferMsg_CreateTransferBuffer::WriteReplyParams( reply_message, id); } else { reply_message->set_reply_error(); } Send(reply_message); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int cdxl_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt) { CDXLVideoContext *c = avctx->priv_data; AVFrame * const p = data; int ret, w, h, encoding, aligned_width, buf_size = pkt->size; const uint8_t *buf = pkt->data; if (buf_size < 32) return AVERROR_INVALIDDATA; encoding = buf[1] & 7; c->format = buf[1] & 0xE0; w = AV_RB16(&buf[14]); h = AV_RB16(&buf[16]); c->bpp = buf[19]; c->palette_size = AV_RB16(&buf[20]); c->palette = buf + 32; c->video = c->palette + c->palette_size; c->video_size = buf_size - c->palette_size - 32; if (c->palette_size > 512) return AVERROR_INVALIDDATA; if (buf_size < c->palette_size + 32) return AVERROR_INVALIDDATA; if (c->bpp < 1) return AVERROR_INVALIDDATA; if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) { avpriv_request_sample(avctx, "Pixel format 0x%0x", c->format); return AVERROR_PATCHWELCOME; } if ((ret = ff_set_dimensions(avctx, w, h)) < 0) return ret; if (c->format == CHUNKY) aligned_width = avctx->width; else aligned_width = FFALIGN(c->avctx->width, 16); c->padded_bits = aligned_width - c->avctx->width; if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8) return AVERROR_INVALIDDATA; if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) { avctx->pix_fmt = AV_PIX_FMT_PAL8; } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) { if (c->palette_size != (1 << (c->bpp - 1))) return AVERROR_INVALIDDATA; avctx->pix_fmt = AV_PIX_FMT_BGR24; } else if (!encoding && c->bpp == 24 && c->format == CHUNKY && !c->palette_size) { avctx->pix_fmt = AV_PIX_FMT_RGB24; } else { avpriv_request_sample(avctx, "Encoding %d, bpp %d and format 0x%x", encoding, c->bpp, c->format); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->pict_type = AV_PICTURE_TYPE_I; if (encoding) { av_fast_padded_malloc(&c->new_video, &c->new_video_size, h * w + AV_INPUT_BUFFER_PADDING_SIZE); if (!c->new_video) return AVERROR(ENOMEM); if (c->bpp == 8) cdxl_decode_ham8(c, p); else cdxl_decode_ham6(c, p); } else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { cdxl_decode_rgb(c, p); } else { cdxl_decode_raw(c, p); } *got_frame = 1; return buf_size; } CWE ID: CWE-119 Target: 1 Example 2: Code: static bool ieee80211_tx_frags(struct ieee80211_local *local, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct sk_buff_head *skbs, bool txpending) { struct ieee80211_tx_control control; struct sk_buff *skb, *tmp; unsigned long flags; skb_queue_walk_safe(skbs, skb, tmp) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); int q = info->hw_queue; #ifdef CONFIG_MAC80211_VERBOSE_DEBUG if (WARN_ON_ONCE(q >= local->hw.queues)) { __skb_unlink(skb, skbs); ieee80211_free_txskb(&local->hw, skb); continue; } #endif spin_lock_irqsave(&local->queue_stop_reason_lock, flags); if (local->queue_stop_reasons[q] || (!txpending && !skb_queue_empty(&local->pending[q]))) { if (unlikely(info->flags & IEEE80211_TX_INTFL_OFFCHAN_TX_OK)) { if (local->queue_stop_reasons[q] & ~BIT(IEEE80211_QUEUE_STOP_REASON_OFFCHANNEL)) { /* * Drop off-channel frames if queues * are stopped for any reason other * than off-channel operation. Never * queue them. */ spin_unlock_irqrestore( &local->queue_stop_reason_lock, flags); ieee80211_purge_tx_queue(&local->hw, skbs); return true; } } else { /* * Since queue is stopped, queue up frames for * later transmission from the tx-pending * tasklet when the queue is woken again. */ if (txpending) skb_queue_splice_init(skbs, &local->pending[q]); else skb_queue_splice_tail_init(skbs, &local->pending[q]); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); return false; } } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); info->control.vif = vif; control.sta = sta; __skb_unlink(skb, skbs); drv_tx(local, &control, skb); } return true; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gsm_xsmp_client_disconnect (GsmXSMPClient *client) { if (client->priv->watch_id > 0) { g_source_remove (client->priv->watch_id); } if (client->priv->conn != NULL) { SmsCleanUp (client->priv->conn); } if (client->priv->ice_connection != NULL) { IceSetShutdownNegotiation (client->priv->ice_connection, FALSE); IceCloseConnection (client->priv->ice_connection); } if (client->priv->protocol_timeout > 0) { g_source_remove (client->priv->protocol_timeout); } } CWE ID: CWE-835 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 x509_crt_verify_child( mbedtls_x509_crt *child, mbedtls_x509_crt *parent, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, int path_cnt, int self_cnt, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { int ret; uint32_t parent_flags = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; mbedtls_x509_crt *grandparent; const mbedtls_md_info_t *md_info; /* Counting intermediate self signed certificates */ if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) self_cnt++; /* path_cnt is 0 for the first intermediate CA */ if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); } if( mbedtls_x509_time_is_past( &child->valid_to ) ) *flags |= MBEDTLS_X509_BADCERT_EXPIRED; if( mbedtls_x509_time_is_future( &child->valid_from ) ) *flags |= MBEDTLS_X509_BADCERT_FUTURE; if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_MD; if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; md_info = mbedtls_md_info_from_type( child->sig_md ); if( md_info == NULL ) { /* * Cannot check 'unknown' hash */ *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } else { mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, child->sig_md, hash, mbedtls_md_get_size( md_info ), child->sig.p, child->sig.len ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } } #if defined(MBEDTLS_X509_CRL_PARSE_C) /* Check trusted CA's CRL for the given crt */ *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile ); #endif /* Look for a grandparent in trusted CAs */ for( grandparent = trust_ca; grandparent != NULL; grandparent = grandparent->next ) { if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } if( grandparent != NULL ) { ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { /* Look for a grandparent upwards the chain */ for( grandparent = parent->next; grandparent != NULL; grandparent = grandparent->next ) { /* +2 because the current step is not yet accounted for * and because max_pathlen is one higher than it should be. * Also self signed certificates do not count to the limit. */ if( grandparent->max_pathlen > 0 && grandparent->max_pathlen < 2 + path_cnt - self_cnt ) { continue; } if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } /* Is our parent part of the chain or at the top? */ if( grandparent != NULL ) { ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } } /* child is verified to be a child of the parent, call verify callback */ if( NULL != f_vrfy ) if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) return( ret ); *flags |= parent_flags; return( 0 ); } CWE ID: CWE-287 Target: 1 Example 2: Code: void CStarter::FinalCleanup() { RemoveRecoveryFile(); removeTempExecuteDir(); } CWE ID: CWE-134 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect) { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; int64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; if (whence == AVSEEK_SIZE) return s->filesize; else if (!force_reconnect && ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; else if ((s->filesize == -1 && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) off += s->off; else if (whence == SEEK_END) off += s->filesize; else if (whence != SEEK_SET) return AVERROR(EINVAL); if (off < 0) return AVERROR(EINVAL); s->off = off; if (s->off && h->is_streamed) return AVERROR(ENOSYS); /* we save the old context in case the seek fails */ old_buf_size = s->buf_end - s->buf_ptr; memcpy(old_buf, s->buf_ptr, old_buf_size); s->hd = NULL; /* if it fails, continue on old connection */ if ((ret = http_open_cnx(h, &options)) < 0) { av_dict_free(&options); memcpy(s->buffer, old_buf, old_buf_size); s->buf_ptr = s->buffer; s->buf_end = s->buffer + old_buf_size; s->hd = old_hd; s->off = old_off; return ret; } av_dict_free(&options); ffurl_close(old_hd); return off; } 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 v8::Handle<v8::Value> methodWithNonOptionalArgAndTwoOptionalArgsCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.methodWithNonOptionalArgAndTwoOptionalArgs"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); if (args.Length() <= 1) { imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(int, opt1, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); if (args.Length() <= 2) { imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(int, opt2, toInt32(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))); imp->methodWithNonOptionalArgAndTwoOptionalArgs(nonOpt, opt1, opt2); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: base::Optional<int> GetInsertionIndexForDraggedBoundsStacked( const gfx::Rect& dragged_bounds, bool mouse_has_ever_moved_left, bool mouse_has_ever_moved_right) const { int active_index = *GetActiveTouchIndex(); base::Optional<int> index = GetInsertionIndexFromReversed(dragged_bounds, active_index); if (index != active_index) return index; if (!index) return GetInsertionIndexFrom(dragged_bounds, active_index + 1); if (active_index + 1 < GetTabCount() && tab_strip_->touch_layout_->IsStacked(active_index + 1)) { index = GetInsertionIndexFrom(dragged_bounds, active_index + 1); if (!index && ShouldDragToNextStackedTab(dragged_bounds, active_index, mouse_has_ever_moved_right)) index = active_index + 1; else if (index == -1) index = active_index; } else if (ShouldDragToPreviousStackedTab(dragged_bounds, active_index, mouse_has_ever_moved_left)) { index = active_index - 1; } return index; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Chapters::Display::Clear() { delete[] m_string; m_string = NULL; delete[] m_language; m_language = NULL; delete[] m_country; m_country = NULL; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: main(void) { fprintf(stderr, "pngfix does not work without read support\n"); return 77; } CWE ID: Target: 1 Example 2: Code: static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context) { Image *image; image=(Image *) context; return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DevToolsWindow::OpenDevToolsWindow( content::WebContents* inspected_web_contents) { ToggleDevToolsWindow( inspected_web_contents, true, DevToolsToggleAction::Show(), ""); } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool WorkerProcessLauncherTest::LaunchProcess( IPC::Listener* delegate, ScopedHandle* process_exit_event_out) { process_exit_event_.Set(CreateEvent(NULL, TRUE, FALSE, NULL)); if (!process_exit_event_.IsValid()) return false; channel_name_ = GenerateIpcChannelName(this); if (!CreateIpcChannel(channel_name_, kIpcSecurityDescriptor, task_runner_, delegate, &channel_server_)) { return false; } exit_code_ = STILL_ACTIVE; return DuplicateHandle(GetCurrentProcess(), process_exit_event_, GetCurrentProcess(), process_exit_event_out->Receive(), 0, FALSE, DUPLICATE_SAME_ACCESS) != FALSE; } CWE ID: CWE-399 Target: 1 Example 2: Code: static int net_get_monitor(struct wif *wi) { return net_cmd(wi_priv(wi), NET_GET_MONITOR, NULL, 0); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xfs_vn_create( struct inode *dir, struct dentry *dentry, umode_t mode, bool flags) { return xfs_vn_mknod(dir, dentry, mode, 0); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _crypt_extended_r(const char *key, const char *setting, struct php_crypt_extended_data *data) { int i; uint32_t count, salt, l, r0, r1, keybuf[2]; u_char *p, *q; if (!data->initialized) des_init_local(data); /* * Copy the key, shifting each character up by one bit * and padding with zeros. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf)) { if ((*q++ = *key << 1)) key++; } if (des_setkey((u_char *) keybuf, data)) if (*setting == _PASSWORD_EFMT1) { /* * "new"-style: * setting - underscore, 4 chars of count, 4 chars of salt * key - unlimited characters */ for (i = 1, count = 0; i < 5; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); count |= value << (i - 1) * 6; } if (!count) return(NULL); for (i = 5, salt = 0; i < 9; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); salt |= value << (i - 5) * 6; } while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((u_char *) keybuf, (u_char *) keybuf, 0, 1, data)) return(NULL); /* * And XOR with the next 8 characters of the key. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf) && *key) *q++ ^= *key++ << 1; if (des_setkey((u_char *) keybuf, data)) return(NULL); } memcpy(data->output, setting, 9); data->output[9] = '\0'; p = (u_char *) data->output + 9; } else { /* * "old"-style: * setting - 2 chars of salt * key - up to 8 characters */ count = 25; if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1])) return(NULL); salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); data->output[0] = setting[0]; data->output[1] = setting[1]; p = (u_char *) data->output + 2; } setup_salt(salt, data); /* * Do it. */ if (do_des(0, 0, &r0, &r1, count, data)) return(NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = r1 << 2; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; *p = 0; return(data->output); } CWE ID: CWE-310 Target: 1 Example 2: Code: gzip_body(const struct http *hp, const char *txt, char **body, int *bodylen) { int l, i; z_stream vz; memset(&vz, 0, sizeof vz); l = strlen(txt); *body = calloc(l + OVERHEAD, 1); AN(*body); vz.next_in = TRUST_ME(txt); vz.avail_in = l; vz.next_out = TRUST_ME(*body); vz.avail_out = l + OVERHEAD; assert(Z_OK == deflateInit2(&vz, hp->gziplevel, Z_DEFLATED, 31, 9, Z_DEFAULT_STRATEGY)); assert(Z_STREAM_END == deflate(&vz, Z_FINISH)); i = vz.stop_bit & 7; if (hp->gzipresidual >= 0 && hp->gzipresidual != i) vtc_log(hp->vl, hp->fatal, "Wrong gzip residual got %d wanted %d", i, hp->gzipresidual); *bodylen = vz.total_out; vtc_log(hp->vl, 4, "startbit = %ju %ju/%ju", (uintmax_t)vz.start_bit, (uintmax_t)vz.start_bit >> 3, (uintmax_t)vz.start_bit & 7); vtc_log(hp->vl, 4, "lastbit = %ju %ju/%ju", (uintmax_t)vz.last_bit, (uintmax_t)vz.last_bit >> 3, (uintmax_t)vz.last_bit & 7); vtc_log(hp->vl, 4, "stopbit = %ju %ju/%ju", (uintmax_t)vz.stop_bit, (uintmax_t)vz.stop_bit >> 3, (uintmax_t)vz.stop_bit & 7); assert(Z_OK == deflateEnd(&vz)); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CreateSimpleArtifactWithOpacity(TestPaintArtifact& artifact, float opacity, bool include_preceding_chunk, bool include_subsequent_chunk) { if (include_preceding_chunk) AddSimpleRectChunk(artifact); auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), opacity); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); if (include_subsequent_chunk) AddSimpleRectChunk(artifact); Update(artifact.Build()); } 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: const char* SegmentInfo::GetMuxingAppAsUTF8() const { return m_pMuxingAppAsUTF8; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void drain_all_stock_async(struct mem_cgroup *root_memcg) { /* * If someone calls draining, avoid adding more kworker runs. */ if (!mutex_trylock(&percpu_charge_mutex)) return; drain_all_stock(root_memcg, false); mutex_unlock(&percpu_charge_mutex); } 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 HttpProxyClientSocket::SetReceiveBufferSize(int32 size) { return transport_->socket()->SetReceiveBufferSize(size); } 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 MockContentSettingsClient::allowAutoplay(bool default_value) { return default_value || flags_->autoplay_allowed(); } CWE ID: CWE-119 Target: 1 Example 2: Code: void TestGetCacheState(const std::string& resource_id, const std::string& md5, base::PlatformFileError expected_error, int expected_cache_state, GDataFile* expected_file) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; file_system_->GetCacheState(resource_id, md5, base::Bind(&GDataFileSystemTest::VerifyGetCacheState, base::Unretained(this))); RunAllPendingForIO(); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool XMLHttpRequest::initSend(ExceptionState& es) { if (!scriptExecutionContext()) return false; if (m_state != OPENED || m_loader) { es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "the object's state must be OPENED.")); return false; } m_error = false; return true; } 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: xmlParsePI(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; const xmlChar *target; xmlParserInputState state; int count = 0; if ((RAW == '<') && (NXT(1) == '?')) { xmlParserInputPtr input = ctxt->input; state = ctxt->instate; ctxt->instate = XML_PARSER_PI; /* * this is a Processing Instruction. */ SKIP(2); SHRINK; /* * Parse the target name and check for special support like * namespace. */ target = xmlParsePITarget(ctxt); if (target != NULL) { if ((RAW == '?') && (NXT(1) == '>')) { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "PI declaration doesn't start and stop in the same entity\n"); } SKIP(2); /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, NULL); if (ctxt->instate != XML_PARSER_EOF) ctxt->instate = state; return; } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } cur = CUR; if (!IS_BLANK(cur)) { xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, "ParsePI: PI %s space expected\n", target); } SKIP_BLANKS; cur = CUR_CHAR(l); while (IS_CHAR(cur) && /* checked */ ((cur != '?') || (NXT(1) != '>'))) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); ctxt->instate = state; return; } buf = tmp; } count++; if (count > 50) { GROW; count = 0; } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { SHRINK; GROW; cur = CUR_CHAR(l); } } buf[len] = 0; if (cur != '?') { xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, "ParsePI: PI %s never end ...\n", target); } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "PI declaration doesn't start and stop in the same entity\n"); } SKIP(2); #ifdef LIBXML_CATALOG_ENABLED if (((state == XML_PARSER_MISC) || (state == XML_PARSER_START)) && (xmlStrEqual(target, XML_CATALOG_PI))) { xmlCatalogAllow allow = xmlCatalogGetDefaults(); if ((allow == XML_CATA_ALLOW_DOCUMENT) || (allow == XML_CATA_ALLOW_ALL)) xmlParseCatalogPI(ctxt, buf); } #endif /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, buf); } xmlFree(buf); } else { xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); } if (ctxt->instate != XML_PARSER_EOF) ctxt->instate = state; } } CWE ID: CWE-119 Target: 1 Example 2: Code: Document* Document::topDocument() const { Document* doc = const_cast<Document*>(this); Element* element; while ((element = doc->ownerElement())) doc = &element->document(); return doc; } 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 XSSAuditor::Init(Document* document, XSSAuditorDelegate* auditor_delegate) { DCHECK(IsMainThread()); if (state_ != kUninitialized) return; state_ = kFilteringTokens; if (Settings* settings = document->GetSettings()) is_enabled_ = settings->GetXSSAuditorEnabled(); if (!is_enabled_) return; document_url_ = document->Url().Copy(); if (!document->GetFrame()) { is_enabled_ = false; return; } if (document_url_.IsEmpty()) { is_enabled_ = false; return; } if (document_url_.ProtocolIsData()) { is_enabled_ = false; return; } if (document->Encoding().IsValid()) encoding_ = document->Encoding(); if (DocumentLoader* document_loader = document->GetFrame()->Loader().GetDocumentLoader()) { const AtomicString& header_value = document_loader->GetResponse().HttpHeaderField( HTTPNames::X_XSS_Protection); String error_details; unsigned error_position = 0; String report_url; KURL xss_protection_report_url; ReflectedXSSDisposition xss_protection_header = ParseXSSProtectionHeader( header_value, error_details, error_position, report_url); if (xss_protection_header == kAllowReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled); else if (xss_protection_header == kFilterReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter); else if (xss_protection_header == kBlockReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock); else if (xss_protection_header == kReflectedXSSInvalid) UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid); did_send_valid_xss_protection_header_ = xss_protection_header != kReflectedXSSUnset && xss_protection_header != kReflectedXSSInvalid; if ((xss_protection_header == kFilterReflectedXSS || xss_protection_header == kBlockReflectedXSS) && !report_url.IsEmpty()) { xss_protection_report_url = document->CompleteURL(report_url); if (MixedContentChecker::IsMixedContent(document->GetSecurityOrigin(), xss_protection_report_url)) { error_details = "insecure reporting URL for secure page"; xss_protection_header = kReflectedXSSInvalid; xss_protection_report_url = KURL(); } } if (xss_protection_header == kReflectedXSSInvalid) { document->AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Error parsing header X-XSS-Protection: " + header_value + ": " + error_details + " at character position " + String::Format("%u", error_position) + ". The default protections will be applied.")); } xss_protection_ = xss_protection_header; if (xss_protection_ == kReflectedXSSInvalid || xss_protection_ == kReflectedXSSUnset) { xss_protection_ = kBlockReflectedXSS; } if (auditor_delegate) auditor_delegate->SetReportURL(xss_protection_report_url.Copy()); EncodedFormData* http_body = document_loader->GetRequest().HttpBody(); if (http_body && !http_body->IsEmpty()) http_body_as_string_ = http_body->FlattenToString(); } SetEncoding(encoding_); } 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: void WebGL2RenderingContextBase::texImage3D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, MaybeShared<DOMArrayBufferView> pixels, GLuint src_offset) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texImage3D", "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } TexImageHelperDOMArrayBufferView( kTexImage3D, target, level, internalformat, width, height, depth, border, format, type, 0, 0, 0, pixels.View(), kNullNotReachable, src_offset); } CWE ID: CWE-125 Target: 1 Example 2: Code: struct usb_interface *usb_get_intf(struct usb_interface *intf) { if (intf) get_device(&intf->dev); return intf; } CWE ID: CWE-400 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: my_object_init (MyObject *obj) { obj->val = 0; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DownloadController::CreateGETDownload( const content::ResourceRequestInfo::WebContentsGetter& wc_getter, bool must_download, const DownloadInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&DownloadController::StartAndroidDownload, base::Unretained(this), wc_getter, must_download, info)); } CWE ID: CWE-254 Target: 1 Example 2: Code: bool omx_vdec::release_input_done(void) { bool bRet = false; unsigned i=0,j=0; DEBUG_PRINT_LOW("Value of m_inp_mem_ptr %p",m_inp_mem_ptr); if (m_inp_mem_ptr) { for (; j<drv_ctx.ip_buf.actualcount; j++) { if ( BITMASK_PRESENT(&m_inp_bm_count,j)) { break; } } if (j==drv_ctx.ip_buf.actualcount) { bRet = true; } } else { bRet = true; } return bRet; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TextTrackCue::setEndTime(double value) { if (end_time_ == value || value < 0) return; CueWillChange(); end_time_ = value; CueDidChange(kCueMutationAffectsOrder); } 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: cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { assert((size_t)CDF_SHORT_SEC_SIZE(h) == len); (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + CDF_SHORT_SEC_POS(h, id), len); return len; } CWE ID: CWE-119 Target: 1 Example 2: Code: perf_event_mux_interval_ms_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct pmu *pmu = dev_get_drvdata(dev); int timer, cpu, ret; ret = kstrtoint(buf, 0, &timer); if (ret) return ret; if (timer < 1) return -EINVAL; /* same value, noting to do */ if (timer == pmu->hrtimer_interval_ms) return count; mutex_lock(&mux_interval_mutex); pmu->hrtimer_interval_ms = timer; /* update all cpuctx for this PMU */ get_online_cpus(); for_each_online_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); cpu_function_call(cpu, (remote_function_f)perf_mux_hrtimer_restart, cpuctx); } put_online_cpus(); mutex_unlock(&mux_interval_mutex); return count; } 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: bool WebPage::touchEvent(const Platform::TouchEvent& event) { #if DEBUG_TOUCH_EVENTS BBLOG(LogLevelCritical, "%s", event.toString().c_str()); #endif #if ENABLE(TOUCH_EVENTS) if (!d->m_mainFrame) return false; if (d->m_page->defersLoading()) return false; PluginView* pluginView = d->m_fullScreenPluginView.get(); if (pluginView) return d->dispatchTouchEventToFullScreenPlugin(pluginView, event); Platform::TouchEvent tEvent = event; for (unsigned i = 0; i < event.m_points.size(); i++) { tEvent.m_points[i].m_pos = d->mapFromTransformed(tEvent.m_points[i].m_pos); tEvent.m_points[i].m_screenPos = tEvent.m_points[i].m_screenPos; } if (event.isSingleTap()) d->m_pluginMayOpenNewTab = true; else if (tEvent.m_type == Platform::TouchEvent::TouchStart || tEvent.m_type == Platform::TouchEvent::TouchCancel) d->m_pluginMayOpenNewTab = false; if (tEvent.m_type == Platform::TouchEvent::TouchStart) { d->clearCachedHitTestResult(); d->m_touchEventHandler->doFatFingers(tEvent.m_points[0]); Element* elementUnderFatFinger = d->m_touchEventHandler->lastFatFingersResult().nodeAsElementIfApplicable(); if (elementUnderFatFinger) d->m_touchEventHandler->drawTapHighlight(); } bool handled = false; if (!event.m_type != Platform::TouchEvent::TouchInjected) handled = d->m_mainFrame->eventHandler()->handleTouchEvent(PlatformTouchEvent(&tEvent)); if (d->m_preventDefaultOnTouchStart) { if (tEvent.m_type == Platform::TouchEvent::TouchEnd || tEvent.m_type == Platform::TouchEvent::TouchCancel) d->m_preventDefaultOnTouchStart = false; return true; } if (handled) { if (tEvent.m_type == Platform::TouchEvent::TouchStart) d->m_preventDefaultOnTouchStart = true; return true; } if (event.isTouchHold()) d->m_touchEventHandler->doFatFingers(tEvent.m_points[0]); #endif return false; } 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: image_transform_png_set_tRNS_to_alpha_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* We don't know yet whether there will be a tRNS chunk, but we know that * this transformation should do nothing if there already is an alpha * channel. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } CWE ID: Target: 1 Example 2: Code: void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame, const blink::WebString& title, blink::WebTextDirection direction) { DCHECK(!frame_ || frame_ == frame); if (!frame->parent()) { base::string16 title16 = title; base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel( routing_id_, base::UTF16ToUTF8(title16)); base::string16 shortened_title = title16.substr(0, kMaxTitleChars); Send(new FrameHostMsg_UpdateTitle(routing_id_, shortened_title, direction)); } UpdateEncoding(frame, frame->view()->pageEncoding().utf8()); } 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 ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(RenderProcessHost::FromID(worker_process_id_), nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void serialize(const char* url) { WebURLRequest urlRequest; urlRequest.initialize(); urlRequest.setURL(KURL(m_baseUrl, url)); m_webViewImpl->mainFrame()->loadRequest(urlRequest); Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests(); runPendingTasks(); Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests(); PageSerializer serializer(&m_resources, m_rewriteURLs.isEmpty() ? 0: &m_rewriteURLs, m_rewriteFolder); serializer.serialize(m_webViewImpl->mainFrameImpl()->frame()->page()); } CWE ID: CWE-119 Target: 1 Example 2: Code: MockQuotaManagerProxy() : QuotaManagerProxy(NULL, NULL) {} CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: sg_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 (unlikely(iov_count > MAX_UIOVEC)) return -EINVAL; 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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodReturningSequence(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = jsArray(exec, castedThis->globalObject(), impl->methodReturningSequence(intArg)); return JSValue::encode(result); } CWE ID: CWE-20 Target: 1 Example 2: Code: void ResourceDispatcherHostImpl::MaybeUpdateUploadProgress( ResourceRequestInfoImpl *info, net::URLRequest *request) { if (!info->GetUploadSize() || info->waiting_for_upload_progress_ack()) return; uint64 size = info->GetUploadSize(); uint64 position = request->GetUploadProgress(); if (position == info->last_upload_position()) return; // no progress made since last time const uint64 kHalfPercentIncrements = 200; const TimeDelta kOneSecond = TimeDelta::FromMilliseconds(1000); uint64 amt_since_last = position - info->last_upload_position(); TimeDelta time_since_last = TimeTicks::Now() - info->last_upload_ticks(); bool is_finished = (size == position); bool enough_new_progress = (amt_since_last > (size / kHalfPercentIncrements)); bool too_much_time_passed = time_since_last > kOneSecond; if (is_finished || enough_new_progress || too_much_time_passed) { if (request->load_flags() & net::LOAD_ENABLE_UPLOAD_PROGRESS) { info->resource_handler()->OnUploadProgress(info->GetRequestID(), position, size); info->set_waiting_for_upload_progress_ack(true); } info->set_last_upload_ticks(TimeTicks::Now()); info->set_last_upload_position(position); } } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static const char *aac_info(struct Scsi_Host *shost) { struct aac_dev *dev = (struct aac_dev *)shost->hostdata; return aac_drivers[dev->cardtype].name; } 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: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int update_palette256(VGACommonState *s) { int full_update, i; uint32_t v, col, *palette; full_update = 0; palette = s->last_palette; v = 0; for(i = 0; i < 256; i++) { if (s->dac_8bit) { col = rgb_to_pixel32(s->palette[v], s->palette[v + 1], s->palette[v + 2]); } else { col = rgb_to_pixel32(c6_to_8(s->palette[v]), c6_to_8(s->palette[v + 1]), c6_to_8(s->palette[v + 2])); } if (col != palette[i]) { full_update = 1; palette[i] = col; } v += 3; } return full_update; } 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: inline HarfBuzzShaper::HarfBuzzRun::HarfBuzzRun(const HarfBuzzRun& rhs) : m_fontData(rhs.m_fontData) , m_startIndex(rhs.m_startIndex) , m_numCharacters(rhs.m_numCharacters) , m_numGlyphs(rhs.m_numGlyphs) , m_direction(rhs.m_direction) , m_script(rhs.m_script) , m_glyphs(rhs.m_glyphs) , m_advances(rhs.m_advances) , m_glyphToCharacterIndexes(rhs.m_glyphToCharacterIndexes) , m_offsets(rhs.m_offsets) , m_width(rhs.m_width) { } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: status_t GraphicBuffer::unflatten( void const*& buffer, size_t& size, int const*& fds, size_t& count) { if (size < 8*sizeof(int)) return NO_MEMORY; int const* buf = static_cast<int const*>(buffer); if (buf[0] != 'GBFR') return BAD_TYPE; const size_t numFds = buf[8]; const size_t numInts = buf[9]; const size_t sizeNeeded = (10 + numInts) * sizeof(int); if (size < sizeNeeded) return NO_MEMORY; size_t fdCountNeeded = 0; if (count < fdCountNeeded) return NO_MEMORY; if (handle) { free_handle(); } if (numFds || numInts) { width = buf[1]; height = buf[2]; stride = buf[3]; format = buf[4]; usage = buf[5]; native_handle* h = native_handle_create(numFds, numInts); memcpy(h->data, fds, numFds*sizeof(int)); memcpy(h->data + numFds, &buf[10], numInts*sizeof(int)); handle = h; } else { width = height = stride = format = usage = 0; handle = NULL; } mId = static_cast<uint64_t>(buf[6]) << 32; mId |= static_cast<uint32_t>(buf[7]); mOwner = ownHandle; if (handle != 0) { status_t err = mBufferMapper.registerBuffer(handle); if (err != NO_ERROR) { width = height = stride = format = usage = 0; handle = NULL; ALOGE("unflatten: registerBuffer failed: %s (%d)", strerror(-err), err); return err; } } buffer = reinterpret_cast<void const*>(static_cast<int const*>(buffer) + sizeNeeded); size -= sizeNeeded; fds += numFds; count -= numFds; return NO_ERROR; } CWE ID: CWE-189 Target: 1 Example 2: Code: void jsvAppendPrintf(JsVar *var, const char *fmt, ...) { JsvStringIterator it; jsvStringIteratorNew(&it, var, 0); jsvStringIteratorGotoEnd(&it); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsvStringIteratorPrintfCallback,&it, fmt, argp); va_end(argp); jsvStringIteratorFree(&it); } 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 long Chapters::Atom::GetStartTime(const Chapters* pChapters) const { return GetTime(pChapters, m_start_timecode); } 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: rpl_daoack_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp; const char *dagid_str = "<elided>"; ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN); if (length < ND_RPL_DAOACK_MIN_LEN) goto tooshort; bp += ND_RPL_DAOACK_MIN_LEN; length -= ND_RPL_DAOACK_MIN_LEN; if(RPL_DAOACK_D(daoack->rpl_flags)) { ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, daoack->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]", dagid_str, daoack->rpl_daoseq, daoack->rpl_instanceid, daoack->rpl_status)); /* no officially defined options for DAOACK, but print any we find */ if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|dao-truncated]")); return; tooshort: ND_PRINT((ndo," [|dao-length too short]")); return; } CWE ID: CWE-125 Target: 1 Example 2: Code: explicit DeferredTaskSelectionCancelled(WebPagePrivate* webPagePrivate) : DeferredTaskType(webPagePrivate) { } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void InspectorPageAgent::Will(const probe::RecalculateStyle&) {} 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 GpuCommandBufferStub::OnRegisterTransferBuffer( base::SharedMemoryHandle transfer_buffer, size_t size, int32 id_request, IPC::Message* reply_message) { #if defined(OS_WIN) base::SharedMemory shared_memory(transfer_buffer, false, channel_->renderer_process()); #else #endif if (command_buffer_.get()) { int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory, size, id_request); GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message, id); } else { reply_message->set_reply_error(); } Send(reply_message); } CWE ID: Target: 1 Example 2: Code: void Layer::SetAnchorPointZ(float anchor_point_z) { DCHECK(IsPropertyChangeAllowed()); if (anchor_point_z_ == anchor_point_z) return; anchor_point_z_ = anchor_point_z; SetNeedsCommit(); } 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: status_t Parcel::writeInt32(int32_t val) { return writeAligned(val); } 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: OmniboxPopupViewGtk::OmniboxPopupViewGtk(const gfx::Font& font, OmniboxView* omnibox_view, AutocompleteEditModel* edit_model, GtkWidget* location_bar) : model_(new AutocompletePopupModel(this, edit_model)), omnibox_view_(omnibox_view), location_bar_(location_bar), window_(gtk_window_new(GTK_WINDOW_POPUP)), layout_(NULL), theme_service_(ThemeServiceGtk::GetFrom(edit_model->profile())), font_(font.DeriveFont(kEditFontAdjust)), ignore_mouse_drag_(false), opened_(false) { gtk_widget_set_can_focus(window_, FALSE); gtk_window_set_resizable(GTK_WINDOW(window_), FALSE); gtk_widget_set_app_paintable(window_, TRUE); gtk_widget_set_double_buffered(window_, TRUE); layout_ = gtk_widget_create_pango_layout(window_, NULL); pango_layout_set_auto_dir(layout_, FALSE); pango_layout_set_ellipsize(layout_, PANGO_ELLIPSIZE_END); gtk_widget_add_events(window_, GDK_BUTTON_MOTION_MASK | GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK); g_signal_connect(window_, "motion-notify-event", G_CALLBACK(HandleMotionThunk), this); g_signal_connect(window_, "button-press-event", G_CALLBACK(HandleButtonPressThunk), this); g_signal_connect(window_, "button-release-event", G_CALLBACK(HandleButtonReleaseThunk), this); g_signal_connect(window_, "expose-event", G_CALLBACK(HandleExposeThunk), this); registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED, content::Source<ThemeService>(theme_service_)); theme_service_->InitThemesFor(this); } CWE ID: CWE-399 Target: 1 Example 2: Code: renderCoTable(struct table *tbl, int maxlimit) { struct readbuffer obuf; struct html_feed_environ h_env; struct environment envs[MAX_ENV_LEVEL]; struct table *t; int i, col, row; int indent, maxwidth; if (cotable_level >= MAX_COTABLE_LEVEL) return; /* workaround to prevent infinite recursion */ cotable_level++; for (i = 0; i < tbl->ntable; i++) { t = tbl->tables[i].ptr; if (t == NULL) continue; col = tbl->tables[i].col; row = tbl->tables[i].row; indent = tbl->tables[i].indent; init_henv(&h_env, &obuf, envs, MAX_ENV_LEVEL, tbl->tables[i].buf, get_spec_cell_width(tbl, row, col), indent); check_row(tbl, row); if (h_env.limit > maxlimit) h_env.limit = maxlimit; if (t->total_width == 0) maxwidth = h_env.limit - indent; else if (t->total_width > 0) maxwidth = t->total_width; else maxwidth = t->total_width = -t->total_width * h_env.limit / 100; renderTable(t, maxwidth, &h_env); } } CWE ID: CWE-835 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PageHandler::DidDetachInterstitialPage() { if (!enabled_) return; frontend_->InterstitialHidden(); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void dma_rx(struct b43_dmaring *ring, int *slot) { const struct b43_dma_ops *ops = ring->ops; struct b43_dmadesc_generic *desc; struct b43_dmadesc_meta *meta; struct b43_rxhdr_fw4 *rxhdr; struct sk_buff *skb; u16 len; int err; dma_addr_t dmaaddr; desc = ops->idx2desc(ring, *slot, &meta); sync_descbuffer_for_cpu(ring, meta->dmaaddr, ring->rx_buffersize); skb = meta->skb; rxhdr = (struct b43_rxhdr_fw4 *)skb->data; len = le16_to_cpu(rxhdr->frame_len); if (len == 0) { int i = 0; do { udelay(2); barrier(); len = le16_to_cpu(rxhdr->frame_len); } while (len == 0 && i++ < 5); if (unlikely(len == 0)) { dmaaddr = meta->dmaaddr; goto drop_recycle_buffer; } } if (unlikely(b43_rx_buffer_is_poisoned(ring, skb))) { /* Something went wrong with the DMA. * The device did not touch the buffer and did not overwrite the poison. */ b43dbg(ring->dev->wl, "DMA RX: Dropping poisoned buffer.\n"); dmaaddr = meta->dmaaddr; goto drop_recycle_buffer; } if (unlikely(len > ring->rx_buffersize)) { /* The data did not fit into one descriptor buffer * and is split over multiple buffers. * This should never happen, as we try to allocate buffers * big enough. So simply ignore this packet. */ int cnt = 0; s32 tmp = len; while (1) { desc = ops->idx2desc(ring, *slot, &meta); /* recycle the descriptor buffer. */ b43_poison_rx_buffer(ring, meta->skb); sync_descbuffer_for_device(ring, meta->dmaaddr, ring->rx_buffersize); *slot = next_slot(ring, *slot); cnt++; tmp -= ring->rx_buffersize; if (tmp <= 0) break; } b43err(ring->dev->wl, "DMA RX buffer too small " "(len: %u, buffer: %u, nr-dropped: %d)\n", len, ring->rx_buffersize, cnt); goto drop; } dmaaddr = meta->dmaaddr; err = setup_rx_descbuffer(ring, desc, meta, GFP_ATOMIC); if (unlikely(err)) { b43dbg(ring->dev->wl, "DMA RX: setup_rx_descbuffer() failed\n"); goto drop_recycle_buffer; } unmap_descbuffer(ring, dmaaddr, ring->rx_buffersize, 0); skb_put(skb, len + ring->frameoffset); skb_pull(skb, ring->frameoffset); b43_rx(ring->dev, skb, rxhdr); drop: return; drop_recycle_buffer: /* Poison and recycle the RX buffer. */ b43_poison_rx_buffer(ring, skb); sync_descbuffer_for_device(ring, dmaaddr, ring->rx_buffersize); } CWE ID: CWE-119 Target: 1 Example 2: Code: void ieee80211_ctstoself_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const void *frame, size_t frame_len, const struct ieee80211_tx_info *frame_txctl, struct ieee80211_cts *cts) { const struct ieee80211_hdr *hdr = frame; cts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_CTS); cts->duration = ieee80211_ctstoself_duration(hw, vif, frame_len, frame_txctl); memcpy(cts->ra, hdr->addr1, sizeof(cts->ra)); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void add_bytes_l2_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w) { long i; for (i = 0; i <= w - sizeof(long); i += sizeof(long)) { long a = *(long *)(src1 + i); long b = *(long *)(src2 + i); *(long *)(dst + i) = ((a & pb_7f) + (b & pb_7f)) ^ ((a ^ b) & pb_80); } for (; i < w; i++) dst[i] = src1[i] + src2[i]; } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CorePageLoadMetricsObserver::RecordTimingHistograms( const page_load_metrics::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { if (info.started_in_foreground && info.first_background_time) { const base::TimeDelta first_background_time = info.first_background_time.value(); if (!info.time_to_commit) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforeCommit, first_background_time); } else if (!timing.first_paint || timing.first_paint > first_background_time) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforePaint, first_background_time); } if (timing.parse_start && first_background_time >= timing.parse_start && (!timing.parse_stop || timing.parse_stop > first_background_time)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundDuringParse, first_background_time); } } if (failed_provisional_load_info_.error != net::OK) { DCHECK(failed_provisional_load_info_.interval); if (WasStartedInForegroundOptionalEventInForeground( failed_provisional_load_info_.interval, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFailedProvisionalLoad, failed_provisional_load_info_.interval.value()); } } if (!info.time_to_commit || timing.IsEmpty()) return; const base::TimeDelta time_to_commit = info.time_to_commit.value(); if (WasStartedInForegroundOptionalEventInForeground(info.time_to_commit, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramCommit, time_to_commit); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramCommit, time_to_commit); } if (timing.dom_content_loaded_event_start) { if (WasStartedInForegroundOptionalEventInForeground( timing.dom_content_loaded_event_start, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramDomContentLoaded, timing.dom_content_loaded_event_start.value()); PAGE_LOAD_HISTOGRAM(internal::kHistogramDomLoadingToDomContentLoaded, timing.dom_content_loaded_event_start.value() - timing.dom_loading.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramDomContentLoaded, timing.dom_content_loaded_event_start.value()); } } if (timing.load_event_start) { if (WasStartedInForegroundOptionalEventInForeground(timing.load_event_start, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramLoad, timing.load_event_start.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramLoad, timing.load_event_start.value()); } } if (timing.first_layout) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_layout, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstLayout, timing.first_layout.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstLayout, timing.first_layout.value()); } } if (timing.first_paint) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaint, timing.first_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaint, timing.first_paint.value()); } if (!info.started_in_foreground && info.first_foreground_time && timing.first_paint > info.first_foreground_time.value() && (!info.first_background_time || timing.first_paint < info.first_background_time.value())) { PAGE_LOAD_HISTOGRAM( internal::kHistogramForegroundToFirstPaint, timing.first_paint.value() - info.first_foreground_time.value()); } } if (timing.first_text_paint) { if (WasStartedInForegroundOptionalEventInForeground(timing.first_text_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstTextPaint, timing.first_text_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstTextPaint, timing.first_text_paint.value()); } } if (timing.first_image_paint) { if (WasStartedInForegroundOptionalEventInForeground( timing.first_image_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstImagePaint, timing.first_image_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstImagePaint, timing.first_image_paint.value()); } } if (timing.first_contentful_paint) { if (WasStartedInForegroundOptionalEventInForeground( timing.first_contentful_paint, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaint, timing.first_contentful_paint.value()); if (base::TimeTicks::IsHighResolution()) { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintHigh, timing.first_contentful_paint.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintLow, timing.first_contentful_paint.value()); } PAGE_LOAD_HISTOGRAM( internal::kHistogramParseStartToFirstContentfulPaint, timing.first_contentful_paint.value() - timing.parse_start.value()); PAGE_LOAD_HISTOGRAM( internal::kHistogramDomLoadingToFirstContentfulPaint, timing.first_contentful_paint.value() - timing.dom_loading.value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstContentfulPaint, timing.first_contentful_paint.value()); } } if (timing.parse_start) { if (WasParseInForeground(timing.parse_start, timing.parse_stop, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramParseBlockedOnScriptLoad, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal::kHistogramParseBlockedOnScriptLoadDocumentWrite, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } else { PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoad, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoadDocumentWrite, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } } if (timing.parse_stop) { base::TimeDelta parse_duration = timing.parse_stop.value() - timing.parse_start.value(); if (WasStartedInForegroundOptionalEventInForeground(timing.parse_stop, info)) { PAGE_LOAD_HISTOGRAM(internal::kHistogramParseDuration, parse_duration); PAGE_LOAD_HISTOGRAM( internal::kHistogramParseBlockedOnScriptLoadParseComplete, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal:: kHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } else { PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramParseDuration, parse_duration); PAGE_LOAD_HISTOGRAM( internal::kBackgroundHistogramParseBlockedOnScriptLoadParseComplete, timing.parse_blocked_on_script_load_duration.value()); PAGE_LOAD_HISTOGRAM( internal:: kBackgroundHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete, timing.parse_blocked_on_script_load_from_document_write_duration .value()); } } if (info.started_in_foreground) { if (info.first_background_time) PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstBackground, info.first_background_time.value()); } else { if (info.first_foreground_time) PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstForeground, info.first_foreground_time.value()); } } CWE ID: Target: 1 Example 2: Code: static int cm_migrate(struct ib_cm_id *cm_id) { struct cm_id_private *cm_id_priv; unsigned long flags; int ret = 0; cm_id_priv = container_of(cm_id, struct cm_id_private, id); spin_lock_irqsave(&cm_id_priv->lock, flags); if (cm_id->state == IB_CM_ESTABLISHED && (cm_id->lap_state == IB_CM_LAP_UNINIT || cm_id->lap_state == IB_CM_LAP_IDLE)) { cm_id->lap_state = IB_CM_LAP_IDLE; cm_id_priv->av = cm_id_priv->alt_av; } else ret = -EINVAL; spin_unlock_irqrestore(&cm_id_priv->lock, flags); 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: bool V8WindowShell::installDOMWindow() { DOMWrapperWorld::setInitializingWindow(true); DOMWindow* window = m_frame->domWindow(); v8::Local<v8::Object> windowWrapper = V8ObjectConstructor::newInstance(V8PerContextData::from(m_context.newLocal(m_isolate))->constructorForType(&V8Window::info)); if (windowWrapper.IsEmpty()) return false; V8Window::installPerContextEnabledProperties(windowWrapper, window, m_isolate); V8DOMWrapper::setNativeInfo(v8::Handle<v8::Object>::Cast(windowWrapper->GetPrototype()), &V8Window::info, window); v8::Handle<v8::Object> innerGlobalObject = toInnerGlobalObject(m_context.newLocal(m_isolate)); V8DOMWrapper::setNativeInfo(innerGlobalObject, &V8Window::info, window); innerGlobalObject->SetPrototype(windowWrapper); V8DOMWrapper::associateObjectWithWrapper<V8Window>(PassRefPtr<DOMWindow>(window), &V8Window::info, windowWrapper, m_isolate, WrapperConfiguration::Dependent); DOMWrapperWorld::setInitializingWindow(false); return true; } 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: OMX_ERRORTYPE SoftAAC2::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 0) { return OMX_ErrorUndefined; } aacParams->nBitRate = 0; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = mIsADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; if (!isConfigured()) { aacParams->nChannels = 1; aacParams->nSampleRate = 44100; aacParams->nFrameLength = 0; } else { aacParams->nChannels = mStreamInfo->numChannels; aacParams->nSampleRate = mStreamInfo->sampleRate; aacParams->nFrameLength = mStreamInfo->frameSize; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->eChannelMapping[2] = OMX_AUDIO_ChannelCF; pcmParams->eChannelMapping[3] = OMX_AUDIO_ChannelLFE; pcmParams->eChannelMapping[4] = OMX_AUDIO_ChannelLS; pcmParams->eChannelMapping[5] = OMX_AUDIO_ChannelRS; if (!isConfigured()) { pcmParams->nChannels = 1; pcmParams->nSamplingRate = 44100; } else { pcmParams->nChannels = mStreamInfo->numChannels; pcmParams->nSamplingRate = mStreamInfo->sampleRate; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int __perf_event_overflow(struct perf_event *event, int throttle, struct perf_sample_data *data, struct pt_regs *regs) { int events = atomic_read(&event->event_limit); struct hw_perf_event *hwc = &event->hw; u64 seq; int ret = 0; /* * Non-sampling counters might still use the PMI to fold short * hardware counters, ignore those. */ if (unlikely(!is_sampling_event(event))) return 0; seq = __this_cpu_read(perf_throttled_seq); if (seq != hwc->interrupts_seq) { hwc->interrupts_seq = seq; hwc->interrupts = 1; } else { hwc->interrupts++; if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) { __this_cpu_inc(perf_throttled_count); hwc->interrupts = MAX_INTERRUPTS; perf_log_throttle(event, 0); tick_nohz_full_kick(); ret = 1; } } if (event->attr.freq) { u64 now = perf_clock(); s64 delta = now - hwc->freq_time_stamp; hwc->freq_time_stamp = now; if (delta > 0 && delta < 2*TICK_NSEC) perf_adjust_period(event, delta, hwc->last_period, true); } /* * XXX event_limit might not quite work as expected on inherited * events */ event->pending_kill = POLL_IN; if (events && atomic_dec_and_test(&event->event_limit)) { ret = 1; event->pending_kill = POLL_HUP; event->pending_disable = 1; irq_work_queue(&event->pending); } if (event->overflow_handler) event->overflow_handler(event, data, regs); else perf_event_output(event, data, regs); if (event->fasync && event->pending_kill) { event->pending_wakeup = 1; irq_work_queue(&event->pending); } 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: void WriteFromUrlOperation::VerifyDownloadCompare( const base::Closure& continuation, const std::string& download_hash) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (download_hash != hash_) { Error(error::kDownloadHashError); return; } BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind( &WriteFromUrlOperation::VerifyDownloadComplete, this, continuation)); } 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 gss_iakerbmechglue_init(void) { struct gss_mech_config mech_iakerb; struct gss_config iakerb_mechanism = krb5_mechanism; /* IAKERB mechanism mirrors krb5, but with different context SPIs */ iakerb_mechanism.gss_accept_sec_context = iakerb_gss_accept_sec_context; iakerb_mechanism.gss_init_sec_context = iakerb_gss_init_sec_context; iakerb_mechanism.gss_delete_sec_context = iakerb_gss_delete_sec_context; iakerb_mechanism.gss_acquire_cred = iakerb_gss_acquire_cred; iakerb_mechanism.gssspi_acquire_cred_with_password = iakerb_gss_acquire_cred_with_password; memset(&mech_iakerb, 0, sizeof(mech_iakerb)); mech_iakerb.mech = &iakerb_mechanism; mech_iakerb.mechNameStr = "iakerb"; mech_iakerb.mech_type = (gss_OID)gss_mech_iakerb; gssint_register_mechinfo(&mech_iakerb); return 0; } CWE ID: CWE-18 Target: 1 Example 2: Code: struct fib6_node * fib6_locate(struct fib6_node *root, const struct in6_addr *daddr, int dst_len, const struct in6_addr *saddr, int src_len) { struct fib6_node *fn; fn = fib6_locate_1(root, daddr, dst_len, offsetof(struct rt6_info, rt6i_dst)); #ifdef CONFIG_IPV6_SUBTREES if (src_len) { WARN_ON(saddr == NULL); if (fn && fn->subtree) fn = fib6_locate_1(fn->subtree, saddr, src_len, offsetof(struct rt6_info, rt6i_src)); } #endif if (fn && fn->fn_flags & RTN_RTINFO) return fn; return NULL; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionCode& ec) { if (!m_start.container()) { ec = INVALID_STATE_ERR; return 0; } Node* element = m_start.container()->isElementNode() ? m_start.container() : m_start.container()->parentNode(); if (!element || !element->isHTMLElement()) { ec = NOT_SUPPORTED_ERR; return 0; } RefPtr<DocumentFragment> fragment = createDocumentFragmentForElement(markup, toElement(element), AllowScriptingContentAndDoNotMarkAlreadyStarted); if (!fragment) { ec = NOT_SUPPORTED_ERR; return 0; } return fragment.release(); } 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: fst_get_iface(struct fst_card_info *card, struct fst_port_info *port, struct ifreq *ifr) { sync_serial_settings sync; int i; /* First check what line type is set, we'll default to reporting X.21 * if nothing is set as IF_IFACE_SYNC_SERIAL implies it can't be * changed */ switch (port->hwif) { case E1: ifr->ifr_settings.type = IF_IFACE_E1; break; case T1: ifr->ifr_settings.type = IF_IFACE_T1; break; case V35: ifr->ifr_settings.type = IF_IFACE_V35; break; case V24: ifr->ifr_settings.type = IF_IFACE_V24; break; case X21D: ifr->ifr_settings.type = IF_IFACE_X21D; break; case X21: default: ifr->ifr_settings.type = IF_IFACE_X21; break; } if (ifr->ifr_settings.size == 0) { return 0; /* only type requested */ } if (ifr->ifr_settings.size < sizeof (sync)) { return -ENOMEM; } i = port->index; sync.clock_rate = FST_RDL(card, portConfig[i].lineSpeed); /* Lucky card and linux use same encoding here */ sync.clock_type = FST_RDB(card, portConfig[i].internalClock) == INTCLK ? CLOCK_INT : CLOCK_EXT; sync.loopback = 0; if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &sync, sizeof (sync))) { return -EFAULT; } ifr->ifr_settings.size = sizeof (sync); return 0; } CWE ID: CWE-399 Target: 1 Example 2: Code: void GLES2DecoderImpl::SetIgnoreCachedStateForTest(bool ignore) { state_.SetIgnoreCachedStateForTest(ignore); } 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 get_frame_stats(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, vpx_fixed_buf_t *stats) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, "Failed to get frame stats."); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_STATS_PKT) { const uint8_t *const pkt_buf = pkt->data.twopass_stats.buf; const size_t pkt_size = pkt->data.twopass_stats.sz; stats->buf = realloc(stats->buf, stats->sz + pkt_size); memcpy((uint8_t *)stats->buf + stats->sz, pkt_buf, pkt_size); stats->sz += pkt_size; } } } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool SubsetterImpl::ResolveCompositeGlyphs(const unsigned int* glyph_ids, size_t glyph_count, IntegerSet* glyph_id_processed) { if (glyph_ids == NULL || glyph_count == 0 || glyph_id_processed == NULL) { return false; } GlyphTablePtr glyph_table = down_cast<GlyphTable*>(font_->GetTable(Tag::glyf)); LocaTablePtr loca_table = down_cast<LocaTable*>(font_->GetTable(Tag::loca)); if (glyph_table == NULL || loca_table == NULL) { return false; } IntegerSet glyph_id_remaining; glyph_id_remaining.insert(0); // Always include glyph id 0. for (size_t i = 0; i < glyph_count; ++i) { glyph_id_remaining.insert(glyph_ids[i]); } while (!glyph_id_remaining.empty()) { IntegerSet comp_glyph_id; for (IntegerSet::iterator i = glyph_id_remaining.begin(), e = glyph_id_remaining.end(); i != e; ++i) { if (*i < 0 || *i >= loca_table->NumGlyphs()) { continue; } int32_t length = loca_table->GlyphLength(*i); if (length == 0) { continue; } int32_t offset = loca_table->GlyphOffset(*i); GlyphPtr glyph; glyph.Attach(glyph_table->GetGlyph(offset, length)); if (glyph == NULL) { continue; } if (glyph->GlyphType() == GlyphType::kComposite) { Ptr<GlyphTable::CompositeGlyph> comp_glyph = down_cast<GlyphTable::CompositeGlyph*>(glyph.p_); for (int32_t j = 0; j < comp_glyph->NumGlyphs(); ++j) { int32_t glyph_id = comp_glyph->GlyphIndex(j); if (glyph_id_processed->find(glyph_id) == glyph_id_processed->end() && glyph_id_remaining.find(glyph_id) == glyph_id_remaining.end()) { comp_glyph_id.insert(comp_glyph->GlyphIndex(j)); } } } glyph_id_processed->insert(*i); } glyph_id_remaining.clear(); glyph_id_remaining = comp_glyph_id; } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void bond_miimon_commit(struct bonding *bond) { struct slave *slave; int i; bond_for_each_slave(bond, slave, i) { switch (slave->new_link) { case BOND_LINK_NOCHANGE: continue; case BOND_LINK_UP: slave->link = BOND_LINK_UP; slave->jiffies = jiffies; if (bond->params.mode == BOND_MODE_8023AD) { /* prevent it from being the active one */ bond_set_backup_slave(slave); } else if (bond->params.mode != BOND_MODE_ACTIVEBACKUP) { /* make it immediately active */ bond_set_active_slave(slave); } else if (slave != bond->primary_slave) { /* prevent it from being the active one */ bond_set_backup_slave(slave); } bond_update_speed_duplex(slave); pr_info("%s: link status definitely up for interface %s, %u Mbps %s duplex.\n", bond->dev->name, slave->dev->name, slave->speed, slave->duplex ? "full" : "half"); /* notify ad that the link status has changed */ if (bond->params.mode == BOND_MODE_8023AD) bond_3ad_handle_link_change(slave, BOND_LINK_UP); if (bond_is_lb(bond)) bond_alb_handle_link_change(bond, slave, BOND_LINK_UP); if (!bond->curr_active_slave || (slave == bond->primary_slave)) goto do_failover; continue; case BOND_LINK_DOWN: if (slave->link_failure_count < UINT_MAX) slave->link_failure_count++; slave->link = BOND_LINK_DOWN; if (bond->params.mode == BOND_MODE_ACTIVEBACKUP || bond->params.mode == BOND_MODE_8023AD) bond_set_slave_inactive_flags(slave); pr_info("%s: link status definitely down for interface %s, disabling it\n", bond->dev->name, slave->dev->name); if (bond->params.mode == BOND_MODE_8023AD) bond_3ad_handle_link_change(slave, BOND_LINK_DOWN); if (bond_is_lb(bond)) bond_alb_handle_link_change(bond, slave, BOND_LINK_DOWN); if (slave == bond->curr_active_slave) goto do_failover; continue; default: pr_err("%s: invalid new link %d on slave %s\n", bond->dev->name, slave->new_link, slave->dev->name); slave->new_link = BOND_LINK_NOCHANGE; continue; } do_failover: ASSERT_RTNL(); block_netpoll_tx(); write_lock_bh(&bond->curr_slave_lock); bond_select_active_slave(bond); write_unlock_bh(&bond->curr_slave_lock); unblock_netpoll_tx(); } bond_set_carrier(bond); } 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: ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintSettingsInitializerWin::InitPrintSettings( HDC hdc, const DEVMODE& dev_mode, const PageRanges& new_ranges, const std::wstring& new_device_name, bool print_selection_only, PrintSettings* print_settings) { DCHECK(hdc); DCHECK(print_settings); print_settings->set_printer_name(dev_mode.dmDeviceName); print_settings->set_device_name(new_device_name); print_settings->ranges = new_ranges; print_settings->set_landscape(dev_mode.dmOrientation == DMORIENT_LANDSCAPE); print_settings->selection_only = print_selection_only; int dpi = GetDeviceCaps(hdc, LOGPIXELSX); print_settings->set_dpi(dpi); const int kAlphaCaps = SB_CONST_ALPHA | SB_PIXEL_ALPHA; print_settings->set_supports_alpha_blend( (GetDeviceCaps(hdc, SHADEBLENDCAPS) & kAlphaCaps) == kAlphaCaps); DCHECK_EQ(dpi, GetDeviceCaps(hdc, LOGPIXELSY)); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); gfx::Size physical_size_device_units(GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT)); gfx::Rect printable_area_device_units(GetDeviceCaps(hdc, PHYSICALOFFSETX), GetDeviceCaps(hdc, PHYSICALOFFSETY), GetDeviceCaps(hdc, HORZRES), GetDeviceCaps(hdc, VERTRES)); print_settings->SetPrinterPrintableArea(physical_size_device_units, printable_area_device_units, dpi); } CWE ID: CWE-399 Target: 1 Example 2: Code: link_info_done (NautilusDirectory *directory, NautilusFile *file, const char *uri, const char *name, GIcon *icon, gboolean is_launcher, gboolean is_foreign) { gboolean is_trusted; file->details->link_info_is_up_to_date = TRUE; is_trusted = is_link_trusted (file, is_launcher); if (is_trusted) { nautilus_file_set_display_name (file, name, name, TRUE); } else { nautilus_file_set_display_name (file, NULL, NULL, TRUE); } file->details->got_link_info = TRUE; g_clear_object (&file->details->custom_icon); if (uri) { g_free (file->details->activation_uri); file->details->activation_uri = NULL; file->details->got_custom_activation_uri = TRUE; file->details->activation_uri = g_strdup (uri); } if (is_trusted && (icon != NULL)) { file->details->custom_icon = g_object_ref (icon); } file->details->is_launcher = is_launcher; file->details->is_foreign_link = is_foreign; file->details->is_trusted_link = is_trusted; nautilus_directory_async_state_changed (directory); } 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 WallpaperManager::SetDefaultWallpaperPath( const base::FilePath& default_small_wallpaper_file, std::unique_ptr<gfx::ImageSkia> small_wallpaper_image, const base::FilePath& default_large_wallpaper_file, std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) { default_small_wallpaper_file_ = default_small_wallpaper_file; default_large_wallpaper_file_ = default_large_wallpaper_file; ash::WallpaperController* controller = ash::Shell::Get()->wallpaper_controller(); const bool need_update_screen = default_wallpaper_image_.get() && controller->WallpaperIsAlreadyLoaded(default_wallpaper_image_->image(), false /* compare_layouts */, wallpaper::WALLPAPER_LAYOUT_CENTER); default_wallpaper_image_.reset(); if (GetAppropriateResolution() == WALLPAPER_RESOLUTION_SMALL) { if (small_wallpaper_image) { default_wallpaper_image_.reset( new user_manager::UserImage(*small_wallpaper_image)); default_wallpaper_image_->set_file_path(default_small_wallpaper_file); } } else { if (large_wallpaper_image) { default_wallpaper_image_.reset( new user_manager::UserImage(*large_wallpaper_image)); default_wallpaper_image_->set_file_path(default_large_wallpaper_file); } } if (need_update_screen) DoSetDefaultWallpaper(EmptyAccountId(), MovableOnDestroyCallbackHolder()); } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep) { std::string idx = request::findValue(&req, "idx"); if (idx == "") { return; } std::vector<std::vector<std::string> > result; result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%s", idx.c_str()); if (result.empty()) return; reply::set_content(&rep, result[0][0].begin(), result[0][0].end()); std::string oname = "floorplan"; if (result[0][0].size() > 10) { if (result[0][0][0] == 'P') oname += ".png"; else if (result[0][0][0] == -1) oname += ".jpg"; else if (result[0][0][0] == 'B') oname += ".bmp"; else if (result[0][0][0] == 'G') oname += ".gif"; } reply::add_header_attachment(&rep, oname); } CWE ID: CWE-89 Target: 1 Example 2: Code: static int t1_getbyte(void) { int c = t1_getchar(); if (t1_pfa) return c; if (t1_block_length == 0) { if (c != 128) normal_error("type 1","invalid marker"); c = t1_getchar(); if (c == 3) { while (!t1_eof()) (void) t1_getchar(); return EOF; } t1_block_length = t1_getchar() & 0xff; t1_block_length |= (t1_getchar() & 0xff) << 8; t1_block_length |= (t1_getchar() & 0xff) << 16; t1_block_length |= (t1_getchar() & 0xff) << 24; c = t1_getchar(); } t1_block_length--; return c; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AsyncPixelTransfersCompletedQuery::End( base::subtle::Atomic32 submit_count) { AsyncMemoryParams mem_params; Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id()); if (!buffer.shared_memory) return false; mem_params.shared_memory = buffer.shared_memory; mem_params.shm_size = buffer.size; mem_params.shm_data_offset = shm_offset(); mem_params.shm_data_size = sizeof(QuerySync); observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count); manager()->decoder()->GetAsyncPixelTransferManager() ->AsyncNotifyCompletion(mem_params, observer_); return AddToPendingTransferQueue(submit_count); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=MagickMin(quantum/number_coordinates,BezierQuantum); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } CWE ID: Target: 1 Example 2: Code: quantifiers_memory_node_info(Node* node) { int r = BODY_IS_EMPTY; switch (NODE_TYPE(node)) { case NODE_LIST: case NODE_ALT: { int v; do { v = quantifiers_memory_node_info(NODE_CAR(node)); if (v > r) r = v; } while (IS_NOT_NULL(node = NODE_CDR(node))); } break; #ifdef USE_CALL case NODE_CALL: if (NODE_IS_RECURSION(node)) { return BODY_IS_EMPTY_REC; /* tiny version */ } else r = quantifiers_memory_node_info(NODE_BODY(node)); break; #endif case NODE_QUANT: { QuantNode* qn = QUANT_(node); if (qn->upper != 0) { r = quantifiers_memory_node_info(NODE_BODY(node)); } } break; case NODE_BAG: { BagNode* en = BAG_(node); switch (en->type) { case BAG_MEMORY: if (NODE_IS_RECURSION(node)) { return BODY_IS_EMPTY_REC; } return BODY_IS_EMPTY_MEM; break; case BAG_OPTION: case BAG_STOP_BACKTRACK: r = quantifiers_memory_node_info(NODE_BODY(node)); break; case BAG_IF_ELSE: { int v; r = quantifiers_memory_node_info(NODE_BODY(node)); if (IS_NOT_NULL(en->te.Then)) { v = quantifiers_memory_node_info(en->te.Then); if (v > r) r = v; } if (IS_NOT_NULL(en->te.Else)) { v = quantifiers_memory_node_info(en->te.Else); if (v > r) r = v; } } break; } } break; case NODE_BACKREF: case NODE_STRING: case NODE_CTYPE: case NODE_CCLASS: case NODE_ANCHOR: case NODE_GIMMICK: default: break; } return r; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: const BlockEntry* Cues::GetBlock( const CuePoint* pCP, const CuePoint::TrackPosition* pTP) const { if (pCP == NULL) return NULL; if (pTP == NULL) return NULL; return m_pSegment->GetBlock(*pCP, *pTP); } 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: pch_write_line (lin line, FILE *file) { bool after_newline = p_line[line][p_len[line] - 1] == '\n'; if (! fwrite (p_line[line], sizeof (*p_line[line]), p_len[line], file)) write_fatal (); return after_newline; } CWE ID: CWE-119 Target: 1 Example 2: Code: const gfx::Transform& LayerTreeHostImpl::DrawTransform() const { return external_transform_; } 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 XfrmController::fillNlAttrXfrmMark(const XfrmId& record, nlattr_xfrm_mark* mark) { mark->mark.v = record.mark.v; // set to 0 if it's not used mark->mark.m = record.mark.m; // set to 0 if it's not used int len = NLA_HDRLEN + sizeof(xfrm_mark); fillXfrmNlaHdr(&mark->hdr, XFRMA_MARK, len); return len; } CWE ID: CWE-909 Output:
0
Here are some example code snippets. Analyze the following 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 rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); assert(send_buf != NULL); } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; } CWE ID: CWE-190 Target: 1 Example 2: Code: Ins_DIV( INS_ARG ) { DO_DIV } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int id_create(void *ptr) { static int id = 0; id_link(++id, ptr); return id; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PixelBufferRasterWorkerPool::OnRasterTasksFinished() { if (!should_notify_client_if_no_tasks_are_pending_) return; CheckForCompletedRasterTasks(); } CWE ID: CWE-20 Target: 1 Example 2: Code: void Document::removeFromTopLayer(Element* element) { if (!element->isInTopLayer()) return; size_t position = m_topLayerElements.find(element); ASSERT(position != notFound); m_topLayerElements.remove(position); element->setIsInTopLayer(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: static CURLcode smtp_connect(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; struct smtp_conn *smtpc = &conn->proto.smtpc; struct pingpong *pp = &smtpc->pp; *done = FALSE; /* default to not done yet */ /* We always support persistent connections in SMTP */ connkeep(conn, "SMTP default"); /* Set the default response time-out */ pp->response_time = RESP_TIMEOUT; pp->statemach_act = smtp_statemach_act; pp->endofresp = smtp_endofresp; pp->conn = conn; /* Initialize the SASL storage */ Curl_sasl_init(&smtpc->sasl, &saslsmtp); /* Initialise the pingpong layer */ Curl_pp_init(pp); /* Parse the URL options */ result = smtp_parse_url_options(conn); if(result) return result; /* Parse the URL path */ result = smtp_parse_url_path(conn); if(result) return result; /* Start off waiting for the server greeting response */ state(conn, SMTP_SERVERGREET); result = smtp_multi_statemach(conn, done); return result; } 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 size_t php_stream_temp_read(php_stream *stream, char *buf, size_t count TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; size_t got; assert(ts != NULL); if (!ts->innerstream) { return -1; } got = php_stream_read(ts->innerstream, buf, count); stream->eof = ts->innerstream->eof; return got; } CWE ID: CWE-20 Target: 1 Example 2: Code: virDomainMigrateFinish3(virConnectPtr dconn, const char *dname, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *dconnuri, const char *uri, unsigned long flags, int cancelled) { VIR_DEBUG("dconn=%p, dname=%s, cookiein=%p, cookieinlen=%d, cookieout=%p," "cookieoutlen=%p, dconnuri=%s, uri=%s, flags=%lx, retcode=%d", dconn, NULLSTR(dname), cookiein, cookieinlen, cookieout, cookieoutlen, NULLSTR(dconnuri), NULLSTR(uri), flags, cancelled); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish3) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish3(dconn, dname, cookiein, cookieinlen, cookieout, cookieoutlen, dconnuri, uri, flags, cancelled); if (!ret && !cancelled) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int em_sbb(struct x86_emulate_ctxt *ctxt) { emulate_2op_SrcV(ctxt, "sbb"); return X86EMUL_CONTINUE; } 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: FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetExternalFileEntry", base::Bind(&FileBrowserHandlerCustomBindings::GetExternalFileEntry, base::Unretained(this))); RouteFunction("GetEntryURL", base::Bind(&FileBrowserHandlerCustomBindings::GetEntryURL, base::Unretained(this))); } CWE ID: Target: 1 Example 2: Code: void Document::executeScriptsWaitingForResourcesIfNeeded() { if (!haveStylesheetsAndImportsLoaded()) return; if (ScriptableDocumentParser* parser = scriptableDocumentParser()) parser->executeScriptsWaitingForResources(); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int comedi_fasync(int fd, struct file *file, int on) { const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_device *dev = dev_file_info->device; return fasync_helper(fd, file, on, &dev->async_queue); } 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: file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } } CWE ID: CWE-476 Target: 1 Example 2: Code: Browser::~Browser() { if (profile_->GetProfileSyncService()) profile_->GetProfileSyncService()->RemoveObserver(this); BrowserList::RemoveBrowser(this); #if !defined(OS_MACOSX) if (!BrowserList::HasBrowserWithProfile(profile_)) { TabRestoreServiceFactory::ResetForProfile(profile_); } #endif SessionService* session_service = SessionServiceFactory::GetForProfile(profile_); if (session_service) session_service->WindowClosed(session_id_); TabRestoreService* tab_restore_service = TabRestoreServiceFactory::GetForProfile(profile()); if (tab_restore_service) tab_restore_service->BrowserClosed(tab_restore_service_delegate()); profile_pref_registrar_.RemoveAll(); local_pref_registrar_.RemoveAll(); encoding_auto_detect_.Destroy(); use_vertical_tabs_.Destroy(); use_compact_navigation_bar_.Destroy(); if (profile_->IsOffTheRecord() && !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) { profile_->GetOriginalProfile()->DestroyOffTheRecordProfile(); } if (select_file_dialog_.get()) select_file_dialog_->ListenerDestroyed(); TabRestoreServiceDestroyed(tab_restore_service_); } 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: Accelerator GetAccelerator(KeyboardCode code, int mask) { return Accelerator(code, mask & (1 << 0), mask & (1 << 1), mask & (1 << 2)); } 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: ztype(i_ctx_t *i_ctx_p) { os_ptr op = osp; ref tnref; int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref); if (code < 0) return code; if (!r_has_type(&tnref, t_name)) { /* Must be either a stack underflow or a t_[a]struct. */ check_op(2); { /* Get the type name from the structure. */ if (op[-1].value.pstruct != 0x00) { const char *sname = gs_struct_type_name_string(gs_object_type(imemory, op[-1].value.pstruct)); int code = name_ref(imemory, (const byte *)sname, strlen(sname), (ref *) (op - 1), 0); if (code < 0) return code; } else return_error(gs_error_stackunderflow); } r_set_attrs(op - 1, a_executable); } else { ref_assign(op - 1, &tnref); } pop(1); return 0; } CWE ID: CWE-704 Target: 1 Example 2: Code: static future_t *clean_up(void) { gki_buffer_cleanup(); pthread_mutex_destroy(&gki_cb.lock); return NULL; } 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 target_revfn(u8 af, const char *name, u8 revision, int *bestp) { const struct xt_target *t; int have_rev = 0; list_for_each_entry(t, &xt[af].target, list) { if (strcmp(t->name, name) == 0) { if (t->revision > *bestp) *bestp = t->revision; if (t->revision == revision) have_rev = 1; } } if (af != NFPROTO_UNSPEC && !have_rev) return target_revfn(NFPROTO_UNSPEC, name, revision, bestp); return have_rev; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int chacha20_poly1305_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_CHACHA_AEAD_CTX *actx = aead_data(ctx); switch(type) { case EVP_CTRL_INIT: if (actx == NULL) actx = ctx->cipher_data = OPENSSL_zalloc(sizeof(*actx) + Poly1305_ctx_size()); if (actx == NULL) { EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_INITIALIZATION_ERROR); return 0; } actx->len.aad = 0; actx->len.text = 0; actx->aad = 0; actx->mac_inited = 0; actx->tag_len = 0; actx->nonce_len = 12; actx->tls_payload_length = NO_TLS_PAYLOAD_LENGTH; return 1; case EVP_CTRL_COPY: if (actx) { EVP_CIPHER_CTX *dst = (EVP_CIPHER_CTX *)ptr; dst->cipher_data = OPENSSL_memdup(actx, sizeof(*actx) + Poly1305_ctx_size()); if (dst->cipher_data == NULL) { EVPerr(EVP_F_CHACHA20_POLY1305_CTRL, EVP_R_COPY_ERROR); return 0; } } return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0 || arg > CHACHA_CTR_SIZE) return 0; actx->nonce_len = arg; return 1; case EVP_CTRL_AEAD_SET_IV_FIXED: if (arg != 12) return 0; actx->nonce[0] = actx->key.counter[1] = CHACHA_U8TOU32((unsigned char *)ptr); actx->nonce[1] = actx->key.counter[2] = CHACHA_U8TOU32((unsigned char *)ptr+4); actx->nonce[2] = actx->key.counter[3] = CHACHA_U8TOU32((unsigned char *)ptr+8); return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE) return 0; if (ptr != NULL) { memcpy(actx->tag, ptr, arg); actx->tag_len = arg; } return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > POLY1305_BLOCK_SIZE || !ctx->encrypt) return 0; memcpy(ptr, actx->tag, arg); return 1; case EVP_CTRL_AEAD_TLS1_AAD: if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; { unsigned int len; unsigned char *aad = ptr, temp[POLY1305_BLOCK_SIZE]; len = aad[EVP_AEAD_TLS1_AAD_LEN - 2] << 8 | aad[EVP_AEAD_TLS1_AAD_LEN - 1]; if (!ctx->encrypt) { len -= POLY1305_BLOCK_SIZE; /* discount attached tag */ memcpy(temp, aad, EVP_AEAD_TLS1_AAD_LEN - 2); aad = temp; temp[EVP_AEAD_TLS1_AAD_LEN - 2] = (unsigned char)(len >> 8); temp[EVP_AEAD_TLS1_AAD_LEN - 1] = (unsigned char)len; } actx->tls_payload_length = len; /* * merge record sequence number as per * draft-ietf-tls-chacha20-poly1305-03 */ actx->key.counter[1] = actx->nonce[0]; actx->key.counter[2] = actx->nonce[1] ^ CHACHA_U8TOU32(aad); actx->key.counter[3] = actx->nonce[2] ^ CHACHA_U8TOU32(aad+4); actx->mac_inited = 0; chacha20_poly1305_cipher(ctx, NULL, aad, EVP_AEAD_TLS1_AAD_LEN); return POLY1305_BLOCK_SIZE; /* tag length */ } case EVP_CTRL_AEAD_SET_MAC_KEY: /* no-op */ return 1; default: return -1; } } CWE ID: CWE-125 Target: 1 Example 2: Code: bool SVGLayoutSupport::layoutSizeOfNearestViewportChanged(const LayoutObject* start) { for (; start; start = start->parent()) { if (start->isSVGRoot()) return toLayoutSVGRoot(start)->isLayoutSizeChanged(); if (start->isSVGViewportContainer()) return toLayoutSVGViewportContainer(start)->isLayoutSizeChanged(); } ASSERT_NOT_REACHED(); return false; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Storage::StorageType GetTypeName(storage::QuotaClient::ID id) { switch (id) { case storage::QuotaClient::kFileSystem: return Storage::StorageTypeEnum::File_systems; case storage::QuotaClient::kDatabase: return Storage::StorageTypeEnum::Websql; case storage::QuotaClient::kAppcache: return Storage::StorageTypeEnum::Appcache; case storage::QuotaClient::kIndexedDatabase: return Storage::StorageTypeEnum::Indexeddb; case storage::QuotaClient::kServiceWorkerCache: return Storage::StorageTypeEnum::Cache_storage; case storage::QuotaClient::kServiceWorker: return Storage::StorageTypeEnum::Service_workers; default: return Storage::StorageTypeEnum::Other; } } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderFrameHostImpl::OnDidAddMessageToConsole( int32_t level, const base::string16& message, int32_t line_no, const base::string16& source_id) { if (level < logging::LOG_VERBOSE || level > logging::LOG_FATAL) { bad_message::ReceivedBadMessage( GetProcess(), bad_message::RFH_DID_ADD_CONSOLE_MESSAGE_BAD_SEVERITY); return; } if (delegate_->DidAddMessageToConsole(level, message, line_no, source_id)) return; const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(level, message, line_no, is_builtin_component, is_off_the_record, source_id); } CWE ID: CWE-416 Target: 1 Example 2: Code: inline uint32_t web_client_api_request_v1_data_format(char *name) { uint32_t hash = simple_hash(name); int i; for(i = 0; api_v1_data_formats[i].name ; i++) { if (unlikely(hash == api_v1_data_formats[i].hash && !strcmp(name, api_v1_data_formats[i].name))) { return api_v1_data_formats[i].value; } } return DATASOURCE_JSON; } 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 IsNavigationTimingType( Performance::PerformanceMeasurePassedInParameterType type) { return type != Performance::kObjectObject && type != Performance::kOther; } 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: SecureProxyChecker::SecureProxyChecker( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : url_loader_factory_(std::move(url_loader_factory)) {} CWE ID: CWE-416 Target: 1 Example 2: Code: gst_vmnc_dec_sink_event (GstVideoDecoder * bdec, GstEvent * event) { const GstSegment *segment; if (GST_EVENT_TYPE (event) != GST_EVENT_SEGMENT) goto done; gst_event_parse_segment (event, &segment); if (segment->format == GST_FORMAT_TIME) gst_video_decoder_set_packetized (bdec, TRUE); else gst_video_decoder_set_packetized (bdec, FALSE); done: return GST_VIDEO_DECODER_CLASS (gst_vmnc_dec_parent_class)->sink_event (bdec, event); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void build_l4proto_icmp(const struct nf_conntrack *ct, struct nethdr *n) { ct_build_u8(ct, ATTR_ICMP_TYPE, n, NTA_ICMP_TYPE); ct_build_u8(ct, ATTR_ICMP_CODE, n, NTA_ICMP_CODE); ct_build_u16(ct, ATTR_ICMP_ID, n, NTA_ICMP_ID); ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); } CWE ID: CWE-17 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 mwifiex_update_vs_ie(const u8 *ies, int ies_len, struct mwifiex_ie **ie_ptr, u16 mask, unsigned int oui, u8 oui_type) { struct ieee_types_header *vs_ie; struct mwifiex_ie *ie = *ie_ptr; const u8 *vendor_ie; vendor_ie = cfg80211_find_vendor_ie(oui, oui_type, ies, ies_len); if (vendor_ie) { if (!*ie_ptr) { *ie_ptr = kzalloc(sizeof(struct mwifiex_ie), GFP_KERNEL); if (!*ie_ptr) return -ENOMEM; ie = *ie_ptr; } vs_ie = (struct ieee_types_header *)vendor_ie; memcpy(ie->ie_buffer + le16_to_cpu(ie->ie_length), vs_ie, vs_ie->len + 2); le16_unaligned_add_cpu(&ie->ie_length, vs_ie->len + 2); ie->mgmt_subtype_mask = cpu_to_le16(mask); ie->ie_index = cpu_to_le16(MWIFIEX_AUTO_IDX_MASK); } *ie_ptr = ie; return 0; } CWE ID: CWE-120 Target: 1 Example 2: Code: static ssize_t tun_get_user(struct tun_struct *tun, const struct iovec *iv, size_t count, int noblock) { struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) }; struct sk_buff *skb; size_t len = count, align = NET_SKB_PAD; struct virtio_net_hdr gso = { 0 }; int offset = 0; if (!(tun->flags & TUN_NO_PI)) { if ((len -= sizeof(pi)) > count) return -EINVAL; if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi))) return -EFAULT; offset += sizeof(pi); } if (tun->flags & TUN_VNET_HDR) { if ((len -= tun->vnet_hdr_sz) > count) return -EINVAL; if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso))) return -EFAULT; if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && gso.csum_start + gso.csum_offset + 2 > gso.hdr_len) gso.hdr_len = gso.csum_start + gso.csum_offset + 2; if (gso.hdr_len > len) return -EINVAL; offset += tun->vnet_hdr_sz; } if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) { align += NET_IP_ALIGN; if (unlikely(len < ETH_HLEN || (gso.hdr_len && gso.hdr_len < ETH_HLEN))) return -EINVAL; } skb = tun_alloc_skb(tun, align, len, gso.hdr_len, noblock); if (IS_ERR(skb)) { if (PTR_ERR(skb) != -EAGAIN) tun->dev->stats.rx_dropped++; return PTR_ERR(skb); } if (skb_copy_datagram_from_iovec(skb, 0, iv, offset, len)) { tun->dev->stats.rx_dropped++; kfree_skb(skb); return -EFAULT; } if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { if (!skb_partial_csum_set(skb, gso.csum_start, gso.csum_offset)) { tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } } switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: if (tun->flags & TUN_NO_PI) { switch (skb->data[0] & 0xf0) { case 0x40: pi.proto = htons(ETH_P_IP); break; case 0x60: pi.proto = htons(ETH_P_IPV6); break; default: tun->dev->stats.rx_dropped++; kfree_skb(skb); return -EINVAL; } } skb_reset_mac_header(skb); skb->protocol = pi.proto; skb->dev = tun->dev; break; case TUN_TAP_DEV: skb->protocol = eth_type_trans(skb, tun->dev); break; } if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) { pr_debug("GSO!\n"); switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) { case VIRTIO_NET_HDR_GSO_TCPV4: skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; break; case VIRTIO_NET_HDR_GSO_TCPV6: skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6; break; case VIRTIO_NET_HDR_GSO_UDP: skb_shinfo(skb)->gso_type = SKB_GSO_UDP; break; default: tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN) skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; skb_shinfo(skb)->gso_size = gso.gso_size; if (skb_shinfo(skb)->gso_size == 0) { tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } /* Header must be checked, and gso_segs computed. */ skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY; skb_shinfo(skb)->gso_segs = 0; } netif_rx_ni(skb); tun->dev->stats.rx_packets++; tun->dev->stats.rx_bytes += len; return count; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void sctp_generate_t3_rtx_event(unsigned long peer) { int error; struct sctp_transport *transport = (struct sctp_transport *) peer; struct sctp_association *asoc = transport->asoc; struct net *net = sock_net(asoc->base.sk); /* Check whether a task is in the sock. */ bh_lock_sock(asoc->base.sk); if (sock_owned_by_user(asoc->base.sk)) { pr_debug("%s: sock is busy\n", __func__); /* Try again later. */ if (!mod_timer(&transport->T3_rtx_timer, jiffies + (HZ/20))) sctp_transport_hold(transport); goto out_unlock; } /* Is this transport really dead and just waiting around for * the timer to let go of the reference? */ if (transport->dead) goto out_unlock; /* Run through the state machine. */ error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT, SCTP_ST_TIMEOUT(SCTP_EVENT_TIMEOUT_T3_RTX), asoc->state, asoc->ep, asoc, transport, GFP_ATOMIC); if (error) asoc->base.sk->sk_err = -error; out_unlock: bh_unlock_sock(asoc->base.sk); sctp_transport_put(transport); } 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 BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock) { uint8_t *buf; uint32_t len; while (packet_get_head_l(sock, &buf, &len)) { int sent = send(sock->our_fd, buf, len, MSG_DONTWAIT); if (sent == (signed)len) osi_free(buf); else if (sent >= 0) { packet_put_head_l(sock, buf + sent, len - sent); osi_free(buf); if (!sent) /* special case if other end not keeping up */ return TRUE; } else { packet_put_head_l(sock, buf, len); osi_free(buf); return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN; } } return FALSE; } CWE ID: CWE-284 Target: 1 Example 2: Code: void dev_close_many(struct list_head *head, bool unlink) { struct net_device *dev, *tmp; /* Remove the devices that don't need to be closed */ list_for_each_entry_safe(dev, tmp, head, close_list) if (!(dev->flags & IFF_UP)) list_del_init(&dev->close_list); __dev_close_many(head); list_for_each_entry_safe(dev, tmp, head, close_list) { rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL); call_netdevice_notifiers(NETDEV_DOWN, dev); if (unlink) list_del_init(&dev->close_list); } } 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 ssize_t rd_set_configfs_dev_params(struct se_device *dev, const char *page, ssize_t count) { struct rd_dev *rd_dev = RD_DEV(dev); char *orig, *ptr, *opts; substring_t args[MAX_OPT_ARGS]; int ret = 0, arg, token; opts = kstrdup(page, GFP_KERNEL); if (!opts) return -ENOMEM; orig = opts; while ((ptr = strsep(&opts, ",\n")) != NULL) { if (!*ptr) continue; token = match_token(ptr, tokens, args); switch (token) { case Opt_rd_pages: match_int(args, &arg); rd_dev->rd_page_count = arg; pr_debug("RAMDISK: Referencing Page" " Count: %u\n", rd_dev->rd_page_count); rd_dev->rd_flags |= RDF_HAS_PAGE_COUNT; break; case Opt_rd_nullio: match_int(args, &arg); if (arg != 1) break; pr_debug("RAMDISK: Setting NULLIO flag: %d\n", arg); rd_dev->rd_flags |= RDF_NULLIO; break; default: break; } } kfree(orig); return (!ret) ? count : ret; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline void x86_assign_hw_event(struct perf_event *event, struct cpu_hw_events *cpuc, int i) { struct hw_perf_event *hwc = &event->hw; hwc->idx = cpuc->assign[i]; hwc->last_cpu = smp_processor_id(); hwc->last_tag = ++cpuc->tags[i]; if (hwc->idx == X86_PMC_IDX_FIXED_BTS) { hwc->config_base = 0; hwc->event_base = 0; } else if (hwc->idx >= X86_PMC_IDX_FIXED) { hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL; hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0; } else { hwc->config_base = x86_pmu_config_addr(hwc->idx); hwc->event_base = x86_pmu_event_addr(hwc->idx); } } CWE ID: CWE-189 Target: 1 Example 2: Code: static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSbyte(int8 value) { if (value<0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } 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 DevToolsUIBindings::RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) { if (!(boundary_value >= 0 && boundary_value <= 100 && sample >= 0 && sample < boundary_value)) { frontend_host_->BadMessageRecieved(); return; } if (name == kDevToolsActionTakenHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else if (name == kDevToolsPanelShownHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else frontend_host_->BadMessageRecieved(); } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void ftrace_syscall_exit(void *data, struct pt_regs *regs, long ret) { struct trace_array *tr = data; struct ftrace_event_file *ftrace_file; struct syscall_trace_exit *entry; struct syscall_metadata *sys_data; struct ring_buffer_event *event; struct ring_buffer *buffer; unsigned long irq_flags; int pc; int syscall_nr; syscall_nr = trace_get_syscall_nr(current, regs); if (syscall_nr < 0) return; /* Here we're inside tp handler's rcu_read_lock_sched (__DO_TRACE()) */ ftrace_file = rcu_dereference_sched(tr->exit_syscall_files[syscall_nr]); if (!ftrace_file) return; if (ftrace_trigger_soft_disabled(ftrace_file)) return; sys_data = syscall_nr_to_meta(syscall_nr); if (!sys_data) return; local_save_flags(irq_flags); pc = preempt_count(); buffer = tr->trace_buffer.buffer; event = trace_buffer_lock_reserve(buffer, sys_data->exit_event->event.type, sizeof(*entry), irq_flags, pc); if (!event) return; entry = ring_buffer_event_data(event); entry->nr = syscall_nr; entry->ret = syscall_get_return_value(current, regs); event_trigger_unlock_commit(ftrace_file, buffer, event, entry, irq_flags, pc); } CWE ID: CWE-264 Target: 1 Example 2: Code: static void rb_free_rcu(struct rcu_head *rcu_head) { struct ring_buffer *rb; rb = container_of(rcu_head, struct ring_buffer, rcu_head); rb_free(rb); } 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: int64_t LayerTreeHostQt::adoptImageBackingStore(Image* image) { if (!image) return InvalidWebLayerID; QPixmap* pixmap = image->nativeImageForCurrentFrame(); if (!pixmap) return InvalidWebLayerID; int64_t key = pixmap->cacheKey(); HashMap<int64_t, int>::iterator it = m_directlyCompositedImageRefCounts.find(key); if (it != m_directlyCompositedImageRefCounts.end()) { ++(it->second); return key; } RefPtr<ShareableBitmap> bitmap = ShareableBitmap::createShareable(image->size(), image->currentFrameHasAlpha() ? ShareableBitmap::SupportsAlpha : 0); { OwnPtr<WebCore::GraphicsContext> graphicsContext = bitmap->createGraphicsContext(); graphicsContext->drawImage(image, ColorSpaceDeviceRGB, IntPoint::zero()); } ShareableBitmap::Handle handle; bitmap->createHandle(handle); m_webPage->send(Messages::LayerTreeHostProxy::CreateDirectlyCompositedImage(key, handle)); m_directlyCompositedImageRefCounts.add(key, 1); return key; } 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: krb5_gss_export_sec_context(minor_status, context_handle, interprocess_token) OM_uint32 *minor_status; gss_ctx_id_t *context_handle; gss_buffer_t interprocess_token; { krb5_context context = NULL; krb5_error_code kret; OM_uint32 retval; size_t bufsize, blen; krb5_gss_ctx_id_t ctx; krb5_octet *obuffer, *obp; /* Assume a tragic failure */ obuffer = (krb5_octet *) NULL; retval = GSS_S_FAILURE; *minor_status = 0; ctx = (krb5_gss_ctx_id_t) *context_handle; context = ctx->k5_context; kret = krb5_gss_ser_init(context); if (kret) goto error_out; /* Determine size needed for externalization of context */ bufsize = 0; if ((kret = kg_ctx_size(context, (krb5_pointer) ctx, &bufsize))) goto error_out; /* Allocate the buffer */ if ((obuffer = gssalloc_malloc(bufsize)) == NULL) { kret = ENOMEM; goto error_out; } obp = obuffer; blen = bufsize; /* Externalize the context */ if ((kret = kg_ctx_externalize(context, (krb5_pointer) ctx, &obp, &blen))) goto error_out; /* Success! Return the buffer */ interprocess_token->length = bufsize - blen; interprocess_token->value = obuffer; *minor_status = 0; retval = GSS_S_COMPLETE; /* Now, clean up the context state */ (void)krb5_gss_delete_sec_context(minor_status, context_handle, NULL); *context_handle = GSS_C_NO_CONTEXT; return (GSS_S_COMPLETE); error_out: if (retval != GSS_S_COMPLETE) if (kret != 0 && context != 0) save_error_info((OM_uint32)kret, context); if (obuffer && bufsize) { memset(obuffer, 0, bufsize); xfree(obuffer); } if (*minor_status == 0) *minor_status = (OM_uint32) kret; return(retval); } CWE ID: Target: 1 Example 2: Code: void ResetAllFlags(flags_ui::FlagsStorage* flags_storage) { FlagsStateSingleton::GetFlagsState()->ResetAllFlags(flags_storage); } 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: process_add_smartcard_key(SocketEntry *e) { char *provider = NULL, *pin; int r, i, version, count = 0, success = 0, confirm = 0; u_int seconds; time_t death = 0; u_char type; struct sshkey **keys = NULL, *k; Identity *id; Idtab *tab; if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 || (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); while (sshbuf_len(e->request)) { if ((r = sshbuf_get_u8(e->request, &type)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); switch (type) { case SSH_AGENT_CONSTRAIN_LIFETIME: if ((r = sshbuf_get_u32(e->request, &seconds)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); death = monotime() + seconds; break; case SSH_AGENT_CONSTRAIN_CONFIRM: confirm = 1; break; default: error("process_add_smartcard_key: " "Unknown constraint type %d", type); goto send; } } if (lifetime && !death) death = monotime() + lifetime; count = pkcs11_add_provider(provider, pin, &keys); for (i = 0; i < count; i++) { k = keys[i]; version = k->type == KEY_RSA1 ? 1 : 2; tab = idtab_lookup(version); if (lookup_identity(k, version) == NULL) { id = xcalloc(1, sizeof(Identity)); id->key = k; id->provider = xstrdup(provider); id->comment = xstrdup(provider); /* XXX */ id->death = death; id->confirm = confirm; TAILQ_INSERT_TAIL(&tab->idlist, id, next); tab->nentries++; success = 1; } else { sshkey_free(k); } keys[i] = NULL; } send: free(pin); free(provider); free(keys); send_status(e, success); } CWE ID: CWE-426 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 locationWithPerWorldBindingsAttributeSetterForMainWorld(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } CWE ID: CWE-399 Target: 1 Example 2: Code: void RenderThreadImpl::OnCreateNewView(const ViewMsg_New_Params& params) { EnsureWebKitInitialized(); RenderViewImpl::Create( params.parent_window, MSG_ROUTING_NONE, params.renderer_preferences, params.web_preferences, new SharedRenderViewCounter(0), params.view_id, params.surface_id, params.session_storage_namespace_id, params.frame_name, params.next_page_id, params.screen_info, params.guest); } 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 op32_get_current_rxslot(struct b43_dmaring *ring) { u32 val; val = b43_dma_read(ring, B43_DMA32_RXSTATUS); val &= B43_DMA32_RXDPTR; return (val / sizeof(struct b43_dmadesc32)); } 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: bool MediaElementAudioSourceHandler::WouldTaintOrigin() { if (MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) { return false; } if (!MediaElement()->HasSingleSecurityOrigin()) { return true; } return Context()->WouldTaintOrigin(MediaElement()->currentSrc()); } CWE ID: CWE-732 Target: 1 Example 2: Code: void XSSAuditor::SetEncoding(const WTF::TextEncoding& encoding) { const size_t kMiniumLengthForSuffixTree = 512; // FIXME: Tune this parameter. const int kSuffixTreeDepth = 5; if (!encoding.IsValid()) return; encoding_ = encoding; decoded_url_ = Canonicalize(document_url_.GetString(), kNoTruncation); if (decoded_url_.Find(IsRequiredForInjection) == kNotFound) decoded_url_ = String(); if (!http_body_as_string_.IsEmpty()) { decoded_http_body_ = Canonicalize(http_body_as_string_, kNoTruncation); http_body_as_string_ = String(); if (decoded_http_body_.Find(IsRequiredForInjection) == kNotFound) decoded_http_body_ = String(); if (decoded_http_body_.length() >= kMiniumLengthForSuffixTree) decoded_http_body_suffix_tree_ = WTF::WrapUnique( new SuffixTree<ASCIICodebook>(decoded_http_body_, kSuffixTreeDepth)); } if (decoded_url_.IsEmpty() && decoded_http_body_.IsEmpty()) is_enabled_ = false; } 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: static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c) { struct xfrm_user_expire *ue; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0); if (nlh == NULL) return -EMSGSIZE; ue = nlmsg_data(nlh); copy_to_user_state(x, &ue->state); ue->hard = (c->data.hard != 0) ? 1 : 0; err = xfrm_mark_put(skb, &x->mark); if (err) return err; return nlmsg_end(skb, nlh); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WebGL2RenderingContextBase::framebufferTextureLayer(GLenum target, GLenum attachment, WebGLTexture* texture, GLint level, GLint layer) { if (isContextLost() || !ValidateFramebufferFuncParameters( "framebufferTextureLayer", target, attachment)) return; if (texture && !texture->Validate(ContextGroup(), this)) { SynthesizeGLError(GL_INVALID_VALUE, "framebufferTextureLayer", "no texture or texture not from this context"); return; } GLenum textarget = texture ? texture->GetTarget() : 0; if (texture) { if (textarget != GL_TEXTURE_3D && textarget != GL_TEXTURE_2D_ARRAY) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "invalid texture type"); return; } if (!ValidateTexFuncLayer("framebufferTextureLayer", textarget, layer)) return; if (!ValidateTexFuncLevel("framebufferTextureLayer", textarget, level)) return; } WebGLFramebuffer* framebuffer_binding = GetFramebufferBinding(target); if (!framebuffer_binding || !framebuffer_binding->Object()) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "no framebuffer bound"); return; } if (framebuffer_binding && framebuffer_binding->Opaque()) { SynthesizeGLError(GL_INVALID_OPERATION, "framebufferTextureLayer", "opaque framebuffer bound"); return; } framebuffer_binding->SetAttachmentForBoundFramebuffer( target, attachment, textarget, texture, level, layer); ApplyStencilTest(); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int raw_v4_input(struct sk_buff *skb, const struct iphdr *iph, int hash) { int sdif = inet_sdif(skb); struct sock *sk; struct hlist_head *head; int delivered = 0; struct net *net; read_lock(&raw_v4_hashinfo.lock); head = &raw_v4_hashinfo.ht[hash]; if (hlist_empty(head)) goto out; net = dev_net(skb->dev); sk = __raw_v4_lookup(net, __sk_head(head), iph->protocol, iph->saddr, iph->daddr, skb->dev->ifindex, sdif); while (sk) { delivered = 1; if ((iph->protocol != IPPROTO_ICMP || !icmp_filter(sk, skb)) && ip_mc_sf_allow(sk, iph->daddr, iph->saddr, skb->dev->ifindex, sdif)) { struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); /* Not releasing hash table! */ if (clone) raw_rcv(sk, clone); } sk = __raw_v4_lookup(net, sk_next(sk), iph->protocol, iph->saddr, iph->daddr, skb->dev->ifindex, sdif); } out: read_unlock(&raw_v4_hashinfo.lock); return delivered; } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline bool unconditional(const struct ip6t_ip6 *ipv6) { static const struct ip6t_ip6 uncond; return memcmp(ipv6, &uncond, sizeof(uncond)) == 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 int usb_console_setup(struct console *co, char *options) { struct usbcons_info *info = &usbcons_info; int baud = 9600; int bits = 8; int parity = 'n'; int doflow = 0; int cflag = CREAD | HUPCL | CLOCAL; char *s; struct usb_serial *serial; struct usb_serial_port *port; int retval; struct tty_struct *tty = NULL; struct ktermios dummy; if (options) { baud = simple_strtoul(options, NULL, 10); s = options; while (*s >= '0' && *s <= '9') s++; if (*s) parity = *s++; if (*s) bits = *s++ - '0'; if (*s) doflow = (*s++ == 'r'); } /* Sane default */ if (baud == 0) baud = 9600; switch (bits) { case 7: cflag |= CS7; break; default: case 8: cflag |= CS8; break; } switch (parity) { case 'o': case 'O': cflag |= PARODD; break; case 'e': case 'E': cflag |= PARENB; break; } co->cflag = cflag; /* * no need to check the index here: if the index is wrong, console * code won't call us */ port = usb_serial_port_get_by_minor(co->index); if (port == NULL) { /* no device is connected yet, sorry :( */ pr_err("No USB device connected to ttyUSB%i\n", co->index); return -ENODEV; } serial = port->serial; retval = usb_autopm_get_interface(serial->interface); if (retval) goto error_get_interface; tty_port_tty_set(&port->port, NULL); info->port = port; ++port->port.count; if (!tty_port_initialized(&port->port)) { if (serial->type->set_termios) { /* * allocate a fake tty so the driver can initialize * the termios structure, then later call set_termios to * configure according to command line arguments */ tty = kzalloc(sizeof(*tty), GFP_KERNEL); if (!tty) { retval = -ENOMEM; goto reset_open_count; } kref_init(&tty->kref); tty->driver = usb_serial_tty_driver; tty->index = co->index; init_ldsem(&tty->ldisc_sem); spin_lock_init(&tty->files_lock); INIT_LIST_HEAD(&tty->tty_files); kref_get(&tty->driver->kref); __module_get(tty->driver->owner); tty->ops = &usb_console_fake_tty_ops; tty_init_termios(tty); tty_port_tty_set(&port->port, tty); } /* only call the device specific open if this * is the first time the port is opened */ retval = serial->type->open(NULL, port); if (retval) { dev_err(&port->dev, "could not open USB console port\n"); goto fail; } if (serial->type->set_termios) { tty->termios.c_cflag = cflag; tty_termios_encode_baud_rate(&tty->termios, baud, baud); memset(&dummy, 0, sizeof(struct ktermios)); serial->type->set_termios(tty, port, &dummy); tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); } tty_port_set_initialized(&port->port, 1); } /* Now that any required fake tty operations are completed restore * the tty port count */ --port->port.count; /* The console is special in terms of closing the device so * indicate this port is now acting as a system console. */ port->port.console = 1; mutex_unlock(&serial->disc_mutex); return retval; fail: tty_port_tty_set(&port->port, NULL); tty_kref_put(tty); reset_open_count: port->port.count = 0; usb_autopm_put_interface(serial->interface); error_get_interface: usb_serial_put(serial); mutex_unlock(&serial->disc_mutex); return retval; } CWE ID: CWE-416 Target: 1 Example 2: Code: static bool ldm_compare_tocblocks (const struct tocblock *toc1, const struct tocblock *toc2) { BUG_ON (!toc1 || !toc2); return ((toc1->bitmap1_start == toc2->bitmap1_start) && (toc1->bitmap1_size == toc2->bitmap1_size) && (toc1->bitmap2_start == toc2->bitmap2_start) && (toc1->bitmap2_size == toc2->bitmap2_size) && !strncmp (toc1->bitmap1_name, toc2->bitmap1_name, sizeof (toc1->bitmap1_name)) && !strncmp (toc1->bitmap2_name, toc2->bitmap2_name, sizeof (toc1->bitmap2_name))); } 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 AddAllUsers() { for (size_t i = 0; i < arraysize(kTestAccounts); ++i) AddUser(kTestAccounts[i], i >= SECONDARY_ACCOUNT_INDEX_START); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ShellContentUtilityClient::ShellContentUtilityClient() { if (base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessType) == switches::kUtilityProcess) network_service_test_helper_ = std::make_unique<NetworkServiceTestHelper>(); } CWE ID: CWE-264 Target: 1 Example 2: Code: static void voidMethodShortArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectPythonV8Internal::voidMethodShortArgMethod(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: virtual void TreeNodeChanged(TreeModel* model, TreeModelNode* node) { changed_count_++; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void TypingCommand::insertText(Document& document, const String& text, Options options, TextCompositionType composition, const bool isIncrementalInsertion) { LocalFrame* frame = document.frame(); DCHECK(frame); if (!text.isEmpty()) document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing( isSpaceOrNewline(text[0])); insertText(document, text, frame->selection().computeVisibleSelectionInDOMTreeDeprecated(), options, composition, isIncrementalInsertion); } CWE ID: Target: 1 Example 2: Code: static void ebt_standard_compat_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v >= 0) v += xt_compat_calc_jump(NFPROTO_BRIDGE, v); memcpy(dst, &v, sizeof(v)); } 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 DXVAVideoDecodeAccelerator::Decode( const media::BitstreamBuffer& bitstream_buffer) { DCHECK(CalledOnValidThread()); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped), "Invalid state: " << state_, ILLEGAL_STATE,); base::win::ScopedComPtr<IMFSample> sample; sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer, renderer_process_, input_stream_info_.cbSize, input_stream_info_.cbAlignment)); RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample", PLATFORM_FAILURE,); if (!inputs_before_decode_) { TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, ""); } inputs_before_decode_++; RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0), "Failed to create input sample", PLATFORM_FAILURE,); HRESULT hr = decoder_->ProcessInput(0, sample, 0); RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample", PLATFORM_FAILURE,); RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0), "Failed to send eos message to MFT", PLATFORM_FAILURE,); state_ = kEosDrain; last_input_buffer_id_ = bitstream_buffer.id(); DoDecode(); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal), "Failed to process output. Unexpected decoder state: " << state_, ILLEGAL_STATE,); MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this, bitstream_buffer.id())); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int clie_5_attach(struct usb_serial *serial) { struct usb_serial_port *port; unsigned int pipe; int j; /* TH55 registers 2 ports. Communication in from the UX50/TH55 uses bulk_in_endpointAddress from port 0. Communication out to the UX50/TH55 uses bulk_out_endpointAddress from port 1 Lets do a quick and dirty mapping */ /* some sanity check */ if (serial->num_ports < 2) return -1; /* port 0 now uses the modified endpoint Address */ port = serial->port[0]; port->bulk_out_endpointAddress = serial->port[1]->bulk_out_endpointAddress; pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress); for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j) port->write_urbs[j]->pipe = pipe; return 0; } CWE ID: Target: 1 Example 2: Code: int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr, int len, const void *val, long cookie) { struct kvm_io_bus *bus; struct kvm_io_range range; range = (struct kvm_io_range) { .addr = addr, .len = len, }; bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu); if (!bus) return -ENOMEM; /* First try the device referenced by cookie. */ if ((cookie >= 0) && (cookie < bus->dev_count) && (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0)) if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len, val)) return cookie; /* * cookie contained garbage; fall back to search and return the * correct cookie value. */ return __kvm_io_bus_write(vcpu, bus, &range, val); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void InputHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { if (frame_host == host_) return; ClearInputState(); if (host_) { host_->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (ignore_input_events_) host_->GetRenderWidgetHost()->SetIgnoreInputEvents(false); } host_ = frame_host; if (host_) { host_->GetRenderWidgetHost()->AddInputEventObserver(this); if (ignore_input_events_) host_->GetRenderWidgetHost()->SetIgnoreInputEvents(true); } } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err) { char *colon; char *host = NULL; #ifdef HAVE_IPV6 char *p; if (*(str) == '[' && str_len > 1) { /* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */ p = memchr(str + 1, ']', str_len - 2); if (!p || *(p + 1) != ':') { if (get_err) { *err = strpprintf(0, "Failed to parse IPv6 address \"%s\"", str); } return NULL; } *portno = atoi(p + 2); return estrndup(str + 1, p - str - 1); } #endif if (str_len) { colon = memchr(str, ':', str_len - 1); } else { colon = NULL; } if (colon) { *portno = atoi(colon + 1); host = estrndup(str, colon - str); } else { if (get_err) { *err = strpprintf(0, "Failed to parse address \"%s\"", str); } return NULL; } return host; } CWE ID: CWE-918 Target: 1 Example 2: Code: TabContentsWrapper* ReleaseOwnership() { return target_contents_owner_.release(); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int SoundPool::load(int fd, int64_t offset, int64_t length, int priority __unused) { ALOGV("load: fd=%d, offset=%" PRId64 ", length=%" PRId64 ", priority=%d", fd, offset, length, priority); Mutex::Autolock lock(&mLock); sp<Sample> sample = new Sample(++mNextSampleID, fd, offset, length); mSamples.add(sample->sampleID(), sample); doLoad(sample); return sample->sampleID(); } 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 main(int argc, char *argv[]) { char buff[1024]; int fd, nr, nw; if (argc < 2) { fprintf(stderr, "usage: %s output-filename\n" " %s |output-command\n" " %s :host:port\n", argv[0], argv[0], argv[0]); return 1; } fd = open_gen_fd(argv[1]); if (fd < 0) { perror("open_gen_fd"); exit(EXIT_FAILURE); } while ((nr = read(0, buff, sizeof (buff))) != 0) { if (nr < 0) { if (errno == EINTR) continue; perror("read"); exit(EXIT_FAILURE); } nw = write(fd, buff, nr); if (nw < 0) { perror("write"); exit(EXIT_FAILURE); } } return 0; } CWE ID: Target: 1 Example 2: Code: xfs_attr3_leaf_order( struct xfs_buf *leaf1_bp, struct xfs_attr3_icleaf_hdr *leaf1hdr, struct xfs_buf *leaf2_bp, struct xfs_attr3_icleaf_hdr *leaf2hdr) { struct xfs_attr_leaf_entry *entries1; struct xfs_attr_leaf_entry *entries2; entries1 = xfs_attr3_leaf_entryp(leaf1_bp->b_addr); entries2 = xfs_attr3_leaf_entryp(leaf2_bp->b_addr); if (leaf1hdr->count > 0 && leaf2hdr->count > 0 && ((be32_to_cpu(entries2[0].hashval) < be32_to_cpu(entries1[0].hashval)) || (be32_to_cpu(entries2[leaf2hdr->count - 1].hashval) < be32_to_cpu(entries1[leaf1hdr->count - 1].hashval)))) { return 1; } return 0; } CWE ID: CWE-19 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need) { #ifdef CONFIG_F2FS_FAULT_INJECTION if (time_to_inject(sbi, FAULT_CHECKPOINT)) { f2fs_show_injection_info(FAULT_CHECKPOINT); f2fs_stop_checkpoint(sbi, false); } #endif /* balance_fs_bg is able to be pending */ if (need && excess_cached_nats(sbi)) f2fs_balance_fs_bg(sbi); /* * We should do GC or end up with checkpoint, if there are so many dirty * dir/node pages without enough free segments. */ if (has_not_enough_free_secs(sbi, 0, 0)) { mutex_lock(&sbi->gc_mutex); f2fs_gc(sbi, false, false, NULL_SEGNO); } } 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 v8::Handle<v8::Value> acceptTransferListCallback(const v8::Arguments& args) { INC_STATS("DOM.TestSerializedScriptValueInterface.acceptTransferList"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(args.Holder()); MessagePortArray messagePortArrayTransferList; ArrayBufferArray arrayBufferArrayTransferList; if (args.Length() > 1) { if (!extractTransferables(args[1], messagePortArrayTransferList, arrayBufferArrayTransferList)) return V8Proxy::throwTypeError("Could not extract transferables"); } bool dataDidThrow = false; RefPtr<SerializedScriptValue> data = SerializedScriptValue::create(args[0], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate()); if (dataDidThrow) return v8::Undefined(); if (args.Length() <= 1) { imp->acceptTransferList(data); return v8::Handle<v8::Value>(); } imp->acceptTransferList(data, messagePortArrayTransferList); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: oldgnu_add_sparse (struct tar_sparse_file *file, struct sparse *s) { struct sp_array sp; if (s->numbytes[0] == '\0') return add_finish; sp.offset = OFF_FROM_HEADER (s->offset); sp.numbytes = OFF_FROM_HEADER (s->numbytes); if (sp.offset < 0 || sp.numbytes < 0 || INT_ADD_OVERFLOW (sp.offset, sp.numbytes) || file->stat_info->stat.st_size < sp.offset + sp.numbytes || file->stat_info->archive_file_size < 0) return add_fail; sparse_add_map (file->stat_info, &sp); return add_ok; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Chapters::Display::ShallowCopy(Display& rhs) const { rhs.m_string = m_string; rhs.m_language = m_language; rhs.m_country = m_country; } 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 get_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { /* * Because the kvm_regs structure is a mix of 32, 64 and * 128bit fields, we index it as if it was a 32bit * array. Hence below, nr_regs is the number of entries, and * off the index in the "array". */ __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); u32 off; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (copy_to_user(uaddr, ((u32 *)regs) + off, KVM_REG_SIZE(reg->id))) return -EFAULT; return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: static u64 svm_read_tsc_offset(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); return svm->vmcb->control.tsc_offset; } 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 size_t consume_init_expr (ut8 *buf, ut8 *max, ut8 eoc, void *out, ut32 *offset) { ut32 i = 0; while (buf + i < max && buf[i] != eoc) { i += 1; } if (buf[i] != eoc) { return 0; } if (offset) { *offset += i + 1; } return i + 1; } 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: JSValue JSDirectoryEntry::getFile(ExecState* exec) { if (exec->argumentCount() < 1) return throwError(exec, createTypeError(exec, "Not enough arguments")); DirectoryEntry* imp = static_cast<DirectoryEntry*>(impl()); const String& path = valueToStringWithUndefinedOrNullCheck(exec, exec->argument(0)); if (exec->hadException()) return jsUndefined(); int argsCount = exec->argumentCount(); if (argsCount <= 1) { imp->getFile(path); return jsUndefined(); } RefPtr<WebKitFlags> flags; if (!exec->argument(1).isNull() && !exec->argument(1).isUndefined() && exec->argument(1).isObject()) { JSObject* object = exec->argument(1).getObject(); flags = WebKitFlags::create(); JSValue jsCreate = object->get(exec, Identifier(exec, "create")); flags->setCreate(jsCreate.toBoolean(exec)); JSValue jsExclusive = object->get(exec, Identifier(exec, "exclusive")); flags->setExclusive(jsExclusive.toBoolean(exec)); } if (exec->hadException()) return jsUndefined(); RefPtr<EntryCallback> successCallback; if (exec->argumentCount() > 2 && !exec->argument(2).isNull() && !exec->argument(2).isUndefined()) { if (!exec->argument(2).isObject()) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } successCallback = JSEntryCallback::create(asObject(exec->argument(2)), globalObject()); } RefPtr<ErrorCallback> errorCallback; if (exec->argumentCount() > 3 && !exec->argument(3).isNull() && !exec->argument(3).isUndefined()) { if (!exec->argument(3).isObject()) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } errorCallback = JSErrorCallback::create(asObject(exec->argument(3)), globalObject()); } imp->getFile(path, flags, successCallback, errorCallback); return jsUndefined(); } CWE ID: CWE-20 Target: 1 Example 2: Code: void Document::SetViewportDescription( const ViewportDescription& viewport_description) { if (viewport_description.IsLegacyViewportType()) { if (viewport_description == legacy_viewport_description_) return; legacy_viewport_description_ = viewport_description; } else { if (viewport_description == viewport_description_) return; viewport_description_ = viewport_description; if (!viewport_description.IsSpecifiedByAuthor()) viewport_default_min_width_ = viewport_description.min_width; } UpdateViewportDescription(); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long long mkvparser::GetUIntLength( IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); long long total, available; int status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); len = 1; if (pos >= available) return pos; //too few bytes available //// TODO(vigneshv): This function assumes that unsigned values never have their //// high bit set. unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) return status; assert(status == 0); if (b == 0) //we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } return 0; //success } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void NavigationObserver::PromptToEnableExtensionIfNecessary( NavigationController* nav_controller) { if (!in_progress_prompt_extension_id_.empty()) return; NavigationEntry* nav_entry = nav_controller->GetVisibleEntry(); if (!nav_entry) return; const GURL& url = (nav_entry->GetPageType() == content::PAGE_TYPE_ERROR && nav_entry->GetURL() == url::kAboutBlankURL && nav_entry->GetVirtualURL().SchemeIs(kExtensionScheme)) ? nav_entry->GetVirtualURL() : nav_entry->GetURL(); if (!url.SchemeIs(kExtensionScheme)) return; const Extension* extension = ExtensionRegistry::Get(profile_) ->disabled_extensions() .GetExtensionOrAppByURL(url); if (!extension) return; if (!prompted_extensions_.insert(extension->id()).second && !g_repeat_prompting) { return; } ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile_); if (extension_prefs->DidExtensionEscalatePermissions(extension->id())) { in_progress_prompt_extension_id_ = extension->id(); in_progress_prompt_navigation_controller_ = nav_controller; extension_install_prompt_.reset( new ExtensionInstallPrompt(nav_controller->GetWebContents())); ExtensionInstallPrompt::PromptType type = ExtensionInstallPrompt::GetReEnablePromptTypeForExtension(profile_, extension); extension_install_prompt_->ShowDialog( base::Bind(&NavigationObserver::OnInstallPromptDone, weak_factory_.GetWeakPtr()), extension, nullptr, base::MakeUnique<ExtensionInstallPrompt::Prompt>(type), ExtensionInstallPrompt::GetDefaultShowDialogCallback()); } } CWE ID: CWE-20 Target: 1 Example 2: Code: GBool StreamPredictor::getNextLine() { int curPred; Guchar upLeftBuf[gfxColorMaxComps * 2 + 1]; int left, up, upLeft, p, pa, pb, pc; int c; Gulong inBuf, outBuf, bitMask; int inBits, outBits; int i, j, k, kk; if (predictor >= 10) { if ((curPred = str->getRawChar()) == EOF) { return gFalse; } curPred += 10; } else { curPred = predictor; } int *rawCharLine = new int[rowBytes - pixBytes]; str->getRawChars(rowBytes - pixBytes, rawCharLine); memset(upLeftBuf, 0, pixBytes + 1); for (i = pixBytes; i < rowBytes; ++i) { for (j = pixBytes; j > 0; --j) { upLeftBuf[j] = upLeftBuf[j-1]; } upLeftBuf[0] = predLine[i]; if ((c = rawCharLine[i - pixBytes]) == EOF) { if (i > pixBytes) { break; } delete[] rawCharLine; return gFalse; } switch (curPred) { case 11: // PNG sub predLine[i] = predLine[i - pixBytes] + (Guchar)c; break; case 12: // PNG up predLine[i] = predLine[i] + (Guchar)c; break; case 13: // PNG average predLine[i] = ((predLine[i - pixBytes] + predLine[i]) >> 1) + (Guchar)c; break; case 14: // PNG Paeth left = predLine[i - pixBytes]; up = predLine[i]; upLeft = upLeftBuf[pixBytes]; p = left + up - upLeft; if ((pa = p - left) < 0) pa = -pa; if ((pb = p - up) < 0) pb = -pb; if ((pc = p - upLeft) < 0) pc = -pc; if (pa <= pb && pa <= pc) predLine[i] = left + (Guchar)c; else if (pb <= pc) predLine[i] = up + (Guchar)c; else predLine[i] = upLeft + (Guchar)c; break; case 10: // PNG none default: // no predictor or TIFF predictor predLine[i] = (Guchar)c; break; } } delete[] rawCharLine; if (predictor == 2) { if (nBits == 1) { inBuf = predLine[pixBytes - 1]; for (i = pixBytes; i < rowBytes; i += 8) { inBuf = (inBuf << 8) | predLine[i]; predLine[i] ^= inBuf >> nComps; } } else if (nBits == 8) { for (i = pixBytes; i < rowBytes; ++i) { predLine[i] += predLine[i - nComps]; } } else { memset(upLeftBuf, 0, nComps + 1); bitMask = (1 << nBits) - 1; inBuf = outBuf = 0; inBits = outBits = 0; j = k = pixBytes; for (i = 0; i < width; ++i) { for (kk = 0; kk < nComps; ++kk) { if (inBits < nBits) { inBuf = (inBuf << 8) | (predLine[j++] & 0xff); inBits += 8; } upLeftBuf[kk] = (Guchar)((upLeftBuf[kk] + (inBuf >> (inBits - nBits))) & bitMask); inBits -= nBits; outBuf = (outBuf << nBits) | upLeftBuf[kk]; outBits += nBits; if (outBits >= 8) { predLine[k++] = (Guchar)(outBuf >> (outBits - 8)); outBits -= 8; } } } if (outBits > 0) { predLine[k++] = (Guchar)((outBuf << (8 - outBits)) + (inBuf & ((1 << (8 - outBits)) - 1))); } } } predIdx = pixBytes; return gTrue; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct ion_client *client = filp->private_data; struct ion_device *dev = client->dev; struct ion_handle *cleanup_handle = NULL; int ret = 0; unsigned int dir; union { struct ion_fd_data fd; struct ion_allocation_data allocation; struct ion_handle_data handle; struct ion_custom_data custom; } data; dir = ion_ioctl_dir(cmd); if (_IOC_SIZE(cmd) > sizeof(data)) return -EINVAL; if (dir & _IOC_WRITE) if (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd))) return -EFAULT; switch (cmd) { case ION_IOC_ALLOC: { struct ion_handle *handle; handle = ion_alloc(client, data.allocation.len, data.allocation.align, data.allocation.heap_id_mask, data.allocation.flags); if (IS_ERR(handle)) return PTR_ERR(handle); data.allocation.handle = handle->id; cleanup_handle = handle; break; } case ION_IOC_FREE: { struct ion_handle *handle; handle = ion_handle_get_by_id(client, data.handle.handle); if (IS_ERR(handle)) return PTR_ERR(handle); ion_free(client, handle); ion_handle_put(handle); break; } case ION_IOC_SHARE: case ION_IOC_MAP: { struct ion_handle *handle; handle = ion_handle_get_by_id(client, data.handle.handle); if (IS_ERR(handle)) return PTR_ERR(handle); data.fd.fd = ion_share_dma_buf_fd(client, handle); ion_handle_put(handle); if (data.fd.fd < 0) ret = data.fd.fd; break; } case ION_IOC_IMPORT: { struct ion_handle *handle; handle = ion_import_dma_buf_fd(client, data.fd.fd); if (IS_ERR(handle)) ret = PTR_ERR(handle); else data.handle.handle = handle->id; break; } case ION_IOC_SYNC: { ret = ion_sync_for_device(client, data.fd.fd); break; } case ION_IOC_CUSTOM: { if (!dev->custom_ioctl) return -ENOTTY; ret = dev->custom_ioctl(client, data.custom.cmd, data.custom.arg); break; } default: return -ENOTTY; } if (dir & _IOC_READ) { if (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) { if (cleanup_handle) ion_free(client, cleanup_handle); return -EFAULT; } } return ret; } 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: OMX_ERRORTYPE omx_video::allocate_input_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes) { (void)hComp, (void)port; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned i = 0; DEBUG_PRINT_HIGH("allocate_input_buffer()::"); if (bytes != m_sInPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: Buffer size mismatch error: bytes[%u] != nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_inp_mem_ptr) { DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__, (unsigned int)m_sInPortDef.nBufferSize, (unsigned int)m_sInPortDef.nBufferCountActual); m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \ calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual); if (m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr"); return OMX_ErrorInsufficientResources; } DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr); m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual); if (m_pInput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual); if (m_pInput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion"); return OMX_ErrorInsufficientResources; } #endif for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { m_pInput_pmem[i].fd = -1; #ifdef USE_ION m_pInput_ion[i].ion_device_fd =-1; m_pInput_ion[i].fd_ion_data.fd =-1; m_pInput_ion[i].ion_alloc_data.handle = 0; #endif } } for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } if (i < m_sInPortDef.nBufferCountActual) { *bufferHdr = (m_inp_mem_ptr + i); (*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION; (*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize; (*bufferHdr)->pAppPrivate = appData; (*bufferHdr)->nInputPortIndex = PORT_INDEX_IN; (*bufferHdr)->pInputPortPrivate = (OMX_PTR)&m_pInput_pmem[i]; #ifdef USE_ION #ifdef _MSM8974_ m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,0); #else m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pInput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd; #else m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pInput_pmem[i].fd == 0) { m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pInput_pmem[i].fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].offset = 0; m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL, m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pInput_pmem[i].fd,0); if (m_pInput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap FAILED= %d", errno); close(m_pInput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } else { m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); } (*bufferHdr)->pBuffer = (OMX_U8 *)m_pInput_pmem[i].buffer; DEBUG_PRINT_LOW("Virtual address in allocate buffer is %p", m_pInput_pmem[i].buffer); BITMASK_SET(&m_inp_bm_count,i); if (!mUseProxyColorFormat && (dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true)) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for i/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All i/p buffers are allocated, invalid allocate buf call" "for index [%d]", i); eRet = OMX_ErrorInsufficientResources; } return eRet; } CWE ID: CWE-119 Target: 1 Example 2: Code: efx_tsoh_heap_alloc(struct efx_tx_queue *tx_queue, size_t header_len) { struct efx_tso_header *tsoh; tsoh = kmalloc(TSOH_SIZE(header_len), GFP_ATOMIC | GFP_DMA); if (unlikely(!tsoh)) return NULL; tsoh->dma_addr = pci_map_single(tx_queue->efx->pci_dev, TSOH_BUFFER(tsoh), header_len, PCI_DMA_TODEVICE); if (unlikely(pci_dma_mapping_error(tx_queue->efx->pci_dev, tsoh->dma_addr))) { kfree(tsoh); return NULL; } tsoh->unmap_len = header_len; return tsoh; } 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: long kernel_wait4(pid_t upid, int __user *stat_addr, int options, struct rusage *ru) { struct wait_opts wo; struct pid *pid = NULL; enum pid_type type; long ret; if (options & ~(WNOHANG|WUNTRACED|WCONTINUED| __WNOTHREAD|__WCLONE|__WALL)) return -EINVAL; if (upid == -1) type = PIDTYPE_MAX; else if (upid < 0) { type = PIDTYPE_PGID; pid = find_get_pid(-upid); } else if (upid == 0) { type = PIDTYPE_PGID; pid = get_task_pid(current, PIDTYPE_PGID); } else /* upid > 0 */ { type = PIDTYPE_PID; pid = find_get_pid(upid); } wo.wo_type = type; wo.wo_pid = pid; wo.wo_flags = options | WEXITED; wo.wo_info = NULL; wo.wo_stat = 0; wo.wo_rusage = ru; ret = do_wait(&wo); put_pid(pid); if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr)) ret = -EFAULT; return ret; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CCLayerTreeHostTest::endTest() { if (!isMainThread()) CCMainThread::postTask(createMainThreadTask(this, &CCLayerTreeHostTest::endTest)); else { if (m_beginning) m_endWhenBeginReturns = true; else onEndTest(static_cast<void*>(this)); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static size_t pipe_zero(size_t bytes, struct iov_iter *i) { struct pipe_inode_info *pipe = i->pipe; size_t n, off; int idx; if (!sanity(i)) return 0; bytes = n = push_pipe(i, bytes, &idx, &off); if (unlikely(!n)) return 0; for ( ; n; idx = next_idx(idx, pipe), off = 0) { size_t chunk = min_t(size_t, n, PAGE_SIZE - off); memzero_page(pipe->bufs[idx].page, off, chunk); i->idx = idx; i->iov_offset = off + chunk; n -= chunk; } i->count -= bytes; return bytes; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void streamIteratorRemoveEntry(streamIterator *si, streamID *current) { unsigned char *lp = si->lp; int64_t aux; /* We do not really delete the entry here. Instead we mark it as * deleted flagging it, and also incrementing the count of the * deleted entries in the listpack header. * * We start flagging: */ int flags = lpGetInteger(si->lp_flags); flags |= STREAM_ITEM_FLAG_DELETED; lp = lpReplaceInteger(lp,&si->lp_flags,flags); /* Change the valid/deleted entries count in the master entry. */ unsigned char *p = lpFirst(lp); aux = lpGetInteger(p); lp = lpReplaceInteger(lp,&p,aux-1); p = lpNext(lp,p); /* Seek deleted field. */ aux = lpGetInteger(p); lp = lpReplaceInteger(lp,&p,aux+1); /* Update the number of entries counter. */ si->stream->length--; /* Re-seek the iterator to fix the now messed up state. */ streamID start, end; if (si->rev) { streamDecodeID(si->start_key,&start); end = *current; } else { start = *current; streamDecodeID(si->end_key,&end); } streamIteratorStop(si); streamIteratorStart(si,si->stream,&start,&end,si->rev); /* TODO: perform a garbage collection here if the ration between * deleted and valid goes over a certain limit. */ } CWE ID: CWE-704 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ldp_pdu_print(netdissect_options *ndo, register const u_char *pptr) { const struct ldp_common_header *ldp_com_header; const struct ldp_msg_header *ldp_msg_header; const u_char *tptr,*msg_tptr; u_short tlen; u_short pdu_len,msg_len,msg_type,msg_tlen; int hexdump,processed; ldp_com_header = (const struct ldp_common_header *)pptr; ND_TCHECK(*ldp_com_header); /* * Sanity checking of the header. */ if (EXTRACT_16BITS(&ldp_com_header->version) != LDP_VERSION) { ND_PRINT((ndo, "%sLDP version %u packet not supported", (ndo->ndo_vflag < 1) ? "" : "\n\t", EXTRACT_16BITS(&ldp_com_header->version))); return 0; } pdu_len = EXTRACT_16BITS(&ldp_com_header->pdu_length); if (pdu_len < sizeof(const struct ldp_common_header)-4) { /* length too short */ ND_PRINT((ndo, "%sLDP, pdu-length: %u (too short, < %u)", (ndo->ndo_vflag < 1) ? "" : "\n\t", pdu_len, (u_int)(sizeof(const struct ldp_common_header)-4))); return 0; } /* print the LSR-ID, label-space & length */ ND_PRINT((ndo, "%sLDP, Label-Space-ID: %s:%u, pdu-length: %u", (ndo->ndo_vflag < 1) ? "" : "\n\t", ipaddr_string(ndo, &ldp_com_header->lsr_id), EXTRACT_16BITS(&ldp_com_header->label_space), pdu_len)); /* bail out if non-verbose */ if (ndo->ndo_vflag < 1) return 0; /* ok they seem to want to know everything - lets fully decode it */ tptr = pptr + sizeof(const struct ldp_common_header); tlen = pdu_len - (sizeof(const struct ldp_common_header)-4); /* Type & Length fields not included */ while(tlen>0) { /* did we capture enough for fully decoding the msg header ? */ ND_TCHECK2(*tptr, sizeof(struct ldp_msg_header)); ldp_msg_header = (const struct ldp_msg_header *)tptr; msg_len=EXTRACT_16BITS(ldp_msg_header->length); msg_type=LDP_MASK_MSG_TYPE(EXTRACT_16BITS(ldp_msg_header->type)); if (msg_len < sizeof(struct ldp_msg_header)-4) { /* length too short */ /* FIXME vendor private / experimental check */ ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u (too short, < %u)", tok2str(ldp_msg_values, "Unknown", msg_type), msg_type, msg_len, (u_int)(sizeof(struct ldp_msg_header)-4))); return 0; } /* FIXME vendor private / experimental check */ ND_PRINT((ndo, "\n\t %s Message (0x%04x), length: %u, Message ID: 0x%08x, Flags: [%s if unknown]", tok2str(ldp_msg_values, "Unknown", msg_type), msg_type, msg_len, EXTRACT_32BITS(&ldp_msg_header->id), LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_msg_header->type)) ? "continue processing" : "ignore")); msg_tptr=tptr+sizeof(struct ldp_msg_header); msg_tlen=msg_len-(sizeof(struct ldp_msg_header)-4); /* Type & Length fields not included */ /* did we capture enough for fully decoding the message ? */ ND_TCHECK2(*tptr, msg_len); hexdump=FALSE; switch(msg_type) { case LDP_MSG_NOTIF: case LDP_MSG_HELLO: case LDP_MSG_INIT: case LDP_MSG_KEEPALIVE: case LDP_MSG_ADDRESS: case LDP_MSG_LABEL_MAPPING: case LDP_MSG_ADDRESS_WITHDRAW: case LDP_MSG_LABEL_WITHDRAW: while(msg_tlen >= 4) { processed = ldp_tlv_print(ndo, msg_tptr, msg_tlen); if (processed == 0) break; msg_tlen-=processed; msg_tptr+=processed; } break; /* * FIXME those are the defined messages that lack a decoder * you are welcome to contribute code ;-) */ case LDP_MSG_LABEL_REQUEST: case LDP_MSG_LABEL_RELEASE: case LDP_MSG_LABEL_ABORT_REQUEST: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, msg_tptr, "\n\t ", msg_tlen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag > 1 || hexdump==TRUE) print_unknown_data(ndo, tptr+sizeof(struct ldp_msg_header), "\n\t ", msg_len); tptr += msg_len+4; tlen -= msg_len+4; } return pdu_len+4; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: FetchContext* FrameFetchContext::Detach() { if (IsDetached()) return this; if (document_) { frozen_state_ = new FrozenState( GetReferrerPolicy(), GetOutgoingReferrer(), Url(), GetSecurityOrigin(), GetParentSecurityOrigin(), GetAddressSpace(), GetContentSecurityPolicy(), GetSiteForCookies(), GetRequestorOrigin(), GetRequestorOriginForFrameLoading(), GetClientHintsPreferences(), GetDevicePixelRatio(), GetUserAgent(), IsMainFrame(), IsSVGImageChromeClient()); } else { frozen_state_ = new FrozenState( kReferrerPolicyDefault, String(), NullURL(), GetSecurityOrigin(), GetParentSecurityOrigin(), GetAddressSpace(), GetContentSecurityPolicy(), GetSiteForCookies(), SecurityOrigin::CreateUnique(), SecurityOrigin::CreateUnique(), GetClientHintsPreferences(), GetDevicePixelRatio(), GetUserAgent(), IsMainFrame(), IsSVGImageChromeClient()); } document_ = nullptr; return this; } 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 HistogramEnumerateManifestIsDataURI(bool is_data_uri) { HistogramEnumerate("NaCl.Manifest.IsDataURI", is_data_uri, 2, -1); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: tt_sbit_decoder_init( TT_SBitDecoder decoder, TT_Face face, FT_ULong strike_index, TT_SBit_MetricsRec* metrics ) { FT_Error error; FT_Stream stream = face->root.stream; FT_ULong ebdt_size; error = face->goto_table( face, TTAG_CBDT, stream, &ebdt_size ); if ( error ) error = face->goto_table( face, TTAG_EBDT, stream, &ebdt_size ); if ( error ) error = face->goto_table( face, TTAG_bdat, stream, &ebdt_size ); if ( error ) goto Exit; decoder->face = face; decoder->stream = stream; decoder->bitmap = &face->root.glyph->bitmap; decoder->metrics = metrics; decoder->metrics_loaded = 0; decoder->bitmap_allocated = 0; decoder->ebdt_start = FT_STREAM_POS(); decoder->ebdt_size = ebdt_size; decoder->eblc_base = face->sbit_table; decoder->eblc_limit = face->sbit_table + face->sbit_table_size; /* now find the strike corresponding to the index */ { FT_Byte* p; if ( 8 + 48 * strike_index + 3 * 4 + 34 + 1 > face->sbit_table_size ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } p = decoder->eblc_base + 8 + 48 * strike_index; decoder->strike_index_array = FT_NEXT_ULONG( p ); p += 4; decoder->strike_index_count = FT_NEXT_ULONG( p ); p += 34; decoder->bit_depth = *p; if ( decoder->strike_index_array > face->sbit_table_size || decoder->strike_index_array + 8 * decoder->strike_index_count > face->sbit_table_size ) error = FT_THROW( Invalid_File_Format ); } } CWE ID: CWE-189 Target: 1 Example 2: Code: struct page *alloc_buddy_huge_page_with_mpol(struct hstate *h, struct vm_area_struct *vma, unsigned long addr) { struct page *page; struct mempolicy *mpol; gfp_t gfp_mask = htlb_alloc_mask(h); int nid; nodemask_t *nodemask; nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask); page = alloc_surplus_huge_page(h, gfp_mask, nid, nodemask); mpol_cond_put(mpol); return 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: prng_reset_nonce () { const int size = md_kt_size (nonce_md) + nonce_secret_len; #if 1 /* Must be 1 for real usage */ if (!rand_bytes (nonce_data, size)) msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for PRNG"); #else /* Only for testing -- will cause a predictable PRNG sequence */ { int i; for (i = 0; i < size; ++i) nonce_data[i] = (uint8_t) i; } #endif } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static __u8 *ch_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 17 && rdesc[11] == 0x3c && rdesc[12] == 0x02) { hid_info(hdev, "fixing up Cherry Cymotion report descriptor\n"); rdesc[11] = rdesc[16] = 0xff; rdesc[12] = rdesc[17] = 0x03; } return rdesc; } CWE ID: CWE-119 Target: 1 Example 2: Code: XineramaGetCursorScreen(DeviceIntPtr pDev) { if (!noPanoramiXExtension) { return pDev->spriteInfo->sprite->screen->myNum; } else { return 0; } } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { unsigned long quirks = (unsigned long)hid_get_drvdata(hdev); unsigned int i; if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX)) return rdesc; for (i = 0; i < *rsize - 4; i++) if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) { rdesc[i] = 0x19; rdesc[i + 2] = 0x29; swap(rdesc[i + 3], rdesc[i + 1]); } return rdesc; } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static boolean str_fill_input_buffer(j_decompress_ptr cinfo) { int c; struct str_src_mgr * src = (struct str_src_mgr *)cinfo->src; if (src->abort) return FALSE; if (src->index == 0) { c = 0xFF; src->index++; src->index++; } else if (src->index == 1) { c = 0xD8; src->index++; } else c = src->str->getChar(); if (c != EOF) { src->buffer = c; src->pub.next_input_byte = &src->buffer; src->pub.bytes_in_buffer = 1; return TRUE; } else return FALSE; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int try_to_unuse(unsigned int type) { struct swap_info_struct *si = swap_info[type]; struct mm_struct *start_mm; unsigned char *swap_map; unsigned char swcount; struct page *page; swp_entry_t entry; unsigned int i = 0; int retval = 0; /* * When searching mms for an entry, a good strategy is to * start at the first mm we freed the previous entry from * (though actually we don't notice whether we or coincidence * freed the entry). Initialize this start_mm with a hold. * * A simpler strategy would be to start at the last mm we * freed the previous entry from; but that would take less * advantage of mmlist ordering, which clusters forked mms * together, child after parent. If we race with dup_mmap(), we * prefer to resolve parent before child, lest we miss entries * duplicated after we scanned child: using last mm would invert * that. */ start_mm = &init_mm; atomic_inc(&init_mm.mm_users); /* * Keep on scanning until all entries have gone. Usually, * one pass through swap_map is enough, but not necessarily: * there are races when an instance of an entry might be missed. */ while ((i = find_next_to_unuse(si, i)) != 0) { if (signal_pending(current)) { retval = -EINTR; break; } /* * Get a page for the entry, using the existing swap * cache page if there is one. Otherwise, get a clean * page and read the swap into it. */ swap_map = &si->swap_map[i]; entry = swp_entry(type, i); page = read_swap_cache_async(entry, GFP_HIGHUSER_MOVABLE, NULL, 0); if (!page) { /* * Either swap_duplicate() failed because entry * has been freed independently, and will not be * reused since sys_swapoff() already disabled * allocation from here, or alloc_page() failed. */ if (!*swap_map) continue; retval = -ENOMEM; break; } /* * Don't hold on to start_mm if it looks like exiting. */ if (atomic_read(&start_mm->mm_users) == 1) { mmput(start_mm); start_mm = &init_mm; atomic_inc(&init_mm.mm_users); } /* * Wait for and lock page. When do_swap_page races with * try_to_unuse, do_swap_page can handle the fault much * faster than try_to_unuse can locate the entry. This * apparently redundant "wait_on_page_locked" lets try_to_unuse * defer to do_swap_page in such a case - in some tests, * do_swap_page and try_to_unuse repeatedly compete. */ wait_on_page_locked(page); wait_on_page_writeback(page); lock_page(page); wait_on_page_writeback(page); /* * Remove all references to entry. */ swcount = *swap_map; if (swap_count(swcount) == SWAP_MAP_SHMEM) { retval = shmem_unuse(entry, page); /* page has already been unlocked and released */ if (retval < 0) break; continue; } if (swap_count(swcount) && start_mm != &init_mm) retval = unuse_mm(start_mm, entry, page); if (swap_count(*swap_map)) { int set_start_mm = (*swap_map >= swcount); struct list_head *p = &start_mm->mmlist; struct mm_struct *new_start_mm = start_mm; struct mm_struct *prev_mm = start_mm; struct mm_struct *mm; atomic_inc(&new_start_mm->mm_users); atomic_inc(&prev_mm->mm_users); spin_lock(&mmlist_lock); while (swap_count(*swap_map) && !retval && (p = p->next) != &start_mm->mmlist) { mm = list_entry(p, struct mm_struct, mmlist); if (!atomic_inc_not_zero(&mm->mm_users)) continue; spin_unlock(&mmlist_lock); mmput(prev_mm); prev_mm = mm; cond_resched(); swcount = *swap_map; if (!swap_count(swcount)) /* any usage ? */ ; else if (mm == &init_mm) set_start_mm = 1; else retval = unuse_mm(mm, entry, page); if (set_start_mm && *swap_map < swcount) { mmput(new_start_mm); atomic_inc(&mm->mm_users); new_start_mm = mm; set_start_mm = 0; } spin_lock(&mmlist_lock); } spin_unlock(&mmlist_lock); mmput(prev_mm); mmput(start_mm); start_mm = new_start_mm; } if (retval) { unlock_page(page); page_cache_release(page); break; } /* * If a reference remains (rare), we would like to leave * the page in the swap cache; but try_to_unmap could * then re-duplicate the entry once we drop page lock, * so we might loop indefinitely; also, that page could * not be swapped out to other storage meanwhile. So: * delete from cache even if there's another reference, * after ensuring that the data has been saved to disk - * since if the reference remains (rarer), it will be * read from disk into another page. Splitting into two * pages would be incorrect if swap supported "shared * private" pages, but they are handled by tmpfs files. * * Given how unuse_vma() targets one particular offset * in an anon_vma, once the anon_vma has been determined, * this splitting happens to be just what is needed to * handle where KSM pages have been swapped out: re-reading * is unnecessarily slow, but we can fix that later on. */ if (swap_count(*swap_map) && PageDirty(page) && PageSwapCache(page)) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, }; swap_writepage(page, &wbc); lock_page(page); wait_on_page_writeback(page); } /* * It is conceivable that a racing task removed this page from * swap cache just before we acquired the page lock at the top, * or while we dropped it in unuse_mm(). The page might even * be back in swap cache on another swap area: that we must not * delete, since it may not have been written out to swap yet. */ if (PageSwapCache(page) && likely(page_private(page) == entry.val)) delete_from_swap_cache(page); /* * So we could skip searching mms once swap count went * to 1, we did not mark any present ptes as dirty: must * mark page dirty so shrink_page_list will preserve it. */ SetPageDirty(page); unlock_page(page); page_cache_release(page); /* * Make sure that we aren't completely killing * interactive performance. */ cond_resched(); } mmput(start_mm); return retval; } 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: xmlThrDefSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler) { xmlMutexLock(xmlThrDefMutex); xmlGenericErrorContextThrDef = ctx; if (handler != NULL) xmlGenericErrorThrDef = handler; else xmlGenericErrorThrDef = xmlGenericErrorDefaultFunc; xmlMutexUnlock(xmlThrDefMutex); } 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: gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs) { gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern; gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace; int code; uchar k, num_comps; pinst->saved->overprint_mode = pgs->overprint_mode; pinst->saved->overprint = pgs->overprint; num_comps = pgs->device->color_info.num_components; for (k = 0; k < num_comps; k++) { pgs->color_component_map.color_map[k] = pinst->saved->color_component_map.color_map[k]; } code = pcs->type->set_overprint(pcs, pgs); return code; } CWE ID: CWE-704 Target: 1 Example 2: Code: AcceleratedStaticBitmapImage::CreateFromSkImage( sk_sp<SkImage> image, base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper) { CHECK(image && image->isTextureBacked()); return base::AdoptRef(new AcceleratedStaticBitmapImage( std::move(image), std::move(context_provider_wrapper))); } 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 struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv, int listener) { struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL); if (!cma_xprt) return NULL; svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv); INIT_LIST_HEAD(&cma_xprt->sc_accept_q); INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q); INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q); INIT_LIST_HEAD(&cma_xprt->sc_frmr_q); INIT_LIST_HEAD(&cma_xprt->sc_ctxts); INIT_LIST_HEAD(&cma_xprt->sc_maps); init_waitqueue_head(&cma_xprt->sc_send_wait); spin_lock_init(&cma_xprt->sc_lock); spin_lock_init(&cma_xprt->sc_rq_dto_lock); spin_lock_init(&cma_xprt->sc_frmr_q_lock); spin_lock_init(&cma_xprt->sc_ctxt_lock); spin_lock_init(&cma_xprt->sc_map_lock); /* * Note that this implies that the underlying transport support * has some form of congestion control (see RFC 7530 section 3.1 * paragraph 2). For now, we assume that all supported RDMA * transports are suitable here. */ set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags); if (listener) set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags); return cma_xprt; } 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: long Cluster::GetFirst(const BlockEntry*& pFirst) const { if (m_entries_count <= 0) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //error { pFirst = NULL; return status; } if (m_entries_count <= 0) //empty cluster { pFirst = NULL; return 0; } } assert(m_entries); pFirst = m_entries[0]; assert(pFirst); return 0; //success } CWE ID: CWE-119 Target: 1 Example 2: Code: static void fdctrl_handle_powerdown_mode(FDCtrl *fdctrl, int direction) { fdctrl->pwrd = fdctrl->fifo[1]; fdctrl->fifo[0] = fdctrl->fifo[1]; fdctrl_set_fifo(fdctrl, 1); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: my_object_error_quark (void) { static GQuark quark = 0; if (!quark) quark = g_quark_from_static_string ("my_object_error"); return quark; } 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 read_sequence_header(decoder_info_t *decoder_info, stream_t *stream) { decoder_info->width = get_flc(16, stream); decoder_info->height = get_flc(16, stream); decoder_info->log2_sb_size = get_flc(3, stream); decoder_info->pb_split = get_flc(1, stream); decoder_info->tb_split_enable = get_flc(1, stream); decoder_info->max_num_ref = get_flc(2, stream) + 1; decoder_info->interp_ref = get_flc(2, stream); decoder_info->max_delta_qp = get_flc(1, stream); decoder_info->deblocking = get_flc(1, stream); decoder_info->clpf = get_flc(1, stream); decoder_info->use_block_contexts = get_flc(1, stream); decoder_info->bipred = get_flc(2, stream); decoder_info->qmtx = get_flc(1, stream); if (decoder_info->qmtx) { decoder_info->qmtx_offset = get_flc(6, stream) - 32; } decoder_info->subsample = get_flc(2, stream); decoder_info->subsample = // 0: 400 1: 420 2: 422 3: 444 (decoder_info->subsample & 1) * 20 + (decoder_info->subsample & 2) * 22 + ((decoder_info->subsample & 3) == 3) * 2 + 400; decoder_info->num_reorder_pics = get_flc(4, stream); if (decoder_info->subsample != 400) { decoder_info->cfl_intra = get_flc(1, stream); decoder_info->cfl_inter = get_flc(1, stream); } decoder_info->bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->bitdepth == 10) decoder_info->bitdepth += 2 * get_flc(1, stream); decoder_info->input_bitdepth = get_flc(1, stream) ? 10 : 8; if (decoder_info->input_bitdepth == 10) decoder_info->input_bitdepth += 2 * get_flc(1, stream); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool ExtensionApiTest::InitializeEmbeddedTestServer() { if (!embedded_test_server()->InitializeAndListen()) return false; if (test_config_) { test_config_->SetInteger(kEmbeddedTestServerPort, embedded_test_server()->port()); } return true; } 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: nvmet_fc_handle_fcp_rqst_work(struct work_struct *work) { struct nvmet_fc_fcp_iod *fod = container_of(work, struct nvmet_fc_fcp_iod, work); struct nvmet_fc_tgtport *tgtport = fod->tgtport; nvmet_fc_handle_fcp_rqst(tgtport, fod); } 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: PluginChannel::PluginChannel() : renderer_handle_(0), renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()) { set_send_unblocking_only_during_unblock_dispatch(); ChildProcess::current()->AddRefProcess(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); } CWE ID: Target: 1 Example 2: Code: UTF8ToHtml(unsigned char* out, int *outlen, const unsigned char* in, int *inlen) { const unsigned char* processed = in; const unsigned char* outend; const unsigned char* outstart = out; const unsigned char* instart = in; const unsigned char* inend; unsigned int c, d; int trailing; if ((out == NULL) || (outlen == NULL) || (inlen == NULL)) return(-1); if (in == NULL) { /* * initialization nothing to do */ *outlen = 0; *inlen = 0; return(0); } inend = in + (*inlen); outend = out + (*outlen); while (in < inend) { d = *in++; if (d < 0x80) { c= d; trailing= 0; } else if (d < 0xC0) { /* trailing byte in leading position */ *outlen = out - outstart; *inlen = processed - instart; return(-2); } else if (d < 0xE0) { c= d & 0x1F; trailing= 1; } else if (d < 0xF0) { c= d & 0x0F; trailing= 2; } else if (d < 0xF8) { c= d & 0x07; trailing= 3; } else { /* no chance for this in Ascii */ *outlen = out - outstart; *inlen = processed - instart; return(-2); } if (inend - in < trailing) { break; } for ( ; trailing; trailing--) { if ((in >= inend) || (((d= *in++) & 0xC0) != 0x80)) break; c <<= 6; c |= d & 0x3F; } /* assertion: c is a single UTF-4 value */ if (c < 0x80) { if (out + 1 >= outend) break; *out++ = c; } else { int len; const htmlEntityDesc * ent; const char *cp; char nbuf[16]; /* * Try to lookup a predefined HTML entity for it */ ent = htmlEntityValueLookup(c); if (ent == NULL) { snprintf(nbuf, sizeof(nbuf), "#%u", c); cp = nbuf; } else cp = ent->name; len = strlen(cp); if (out + 2 + len >= outend) break; *out++ = '&'; memcpy(out, cp, len); out += len; *out++ = ';'; } processed = in; } *outlen = out - outstart; *inlen = processed - instart; return(0); } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int samldb_schema_info_update(struct samldb_ctx *ac) { int ret; struct ldb_context *ldb; struct dsdb_schema *schema; /* replicated update should always go through */ if (ldb_request_get_control(ac->req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) { return LDB_SUCCESS; } /* do not update schemaInfo during provisioning */ if (ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) { return LDB_SUCCESS; } ldb = ldb_module_get_ctx(ac->module); schema = dsdb_get_schema(ldb, NULL); if (!schema) { ldb_debug_set(ldb, LDB_DEBUG_FATAL, "samldb_schema_info_update: no dsdb_schema loaded"); DEBUG(0,(__location__ ": %s\n", ldb_errstring(ldb))); return ldb_operr(ldb); } ret = dsdb_module_schema_info_update(ac->module, schema, DSDB_FLAG_NEXT_MODULE| DSDB_FLAG_AS_SYSTEM, ac->req); if (ret != LDB_SUCCESS) { ldb_asprintf_errstring(ldb, "samldb_schema_info_update: dsdb_module_schema_info_update failed with %s", ldb_errstring(ldb)); return ret; } return LDB_SUCCESS; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SupervisedUserService::InitSync(const std::string& refresh_token) { ProfileOAuth2TokenService* token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); token_service->UpdateCredentials(supervised_users::kSupervisedUserPseudoEmail, refresh_token); } CWE ID: CWE-20 Target: 1 Example 2: Code: void reds_on_main_agent_start(MainChannelClient *mcc, uint32_t num_tokens) { SpiceCharDeviceState *dev_state = reds->agent_state.base; RedChannelClient *rcc; if (!vdagent) { return; } spice_assert(vdagent->st && vdagent->st == dev_state); rcc = main_channel_client_get_base(mcc); reds->agent_state.client_agent_started = TRUE; /* * Note that in older releases, send_tokens were set to ~0 on both client * and server. The server ignored the client given tokens. * Thanks to that, when an old client is connected to a new server, * and vice versa, the sending from the server to the client won't have * flow control, but will have no other problem. */ if (!spice_char_device_client_exists(dev_state, rcc->client)) { int client_added; client_added = spice_char_device_client_add(dev_state, rcc->client, TRUE, /* flow control */ REDS_VDI_PORT_NUM_RECEIVE_BUFFS, REDS_AGENT_WINDOW_SIZE, num_tokens, red_channel_client_waits_for_migrate_data(rcc)); if (!client_added) { spice_warning("failed to add client to agent"); red_channel_client_shutdown(rcc); return; } } else { spice_char_device_send_to_client_tokens_set(dev_state, rcc->client, num_tokens); } reds->agent_state.write_filter.discard_all = FALSE; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) { unsigned i; unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; unsigned char *chunk_start, *new_buffer; size_t new_length = (*outlength) + total_chunk_length; if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/ new_buffer = (unsigned char*)realloc(*out, new_length); if(!new_buffer) return 83; /*alloc fail*/ (*out) = new_buffer; (*outlength) = new_length; chunk_start = &(*out)[new_length - total_chunk_length]; for(i = 0; i < total_chunk_length; i++) chunk_start[i] = chunk[i]; return 0; } 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 PeopleHandler::HandleSignout(const base::ListValue* args) { bool delete_profile = false; args->GetBoolean(0, &delete_profile); if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) { DCHECK(delete_profile); } else { SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_); if (signin_manager->IsAuthenticated()) { if (GetSyncService()) ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS); signin_metrics::SignoutDelete delete_metric = delete_profile ? signin_metrics::SignoutDelete::DELETED : signin_metrics::SignoutDelete::KEEPING; signin_manager->SignOutAndRemoveAllAccounts( signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric); } else { DCHECK(!delete_profile) << "Deleting the profile should only be offered the user is syncing."; ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) ->RevokeAllCredentials(); } } if (delete_profile) { webui::DeleteProfileAtPath(profile_->GetPath(), ProfileMetrics::DELETE_PROFILE_SETTINGS); } } CWE ID: CWE-20 Target: 1 Example 2: Code: AcpiNsGetInternalNameLength ( ACPI_NAMESTRING_INFO *Info) { const char *NextExternalChar; UINT32 i; ACPI_FUNCTION_ENTRY (); NextExternalChar = Info->ExternalName; Info->NumCarats = 0; Info->NumSegments = 0; Info->FullyQualified = FALSE; /* * For the internal name, the required length is 4 bytes per segment, * plus 1 each for RootPrefix, MultiNamePrefixOp, segment count, * trailing null (which is not really needed, but no there's harm in * putting it there) * * strlen() + 1 covers the first NameSeg, which has no path separator */ if (ACPI_IS_ROOT_PREFIX (*NextExternalChar)) { Info->FullyQualified = TRUE; NextExternalChar++; /* Skip redundant RootPrefix, like \\_SB.PCI0.SBRG.EC0 */ while (ACPI_IS_ROOT_PREFIX (*NextExternalChar)) { NextExternalChar++; } } else { /* Handle Carat prefixes */ while (ACPI_IS_PARENT_PREFIX (*NextExternalChar)) { Info->NumCarats++; NextExternalChar++; } } /* * Determine the number of ACPI name "segments" by counting the number of * path separators within the string. Start with one segment since the * segment count is [(# separators) + 1], and zero separators is ok. */ if (*NextExternalChar) { Info->NumSegments = 1; for (i = 0; NextExternalChar[i]; i++) { if (ACPI_IS_PATH_SEPARATOR (NextExternalChar[i])) { Info->NumSegments++; } } } Info->Length = (ACPI_NAME_SIZE * Info->NumSegments) + 4 + Info->NumCarats; Info->NextExternalChar = NextExternalChar; } CWE ID: CWE-755 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 RenderMessageFilter::OnCreateWindow( const ViewHostMsg_CreateWindow_Params& params, int* route_id, int* surface_id, int64* cloned_session_storage_namespace_id) { bool no_javascript_access; bool can_create_window = GetContentClient()->browser()->CanCreateWindow( GURL(params.opener_url), GURL(params.opener_security_origin), params.window_container_type, resource_context_, render_process_id_, &no_javascript_access); if (!can_create_window) { *route_id = MSG_ROUTING_NONE; *surface_id = 0; return; } scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace = new SessionStorageNamespaceImpl(dom_storage_context_, params.session_storage_namespace_id); *cloned_session_storage_namespace_id = cloned_namespace->id(); render_widget_helper_->CreateNewWindow(params, no_javascript_access, peer_handle(), route_id, surface_id, cloned_namespace); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static base::Callback<void(const gfx::Image&)> Wrap( const base::Callback<void(const SkBitmap&)>& image_decoded_callback) { auto* handler = new ImageDecodedHandlerWithTimeout(image_decoded_callback); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr(), gfx::Image()), base::TimeDelta::FromSeconds(kDecodeLogoTimeoutSeconds)); return base::Bind(&ImageDecodedHandlerWithTimeout::OnImageDecoded, handler->weak_ptr_factory_.GetWeakPtr()); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int prepare_reply(struct genl_info *info, u8 cmd, struct sk_buff **skbp, size_t size) { struct sk_buff *skb; void *reply; /* * If new attributes are added, please revisit this allocation */ skb = genlmsg_new(size, GFP_KERNEL); if (!skb) return -ENOMEM; if (!info) { int seq = this_cpu_inc_return(taskstats_seqnum) - 1; reply = genlmsg_put(skb, 0, seq, &family, 0, cmd); } else reply = genlmsg_put_reply(skb, info, &family, 0, cmd); if (reply == NULL) { nlmsg_free(skb); return -EINVAL; } *skbp = skb; return 0; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int usbnet_nway_reset(struct net_device *net) { struct usbnet *dev = netdev_priv(net); if (!dev->mii.mdio_write) return -EOPNOTSUPP; return mii_nway_restart(&dev->mii); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } CWE ID: CWE-20 Target: 1 Example 2: Code: check_sparse_region (struct tar_sparse_file *file, off_t beg, off_t end) { if (!lseek_or_error (file, beg)) return false; while (beg < end) { size_t bytes_read; size_t rdsize = BLOCKSIZE < end - beg ? BLOCKSIZE : end - beg; char diff_buffer[BLOCKSIZE]; bytes_read = safe_read (file->fd, diff_buffer, rdsize); if (bytes_read == SAFE_READ_ERROR) { read_diag_details (file->stat_info->orig_file_name, beg, rdsize); return false; } if (!zero_block_p (diff_buffer, bytes_read)) { char begbuf[INT_BUFSIZE_BOUND (off_t)]; report_difference (file->stat_info, _("File fragment at %s is not a hole"), offtostr (beg, begbuf)); return false; } beg += bytes_read; } return true; } CWE ID: CWE-835 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int nf_tables_fill_gen_info(struct sk_buff *skb, struct net *net, u32 portid, u32 seq) { struct nlmsghdr *nlh; struct nfgenmsg *nfmsg; int event = (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_NEWGEN; nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), 0); if (nlh == NULL) goto nla_put_failure; nfmsg = nlmsg_data(nlh); nfmsg->nfgen_family = AF_UNSPEC; nfmsg->version = NFNETLINK_V0; nfmsg->res_id = htons(net->nft.base_seq & 0xffff); if (nla_put_be32(skb, NFTA_GEN_ID, htonl(net->nft.base_seq))) goto nla_put_failure; return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_trim(skb, nlh); return -EMSGSIZE; } 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: void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& suggested_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); callback.Run(suggested_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")), content::DOWNLOAD_INTERRUPT_REASON_NONE); } CWE ID: Target: 1 Example 2: Code: void GLES2DecoderPassthroughImpl::SetSurface( const scoped_refptr<gl::GLSurface>& surface) { DCHECK(context_->IsCurrent(nullptr)); DCHECK(surface_.get()); surface_ = surface; } 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: video_usercopy(struct file *file, unsigned int cmd, unsigned long arg, v4l2_kioctl func) { char sbuf[128]; void *mbuf = NULL; void *parg = NULL; long err = -EINVAL; int is_ext_ctrl; size_t ctrls_size = 0; void __user *user_ptr = NULL; is_ext_ctrl = (cmd == VIDIOC_S_EXT_CTRLS || cmd == VIDIOC_G_EXT_CTRLS || cmd == VIDIOC_TRY_EXT_CTRLS); /* Copy arguments into temp kernel buffer */ switch (_IOC_DIR(cmd)) { case _IOC_NONE: parg = NULL; break; case _IOC_READ: case _IOC_WRITE: case (_IOC_WRITE | _IOC_READ): if (_IOC_SIZE(cmd) <= sizeof(sbuf)) { parg = sbuf; } else { /* too big to allocate from stack */ mbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL); if (NULL == mbuf) return -ENOMEM; parg = mbuf; } err = -EFAULT; if (_IOC_DIR(cmd) & _IOC_WRITE) if (copy_from_user(parg, (void __user *)arg, _IOC_SIZE(cmd))) goto out; break; } if (is_ext_ctrl) { struct v4l2_ext_controls *p = parg; /* In case of an error, tell the caller that it wasn't a specific control that caused it. */ p->error_idx = p->count; user_ptr = (void __user *)p->controls; if (p->count) { ctrls_size = sizeof(struct v4l2_ext_control) * p->count; /* Note: v4l2_ext_controls fits in sbuf[] so mbuf is still NULL. */ mbuf = kmalloc(ctrls_size, GFP_KERNEL); err = -ENOMEM; if (NULL == mbuf) goto out_ext_ctrl; err = -EFAULT; if (copy_from_user(mbuf, user_ptr, ctrls_size)) goto out_ext_ctrl; p->controls = mbuf; } } /* call driver */ err = func(file, cmd, parg); if (err == -ENOIOCTLCMD) err = -EINVAL; if (is_ext_ctrl) { struct v4l2_ext_controls *p = parg; p->controls = (void *)user_ptr; if (p->count && err == 0 && copy_to_user(user_ptr, mbuf, ctrls_size)) err = -EFAULT; goto out_ext_ctrl; } if (err < 0) goto out; out_ext_ctrl: /* Copy results into user buffer */ switch (_IOC_DIR(cmd)) { case _IOC_READ: case (_IOC_WRITE | _IOC_READ): if (copy_to_user((void __user *)arg, parg, _IOC_SIZE(cmd))) err = -EFAULT; break; } out: kfree(mbuf); return err; } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type) { /* XML 1.0 HTML 4.01 HTML 5 * 0x09..0x0A 0x09..0x0A 0x09..0x0A * 0x0D 0x0D 0x0C..0x0D * 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E * 0x00A0..0xD7FF 0x00A0..0xD7FF * 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF * 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*) * * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE) * * References: * XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets> * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html> * HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream> * * Not sure this is the relevant part for HTML 5, though. I opted to * disallow the characters that would result in a parse error when * preprocessing of the input stream. See also section 8.1.3. * * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to * XHTML 1.0 the same rules as for XML 1.0. * See <http://cmsmcq.com/2007/C1.xml>. */ switch (document_type) { case ENT_HTML_DOC_HTML401: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF); case ENT_HTML_DOC_HTML5: return (uni_cp >= 0x20 && uni_cp <= 0x7E) || (uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */ (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */ (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */ case ENT_HTML_DOC_XHTML: case ENT_HTML_DOC_XML1: return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) || (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) || (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF); default: return 1; } } CWE ID: CWE-190 Target: 1 Example 2: Code: void comps_objmrtree_clear(COMPS_ObjMRTree * rt) { COMPS_HSListItem *it, *oldit; if (rt == NULL) return; if (rt->subnodes == NULL) return; oldit = rt->subnodes->first; it = (oldit)?oldit->next:NULL; for (;it != NULL; it=it->next) { if (rt->subnodes->data_destructor != NULL) rt->subnodes->data_destructor(oldit->data); free(oldit); oldit = it; } if (oldit) { if (rt->subnodes->data_destructor != NULL) rt->subnodes->data_destructor(oldit->data); free(oldit); } } 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: ospf6_print(netdissect_options *ndo, register const u_char *bp, register u_int length) { register const struct ospf6hdr *op; register const u_char *dataend; register const char *cp; uint16_t datalen; op = (const struct ospf6hdr *)bp; /* If the type is valid translate it, or just print the type */ /* value. If it's not valid, say so and return */ ND_TCHECK(op->ospf6_type); cp = tok2str(ospf6_type_values, "unknown packet type (%u)", op->ospf6_type); ND_PRINT((ndo, "OSPFv%u, %s, length %d", op->ospf6_version, cp, length)); if (*cp == 'u') { return; } if(!ndo->ndo_vflag) { /* non verbose - so lets bail out here */ return; } /* OSPFv3 data always comes first and optional trailing data may follow. */ ND_TCHECK(op->ospf6_len); datalen = EXTRACT_16BITS(&op->ospf6_len); if (datalen > length) { ND_PRINT((ndo, " [len %d]", datalen)); return; } dataend = bp + datalen; ND_TCHECK(op->ospf6_routerid); ND_PRINT((ndo, "\n\tRouter-ID %s", ipaddr_string(ndo, &op->ospf6_routerid))); ND_TCHECK(op->ospf6_areaid); if (EXTRACT_32BITS(&op->ospf6_areaid) != 0) ND_PRINT((ndo, ", Area %s", ipaddr_string(ndo, &op->ospf6_areaid))); else ND_PRINT((ndo, ", Backbone Area")); ND_TCHECK(op->ospf6_instanceid); if (op->ospf6_instanceid) ND_PRINT((ndo, ", Instance %u", op->ospf6_instanceid)); /* Do rest according to version. */ switch (op->ospf6_version) { case 3: /* ospf version 3 */ if (ospf6_decode_v3(ndo, op, dataend) || ospf6_decode_v3_trailer(ndo, op, dataend, length - datalen)) goto trunc; break; } /* end switch on version */ return; trunc: ND_PRINT((ndo, "%s", tstr)); } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem ) { cJSON *c = array->child; while ( c && which > 0 ) { c = c->next; --which; } if ( ! c ) return; newitem->next = c->next; newitem->prev = c->prev; if ( newitem->next ) newitem->next->prev = newitem; if ( c == array->child ) array->child = newitem; else newitem->prev->next = newitem; c->next = c->prev = 0; cJSON_Delete( c ); } CWE ID: CWE-119 Target: 1 Example 2: Code: void *jas_alloc3(size_t num_arrays, size_t array_size, size_t element_size) { size_t size; if (!jas_safe_size_mul(array_size, element_size, &size) || !jas_safe_size_mul(size, num_arrays, &size)) { return 0; } return jas_malloc(size); } 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 SetOnSentData( const base::Callback<void(SocketStreamEvent*)>& callback) { on_sent_data_ = callback; } 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: isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); } CWE ID: CWE-125 Target: 1 Example 2: Code: struct kvm_vcpu *kvm_arm_get_running_vcpu(void) { BUG_ON(preemptible()); return __get_cpu_var(kvm_arm_running_vcpu); } 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 NetworkHandler::GetAllCookies( std::unique_ptr<GetAllCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } scoped_refptr<CookieRetriever> retriever = new CookieRetriever(std::move(callback)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &CookieRetriever::RetrieveAllCookiesOnIO, retriever, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()))); } 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: struct sctp_chunk *sctp_inq_pop(struct sctp_inq *queue) { struct sctp_chunk *chunk; sctp_chunkhdr_t *ch = NULL; /* The assumption is that we are safe to process the chunks * at this time. */ if ((chunk = queue->in_progress)) { /* There is a packet that we have been working on. * Any post processing work to do before we move on? */ if (chunk->singleton || chunk->end_of_packet || chunk->pdiscard) { sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; } else { /* Nothing to do. Next chunk in the packet, please. */ ch = (sctp_chunkhdr_t *) chunk->chunk_end; /* Force chunk->skb->data to chunk->chunk_end. */ skb_pull(chunk->skb, chunk->chunk_end - chunk->skb->data); /* Verify that we have at least chunk headers * worth of buffer left. */ if (skb_headlen(chunk->skb) < sizeof(sctp_chunkhdr_t)) { sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; } } } /* Do we need to take the next packet out of the queue to process? */ if (!chunk) { struct list_head *entry; /* Is the queue empty? */ if (list_empty(&queue->in_chunk_list)) return NULL; entry = queue->in_chunk_list.next; chunk = queue->in_progress = list_entry(entry, struct sctp_chunk, list); list_del_init(entry); /* This is the first chunk in the packet. */ chunk->singleton = 1; ch = (sctp_chunkhdr_t *) chunk->skb->data; chunk->data_accepted = 0; } chunk->chunk_hdr = ch; chunk->chunk_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length)); /* In the unlikely case of an IP reassembly, the skb could be * non-linear. If so, update chunk_end so that it doesn't go past * the skb->tail. */ if (unlikely(skb_is_nonlinear(chunk->skb))) { if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) chunk->chunk_end = skb_tail_pointer(chunk->skb); } skb_pull(chunk->skb, sizeof(sctp_chunkhdr_t)); chunk->subh.v = NULL; /* Subheader is no longer valid. */ if (chunk->chunk_end < skb_tail_pointer(chunk->skb)) { /* This is not a singleton */ chunk->singleton = 0; } else if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) { /* RFC 2960, Section 6.10 Bundling * * Partial chunks MUST NOT be placed in an SCTP packet. * If the receiver detects a partial chunk, it MUST drop * the chunk. * * Since the end of the chunk is past the end of our buffer * (which contains the whole packet, we can freely discard * the whole packet. */ sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; return NULL; } else { /* We are at the end of the packet, so mark the chunk * in case we need to send a SACK. */ chunk->end_of_packet = 1; } pr_debug("+++sctp_inq_pop+++ chunk:%p[%s], length:%d, skb->len:%d\n", chunk, sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)), ntohs(chunk->chunk_hdr->length), chunk->skb->len); return chunk; } CWE ID: CWE-399 Target: 1 Example 2: Code: WORK_STATE ossl_statem_client_post_process_message(SSL *s, WORK_STATE wst) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { case TLS_ST_CR_CERT_REQ: return tls_prepare_client_certificate(s, wst); #ifndef OPENSSL_NO_SCTP case TLS_ST_CR_SRVR_DONE: /* We only get here if we are using SCTP and we are renegotiating */ if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->s3->in_read_app_data = 2; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); ossl_statem_set_sctp_read_sock(s, 1); return WORK_MORE_A; } ossl_statem_set_sctp_read_sock(s, 0); return WORK_FINISHED_STOP; #endif default: break; } /* Shouldn't happen */ return WORK_ERROR; } 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 proc_stat_read(char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { struct fuse_context *fc = fuse_get_context(); struct file_info *d = (struct file_info *)fi->fh; char *cg; char *cpuset = NULL; char *line = NULL; size_t linelen = 0, total_len = 0, rv = 0; int curcpu = -1; /* cpu numbering starts at 0 */ unsigned long user = 0, nice = 0, system = 0, idle = 0, iowait = 0, irq = 0, softirq = 0, steal = 0, guest = 0; unsigned long user_sum = 0, nice_sum = 0, system_sum = 0, idle_sum = 0, iowait_sum = 0, irq_sum = 0, softirq_sum = 0, steal_sum = 0, guest_sum = 0; #define CPUALL_MAX_SIZE BUF_RESERVE_SIZE char cpuall[CPUALL_MAX_SIZE]; /* reserve for cpu all */ char *cache = d->buf + CPUALL_MAX_SIZE; size_t cache_size = d->buflen - CPUALL_MAX_SIZE; FILE *f = NULL; if (offset){ if (offset > d->size) return -EINVAL; if (!d->cached) return 0; int left = d->size - offset; total_len = left > size ? size: left; memcpy(buf, d->buf + offset, total_len); return total_len; } cg = get_pid_cgroup(fc->pid, "cpuset"); if (!cg) return read_file("/proc/stat", buf, size, d); cpuset = get_cpuset(cg); if (!cpuset) goto err; f = fopen("/proc/stat", "r"); if (!f) goto err; if (getline(&line, &linelen, f) < 0) { fprintf(stderr, "proc_stat_read read first line failed\n"); goto err; } while (getline(&line, &linelen, f) != -1) { size_t l; int cpu; char cpu_char[10]; /* That's a lot of cores */ char *c; if (sscanf(line, "cpu%9[^ ]", cpu_char) != 1) { /* not a ^cpuN line containing a number N, just print it */ l = snprintf(cache, cache_size, "%s", line); if (l < 0) { perror("Error writing to cache"); rv = 0; goto err; } if (l >= cache_size) { fprintf(stderr, "Internal error: truncated write to cache\n"); rv = 0; goto err; } if (l < cache_size) { cache += l; cache_size -= l; total_len += l; continue; } else { cache += cache_size; total_len += cache_size; cache_size = 0; break; } } if (sscanf(cpu_char, "%d", &cpu) != 1) continue; if (!cpu_in_cpuset(cpu, cpuset)) continue; curcpu ++; c = strchr(line, ' '); if (!c) continue; l = snprintf(cache, cache_size, "cpu%d%s", curcpu, c); if (l < 0) { perror("Error writing to cache"); rv = 0; goto err; } if (l >= cache_size) { fprintf(stderr, "Internal error: truncated write to cache\n"); rv = 0; goto err; } cache += l; cache_size -= l; total_len += l; if (sscanf(line, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu", &user, &nice, &system, &idle, &iowait, &irq, &softirq, &steal, &guest) != 9) continue; user_sum += user; nice_sum += nice; system_sum += system; idle_sum += idle; iowait_sum += iowait; irq_sum += irq; softirq_sum += softirq; steal_sum += steal; guest_sum += guest; } cache = d->buf; int cpuall_len = snprintf(cpuall, CPUALL_MAX_SIZE, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu\n", "cpu ", user_sum, nice_sum, system_sum, idle_sum, iowait_sum, irq_sum, softirq_sum, steal_sum, guest_sum); if (cpuall_len > 0 && cpuall_len < CPUALL_MAX_SIZE){ memcpy(cache, cpuall, cpuall_len); cache += cpuall_len; } else{ /* shouldn't happen */ fprintf(stderr, "proc_stat_read copy cpuall failed, cpuall_len=%d\n", cpuall_len); cpuall_len = 0; } memmove(cache, d->buf + CPUALL_MAX_SIZE, total_len); total_len += cpuall_len; d->cached = 1; d->size = total_len; if (total_len > size ) total_len = size; memcpy(buf, d->buf, total_len); rv = total_len; err: if (f) fclose(f); free(line); free(cpuset); free(cg); return rv; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void StyleResolver::matchUARules(ElementRuleCollector& collector) { collector.setMatchingUARules(true); if (CSSDefaultStyleSheets::simpleDefaultStyleSheet) collector.matchedResult().isCacheable = false; RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print") ? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle; matchUARules(collector, userAgentStyleSheet); if (document().inQuirksMode()) matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle); if (document().isViewSource()) matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle()); collector.setMatchingUARules(false); matchWatchSelectorRules(collector); } CWE ID: CWE-399 Target: 1 Example 2: Code: getKeyRequest(Vector<uint8_t> const &sessionId, Vector<uint8_t> const &initData, String8 const &mimeType, DrmPlugin::KeyType keyType, KeyedVector<String8, String8> const &optionalParameters, Vector<uint8_t> &request, String8 &defaultUrl, DrmPlugin::KeyRequestType *keyRequestType) { Parcel data, reply; data.writeInterfaceToken(IDrm::getInterfaceDescriptor()); writeVector(data, sessionId); writeVector(data, initData); data.writeString8(mimeType); data.writeInt32((uint32_t)keyType); data.writeInt32(optionalParameters.size()); for (size_t i = 0; i < optionalParameters.size(); ++i) { data.writeString8(optionalParameters.keyAt(i)); data.writeString8(optionalParameters.valueAt(i)); } status_t status = remote()->transact(GET_KEY_REQUEST, data, &reply); if (status != OK) { return status; } readVector(reply, request); defaultUrl = reply.readString8(); *keyRequestType = static_cast<DrmPlugin::KeyRequestType>(reply.readInt32()); return reply.readInt32(); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Browser::CanOverscrollContent() const { #if defined(OS_WIN) bool allow_overscroll = ui::GetTouchScreensAvailability() == ui::TouchScreensAvailability::ENABLED; #elif defined(USE_AURA) bool allow_overscroll = true; #else bool allow_overscroll = false; #endif if (!allow_overscroll) return false; const std::string value = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kOverscrollHistoryNavigation); bool overscroll_enabled = value != "0"; if (!overscroll_enabled) return false; if (is_app() || is_devtools() || !is_type_tabbed()) return false; if (value == "1" && bookmark_bar_state_ == BookmarkBar::DETACHED) return false; return true; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } /* * we assume that no multi-byte character can take more than 5 bytes. * we assume that no multi-byte character can take more than 5 bytes. * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = strnlen(str, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); *bytes_consumed = 1; return INVALID_CODEPOINT; } CWE ID: CWE-200 Target: 1 Example 2: Code: static struct kwajd_stream *lzh_init(struct mspack_system *sys, struct mspack_file *in, struct mspack_file *out) { struct kwajd_stream *lzh; if (!sys || !in || !out) return NULL; if (!(lzh = (struct kwajd_stream *) sys->alloc(sys, sizeof(struct kwajd_stream)))) return NULL; lzh->sys = sys; lzh->input = in; lzh->output = out; return lzh; } 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: views::View* AutofillDialogViews::CreateFootnoteView() { footnote_view_ = new LayoutPropagationView(); footnote_view_->SetLayoutManager( new views::BoxLayout(views::BoxLayout::kVertical, kDialogEdgePadding, kDialogEdgePadding, 0)); footnote_view_->SetBorder( views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor)); footnote_view_->set_background( views::Background::CreateSolidBackground(kShadingColor)); legal_document_view_ = new views::StyledLabel(base::string16(), this); footnote_view_->AddChildView(legal_document_view_); footnote_view_->SetVisible(false); return footnote_view_; } 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 struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); unsigned int mss; unsigned int unfrag_ip6hlen, unfrag_len; struct frag_hdr *fptr; u8 *packet_start, *prevhdr; u8 nexthdr; u8 frag_hdr_sz = sizeof(struct frag_hdr); int offset; __wsum csum; int tnl_hlen; mss = skb_shinfo(skb)->gso_size; if (unlikely(skb->len <= mss)) goto out; if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) { /* Packet is from an untrusted source, reset gso_segs. */ int type = skb_shinfo(skb)->gso_type; if (unlikely(type & ~(SKB_GSO_UDP | SKB_GSO_DODGY | SKB_GSO_UDP_TUNNEL | SKB_GSO_GRE | SKB_GSO_IPIP | SKB_GSO_SIT | SKB_GSO_MPLS) || !(type & (SKB_GSO_UDP)))) goto out; skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss); segs = NULL; goto out; } if (skb->encapsulation && skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL) segs = skb_udp_tunnel_segment(skb, features); else { /* Do software UFO. Complete and fill in the UDP checksum as HW cannot * do checksum of UDP packets sent as multiple IP fragments. */ offset = skb_checksum_start_offset(skb); csum = skb_checksum(skb, offset, skb->len - offset, 0); offset += skb->csum_offset; *(__sum16 *)(skb->data + offset) = csum_fold(csum); skb->ip_summed = CHECKSUM_NONE; /* Check if there is enough headroom to insert fragment header. */ tnl_hlen = skb_tnl_header_len(skb); if (skb_headroom(skb) < (tnl_hlen + frag_hdr_sz)) { if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz)) goto out; } /* Find the unfragmentable header and shift it left by frag_hdr_sz * bytes to insert fragment header. */ unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; *prevhdr = NEXTHDR_FRAGMENT; unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) + unfrag_ip6hlen + tnl_hlen; packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset; memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len); SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz; skb->mac_header -= frag_hdr_sz; skb->network_header -= frag_hdr_sz; fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen); fptr->nexthdr = nexthdr; fptr->reserved = 0; ipv6_select_ident(fptr, (struct rt6_info *)skb_dst(skb)); /* Fragment the skb. ipv6 header and the remaining fields of the * fragment header are updated in ipv6_gso_segment() */ segs = skb_segment(skb, features); } out: return segs; } CWE ID: CWE-189 Target: 1 Example 2: Code: void CL_ClearState (void) { Com_Memset( &cl, 0, sizeof( cl ) ); } CWE ID: CWE-269 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void encrypted_rcu_free(struct rcu_head *rcu) { struct encrypted_key_payload *epayload; epayload = container_of(rcu, struct encrypted_key_payload, rcu); memset(epayload->decrypted_data, 0, epayload->decrypted_datalen); kfree(epayload); } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int InternalPageInfoBubbleView::GetDialogButtons() const { return ui::DIALOG_BUTTON_NONE; } CWE ID: CWE-704 Target: 1 Example 2: Code: robj *dupLastObjectIfNeeded(list *reply) { robj *new, *cur; listNode *ln; serverAssert(listLength(reply) > 0); ln = listLast(reply); cur = listNodeValue(ln); if (cur->refcount > 1) { new = dupStringObject(cur); decrRefCount(cur); listNodeValue(ln) = new; } return listNodeValue(ln); } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DevToolsAgent::runtimePropertyChanged( const WebKit::WebString& name, const WebKit::WebString& value) { Send(new DevToolsHostMsg_RuntimePropertyChanged( routing_id(), name.utf8(), value.utf8())); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool LayoutSVGResourceMarker::calculateLocalTransform() { return selfNeedsLayout(); } CWE ID: Target: 1 Example 2: Code: smp_fetch_http_first_req(const struct arg *args, struct sample *smp, const char *kw, void *private) { smp->data.type = SMP_T_BOOL; smp->data.u.sint = !(smp->strm->txn->flags & TX_NOT_FIRST); return 1; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void UrlmonUrlRequestManager::StartRequest(int request_id, const AutomationURLRequest& request_info) { DVLOG(1) << __FUNCTION__ << " id: " << request_id; DCHECK_EQ(0, calling_delegate_); if (stopping_) { DLOG(WARNING) << __FUNCTION__ << " request not started (stopping)"; return; } DCHECK(request_map_.find(request_id) == request_map_.end()); DCHECK(GURL(request_info.url).is_valid()); scoped_refptr<UrlmonUrlRequest> new_request; bool is_started = false; if (pending_request_) { if (pending_request_->url() != request_info.url) { DLOG(INFO) << __FUNCTION__ << "Received url request for url:" << request_info.url << ". Stopping pending url request for url:" << pending_request_->url(); pending_request_->Stop(); pending_request_ = NULL; } else { new_request.swap(pending_request_); is_started = true; DVLOG(1) << __FUNCTION__ << new_request->me() << " assigned id " << request_id; } } if (!is_started) { CComObject<UrlmonUrlRequest>* created_request = NULL; CComObject<UrlmonUrlRequest>::CreateInstance(&created_request); new_request = created_request; } new_request->Initialize(static_cast<PluginUrlRequestDelegate*>(this), request_id, request_info.url, request_info.method, request_info.referrer, request_info.extra_request_headers, request_info.upload_data, static_cast<ResourceType::Type>(request_info.resource_type), enable_frame_busting_, request_info.load_flags); new_request->set_parent_window(notification_window_); new_request->set_privileged_mode(privileged_mode_); request_map_[request_id] = new_request; if (!is_started) { new_request->Start(); } else { DCHECK(!new_request->response_headers().empty()); new_request->OnResponse( 0, UTF8ToWide(new_request->response_headers()).c_str(), NULL, NULL); } } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, nfs4_stateid *delegation, int open_flags) { struct nfs_inode *nfsi = NFS_I(state->inode); struct nfs_delegation *deleg_cur; int ret = 0; open_flags &= (FMODE_READ|FMODE_WRITE); rcu_read_lock(); deleg_cur = rcu_dereference(nfsi->delegation); if (deleg_cur == NULL) goto no_delegation; spin_lock(&deleg_cur->lock); if (nfsi->delegation != deleg_cur || (deleg_cur->type & open_flags) != open_flags) goto no_delegation_unlock; if (delegation == NULL) delegation = &deleg_cur->stateid; else if (memcmp(deleg_cur->stateid.data, delegation->data, NFS4_STATEID_SIZE) != 0) goto no_delegation_unlock; nfs_mark_delegation_referenced(deleg_cur); __update_open_stateid(state, open_stateid, &deleg_cur->stateid, open_flags); ret = 1; no_delegation_unlock: spin_unlock(&deleg_cur->lock); no_delegation: rcu_read_unlock(); if (!ret && open_stateid != NULL) { __update_open_stateid(state, open_stateid, NULL, open_flags); ret = 1; } return ret; } CWE ID: Target: 1 Example 2: Code: void WebLocalFrameImpl::SetName(const WebString& name) { GetFrame()->Tree().SetName(name, FrameTree::kReplicate); } 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: scoped_refptr<InspectorTaskRunner> LocalFrame::GetInspectorTaskRunner() { return inspector_task_runner_; } CWE ID: CWE-285 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void get_checksum2(char *buf, int32 len, char *sum) { md_context m; switch (xfersum_type) { case CSUM_MD5: { uchar seedbuf[4]; md5_begin(&m); if (proper_seed_order) { if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } md5_update(&m, (uchar *)buf, len); } else { md5_update(&m, (uchar *)buf, len); if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } } md5_result(&m, (uchar *)sum); break; } case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: { int32 i; static char *buf1; static int32 len1; mdfour_begin(&m); if (len > len1) { if (buf1) free(buf1); buf1 = new_array(char, len+4); len1 = len; if (!buf1) out_of_memory("get_checksum2"); } memcpy(buf1, buf, len); if (checksum_seed) { SIVAL(buf1,len,checksum_seed); len += 4; } for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) mdfour_update(&m, (uchar *)(buf1+i), CSUM_CHUNK); /* * Prior to version 27 an incorrect MD4 checksum was computed * by failing to call mdfour_tail() for block sizes that * are multiples of 64. This is fixed by calling mdfour_update() * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ if (len - i > 0 || xfersum_type != CSUM_MD4_BUSTED) mdfour_update(&m, (uchar *)(buf1+i), len-i); mdfour_result(&m, (uchar *)sum); } } } CWE ID: CWE-354 Target: 1 Example 2: Code: void sigalrm_handler() { rotate = (rotate + 1) % 4; } 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: __reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode, int type, struct posix_acl *acl) { char *name; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name = XATTR_NAME_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = reiserfs_posix_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0); /* * Ensure that the inode gets dirtied if we're only using * the mode bits and an old ACL didn't exist. We don't need * to check if the inode is hashed here since we won't get * called by reiserfs_inherit_default_acl(). */ if (error == -ENODATA) { error = 0; if (type == ACL_TYPE_ACCESS) { inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); } } kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } CWE ID: CWE-285 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin(PluginView* pluginView, const Platform::TouchPoint& point) { NPEvent npEvent; NPMouseEvent mouse; switch (point.m_state) { case Platform::TouchPoint::TouchPressed: mouse.type = MOUSE_BUTTON_DOWN; break; case Platform::TouchPoint::TouchReleased: mouse.type = MOUSE_BUTTON_UP; break; case Platform::TouchPoint::TouchMoved: mouse.type = MOUSE_MOTION; break; case Platform::TouchPoint::TouchStationary: return true; } mouse.x = point.m_screenPos.x(); mouse.y = point.m_screenPos.y(); mouse.button = mouse.type != MOUSE_BUTTON_UP; mouse.flags = 0; npEvent.type = NP_MouseEvent; npEvent.data = &mouse; pluginView->dispatchFullScreenNPEvent(npEvent); return true; } CWE ID: Target: 1 Example 2: Code: RGBA32 AXObject::backgroundColor() const { updateCachedAttributeValuesIfNeeded(); return m_cachedBackgroundColor; } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int openpt_in_namespace(pid_t pid, int flags) { _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1; _cleanup_close_pair_ int pair[2] = { -1, -1 }; pid_t child; int r; assert(pid > 0); r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd); if (r < 0) return r; if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0) return -errno; r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG, pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child); if (r < 0) return r; if (r == 0) { int master; pair[0] = safe_close(pair[0]); master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC); if (master < 0) _exit(EXIT_FAILURE); if (unlockpt(master) < 0) _exit(EXIT_FAILURE); if (send_one_fd(pair[1], master, 0) < 0) _exit(EXIT_FAILURE); _exit(EXIT_SUCCESS); } pair[1] = safe_close(pair[1]); r = wait_for_terminate_and_check("(sd-openptns)", child, 0); if (r < 0) return r; if (r != EXIT_SUCCESS) return -EIO; return receive_one_fd(pair[0], 0); } CWE ID: CWE-255 Output:
0
Here are some example code snippets. Analyze the following 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 PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } CWE ID: CWE-119 Target: 1 Example 2: Code: void PresentationConnection::send(Blob* data, ExceptionState& exceptionState) { ASSERT(data); if (!canSendMessage(exceptionState)) return; m_messages.append(new Message(data->blobDataHandle())); handleMessageQueue(); } 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 *__netdev_alloc_frag(unsigned int fragsz, gfp_t gfp_mask) { struct page_frag_cache *nc; unsigned long flags; void *data; local_irq_save(flags); nc = this_cpu_ptr(&netdev_alloc_cache); data = page_frag_alloc(nc, fragsz, gfp_mask); local_irq_restore(flags); return data; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GpuChannelHost::Connect( const IPC::ChannelHandle& channel_handle, base::ProcessHandle client_process_for_gpu) { DCHECK(factory_->IsMainThread()); scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy(); channel_.reset(new IPC::SyncChannel( channel_handle, IPC::Channel::MODE_CLIENT, NULL, io_loop, true, factory_->GetShutDownEvent())); sync_filter_ = new IPC::SyncMessageFilter( factory_->GetShutDownEvent()); channel_->AddFilter(sync_filter_.get()); channel_filter_ = new MessageFilter(this); channel_->AddFilter(channel_filter_.get()); state_ = kConnected; Send(new GpuChannelMsg_Initialize(client_process_for_gpu)); } CWE ID: Target: 1 Example 2: Code: LogLuv24toXYZ(uint32 p, float XYZ[3]) { int Ce; double L, u, v, s, x, y; /* decode luminance */ L = LogL10toY(p>>14 & 0x3ff); if (L <= 0.) { XYZ[0] = XYZ[1] = XYZ[2] = 0.; return; } /* decode color */ Ce = p & 0x3fff; if (uv_decode(&u, &v, Ce) < 0) { u = U_NEU; v = V_NEU; } s = 1./(6.*u - 16.*v + 12.); x = 9.*u * s; y = 4.*v * s; /* convert to XYZ */ XYZ[0] = (float)(x/y * L); XYZ[1] = (float)L; XYZ[2] = (float)((1.-x-y)/y * L); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static long ec_device_ioctl_xcmd(struct cros_ec_dev *ec, void __user *arg) { long ret; struct cros_ec_command u_cmd; struct cros_ec_command *s_cmd; if (copy_from_user(&u_cmd, arg, sizeof(u_cmd))) return -EFAULT; if ((u_cmd.outsize > EC_MAX_MSG_BYTES) || (u_cmd.insize > EC_MAX_MSG_BYTES)) return -EINVAL; s_cmd = kmalloc(sizeof(*s_cmd) + max(u_cmd.outsize, u_cmd.insize), GFP_KERNEL); if (!s_cmd) return -ENOMEM; if (copy_from_user(s_cmd, arg, sizeof(*s_cmd) + u_cmd.outsize)) { ret = -EFAULT; goto exit; } s_cmd->command += ec->cmd_offset; ret = cros_ec_cmd_xfer(ec->ec_dev, s_cmd); /* Only copy data to userland if data was received. */ if (ret < 0) goto exit; if (copy_to_user(arg, s_cmd, sizeof(*s_cmd) + u_cmd.insize)) ret = -EFAULT; exit: kfree(s_cmd); return ret; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void iriap_getvaluebyclass_indication(struct iriap_cb *self, struct sk_buff *skb) { struct ias_object *obj; struct ias_attrib *attrib; int name_len; int attr_len; char name[IAS_MAX_CLASSNAME + 1]; /* 60 bytes */ char attr[IAS_MAX_ATTRIBNAME + 1]; /* 60 bytes */ __u8 *fp; int n; IRDA_DEBUG(4, "%s()\n", __func__); IRDA_ASSERT(self != NULL, return;); IRDA_ASSERT(self->magic == IAS_MAGIC, return;); IRDA_ASSERT(skb != NULL, return;); fp = skb->data; n = 1; name_len = fp[n++]; memcpy(name, fp+n, name_len); n+=name_len; name[name_len] = '\0'; attr_len = fp[n++]; memcpy(attr, fp+n, attr_len); n+=attr_len; attr[attr_len] = '\0'; IRDA_DEBUG(4, "LM-IAS: Looking up %s: %s\n", name, attr); obj = irias_find_object(name); if (obj == NULL) { IRDA_DEBUG(2, "LM-IAS: Object %s not found\n", name); iriap_getvaluebyclass_response(self, 0x1235, IAS_CLASS_UNKNOWN, &irias_missing); return; } IRDA_DEBUG(4, "LM-IAS: found %s, id=%d\n", obj->name, obj->id); attrib = irias_find_attrib(obj, attr); if (attrib == NULL) { IRDA_DEBUG(2, "LM-IAS: Attribute %s not found\n", attr); iriap_getvaluebyclass_response(self, obj->id, IAS_ATTRIB_UNKNOWN, &irias_missing); return; } /* We have a match; send the value. */ iriap_getvaluebyclass_response(self, obj->id, IAS_SUCCESS, attrib->value); } CWE ID: CWE-119 Target: 1 Example 2: Code: void ext4_free_inodes_set(struct super_block *sb, struct ext4_group_desc *bg, __u32 count) { bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count); if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT) bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16); } 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 random_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { size_t ret; ret = write_pool(&blocking_pool, buffer, count); if (ret) return ret; ret = write_pool(&nonblocking_pool, buffer, count); if (ret) return ret; return (ssize_t)count; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static ssize_t k90_show_macro_mode(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct usb_interface *usbif = to_usb_interface(dev->parent); struct usb_device *usbdev = interface_to_usbdev(usbif); const char *macro_mode; char data[8]; ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), K90_REQUEST_GET_MODE, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, data, 2, USB_CTRL_SET_TIMEOUT); if (ret < 0) { dev_warn(dev, "Failed to get K90 initial mode (error %d).\n", ret); return -EIO; } switch (data[0]) { case K90_MACRO_MODE_HW: macro_mode = "HW"; break; case K90_MACRO_MODE_SW: macro_mode = "SW"; break; default: dev_warn(dev, "K90 in unknown mode: %02hhx.\n", data[0]); return -EIO; } return snprintf(buf, PAGE_SIZE, "%s\n", macro_mode); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void oz_acquire_port(struct oz_port *port, void *hpd) { INIT_LIST_HEAD(&port->isoc_out_ep); INIT_LIST_HEAD(&port->isoc_in_ep); port->flags |= OZ_PORT_F_PRESENT | OZ_PORT_F_CHANGED; port->status |= USB_PORT_STAT_CONNECTION | (USB_PORT_STAT_C_CONNECTION << 16); oz_usb_get(hpd); port->hpd = hpd; } 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: ptaSetPt(PTA *pta, l_int32 index, l_float32 x, l_float32 y) { PROCNAME("ptaSetPt"); if (!pta) return ERROR_INT("pta not defined", procName, 1); if (index < 0 || index >= pta->n) return ERROR_INT("invalid index", procName, 1); pta->x[index] = x; pta->y[index] = y; return 0; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: send_parameters(struct iperf_test *test) { int r = 0; cJSON *j; j = cJSON_CreateObject(); if (j == NULL) { i_errno = IESENDPARAMS; r = -1; } else { if (test->protocol->id == Ptcp) cJSON_AddTrueToObject(j, "tcp"); else if (test->protocol->id == Pudp) cJSON_AddTrueToObject(j, "udp"); cJSON_AddIntToObject(j, "omit", test->omit); if (test->server_affinity != -1) cJSON_AddIntToObject(j, "server_affinity", test->server_affinity); if (test->duration) cJSON_AddIntToObject(j, "time", test->duration); if (test->settings->bytes) cJSON_AddIntToObject(j, "num", test->settings->bytes); if (test->settings->blocks) cJSON_AddIntToObject(j, "blockcount", test->settings->blocks); if (test->settings->mss) cJSON_AddIntToObject(j, "MSS", test->settings->mss); if (test->no_delay) cJSON_AddTrueToObject(j, "nodelay"); cJSON_AddIntToObject(j, "parallel", test->num_streams); if (test->reverse) cJSON_AddTrueToObject(j, "reverse"); if (test->settings->socket_bufsize) cJSON_AddIntToObject(j, "window", test->settings->socket_bufsize); if (test->settings->blksize) cJSON_AddIntToObject(j, "len", test->settings->blksize); if (test->settings->rate) cJSON_AddIntToObject(j, "bandwidth", test->settings->rate); if (test->settings->burst) cJSON_AddIntToObject(j, "burst", test->settings->burst); if (test->settings->tos) cJSON_AddIntToObject(j, "TOS", test->settings->tos); if (test->settings->flowlabel) cJSON_AddIntToObject(j, "flowlabel", test->settings->flowlabel); if (test->title) cJSON_AddStringToObject(j, "title", test->title); if (test->congestion) cJSON_AddStringToObject(j, "congestion", test->congestion); if (test->get_server_output) cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test)); if (test->debug) { printf("send_parameters:\n%s\n", cJSON_Print(j)); } if (JSON_write(test->ctrl_sck, j) < 0) { i_errno = IESENDPARAMS; r = -1; } cJSON_Delete(j); } return r; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void nfs41_sequence_call_done(struct rpc_task *task, void *data) { struct nfs4_sequence_data *calldata = data; struct nfs_client *clp = calldata->clp; if (!nfs41_sequence_done(task, task->tk_msg.rpc_resp)) return; if (task->tk_status < 0) { dprintk("%s ERROR %d\n", __func__, task->tk_status); if (atomic_read(&clp->cl_count) == 1) goto out; if (nfs41_sequence_handle_errors(task, clp) == -EAGAIN) { rpc_restart_call_prepare(task); return; } } dprintk("%s rpc_cred %p\n", __func__, task->tk_msg.rpc_cred); out: dprintk("<-- %s\n", __func__); } 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 RenderFrameImpl::BindFrame( const service_manager::BindSourceInfo& browser_info, mojom::FrameRequest request) { browser_info_ = browser_info; frame_binding_.Bind(std::move(request)); } 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: check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: static void update_context(struct ImapData *idata, int oldmsgcount) { struct Header *h = NULL; struct Context *ctx = idata->ctx; if (!idata->uid_hash) idata->uid_hash = mutt_hash_int_create(MAX(6 * ctx->msgcount / 5, 30), 0); for (int msgno = oldmsgcount; msgno < ctx->msgcount; msgno++) { h = ctx->hdrs[msgno]; mutt_hash_int_insert(idata->uid_hash, HEADER_DATA(h)->uid, h); } } 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 inline struct radeon_i2c_bus_rec radeon_lookup_i2c_gpio(struct radeon_device *rdev, uint8_t id) { struct atom_context *ctx = rdev->mode_info.atom_context; ATOM_GPIO_I2C_ASSIGMENT *gpio; struct radeon_i2c_bus_rec i2c; int index = GetIndexIntoMasterTable(DATA, GPIO_I2C_Info); struct _ATOM_GPIO_I2C_INFO *i2c_info; uint16_t data_offset, size; int i, num_indices; memset(&i2c, 0, sizeof(struct radeon_i2c_bus_rec)); i2c.valid = false; if (atom_parse_data_header(ctx, index, &size, NULL, NULL, &data_offset)) { i2c_info = (struct _ATOM_GPIO_I2C_INFO *)(ctx->bios + data_offset); num_indices = (size - sizeof(ATOM_COMMON_TABLE_HEADER)) / sizeof(ATOM_GPIO_I2C_ASSIGMENT); for (i = 0; i < num_indices; i++) { gpio = &i2c_info->asGPIO_Info[i]; if (gpio->sucI2cId.ucAccess == id) { i2c.mask_clk_reg = le16_to_cpu(gpio->usClkMaskRegisterIndex) * 4; i2c.mask_data_reg = le16_to_cpu(gpio->usDataMaskRegisterIndex) * 4; i2c.en_clk_reg = le16_to_cpu(gpio->usClkEnRegisterIndex) * 4; i2c.en_data_reg = le16_to_cpu(gpio->usDataEnRegisterIndex) * 4; i2c.y_clk_reg = le16_to_cpu(gpio->usClkY_RegisterIndex) * 4; i2c.y_data_reg = le16_to_cpu(gpio->usDataY_RegisterIndex) * 4; i2c.a_clk_reg = le16_to_cpu(gpio->usClkA_RegisterIndex) * 4; i2c.a_data_reg = le16_to_cpu(gpio->usDataA_RegisterIndex) * 4; i2c.mask_clk_mask = (1 << gpio->ucClkMaskShift); i2c.mask_data_mask = (1 << gpio->ucDataMaskShift); i2c.en_clk_mask = (1 << gpio->ucClkEnShift); i2c.en_data_mask = (1 << gpio->ucDataEnShift); i2c.y_clk_mask = (1 << gpio->ucClkY_Shift); i2c.y_data_mask = (1 << gpio->ucDataY_Shift); i2c.a_clk_mask = (1 << gpio->ucClkA_Shift); i2c.a_data_mask = (1 << gpio->ucDataA_Shift); if (gpio->sucI2cId.sbfAccess.bfHW_Capable) i2c.hw_capable = true; else i2c.hw_capable = false; if (gpio->sucI2cId.ucAccess == 0xa0) i2c.mm_i2c = true; else i2c.mm_i2c = false; i2c.i2c_id = gpio->sucI2cId.ucAccess; i2c.valid = true; break; } } } return i2c; } 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: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 8; fwd_txfm_ref = fht8x8_ref; } CWE ID: CWE-119 Target: 1 Example 2: Code: static struct trusted_key_payload *trusted_payload_alloc(struct key *key) { struct trusted_key_payload *p = NULL; int ret; ret = key_payload_reserve(key, sizeof *p); if (ret < 0) return p; p = kzalloc(sizeof *p, GFP_KERNEL); if (p) p->migratable = 1; /* migratable by default */ return p; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool ResourcePrefetchPredictor::GetRedirectEndpointsForPreconnect( const url::Origin& entry_origin, const RedirectDataMap& redirect_data, PreconnectPrediction* prediction) const { if (!base::FeatureList::IsEnabled( features::kLoadingPreconnectToRedirectTarget)) { return false; } DCHECK(!prediction || prediction->requests.empty()); RedirectData data; if (!redirect_data.TryGetData(entry_origin.host(), &data)) return false; const float kMinRedirectConfidenceToTriggerPrefetch = 0.1f; bool at_least_one_redirect_endpoint_added = false; for (const auto& redirect : data.redirect_endpoints()) { if (ComputeRedirectConfidence(redirect) < kMinRedirectConfidenceToTriggerPrefetch) { continue; } std::string redirect_scheme = redirect.url_scheme().empty() ? "https" : redirect.url_scheme(); int redirect_port = redirect.has_url_port() ? redirect.url_port() : 443; const url::Origin redirect_origin = url::Origin::CreateFromNormalizedTuple( redirect_scheme, redirect.url(), redirect_port); if (redirect_origin == entry_origin) { continue; } if (prediction) { prediction->requests.emplace_back( redirect_origin.GetURL(), 1 /* num_scokets */, net::NetworkIsolationKey(redirect_origin, redirect_origin)); } at_least_one_redirect_endpoint_added = true; } if (prediction && prediction->host.empty() && at_least_one_redirect_endpoint_added) { prediction->host = entry_origin.host(); } return at_least_one_redirect_endpoint_added; } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr; struct sock *other; unsigned int hash; int err; if (addr->sa_family != AF_UNSPEC) { err = unix_mkname(sunaddr, alen, &hash); if (err < 0) goto out; alen = err; if (test_bit(SOCK_PASSCRED, &sock->flags) && !unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0) goto out; restart: other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err); if (!other) goto out; unix_state_double_lock(sk, other); /* Apparently VFS overslept socket death. Retry. */ if (sock_flag(other, SOCK_DEAD)) { unix_state_double_unlock(sk, other); sock_put(other); goto restart; } err = -EPERM; if (!unix_may_send(sk, other)) goto out_unlock; err = security_unix_may_send(sk->sk_socket, other->sk_socket); if (err) goto out_unlock; } else { /* * 1003.1g breaking connected state with AF_UNSPEC */ other = NULL; unix_state_double_lock(sk, other); } /* * If it was connected, reconnect. */ if (unix_peer(sk)) { struct sock *old_peer = unix_peer(sk); unix_peer(sk) = other; unix_state_double_unlock(sk, other); if (other != old_peer) unix_dgram_disconnected(sk, old_peer); sock_put(old_peer); } else { unix_peer(sk) = other; unix_state_double_unlock(sk, other); } return 0; out_unlock: unix_state_double_unlock(sk, other); sock_put(other); out: return err; } CWE ID: Target: 1 Example 2: Code: base::FilePath BrowserMainLoop::GetStartupTraceFileName( const base::CommandLine& command_line) const { base::FilePath trace_file; if (command_line.HasSwitch(switches::kTraceStartup)) { trace_file = command_line.GetSwitchValuePath( switches::kTraceStartupFile); if (trace_file == base::FilePath().AppendASCII("none")) return trace_file; if (trace_file.empty()) { #if defined(OS_ANDROID) TracingControllerAndroid::GenerateTracingFilePath(&trace_file); #else trace_file = base::FilePath().AppendASCII("chrometrace.log"); #endif } } else { #if defined(OS_ANDROID) TracingControllerAndroid::GenerateTracingFilePath(&trace_file); #else trace_file = tracing::TraceConfigFile::GetInstance()->GetResultFile(); #endif } return trace_file; } CWE ID: CWE-310 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void enforcedRangeLongAttrAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); TestObjectV8Internal::enforcedRangeLongAttrAttributeSetter(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: usage(void) { fprintf(stderr, "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" " [-t life] [command [arg ...]]\n" " ssh-agent [-c | -s] -k\n"); exit(1); } CWE ID: CWE-426 Target: 1 Example 2: Code: init_standard_palette(png_store *ps, png_structp pp, png_infop pi, int npalette, int do_tRNS) { store_palette_entry *ppal = make_standard_palette(ps, npalette, do_tRNS); { int i; png_color palette[256]; /* Set all entries to detect overread errors. */ for (i=0; i<npalette; ++i) { palette[i].red = ppal[i].red; palette[i].green = ppal[i].green; palette[i].blue = ppal[i].blue; } /* Just in case fill in the rest with detectable values: */ for (; i<256; ++i) palette[i].red = palette[i].green = palette[i].blue = 42; png_set_PLTE(pp, pi, palette, npalette); } if (do_tRNS) { int i, j; png_byte tRNS[256]; /* Set all the entries, but skip trailing opaque entries */ for (i=j=0; i<npalette; ++i) if ((tRNS[i] = ppal[i].alpha) < 255) j = i+1; /* Fill in the remainder with a detectable value: */ for (; i<256; ++i) tRNS[i] = 24; # ifdef PNG_WRITE_tRNS_SUPPORTED if (j > 0) png_set_tRNS(pp, pi, tRNS, j, 0/*color*/); # endif } } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val) { if (is_guest_mode(vcpu)) { struct vmcs12 *vmcs12 = get_vmcs12(vcpu); unsigned long orig_val = val; /* * We get here when L2 changed cr0 in a way that did not change * any of L1's shadowed bits (see nested_vmx_exit_handled_cr), * but did change L0 shadowed bits. So we first calculate the * effective cr0 value that L1 would like to write into the * hardware. It consists of the L2-owned bits from the new * value combined with the L1-owned bits from L1's guest_cr0. */ val = (val & ~vmcs12->cr0_guest_host_mask) | (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask); if (!nested_cr0_valid(vcpu, val)) return 1; if (kvm_set_cr0(vcpu, val)) return 1; vmcs_writel(CR0_READ_SHADOW, orig_val); return 0; } else { if (to_vmx(vcpu)->nested.vmxon && ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON)) return 1; return kvm_set_cr0(vcpu, val); } } CWE ID: CWE-399 Output:
0