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: png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
{
png_infop info_ptr = *ptr_ptr;
png_debug(1, "in png_info_init_3");
if (info_ptr == NULL)
return;
if (png_sizeof(png_info) > png_info_struct_size)
{
png_destroy_struct(info_ptr);
info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
*ptr_ptr = info_ptr;
}
/* Set everything to 0 */
png_memset(info_ptr, 0, png_sizeof(png_info));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool PaintController::CacheIsAllInvalid() const {
DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
return current_paint_artifact_.IsEmpty() &&
current_cache_generation_.GetPaintInvalidationReason() !=
PaintInvalidationReason::kNone;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int main(int argc, char* argv[])
{
char* name = argv[0];
bool applyColorCorrection = false;
#if USE(QCMSLIB)
if (argc >= 2 && strcmp(argv[1], "--color-correct") == 0)
applyColorCorrection = (--argc, ++argv, true);
if (argc < 2) {
fprintf(stderr, "Usage: %s [--color-correct] file [iterations] [packetSize]\n", name);
exit(1);
}
#else
if (argc < 2) {
fprintf(stderr, "Usage: %s file [iterations] [packetSize]\n", name);
exit(1);
}
#endif
size_t iterations = 1;
if (argc >= 3) {
char* end = 0;
iterations = strtol(argv[2], &end, 10);
if (*end != '\0' || !iterations) {
fprintf(stderr, "Second argument should be number of iterations. "
"The default is 1. You supplied %s\n", argv[2]);
exit(1);
}
}
size_t packetSize = 0;
if (argc >= 4) {
char* end = 0;
packetSize = strtol(argv[3], &end, 10);
if (*end != '\0') {
fprintf(stderr, "Third argument should be packet size. Default is "
"0, meaning to decode the entire image in one packet. You "
"supplied %s\n", argv[3]);
exit(1);
}
}
class WebPlatform : public blink::Platform {
public:
const unsigned char* getTraceCategoryEnabledFlag(const char*) override
{
return reinterpret_cast<const unsigned char *>("nope-none-nada");
}
void cryptographicallyRandomValues(unsigned char*, size_t) override
{
}
void screenColorProfile(WebVector<char>* profile) override
{
getScreenColorProfile(profile); // Returns a whacked color profile.
}
};
blink::initializeWithoutV8(new WebPlatform());
#if USE(QCMSLIB)
ImageDecoder::qcmsOutputDeviceProfile(); // Initialize screen colorProfile.
#endif
RefPtr<SharedBuffer> data = readFile(argv[1]);
if (!data.get() || !data->size()) {
fprintf(stderr, "Error reading image data from [%s]\n", argv[1]);
exit(2);
}
data->data();
double totalTime = 0.0;
for (size_t i = 0; i < iterations; ++i) {
double startTime = getCurrentTime();
bool decoded = decodeImageData(data.get(), applyColorCorrection, packetSize);
double elapsedTime = getCurrentTime() - startTime;
totalTime += elapsedTime;
if (!decoded) {
fprintf(stderr, "Image decode failed [%s]\n", argv[1]);
exit(3);
}
}
double averageTime = totalTime / static_cast<double>(iterations);
printf("%f %f\n", totalTime, averageTime);
return 0;
}
CWE ID: CWE-310
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: int32 CommandBufferProxyImpl::CreateTransferBuffer(
size_t size, int32 id_request) {
if (last_state_.error != gpu::error::kNoError)
return -1;
scoped_ptr<base::SharedMemory> shm(
channel_->factory()->AllocateSharedMemory(size));
if (!shm.get())
return -1;
base::SharedMemoryHandle handle = shm->handle();
#if defined(OS_POSIX)
DCHECK(!handle.auto_close);
#endif
int32 id;
if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_,
handle,
size,
id_request,
&id))) {
return -1;
}
return id;
}
CWE ID:
Target: 1
Example 2:
Code: _SSL_get_cert_info (struct cert_info *cert_info, SSL * ssl)
{
X509 *peer_cert;
EVP_PKEY *peer_pkey;
/* EVP_PKEY *ca_pkey; */
/* EVP_PKEY *tmp_pkey; */
char notBefore[64];
char notAfter[64];
int alg;
int sign_alg;
if (!(peer_cert = SSL_get_peer_certificate (ssl)))
return (1); /* FATAL? */
X509_NAME_oneline (X509_get_subject_name (peer_cert), cert_info->subject,
sizeof (cert_info->subject));
X509_NAME_oneline (X509_get_issuer_name (peer_cert), cert_info->issuer,
sizeof (cert_info->issuer));
broke_oneline (cert_info->subject, cert_info->subject_word);
broke_oneline (cert_info->issuer, cert_info->issuer_word);
alg = OBJ_obj2nid (peer_cert->cert_info->key->algor->algorithm);
sign_alg = OBJ_obj2nid (peer_cert->sig_alg->algorithm);
ASN1_TIME_snprintf (notBefore, sizeof (notBefore),
X509_get_notBefore (peer_cert));
ASN1_TIME_snprintf (notAfter, sizeof (notAfter),
X509_get_notAfter (peer_cert));
peer_pkey = X509_get_pubkey (peer_cert);
safe_strcpy (cert_info->algorithm,
(alg == NID_undef) ? "Unknown" : OBJ_nid2ln (alg),
sizeof (cert_info->algorithm));
cert_info->algorithm_bits = EVP_PKEY_bits (peer_pkey);
safe_strcpy (cert_info->sign_algorithm,
(sign_alg == NID_undef) ? "Unknown" : OBJ_nid2ln (sign_alg),
sizeof (cert_info->sign_algorithm));
/* EVP_PKEY_bits(ca_pkey)); */
cert_info->sign_algorithm_bits = 0;
safe_strcpy (cert_info->notbefore, notBefore, sizeof (cert_info->notbefore));
safe_strcpy (cert_info->notafter, notAfter, sizeof (cert_info->notafter));
EVP_PKEY_free (peer_pkey);
/* SSL_SESSION_print_fp(stdout, SSL_get_session(ssl)); */
/*
if (ssl->session->sess_cert->peer_rsa_tmp) {
tmp_pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(tmp_pkey, ssl->session->sess_cert->peer_rsa_tmp);
cert_info->rsa_tmp_bits = EVP_PKEY_bits (tmp_pkey);
EVP_PKEY_free(tmp_pkey);
} else
fprintf(stderr, "REMOTE SIDE DOESN'T PROVIDES ->peer_rsa_tmp\n");
*/
cert_info->rsa_tmp_bits = 0;
X509_free (peer_cert);
return (0);
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ProcessRequest() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
timer.Stop(); // Erase reference to self.
WallpaperManager* manager = WallpaperManager::Get();
if (manager->pending_inactive_ == this)
manager->pending_inactive_ = NULL;
started_load_at_ = base::Time::Now();
if (default_) {
manager->DoSetDefaultWallpaper(account_id_, std::move(on_finish_));
} else if (!user_wallpaper_.isNull()) {
SetWallpaper(user_wallpaper_, info_);
} else if (!wallpaper_path_.empty()) {
manager->task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&WallpaperManager::GetCustomWallpaperInternal,
account_id_, info_, wallpaper_path_,
true /* update wallpaper */,
base::ThreadTaskRunnerHandle::Get(),
base::Passed(std::move(on_finish_)),
manager->weak_factory_.GetWeakPtr()));
} else if (!info_.location.empty()) {
manager->LoadWallpaper(account_id_, info_, true, std::move(on_finish_));
} else {
NOTREACHED();
started_load_at_ = base::Time();
}
on_finish_.reset();
}
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: PepperMediaDeviceManager* PepperMediaDeviceManager::GetForRenderFrame(
RenderFrame* render_frame) {
PepperMediaDeviceManager* handler =
PepperMediaDeviceManager::Get(render_frame);
if (!handler)
handler = new PepperMediaDeviceManager(render_frame);
return handler;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int nfs4_xdr_dec_test_stateid(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs41_test_stateid_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_test_stateid(xdr, res);
out:
return status;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void mm_init_aio(struct mm_struct *mm)
{
#ifdef CONFIG_AIO
spin_lock_init(&mm->ioctx_lock);
INIT_HLIST_HEAD(&mm->ioctx_list);
#endif
}
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: ethertype_print(netdissect_options *ndo,
u_short ether_type, const u_char *p,
u_int length, u_int caplen,
const struct lladdr_info *src, const struct lladdr_info *dst)
{
switch (ether_type) {
case ETHERTYPE_IP:
ip_print(ndo, p, length);
return (1);
case ETHERTYPE_IPV6:
ip6_print(ndo, p, length);
return (1);
case ETHERTYPE_ARP:
case ETHERTYPE_REVARP:
arp_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_DN:
decnet_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_ATALK:
if (ndo->ndo_vflag)
ND_PRINT((ndo, "et1 "));
atalk_print(ndo, p, length);
return (1);
case ETHERTYPE_AARP:
aarp_print(ndo, p, length);
return (1);
case ETHERTYPE_IPX:
ND_PRINT((ndo, "(NOV-ETHII) "));
ipx_print(ndo, p, length);
return (1);
case ETHERTYPE_ISO:
if (length == 0 || caplen == 0) {
ND_PRINT((ndo, " [|osi]"));
return (1);
}
isoclns_print(ndo, p + 1, length - 1, caplen - 1);
return(1);
case ETHERTYPE_PPPOED:
case ETHERTYPE_PPPOES:
case ETHERTYPE_PPPOED2:
case ETHERTYPE_PPPOES2:
pppoe_print(ndo, p, length);
return (1);
case ETHERTYPE_EAPOL:
eap_print(ndo, p, length);
return (1);
case ETHERTYPE_RRCP:
rrcp_print(ndo, p, length, src, dst);
return (1);
case ETHERTYPE_PPP:
if (length) {
ND_PRINT((ndo, ": "));
ppp_print(ndo, p, length);
}
return (1);
case ETHERTYPE_MPCP:
mpcp_print(ndo, p, length);
return (1);
case ETHERTYPE_SLOW:
slow_print(ndo, p, length);
return (1);
case ETHERTYPE_CFM:
case ETHERTYPE_CFM_OLD:
cfm_print(ndo, p, length);
return (1);
case ETHERTYPE_LLDP:
lldp_print(ndo, p, length);
return (1);
case ETHERTYPE_NSH:
nsh_print(ndo, p, length);
return (1);
case ETHERTYPE_LOOPBACK:
loopback_print(ndo, p, length);
return (1);
case ETHERTYPE_MPLS:
case ETHERTYPE_MPLS_MULTI:
mpls_print(ndo, p, length);
return (1);
case ETHERTYPE_TIPC:
tipc_print(ndo, p, length, caplen);
return (1);
case ETHERTYPE_MS_NLB_HB:
msnlb_print(ndo, p);
return (1);
case ETHERTYPE_GEONET_OLD:
case ETHERTYPE_GEONET:
geonet_print(ndo, p, length, src);
return (1);
case ETHERTYPE_CALM_FAST:
calm_fast_print(ndo, p, length, src);
return (1);
case ETHERTYPE_AOE:
aoe_print(ndo, p, length);
return (1);
case ETHERTYPE_MEDSA:
medsa_print(ndo, p, length, caplen, src, dst);
return (1);
case ETHERTYPE_LAT:
case ETHERTYPE_SCA:
case ETHERTYPE_MOPRC:
case ETHERTYPE_MOPDL:
case ETHERTYPE_IEEE1905_1:
/* default_print for now */
default:
return (0);
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static bool i8042_filter(unsigned char data, unsigned char str,
struct serio *serio)
{
if (unlikely(i8042_suppress_kbd_ack)) {
if ((~str & I8042_STR_AUXDATA) &&
(data == 0xfa || data == 0xfe)) {
i8042_suppress_kbd_ack--;
dbg("Extra keyboard ACK - filtered out\n");
return true;
}
}
if (i8042_platform_filter && i8042_platform_filter(data, str, serio)) {
dbg("Filtered out by platform filter\n");
return true;
}
return false;
}
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 Document::MaybeQueueSendDidEditFieldInInsecureContext() {
if (logged_field_edit_ || sensitive_input_edited_task_.IsActive() ||
IsSecureContext()) {
return;
}
logged_field_edit_ = true;
sensitive_input_edited_task_ =
TaskRunnerHelper::Get(TaskType::kUserInteraction, this)
->PostCancellableTask(
BLINK_FROM_HERE,
WTF::Bind(&Document::SendDidEditFieldInInsecureContext,
WrapWeakPersistent(this)));
}
CWE ID: CWE-732
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: sp<MediaSource> MPEG4Extractor::getTrack(size_t index) {
status_t err;
if ((err = readMetaData()) != OK) {
return NULL;
}
Track *track = mFirstTrack;
while (index > 0) {
if (track == NULL) {
return NULL;
}
track = track->next;
--index;
}
if (track == NULL) {
return NULL;
}
Trex *trex = NULL;
int32_t trackId;
if (track->meta->findInt32(kKeyTrackID, &trackId)) {
for (size_t i = 0; i < mTrex.size(); i++) {
Trex *t = &mTrex.editItemAt(index);
if (t->track_ID == (uint32_t) trackId) {
trex = t;
break;
}
}
}
ALOGV("getTrack called, pssh: %zu", mPssh.size());
return new MPEG4Source(this,
track->meta, mDataSource, track->timescale, track->sampleTable,
mSidxEntries, trex, mMoofOffset);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
{
struct rb_root *tm_root;
struct rb_node **new;
struct rb_node *parent = NULL;
struct tree_mod_elem *cur;
BUG_ON(!tm);
tm->seq = btrfs_inc_tree_mod_seq(fs_info);
tm_root = &fs_info->tree_mod_log;
new = &tm_root->rb_node;
while (*new) {
cur = container_of(*new, struct tree_mod_elem, node);
parent = *new;
if (cur->index < tm->index)
new = &((*new)->rb_left);
else if (cur->index > tm->index)
new = &((*new)->rb_right);
else if (cur->seq < tm->seq)
new = &((*new)->rb_left);
else if (cur->seq > tm->seq)
new = &((*new)->rb_right);
else
return -EEXIST;
}
rb_link_node(&tm->node, parent, new);
rb_insert_color(&tm->node, tm_root);
return 0;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
{
tor_addr_to_str(conn->socks_request->address, new_addr,
sizeof(conn->socks_request->address),
1);
control_event_stream_status(conn, STREAM_EVENT_REMAP,
REMAP_STREAM_SOURCE_EXIT);
}
CWE ID: CWE-617
Output: | 0 |
Here are some example code snippets. Analyze the following 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 *ipv6_gso_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
struct ipv6hdr *ipv6h;
const struct net_offload *ops;
int proto;
struct frag_hdr *fptr;
unsigned int unfrag_ip6hlen;
unsigned int payload_len;
u8 *prevhdr;
int offset = 0;
bool encap, udpfrag;
int nhoff;
bool gso_partial;
skb_reset_network_header(skb);
nhoff = skb_network_header(skb) - skb_mac_header(skb);
if (unlikely(!pskb_may_pull(skb, sizeof(*ipv6h))))
goto out;
encap = SKB_GSO_CB(skb)->encap_level > 0;
if (encap)
features &= skb->dev->hw_enc_features;
SKB_GSO_CB(skb)->encap_level += sizeof(*ipv6h);
ipv6h = ipv6_hdr(skb);
__skb_pull(skb, sizeof(*ipv6h));
segs = ERR_PTR(-EPROTONOSUPPORT);
proto = ipv6_gso_pull_exthdrs(skb, ipv6h->nexthdr);
if (skb->encapsulation &&
skb_shinfo(skb)->gso_type & (SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6))
udpfrag = proto == IPPROTO_UDP && encap;
else
udpfrag = proto == IPPROTO_UDP && !skb->encapsulation;
ops = rcu_dereference(inet6_offloads[proto]);
if (likely(ops && ops->callbacks.gso_segment)) {
skb_reset_transport_header(skb);
segs = ops->callbacks.gso_segment(skb, features);
}
if (IS_ERR_OR_NULL(segs))
goto out;
gso_partial = !!(skb_shinfo(segs)->gso_type & SKB_GSO_PARTIAL);
for (skb = segs; skb; skb = skb->next) {
ipv6h = (struct ipv6hdr *)(skb_mac_header(skb) + nhoff);
if (gso_partial)
payload_len = skb_shinfo(skb)->gso_size +
SKB_GSO_CB(skb)->data_offset +
skb->head - (unsigned char *)(ipv6h + 1);
else
payload_len = skb->len - nhoff - sizeof(*ipv6h);
ipv6h->payload_len = htons(payload_len);
skb->network_header = (u8 *)ipv6h - skb->head;
if (udpfrag) {
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
fptr = (struct frag_hdr *)((u8 *)ipv6h + unfrag_ip6hlen);
fptr->frag_off = htons(offset);
if (skb->next)
fptr->frag_off |= htons(IP6_MF);
offset += (ntohs(ipv6h->payload_len) -
sizeof(struct frag_hdr));
}
if (encap)
skb_reset_inner_headers(skb);
}
out:
return segs;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void vga_init(VGACommonState *s, Object *obj, MemoryRegion *address_space,
MemoryRegion *address_space_io, bool init_vga_ports)
{
MemoryRegion *vga_io_memory;
const MemoryRegionPortio *vga_ports, *vbe_ports;
qemu_register_reset(vga_reset, s);
s->bank_offset = 0;
s->legacy_address_space = address_space;
vga_io_memory = vga_init_io(s, obj, &vga_ports, &vbe_ports);
memory_region_add_subregion_overlap(address_space,
0x000a0000,
vga_io_memory,
1);
memory_region_set_coalescing(vga_io_memory);
if (init_vga_ports) {
portio_list_init(&s->vga_port_list, obj, vga_ports, s, "vga");
portio_list_set_flush_coalesced(&s->vga_port_list);
portio_list_add(&s->vga_port_list, address_space_io, 0x3b0);
}
if (vbe_ports) {
portio_list_init(&s->vbe_port_list, obj, vbe_ports, s, "vbe");
portio_list_add(&s->vbe_port_list, address_space_io, 0x1ce);
}
}
CWE ID: CWE-617
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void encode_frame(vpx_codec_ctx_t *codec,
vpx_image_t *img,
int frame_index,
int flags,
VpxVideoWriter *writer) {
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1,
flags, VPX_DL_GOOD_QUALITY);
if (res != VPX_CODEC_OK)
die_codec(codec, "Failed to encode frame");
while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
if (!vpx_video_writer_write_frame(writer,
pkt->data.frame.buf,
pkt->data.frame.sz,
pkt->data.frame.pts)) {
die_codec(codec, "Failed to write compressed frame");
}
printf(keyframe ? "K" : ".");
fflush(stdout);
}
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
{
kfree(mixer->id_elems);
if (mixer->urb) {
kfree(mixer->urb->transfer_buffer);
usb_free_urb(mixer->urb);
}
usb_free_urb(mixer->rc_urb);
kfree(mixer->rc_setup_packet);
kfree(mixer);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void BrowserViewRenderer::SetOffscreenPreRaster(bool enable) {
if (offscreen_pre_raster_ != enable && compositor_)
UpdateMemoryPolicy();
offscreen_pre_raster_ = enable;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int crypto_register_shash(struct shash_alg *alg)
{
struct crypto_alg *base = &alg->base;
int err;
err = shash_prepare_alg(alg);
if (err)
return err;
return crypto_register_alg(base);
}
CWE ID: CWE-310
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: FrameImpl::~FrameImpl() {
window_tree_host_->Hide();
window_tree_host_->compositor()->SetVisible(false);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
{
u64 rt_runtime, rt_period;
rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
if (rt_runtime_us < 0)
rt_runtime = RUNTIME_INF;
return tg_set_bandwidth(tg, rt_period, rt_runtime);
}
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 RenderView::OnViewContextSwapBuffersPosted() {
RenderWidget::OnSwapBuffersPosted();
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int apparmor_setprocattr(struct task_struct *task, char *name,
void *value, size_t size)
{
char *command, *args = value;
size_t arg_size;
int error;
if (size == 0)
return -EINVAL;
/* args points to a PAGE_SIZE buffer, AppArmor requires that
* the buffer must be null terminated or have size <= PAGE_SIZE -1
* so that AppArmor can null terminate them
*/
if (args[size - 1] != '\0') {
if (size == PAGE_SIZE)
return -EINVAL;
args[size] = '\0';
}
/* task can only write its own attributes */
if (current != task)
return -EACCES;
args = value;
args = strim(args);
command = strsep(&args, " ");
if (!args)
return -EINVAL;
args = skip_spaces(args);
if (!*args)
return -EINVAL;
arg_size = size - (args - (char *) value);
if (strcmp(name, "current") == 0) {
if (strcmp(command, "changehat") == 0) {
error = aa_setprocattr_changehat(args, arg_size,
!AA_DO_TEST);
} else if (strcmp(command, "permhat") == 0) {
error = aa_setprocattr_changehat(args, arg_size,
AA_DO_TEST);
} else if (strcmp(command, "changeprofile") == 0) {
error = aa_setprocattr_changeprofile(args, !AA_ONEXEC,
!AA_DO_TEST);
} else if (strcmp(command, "permprofile") == 0) {
error = aa_setprocattr_changeprofile(args, !AA_ONEXEC,
AA_DO_TEST);
} else if (strcmp(command, "permipc") == 0) {
error = aa_setprocattr_permipc(args);
} else {
struct common_audit_data sa;
COMMON_AUDIT_DATA_INIT(&sa, NONE);
sa.aad.op = OP_SETPROCATTR;
sa.aad.info = name;
sa.aad.error = -EINVAL;
return aa_audit(AUDIT_APPARMOR_DENIED, NULL, GFP_KERNEL,
&sa, NULL);
}
} else if (strcmp(name, "exec") == 0) {
error = aa_setprocattr_changeprofile(args, AA_ONEXEC,
!AA_DO_TEST);
} else {
/* only support the "current" and "exec" process attributes */
return -EINVAL;
}
if (!error)
error = size;
return error;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: PDO_API void php_pdo_stmt_addref(pdo_stmt_t *stmt TSRMLS_DC)
{
stmt->refcount++;
}
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: parse_netscreen_hex_dump(FILE_T fh, int pkt_len, const char *cap_int,
const char *cap_dst, struct wtap_pkthdr *phdr, Buffer* buf,
int *err, gchar **err_info)
{
guint8 *pd;
gchar line[NETSCREEN_LINE_LENGTH];
gchar *p;
int n, i = 0, offset = 0;
gchar dststr[13];
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, NETSCREEN_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
while(1) {
/* The last packet is not delimited by an empty line, but by EOF
* So accept EOF as a valid delimiter too
*/
if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
break;
}
/*
* Skip blanks.
* The number of blanks is not fixed - for wireless
* interfaces, there may be 14 extra spaces before
* the hex data.
*/
for (p = &line[0]; g_ascii_isspace(*p); p++)
;
/* packets are delimited with empty lines */
if (*p == '\0') {
break;
}
n = parse_single_hex_dump_line(p, pd, offset);
/* the smallest packet has a length of 6 bytes, if
* the first hex-data is less then check whether
* it is a info-line and act accordingly
*/
if (offset == 0 && n < 6) {
if (info_line(line)) {
if (++i <= NETSCREEN_MAX_INFOLINES) {
continue;
}
} else {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
}
/* If there is no more data and the line was not empty,
* then there must be an error in the file
*/
if(n == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
/* Adjust the offset to the data that was just added to the buffer */
offset += n;
/* If there was more hex-data than was announced in the len=x
* header, then then there must be an error in the file
*/
if(offset > pkt_len) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: too much hex-data");
return FALSE;
}
}
/*
* Determine the encapsulation type, based on the
* first 4 characters of the interface name
*
* XXX convert this to a 'case' structure when adding more
* (non-ethernet) interfacetypes
*/
if (strncmp(cap_int, "adsl", 4) == 0) {
/* The ADSL interface can be bridged with or without
* PPP encapsulation. Check whether the first six bytes
* of the hex data are the same as the destination mac
* address in the header. If they are, assume ethernet
* LinkLayer or else PPP
*/
g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
if (strncmp(dststr, cap_dst, 12) == 0)
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
else
phdr->pkt_encap = WTAP_ENCAP_PPP;
}
else if (strncmp(cap_int, "seri", 4) == 0)
phdr->pkt_encap = WTAP_ENCAP_PPP;
else
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
phdr->caplen = offset;
return TRUE;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: gamma_image_validate(gamma_display *dp, png_const_structp pp,
png_infop pi)
{
/* Get some constants derived from the input and output file formats: */
PNG_CONST png_store* PNG_CONST ps = dp->this.ps;
PNG_CONST png_byte in_ct = dp->this.colour_type;
PNG_CONST png_byte in_bd = dp->this.bit_depth;
PNG_CONST png_uint_32 w = dp->this.w;
PNG_CONST png_uint_32 h = dp->this.h;
PNG_CONST size_t cbRow = dp->this.cbRow;
PNG_CONST png_byte out_ct = png_get_color_type(pp, pi);
PNG_CONST png_byte out_bd = png_get_bit_depth(pp, pi);
/* There are three sources of error, firstly the quantization in the
* file encoding, determined by sbit and/or the file depth, secondly
* the output (screen) gamma and thirdly the output file encoding.
*
* Since this API receives the screen and file gamma in double
* precision it is possible to calculate an exact answer given an input
* pixel value. Therefore we assume that the *input* value is exact -
* sample/maxsample - calculate the corresponding gamma corrected
* output to the limits of double precision arithmetic and compare with
* what libpng returns.
*
* Since the library must quantize the output to 8 or 16 bits there is
* a fundamental limit on the accuracy of the output of +/-.5 - this
* quantization limit is included in addition to the other limits
* specified by the paramaters to the API. (Effectively, add .5
* everywhere.)
*
* The behavior of the 'sbit' paramter is defined by section 12.5
* (sample depth scaling) of the PNG spec. That section forces the
* decoder to assume that the PNG values have been scaled if sBIT is
* present:
*
* png-sample = floor( input-sample * (max-out/max-in) + .5);
*
* This means that only a subset of the possible PNG values should
* appear in the input. However, the spec allows the encoder to use a
* variety of approximations to the above and doesn't require any
* restriction of the values produced.
*
* Nevertheless the spec requires that the upper 'sBIT' bits of the
* value stored in a PNG file be the original sample bits.
* Consequently the code below simply scales the top sbit bits by
* (1<<sbit)-1 to obtain an original sample value.
*
* Because there is limited precision in the input it is arguable that
* an acceptable result is any valid result from input-.5 to input+.5.
* The basic tests below do not do this, however if 'use_input_precision'
* is set a subsequent test is performed above.
*/
PNG_CONST unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U;
int processing;
png_uint_32 y;
PNG_CONST store_palette_entry *in_palette = dp->this.palette;
PNG_CONST int in_is_transparent = dp->this.is_transparent;
int out_npalette = -1;
int out_is_transparent = 0; /* Just refers to the palette case */
store_palette out_palette;
validate_info vi;
/* Check for row overwrite errors */
store_image_check(dp->this.ps, pp, 0);
/* Supply the input and output sample depths here - 8 for an indexed image,
* otherwise the bit depth.
*/
init_validate_info(&vi, dp, pp, in_ct==3?8:in_bd, out_ct==3?8:out_bd);
processing = (vi.gamma_correction > 0 && !dp->threshold_test)
|| in_bd != out_bd || in_ct != out_ct || vi.do_background;
/* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside
* the palette there is no way of finding out, because libpng fails to
* update the palette on png_read_update_info. Indeed, libpng doesn't
* even do the required work until much later, when it doesn't have any
* info pointer. Oops. For the moment 'processing' is turned off if
* out_ct is palette.
*/
if (in_ct == 3 && out_ct == 3)
processing = 0;
if (processing && out_ct == 3)
out_is_transparent = read_palette(out_palette, &out_npalette, pp, pi);
for (y=0; y<h; ++y)
{
png_const_bytep pRow = store_image_row(ps, pp, 0, y);
png_byte std[STANDARD_ROWMAX];
transform_row(pp, std, in_ct, in_bd, y);
if (processing)
{
unsigned int x;
for (x=0; x<w; ++x)
{
double alpha = 1; /* serves as a flag value */
/* Record the palette index for index images. */
PNG_CONST unsigned int in_index =
in_ct == 3 ? sample(std, 3, in_bd, x, 0) : 256;
PNG_CONST unsigned int out_index =
out_ct == 3 ? sample(std, 3, out_bd, x, 0) : 256;
/* Handle input alpha - png_set_background will cause the output
* alpha to disappear so there is nothing to check.
*/
if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 || (in_ct == 3 &&
in_is_transparent))
{
PNG_CONST unsigned int input_alpha = in_ct == 3 ?
dp->this.palette[in_index].alpha :
sample(std, in_ct, in_bd, x, samples_per_pixel);
unsigned int output_alpha = 65536 /* as a flag value */;
if (out_ct == 3)
{
if (out_is_transparent)
output_alpha = out_palette[out_index].alpha;
}
else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0)
output_alpha = sample(pRow, out_ct, out_bd, x,
samples_per_pixel);
if (output_alpha != 65536)
alpha = gamma_component_validate("alpha", &vi, input_alpha,
output_alpha, -1/*alpha*/, 0/*background*/);
else /* no alpha in output */
{
/* This is a copy of the calculation of 'i' above in order to
* have the alpha value to use in the background calculation.
*/
alpha = input_alpha >> vi.isbit_shift;
alpha /= vi.sbit_max;
}
}
/* Handle grayscale or RGB components. */
if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */
(void)gamma_component_validate("gray", &vi,
sample(std, in_ct, in_bd, x, 0),
sample(pRow, out_ct, out_bd, x, 0), alpha/*component*/,
vi.background_red);
else /* RGB or palette */
{
(void)gamma_component_validate("red", &vi,
in_ct == 3 ? in_palette[in_index].red :
sample(std, in_ct, in_bd, x, 0),
out_ct == 3 ? out_palette[out_index].red :
sample(pRow, out_ct, out_bd, x, 0),
alpha/*component*/, vi.background_red);
(void)gamma_component_validate("green", &vi,
in_ct == 3 ? in_palette[in_index].green :
sample(std, in_ct, in_bd, x, 1),
out_ct == 3 ? out_palette[out_index].green :
sample(pRow, out_ct, out_bd, x, 1),
alpha/*component*/, vi.background_green);
(void)gamma_component_validate("blue", &vi,
in_ct == 3 ? in_palette[in_index].blue :
sample(std, in_ct, in_bd, x, 2),
out_ct == 3 ? out_palette[out_index].blue :
sample(pRow, out_ct, out_bd, x, 2),
alpha/*component*/, vi.background_blue);
}
}
}
else if (memcmp(std, pRow, cbRow) != 0)
{
char msg[64];
/* No transform is expected on the threshold tests. */
sprintf(msg, "gamma: below threshold row %lu changed",
(unsigned long)y);
png_error(pp, msg);
}
} /* row (y) loop */
dp->this.ps->validated = 1;
}
CWE ID:
Target: 1
Example 2:
Code: madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
unsigned long start, unsigned long end, int behavior)
{
switch (behavior) {
case MADV_REMOVE:
return madvise_remove(vma, prev, start, end);
case MADV_WILLNEED:
return madvise_willneed(vma, prev, start, end);
case MADV_DONTNEED:
return madvise_dontneed(vma, prev, start, end);
default:
return madvise_behavior(vma, prev, start, end, behavior);
}
}
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: SPL_METHOD(RecursiveDirectoryIterator, getChildren)
{
zval *zpath, *zflags;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
spl_filesystem_object *subdir;
char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
MAKE_STD_ZVAL(zflags);
MAKE_STD_ZVAL(zpath);
ZVAL_LONG(zflags, intern->flags);
ZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1);
spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC);
zval_ptr_dtor(&zpath);
zval_ptr_dtor(&zflags);
subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC);
if (subdir) {
if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) {
subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name);
} else {
subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name);
subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len);
}
subdir->info_class = intern->info_class;
subdir->file_class = intern->file_class;
subdir->oth = intern->oth;
}
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
{
png_color palette[PNG_MAX_PALETTE_LENGTH];
int num, i;
#ifdef PNG_POINTER_INDEXING_SUPPORTED
png_colorp pal_ptr;
#endif
png_debug(1, "in png_handle_PLTE");
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before PLTE");
else if (png_ptr->mode & PNG_HAVE_IDAT)
{
png_warning(png_ptr, "Invalid PLTE after IDAT");
png_crc_finish(png_ptr, length);
return;
}
else if (png_ptr->mode & PNG_HAVE_PLTE)
png_error(png_ptr, "Duplicate PLTE chunk");
png_ptr->mode |= PNG_HAVE_PLTE;
if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
{
png_warning(png_ptr,
"Ignoring PLTE chunk in grayscale PNG");
png_crc_finish(png_ptr, length);
return;
}
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
{
png_crc_finish(png_ptr, length);
return;
}
#endif
if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
{
if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
{
png_warning(png_ptr, "Invalid palette chunk");
png_crc_finish(png_ptr, length);
return;
}
else
{
png_error(png_ptr, "Invalid palette chunk");
}
}
num = (int)length / 3;
#ifdef PNG_POINTER_INDEXING_SUPPORTED
for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
{
png_byte buf[3];
png_crc_read(png_ptr, buf, 3);
pal_ptr->red = buf[0];
pal_ptr->green = buf[1];
pal_ptr->blue = buf[2];
}
#else
for (i = 0; i < num; i++)
{
png_byte buf[3];
png_crc_read(png_ptr, buf, 3);
/* Don't depend upon png_color being any order */
palette[i].red = buf[0];
palette[i].green = buf[1];
palette[i].blue = buf[2];
}
#endif
/* If we actually NEED the PLTE chunk (ie for a paletted image), we do
* whatever the normal CRC configuration tells us. However, if we
* have an RGB image, the PLTE can be considered ancillary, so
* we will act as though it is.
*/
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
#endif
{
png_crc_finish(png_ptr, 0);
}
#ifndef PNG_READ_OPT_PLTE_SUPPORTED
else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
{
/* If we don't want to use the data from an ancillary chunk,
we have two options: an error abort, or a warning and we
ignore the data in this chunk (which should be OK, since
it's considered ancillary for a RGB or RGBA image). */
if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
{
if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
{
png_chunk_error(png_ptr, "CRC error");
}
else
{
png_chunk_warning(png_ptr, "CRC error");
return;
}
}
/* Otherwise, we (optionally) emit a warning and use the chunk. */
else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
{
png_chunk_warning(png_ptr, "CRC error");
}
}
#endif
png_set_PLTE(png_ptr, info_ptr, palette, num);
#ifdef PNG_READ_tRNS_SUPPORTED
if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
{
if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
{
if (png_ptr->num_trans > (png_uint_16)num)
{
png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
png_ptr->num_trans = (png_uint_16)num;
}
if (info_ptr->num_trans > (png_uint_16)num)
{
png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
info_ptr->num_trans = (png_uint_16)num;
}
}
}
#endif
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool GLES2DecoderImpl::GetNumValuesReturnedForGLGet(
GLenum pname, GLsizei* num_values) {
*num_values = 0;
if (state_.GetStateAsGLint(pname, nullptr, num_values)) {
return true;
}
return GetHelper(pname, nullptr, num_values);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len )
{
size_t list_len, name_len;
const char **p;
/* If we didn't send it, the server shouldn't send it */
if( ssl->conf->alpn_list == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*
* the "ProtocolNameList" MUST contain exactly one "ProtocolName"
*/
/* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
if( len < 4 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
list_len = ( buf[0] << 8 ) | buf[1];
if( list_len != len - 2 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
name_len = buf[2];
if( name_len != list_len - 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* Check that the server chosen protocol was in our list and save it */
for( p = ssl->conf->alpn_list; *p != NULL; p++ )
{
if( name_len == strlen( *p ) &&
memcmp( buf + 3, *p, name_len ) == 0 )
{
ssl->alpn_chosen = *p;
return( 0 );
}
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
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 BlockPainter::PaintScrollHitTestDisplayItem(const PaintInfo& paint_info) {
DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled());
if (paint_info.GetGlobalPaintFlags() & kGlobalPaintFlattenCompositingLayers)
return;
const auto* fragment = paint_info.FragmentToPaint(layout_block_);
const auto* properties = fragment ? fragment->PaintProperties() : nullptr;
if (properties && properties->Scroll()) {
DCHECK(properties->ScrollTranslation());
ScopedPaintChunkProperties scroll_hit_test_properties(
paint_info.context.GetPaintController(),
fragment->LocalBorderBoxProperties(), layout_block_,
DisplayItem::kScrollHitTest);
ScrollHitTestDisplayItem::Record(paint_info.context, layout_block_,
DisplayItem::kScrollHitTest,
properties->ScrollTranslation());
}
}
CWE ID:
Target: 1
Example 2:
Code: static sctp_disposition_t sctp_sf_violation_ctsn(
struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[]="The cumulative tsn ack beyond the max tsn currently sent:";
return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
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: inline int web_client_api_request_v1(RRDHOST *host, struct web_client *w, char *url) {
static int initialized = 0;
int i;
if(unlikely(initialized == 0)) {
initialized = 1;
for(i = 0; api_commands[i].command ; i++)
api_commands[i].hash = simple_hash(api_commands[i].command);
}
char *tok = mystrsep(&url, "/?&");
if(tok && *tok) {
debug(D_WEB_CLIENT, "%llu: Searching for API v1 command '%s'.", w->id, tok);
uint32_t hash = simple_hash(tok);
for(i = 0; api_commands[i].command ;i++) {
if(unlikely(hash == api_commands[i].hash && !strcmp(tok, api_commands[i].command))) {
if(unlikely(api_commands[i].acl != WEB_CLIENT_ACL_NOCHECK) && !(w->acl & api_commands[i].acl))
return web_client_permission_denied(w);
return api_commands[i].callback(host, w, url);
}
}
buffer_flush(w->response.data);
buffer_strcat(w->response.data, "Unsupported v1 API command: ");
buffer_strcat_htmlescape(w->response.data, tok);
return 404;
}
else {
buffer_flush(w->response.data);
buffer_sprintf(w->response.data, "Which API v1 command?");
return 400;
}
}
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: int main(int argc, char **argv) {
FILE *infile = NULL;
vpx_codec_ctx_t codec = {0};
vpx_codec_enc_cfg_t cfg = {0};
int frame_count = 0;
vpx_image_t raw = {0};
vpx_codec_err_t res;
VpxVideoInfo info = {0};
VpxVideoWriter *writer = NULL;
const VpxInterface *encoder = NULL;
const int fps = 2; // TODO(dkovalev) add command line argument
const double bits_per_pixel_per_frame = 0.067;
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments");
encoder = get_vpx_encoder_by_name(argv[1]);
if (!encoder)
die("Unsupported codec.");
info.codec_fourcc = encoder->fourcc;
info.frame_width = strtol(argv[2], NULL, 0);
info.frame_height = strtol(argv[3], NULL, 0);
info.time_base.numerator = 1;
info.time_base.denominator = fps;
if (info.frame_width <= 0 ||
info.frame_height <= 0 ||
(info.frame_width % 2) != 0 ||
(info.frame_height % 2) != 0) {
die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
}
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
info.frame_height, 1)) {
die("Failed to allocate image.");
}
printf("Using %s\n", vpx_codec_iface_name(encoder->interface()));
res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = info.frame_width;
cfg.g_h = info.frame_height;
cfg.g_timebase.num = info.time_base.numerator;
cfg.g_timebase.den = info.time_base.denominator;
cfg.rc_target_bitrate = (unsigned int)(bits_per_pixel_per_frame * cfg.g_w *
cfg.g_h * fps / 1000);
cfg.g_lag_in_frames = 0;
writer = vpx_video_writer_open(argv[5], kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing.", argv[5]);
if (!(infile = fopen(argv[4], "rb")))
die("Failed to open %s for reading.", argv[4]);
if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
while (vpx_img_read(&raw, infile)) {
++frame_count;
if (frame_count == 22 && encoder->fourcc == VP8_FOURCC) {
set_roi_map(&cfg, &codec);
} else if (frame_count == 33) {
set_active_map(&cfg, &codec);
} else if (frame_count == 44) {
unset_active_map(&cfg, &codec);
}
encode_frame(&codec, &raw, frame_count, writer);
}
encode_frame(&codec, NULL, -1, writer);
printf("\n");
fclose(infile);
printf("Processed %d frames.\n", frame_count);
vpx_img_free(&raw);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int sctp_v6_add_protocol(void)
{
/* Register notifier for inet6 address additions/deletions. */
register_inet6addr_notifier(&sctp_inet6addr_notifier);
if (inet6_add_protocol(&sctpv6_protocol, IPPROTO_SCTP) < 0)
return -EAGAIN;
return 0;
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: float SVGLayoutSupport::calculateScreenFontSizeScalingFactor(const LayoutObject* layoutObject)
{
ASSERT(layoutObject);
AffineTransform ctm = deprecatedCalculateTransformToLayer(layoutObject) * SubtreeContentTransformScope::currentContentTransformation();
ctm.scale(layoutObject->document().frameHost()->deviceScaleFactorDeprecated());
return narrowPrecisionToFloat(sqrt((pow(ctm.xScale(), 2) + pow(ctm.yScale(), 2)) / 2));
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int virtio_gpu_object_create(struct virtio_gpu_device *vgdev,
unsigned long size, bool kernel, bool pinned,
struct virtio_gpu_object **bo_ptr)
{
struct virtio_gpu_object *bo;
enum ttm_bo_type type;
size_t acc_size;
int ret;
if (kernel)
type = ttm_bo_type_kernel;
else
type = ttm_bo_type_device;
*bo_ptr = NULL;
acc_size = ttm_bo_dma_acc_size(&vgdev->mman.bdev, size,
sizeof(struct virtio_gpu_object));
bo = kzalloc(sizeof(struct virtio_gpu_object), GFP_KERNEL);
if (bo == NULL)
return -ENOMEM;
size = roundup(size, PAGE_SIZE);
ret = drm_gem_object_init(vgdev->ddev, &bo->gem_base, size);
if (ret != 0)
return ret;
bo->dumb = false;
virtio_gpu_init_ttm_placement(bo, pinned);
ret = ttm_bo_init(&vgdev->mman.bdev, &bo->tbo, size, type,
&bo->placement, 0, !kernel, NULL, acc_size,
NULL, NULL, &virtio_gpu_ttm_bo_destroy);
/* ttm_bo_init failure will call the destroy */
if (ret != 0)
return ret;
*bo_ptr = bo;
return 0;
}
CWE ID: CWE-772
Target: 1
Example 2:
Code: MagickExport MagickBooleanType TransformImages(Image **images,
const char *crop_geometry,const char *image_geometry,ExceptionInfo *exception)
{
Image
*image,
**image_list,
*transform_images;
MagickStatusType
status;
register ssize_t
i;
assert(images != (Image **) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
image_list=ImageListToArray(*images,exception);
if (image_list == (Image **) NULL)
return(MagickFalse);
status=MagickTrue;
transform_images=NewImageList();
for (i=0; image_list[i] != (Image *) NULL; i++)
{
image=image_list[i];
status&=TransformImage(&image,crop_geometry,image_geometry,exception);
AppendImageToList(&transform_images,image);
}
*images=transform_images;
image_list=(Image **) RelinquishMagickMemory(image_list);
return(status != 0 ? MagickTrue : MagickFalse);
}
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 SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) {
ALOGE("input buffer too small: got %u, expected %u",
outHeader->nAllocLen, mConfig->outputFrameSize);
android_errorWriteLog(0x534e4554, "27793371");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return;
}
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
if (!memsetSafe(outHeader, 0, outHeader->nFilledLen)) {
return;
}
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
if (!memsetSafe(outHeader, 0, mConfig->outputFrameSize * sizeof(int16_t))) {
return;
}
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(SplFileObject, next)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_file_free_line(intern TSRMLS_CC);
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
}
intern->u.file.current_line_num++;
} /* }}} */
/* {{{ proto void SplFileObject::setFlags(int flags)
CWE ID: CWE-190
Target: 1
Example 2:
Code: FolderHeaderView::FolderHeaderView(FolderHeaderViewDelegate* delegate)
: folder_item_(NULL),
back_button_(new views::ImageButton(this)),
folder_name_view_(new FolderNameView),
folder_name_placeholder_text_(
ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
IDS_APP_LIST_FOLDER_NAME_PLACEHOLDER)),
delegate_(delegate),
folder_name_visible_(true) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
back_button_->SetImage(views::ImageButton::STATE_NORMAL,
rb.GetImageSkiaNamed(IDR_APP_LIST_FOLDER_BACK_NORMAL));
back_button_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
views::ImageButton::ALIGN_MIDDLE);
AddChildView(back_button_);
folder_name_view_->SetFontList(
rb.GetFontList(ui::ResourceBundle::MediumFont));
folder_name_view_->set_placeholder_text_color(kHintTextColor);
folder_name_view_->set_placeholder_text(folder_name_placeholder_text_);
folder_name_view_->SetBorder(views::Border::NullBorder());
folder_name_view_->SetBackgroundColor(kContentsBackgroundColor);
folder_name_view_->set_controller(this);
AddChildView(folder_name_view_);
}
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: JSValue jsTestObjStringAttr(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(slotBase));
UNUSED_PARAM(exec);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
JSValue result = jsString(exec, impl->stringAttr());
return result;
}
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 bool add_free_nid(struct f2fs_sb_info *sbi, nid_t nid, bool build)
{
struct f2fs_nm_info *nm_i = NM_I(sbi);
struct free_nid *i;
struct nat_entry *ne;
int err;
/* 0 nid should not be used */
if (unlikely(nid == 0))
return false;
if (build) {
/* do not add allocated nids */
ne = __lookup_nat_cache(nm_i, nid);
if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) ||
nat_get_blkaddr(ne) != NULL_ADDR))
return false;
}
i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS);
i->nid = nid;
i->state = NID_NEW;
if (radix_tree_preload(GFP_NOFS)) {
kmem_cache_free(free_nid_slab, i);
return true;
}
spin_lock(&nm_i->nid_list_lock);
err = __insert_nid_to_list(sbi, i, FREE_NID_LIST, true);
spin_unlock(&nm_i->nid_list_lock);
radix_tree_preload_end();
if (err) {
kmem_cache_free(free_nid_slab, i);
return true;
}
return true;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: Response InspectorNetworkAgent::setExtraHTTPHeaders(
const std::unique_ptr<protocol::Network::Headers> headers) {
state_->setObject(NetworkAgentState::kExtraRequestHeaders,
headers->toValue());
return Response::OK();
}
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 ID3::Iterator::getstring(String8 *id, bool otherdata) const {
id->setTo("");
const uint8_t *frameData = mFrameData;
if (frameData == NULL) {
return;
}
uint8_t encoding = *frameData;
if (mParent.mVersion == ID3_V1 || mParent.mVersion == ID3_V1_1) {
if (mOffset == 126 || mOffset == 127) {
char tmp[16];
sprintf(tmp, "%d", (int)*frameData);
id->setTo(tmp);
return;
}
id->setTo((const char*)frameData, mFrameSize);
return;
}
if (mFrameSize < getHeaderLength() + 1) {
return;
}
size_t n = mFrameSize - getHeaderLength() - 1;
if (otherdata) {
frameData += 4;
int32_t i = n - 4;
while(--i >= 0 && *++frameData != 0) ;
int skipped = (frameData - mFrameData);
if (skipped >= (int)n) {
return;
}
n -= skipped;
}
if (encoding == 0x00) {
id->setTo((const char*)frameData + 1, n);
} else if (encoding == 0x03) {
id->setTo((const char *)(frameData + 1), n);
} else if (encoding == 0x02) {
int len = n / 2;
const char16_t *framedata = (const char16_t *) (frameData + 1);
char16_t *framedatacopy = NULL;
#if BYTE_ORDER == LITTLE_ENDIAN
framedatacopy = new char16_t[len];
for (int i = 0; i < len; i++) {
framedatacopy[i] = bswap_16(framedata[i]);
}
framedata = framedatacopy;
#endif
id->setTo(framedata, len);
if (framedatacopy != NULL) {
delete[] framedatacopy;
}
} else if (encoding == 0x01) {
int len = n / 2;
const char16_t *framedata = (const char16_t *) (frameData + 1);
char16_t *framedatacopy = NULL;
if (*framedata == 0xfffe) {
framedatacopy = new char16_t[len];
for (int i = 0; i < len; i++) {
framedatacopy[i] = bswap_16(framedata[i]);
}
framedata = framedatacopy;
}
if (*framedata == 0xfeff) {
framedata++;
len--;
}
bool eightBit = true;
for (int i = 0; i < len; i++) {
if (framedata[i] > 0xff) {
eightBit = false;
break;
}
}
if (eightBit) {
char *frame8 = new char[len];
for (int i = 0; i < len; i++) {
frame8[i] = framedata[i];
}
id->setTo(frame8, len);
delete [] frame8;
} else {
id->setTo(framedata, len);
}
if (framedatacopy != NULL) {
delete[] framedatacopy;
}
}
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int dns_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
n = dns_read_name(buffer, bufend, buffer + reader[1],
dest, dest_len - nb_bytes, offset);
if (n == 0)
goto err;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
}
CWE ID: CWE-835
Target: 1
Example 2:
Code: XmlConfigParser* XmlConfigParser::FromContext(void* ctx) {
return static_cast<XmlConfigParser*>(ctx);
}
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: void Document::AddToTopLayer(Element* element, const Element* before) {
if (element->IsInTopLayer())
return;
DCHECK(!top_layer_elements_.Contains(element));
DCHECK(!before || top_layer_elements_.Contains(before));
if (before) {
size_t before_position = top_layer_elements_.Find(before);
top_layer_elements_.insert(before_position, element);
} else {
top_layer_elements_.push_back(element);
}
element->SetIsInTopLayer(true);
}
CWE ID: CWE-732
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ext4_orphan_add(handle_t *handle, struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct ext4_iloc iloc;
int err = 0, rc;
if (!ext4_handle_valid(handle))
return 0;
mutex_lock(&EXT4_SB(sb)->s_orphan_lock);
if (!list_empty(&EXT4_I(inode)->i_orphan))
goto out_unlock;
/*
* Orphan handling is only valid for files with data blocks
* being truncated, or files being unlinked. Note that we either
* hold i_mutex, or the inode can not be referenced from outside,
* so i_nlink should not be bumped due to race
*/
J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)) || inode->i_nlink == 0);
BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
if (err)
goto out_unlock;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_unlock;
/*
* Due to previous errors inode may be already a part of on-disk
* orphan list. If so skip on-disk list modification.
*/
if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <=
(le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count)))
goto mem_insert;
/* Insert this inode at the head of the on-disk orphan list... */
NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan);
EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino);
err = ext4_handle_dirty_super(handle, sb);
rc = ext4_mark_iloc_dirty(handle, inode, &iloc);
if (!err)
err = rc;
/* Only add to the head of the in-memory list if all the
* previous operations succeeded. If the orphan_add is going to
* fail (possibly taking the journal offline), we can't risk
* leaving the inode on the orphan list: stray orphan-list
* entries can cause panics at unmount time.
*
* This is safe: on error we're going to ignore the orphan list
* anyway on the next recovery. */
mem_insert:
if (!err)
list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
jbd_debug(4, "superblock will point to %lu\n", inode->i_ino);
jbd_debug(4, "orphan inode %lu will point to %d\n",
inode->i_ino, NEXT_ORPHAN(inode));
out_unlock:
mutex_unlock(&EXT4_SB(sb)->s_orphan_lock);
ext4_std_error(inode->i_sb, err);
return err;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: SPICE_GNUC_VISIBLE int spice_server_set_image_compression(SpiceServer *s,
spice_image_compression_t comp)
{
spice_assert(reds == s);
set_image_compression(comp);
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LiveSyncTest::SetUpCommandLine(CommandLine* cl) {
if (!cl->HasSwitch(switches::kSyncNotificationMethod))
cl->AppendSwitchASCII(switches::kSyncNotificationMethod, "p2p");
if (!cl->HasSwitch(switches::kEnableSyncSessions))
cl->AppendSwitch(switches::kEnableSyncSessions);
if (!cl->HasSwitch(switches::kEnableSyncTypedUrls))
cl->AppendSwitch(switches::kEnableSyncTypedUrls);
if (!cl->HasSwitch(switches::kDisableBackgroundNetworking))
cl->AppendSwitch(switches::kDisableBackgroundNetworking);
}
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 BrowserEventRouter::TabPinnedStateChanged(WebContents* contents,
int index) {
TabStripModel* tab_strip = NULL;
int tab_index;
if (ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index)) {
DictionaryValue* changed_properties = new DictionaryValue();
changed_properties->SetBoolean(tab_keys::kPinnedKey,
tab_strip->IsTabPinned(tab_index));
DispatchTabUpdatedEvent(contents, changed_properties);
}
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static ssize_t transmit_cmd(struct tpm_chip *chip, struct tpm_cmd_t *cmd,
int len, const char *desc)
{
int err;
len = tpm_transmit(chip,(u8 *) cmd, len);
if (len < 0)
return len;
if (len == TPM_ERROR_SIZE) {
err = be32_to_cpu(cmd->header.out.return_code);
dev_dbg(chip->dev, "A TPM error (%d) occurred %s\n", err, desc);
return err;
}
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: void LogoService::GetLogo(LogoCallbacks callbacks) {
if (!template_url_service_) {
RunCallbacksWithDisabled(std::move(callbacks));
return;
}
const TemplateURL* template_url =
template_url_service_->GetDefaultSearchProvider();
if (!template_url) {
RunCallbacksWithDisabled(std::move(callbacks));
return;
}
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
GURL logo_url;
if (command_line->HasSwitch(switches::kSearchProviderLogoURL)) {
logo_url = GURL(
command_line->GetSwitchValueASCII(switches::kSearchProviderLogoURL));
} else {
#if defined(OS_ANDROID)
logo_url = template_url->logo_url();
#endif
}
GURL base_url;
GURL doodle_url;
const bool is_google = template_url->url_ref().HasGoogleBaseURLs(
template_url_service_->search_terms_data());
if (is_google) {
base_url =
GURL(template_url_service_->search_terms_data().GoogleBaseURLValue());
doodle_url = search_provider_logos::GetGoogleDoodleURL(base_url);
} else if (base::FeatureList::IsEnabled(features::kThirdPartyDoodles)) {
if (command_line->HasSwitch(switches::kThirdPartyDoodleURL)) {
doodle_url = GURL(
command_line->GetSwitchValueASCII(switches::kThirdPartyDoodleURL));
} else {
std::string override_url = base::GetFieldTrialParamValueByFeature(
features::kThirdPartyDoodles,
features::kThirdPartyDoodlesOverrideUrlParam);
if (!override_url.empty()) {
doodle_url = GURL(override_url);
} else {
doodle_url = template_url->doodle_url();
}
}
base_url = doodle_url.GetOrigin();
}
if (!logo_url.is_valid() && !doodle_url.is_valid()) {
RunCallbacksWithDisabled(std::move(callbacks));
return;
}
const bool use_fixed_logo = !doodle_url.is_valid();
if (!logo_tracker_) {
std::unique_ptr<LogoCache> logo_cache = std::move(logo_cache_for_test_);
if (!logo_cache) {
logo_cache = std::make_unique<LogoCache>(cache_directory_);
}
std::unique_ptr<base::Clock> clock = std::move(clock_for_test_);
if (!clock) {
clock = std::make_unique<base::DefaultClock>();
}
logo_tracker_ = std::make_unique<LogoTracker>(
request_context_getter_,
std::make_unique<LogoDelegateImpl>(std::move(image_decoder_)),
std::move(logo_cache), std::move(clock));
}
if (use_fixed_logo) {
logo_tracker_->SetServerAPI(
logo_url, base::Bind(&search_provider_logos::ParseFixedLogoResponse),
base::Bind(&search_provider_logos::UseFixedLogoUrl));
} else if (is_google) {
logo_tracker_->SetServerAPI(
doodle_url,
search_provider_logos::GetGoogleParseLogoResponseCallback(base_url),
search_provider_logos::GetGoogleAppendQueryparamsCallback(
use_gray_background_));
} else {
logo_tracker_->SetServerAPI(
doodle_url,
base::Bind(&search_provider_logos::GoogleNewParseLogoResponse,
base_url),
base::Bind(&search_provider_logos::GoogleNewAppendQueryparamsToLogoURL,
use_gray_background_));
}
logo_tracker_->GetLogo(std::move(callbacks));
}
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: MagickExport unsigned char *DetachBlob(BlobInfo *blob_info)
{
unsigned char
*data;
assert(blob_info != (BlobInfo *) NULL);
if (blob_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (blob_info->mapped != MagickFalse)
{
(void) UnmapBlob(blob_info->data,blob_info->length);
RelinquishMagickResource(MapResource,blob_info->length);
}
blob_info->mapped=MagickFalse;
blob_info->length=0;
blob_info->offset=0;
blob_info->eof=MagickFalse;
blob_info->error=0;
blob_info->exempt=MagickFalse;
blob_info->type=UndefinedStream;
blob_info->file_info.file=(FILE *) NULL;
data=blob_info->data;
blob_info->data=(unsigned char *) NULL;
blob_info->stream=(StreamHandler) NULL;
return(data);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: long kvm_arch_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r = -ENOTTY;
switch (ioctl) {
case KVM_SET_MEMORY_REGION: {
struct kvm_memory_region kvm_mem;
struct kvm_userspace_memory_region kvm_userspace_mem;
r = -EFAULT;
if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem))
goto out;
kvm_userspace_mem.slot = kvm_mem.slot;
kvm_userspace_mem.flags = kvm_mem.flags;
kvm_userspace_mem.guest_phys_addr =
kvm_mem.guest_phys_addr;
kvm_userspace_mem.memory_size = kvm_mem.memory_size;
r = kvm_vm_ioctl_set_memory_region(kvm,
&kvm_userspace_mem, 0);
if (r)
goto out;
break;
}
case KVM_CREATE_IRQCHIP:
r = -EFAULT;
r = kvm_ioapic_init(kvm);
if (r)
goto out;
r = kvm_setup_default_irq_routing(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
kvm_ioapic_destroy(kvm);
mutex_unlock(&kvm->slots_lock);
goto out;
}
break;
case KVM_IRQ_LINE_STATUS:
case KVM_IRQ_LINE: {
struct kvm_irq_level irq_event;
r = -EFAULT;
if (copy_from_user(&irq_event, argp, sizeof irq_event))
goto out;
r = -ENXIO;
if (irqchip_in_kernel(kvm)) {
__s32 status;
status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
irq_event.irq, irq_event.level);
if (ioctl == KVM_IRQ_LINE_STATUS) {
r = -EFAULT;
irq_event.status = status;
if (copy_to_user(argp, &irq_event,
sizeof irq_event))
goto out;
}
r = 0;
}
break;
}
case KVM_GET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip chip;
r = -EFAULT;
if (copy_from_user(&chip, argp, sizeof chip))
goto out;
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto out;
r = kvm_vm_ioctl_get_irqchip(kvm, &chip);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &chip, sizeof chip))
goto out;
r = 0;
break;
}
case KVM_SET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip chip;
r = -EFAULT;
if (copy_from_user(&chip, argp, sizeof chip))
goto out;
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto out;
r = kvm_vm_ioctl_set_irqchip(kvm, &chip);
if (r)
goto out;
r = 0;
break;
}
default:
;
}
out:
return r;
}
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: IDNSpoofChecker::~IDNSpoofChecker() {
uspoof_close(checker_);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void v9fs_attach(void *opaque)
{
V9fsPDU *pdu = opaque;
V9fsState *s = pdu->s;
int32_t fid, afid, n_uname;
V9fsString uname, aname;
V9fsFidState *fidp;
size_t offset = 7;
V9fsQID qid;
ssize_t err;
v9fs_string_init(&uname);
v9fs_string_init(&aname);
err = pdu_unmarshal(pdu, offset, "ddssd", &fid,
&afid, &uname, &aname, &n_uname);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_attach(pdu->tag, pdu->id, fid, afid, uname.data, aname.data);
fidp = alloc_fid(s, fid);
if (fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
fidp->uid = n_uname;
err = v9fs_co_name_to_path(pdu, NULL, "/", &fidp->path);
if (err < 0) {
err = -EINVAL;
clunk_fid(s, fid);
goto out;
}
err = fid_to_qid(pdu, fidp, &qid);
if (err < 0) {
err = -EINVAL;
clunk_fid(s, fid);
goto out;
}
err = pdu_marshal(pdu, offset, "Q", &qid);
if (err < 0) {
clunk_fid(s, fid);
goto out;
}
err += offset;
trace_v9fs_attach_return(pdu->tag, pdu->id,
qid.type, qid.version, qid.path);
/*
* attach could get called multiple times for the same export.
*/
if (!s->migration_blocker) {
s->root_fid = fid;
error_setg(&s->migration_blocker,
"Migration is disabled when VirtFS export path '%s' is mounted in the guest using mount_tag '%s'",
s->ctx.fs_root ? s->ctx.fs_root : "NULL", s->tag);
migrate_add_blocker(s->migration_blocker);
}
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&uname);
v9fs_string_free(&aname);
}
CWE ID: CWE-22
Target: 1
Example 2:
Code: LRESULT RootWindowHostWin::OnMouseRange(UINT message,
WPARAM w_param,
LPARAM l_param) {
MSG msg = { hwnd(), message, w_param, l_param, 0,
{ GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param) } };
MouseEvent event(msg);
bool handled = false;
if (!(event.flags() & ui::EF_IS_NON_CLIENT))
handled = root_window_->DispatchMouseEvent(&event);
SetMsgHandled(handled);
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Browser_Window *window_create(const char *url)
{
Browser_Window *app_data = malloc(sizeof(Browser_Window));
if (!app_data) {
info("ERROR: could not create browser window.\n");
return NULL;
}
/* Create window */
app_data->window = elm_win_add(NULL, "minibrowser-window", ELM_WIN_BASIC);
elm_win_title_set(app_data->window, APP_NAME);
evas_object_smart_callback_add(app_data->window, "delete,request", on_window_deletion, &app_data);
/* Create window background */
Evas_Object *bg = elm_bg_add(app_data->window);
elm_bg_color_set(bg, 193, 192, 191);
evas_object_size_hint_weight_set(bg, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_win_resize_object_add(app_data->window, bg);
evas_object_show(bg);
/* Create vertical layout */
Evas_Object *vertical_layout = elm_box_add(app_data->window);
elm_box_padding_set(vertical_layout, 0, 2);
evas_object_size_hint_weight_set(vertical_layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_win_resize_object_add(app_data->window, vertical_layout);
evas_object_show(vertical_layout);
/* Create horizontal layout for top bar */
Evas_Object *horizontal_layout = elm_box_add(app_data->window);
elm_box_horizontal_set(horizontal_layout, EINA_TRUE);
evas_object_size_hint_weight_set(horizontal_layout, EVAS_HINT_EXPAND, 0.0);
evas_object_size_hint_align_set(horizontal_layout, EVAS_HINT_FILL, 0.0);
elm_box_pack_end(vertical_layout, horizontal_layout);
evas_object_show(horizontal_layout);
/* Create Back button */
app_data->back_button = create_toolbar_button(app_data->window, "arrow_left");
evas_object_smart_callback_add(app_data->back_button, "clicked", on_back_button_clicked, app_data);
elm_object_disabled_set(app_data->back_button, EINA_TRUE);
evas_object_size_hint_weight_set(app_data->back_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->back_button, 0.0, 0.5);
elm_box_pack_end(horizontal_layout, app_data->back_button);
evas_object_show(app_data->back_button);
/* Create Forward button */
app_data->forward_button = create_toolbar_button(app_data->window, "arrow_right");
evas_object_smart_callback_add(app_data->forward_button, "clicked", on_forward_button_clicked, app_data);
elm_object_disabled_set(app_data->forward_button, EINA_TRUE);
evas_object_size_hint_weight_set(app_data->forward_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->forward_button, 0.0, 0.5);
elm_box_pack_end(horizontal_layout, app_data->forward_button);
evas_object_show(app_data->forward_button);
/* Create URL bar */
app_data->url_bar = elm_entry_add(app_data->window);
elm_entry_scrollable_set(app_data->url_bar, EINA_TRUE);
elm_entry_scrollbar_policy_set(app_data->url_bar, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_OFF);
elm_entry_single_line_set(app_data->url_bar, EINA_TRUE);
elm_entry_cnp_mode_set(app_data->url_bar, ELM_CNP_MODE_PLAINTEXT);
elm_entry_text_style_user_push(app_data->url_bar, "DEFAULT='font_size=18'");
evas_object_smart_callback_add(app_data->url_bar, "activated", on_url_bar_activated, app_data);
evas_object_smart_callback_add(app_data->url_bar, "clicked", on_url_bar_clicked, app_data);
evas_object_size_hint_weight_set(app_data->url_bar, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->url_bar, EVAS_HINT_FILL, EVAS_HINT_FILL);
elm_box_pack_end(horizontal_layout, app_data->url_bar);
evas_object_show(app_data->url_bar);
/* Create Refresh button */
Evas_Object *refresh_button = create_toolbar_button(app_data->window, "refresh");
evas_object_smart_callback_add(refresh_button, "clicked", on_refresh_button_clicked, app_data);
evas_object_size_hint_weight_set(refresh_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(refresh_button, 1.0, 0.5);
elm_box_pack_end(horizontal_layout, refresh_button);
evas_object_show(refresh_button);
/* Create Home button */
Evas_Object *home_button = create_toolbar_button(app_data->window, "home");
evas_object_smart_callback_add(home_button, "clicked", on_home_button_clicked, app_data);
evas_object_size_hint_weight_set(home_button, 0.0, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(home_button, 1.0, 0.5);
elm_box_pack_end(horizontal_layout, home_button);
evas_object_show(home_button);
/* Create webview */
Ewk_View_Smart_Class *ewkViewClass = miniBrowserViewSmartClass();
ewkViewClass->run_javascript_alert = on_javascript_alert;
ewkViewClass->run_javascript_confirm = on_javascript_confirm;
ewkViewClass->run_javascript_prompt = on_javascript_prompt;
Evas *evas = evas_object_evas_get(app_data->window);
Evas_Smart *smart = evas_smart_class_new(&ewkViewClass->sc);
app_data->webview = ewk_view_smart_add(evas, smart, ewk_context_default_get());
ewk_view_theme_set(app_data->webview, THEME_DIR "/default.edj");
Ewk_Settings *settings = ewk_view_settings_get(app_data->webview);
ewk_settings_file_access_from_file_urls_allowed_set(settings, EINA_TRUE);
ewk_settings_frame_flattening_enabled_set(settings, frame_flattening_enabled);
ewk_settings_developer_extras_enabled_set(settings, EINA_TRUE);
evas_object_smart_callback_add(app_data->webview, "authentication,request", on_authentication_request, app_data);
evas_object_smart_callback_add(app_data->webview, "close,window", on_close_window, app_data);
evas_object_smart_callback_add(app_data->webview, "create,window", on_new_window, app_data);
evas_object_smart_callback_add(app_data->webview, "download,failed", on_download_failed, app_data);
evas_object_smart_callback_add(app_data->webview, "download,finished", on_download_finished, app_data);
evas_object_smart_callback_add(app_data->webview, "download,request", on_download_request, app_data);
evas_object_smart_callback_add(app_data->webview, "file,chooser,request", on_file_chooser_request, app_data);
evas_object_smart_callback_add(app_data->webview, "icon,changed", on_view_icon_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "load,error", on_error, app_data);
evas_object_smart_callback_add(app_data->webview, "load,progress", on_progress, app_data);
evas_object_smart_callback_add(app_data->webview, "title,changed", on_title_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "url,changed", on_url_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "back,forward,list,changed", on_back_forward_list_changed, app_data);
evas_object_smart_callback_add(app_data->webview, "tooltip,text,set", on_tooltip_text_set, app_data);
evas_object_smart_callback_add(app_data->webview, "tooltip,text,unset", on_tooltip_text_unset, app_data);
evas_object_event_callback_add(app_data->webview, EVAS_CALLBACK_KEY_DOWN, on_key_down, app_data);
evas_object_event_callback_add(app_data->webview, EVAS_CALLBACK_MOUSE_DOWN, on_mouse_down, app_data);
evas_object_size_hint_weight_set(app_data->webview, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(app_data->webview, EVAS_HINT_FILL, EVAS_HINT_FILL);
elm_box_pack_end(vertical_layout, app_data->webview);
evas_object_show(app_data->webview);
if (url)
ewk_view_url_set(app_data->webview, url);
evas_object_resize(app_data->window, DEFAULT_WIDTH, DEFAULT_HEIGHT);
evas_object_show(app_data->window);
view_focus_set(app_data, EINA_TRUE);
return app_data;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
int s = socket(AF_INET, SOCK_DGRAM, 0);
if (s <= 0) {
PLOG(ERROR) << "socket";
return false;
}
uint32_t num_ifs = 0;
if (ioctl_netc_get_num_ifs(s, &num_ifs) < 0) {
PLOG(ERROR) << "ioctl_netc_get_num_ifs";
PCHECK(close(s) == 0);
return false;
}
for (uint32_t i = 0; i < num_ifs; ++i) {
netc_if_info_t interface;
if (ioctl_netc_get_if_info_at(s, &i, &interface) < 0) {
PLOG(WARNING) << "ioctl_netc_get_if_info_at";
continue;
}
if (internal::IsLoopbackOrUnspecifiedAddress(
reinterpret_cast<sockaddr*>(&(interface.addr)))) {
continue;
}
IPEndPoint address;
if (!address.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.addr)),
sizeof(interface.addr))) {
DLOG(WARNING) << "ioctl_netc_get_if_info returned invalid address.";
continue;
}
int prefix_length = 0;
IPEndPoint netmask;
if (netmask.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.netmask)),
sizeof(interface.netmask))) {
prefix_length = MaskPrefixLength(netmask.address());
}
int attributes = 0;
networks->push_back(
NetworkInterface(interface.name, interface.name, interface.index,
NetworkChangeNotifier::CONNECTION_UNKNOWN,
address.address(), prefix_length, attributes));
}
PCHECK(close(s) == 0);
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: do_open_permission(struct svc_rqst *rqstp, struct svc_fh *current_fh, struct nfsd4_open *open, int accmode)
{
__be32 status;
if (open->op_truncate &&
!(open->op_share_access & NFS4_SHARE_ACCESS_WRITE))
return nfserr_inval;
accmode |= NFSD_MAY_READ_IF_EXEC;
if (open->op_share_access & NFS4_SHARE_ACCESS_READ)
accmode |= NFSD_MAY_READ;
if (open->op_share_access & NFS4_SHARE_ACCESS_WRITE)
accmode |= (NFSD_MAY_WRITE | NFSD_MAY_TRUNC);
if (open->op_share_deny & NFS4_SHARE_DENY_READ)
accmode |= NFSD_MAY_WRITE;
status = fh_verify(rqstp, current_fh, S_IFREG, accmode);
return status;
}
CWE ID: CWE-404
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: vips_foreign_is_a( const char *loader, const char *filename )
{
const VipsObjectClass *class;
VipsForeignLoadClass *load_class;
if( !(class = vips_class_find( "VipsForeignLoad", loader )) )
return( FALSE );
load_class = VIPS_FOREIGN_LOAD_CLASS( class );
if( load_class->is_a &&
load_class->is_a( filename ) )
return( TRUE );
return( FALSE );
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: privsep_preauth(Authctxt *authctxt)
{
int status, r;
pid_t pid;
struct ssh_sandbox *box = NULL;
/* Set up unprivileged child process to deal with network data */
pmonitor = monitor_init();
/* Store a pointer to the kex for later rekeying */
pmonitor->m_pkex = &active_state->kex;
if (use_privsep == PRIVSEP_ON)
box = ssh_sandbox_init();
pid = fork();
if (pid == -1) {
fatal("fork of unprivileged child failed");
} else if (pid != 0) {
debug2("Network child is on pid %ld", (long)pid);
pmonitor->m_pid = pid;
if (have_agent) {
r = ssh_get_authentication_socket(&auth_sock);
if (r != 0) {
error("Could not get agent socket: %s",
ssh_err(r));
have_agent = 0;
}
}
if (box != NULL)
ssh_sandbox_parent_preauth(box, pid);
monitor_child_preauth(authctxt, pmonitor);
/* Sync memory */
monitor_sync(pmonitor);
/* Wait for the child's exit status */
while (waitpid(pid, &status, 0) < 0) {
if (errno == EINTR)
continue;
pmonitor->m_pid = -1;
fatal("%s: waitpid: %s", __func__, strerror(errno));
}
privsep_is_preauth = 0;
pmonitor->m_pid = -1;
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) != 0)
fatal("%s: preauth child exited with status %d",
__func__, WEXITSTATUS(status));
} else if (WIFSIGNALED(status))
fatal("%s: preauth child terminated by signal %d",
__func__, WTERMSIG(status));
if (box != NULL)
ssh_sandbox_parent_finish(box);
return 1;
} else {
/* child */
close(pmonitor->m_sendfd);
close(pmonitor->m_log_recvfd);
/* Arrange for logging to be sent to the monitor */
set_log_handler(mm_log_handler, pmonitor);
privsep_preauth_child();
setproctitle("%s", "[net]");
if (box != NULL)
ssh_sandbox_child(box);
return 0;
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int parse_audio_unit(struct mixer_build *state, int unitid)
{
unsigned char *p1;
if (test_and_set_bit(unitid, state->unitbitmap))
return 0; /* the unit already visited */
p1 = find_audio_control_unit(state, unitid);
if (!p1) {
usb_audio_err(state->chip, "unit %d not found!\n", unitid);
return -EINVAL;
}
switch (p1[2]) {
case UAC_INPUT_TERMINAL:
return 0; /* NOP */
case UAC_MIXER_UNIT:
return parse_audio_mixer_unit(state, unitid, p1);
case UAC2_CLOCK_SOURCE:
return parse_clock_source_unit(state, unitid, p1);
case UAC_SELECTOR_UNIT:
case UAC2_CLOCK_SELECTOR:
return parse_audio_selector_unit(state, unitid, p1);
case UAC_FEATURE_UNIT:
return parse_audio_feature_unit(state, unitid, p1);
case UAC1_PROCESSING_UNIT:
/* UAC2_EFFECT_UNIT has the same value */
if (state->mixer->protocol == UAC_VERSION_1)
return parse_audio_processing_unit(state, unitid, p1);
else
return 0; /* FIXME - effect units not implemented yet */
case UAC1_EXTENSION_UNIT:
/* UAC2_PROCESSING_UNIT_V2 has the same value */
if (state->mixer->protocol == UAC_VERSION_1)
return parse_audio_extension_unit(state, unitid, p1);
else /* UAC_VERSION_2 */
return parse_audio_processing_unit(state, unitid, p1);
case UAC2_EXTENSION_UNIT_V2:
return parse_audio_extension_unit(state, unitid, p1);
default:
usb_audio_err(state->chip,
"unit %u: unexpected type 0x%02x\n", unitid, p1[2]);
return -EINVAL;
}
}
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 Element::rareDataChildrenAffectedByForwardPositionalRules() const
{
ASSERT(hasRareData());
return elementRareData()->childrenAffectedByForwardPositionalRules();
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
}
CWE ID: CWE-754
Target: 1
Example 2:
Code: gfx::OverlayTransform GetGFXOverlayTransform(GLenum plane_transform) {
switch (plane_transform) {
case GL_OVERLAY_TRANSFORM_NONE_CHROMIUM:
return gfx::OVERLAY_TRANSFORM_NONE;
case GL_OVERLAY_TRANSFORM_FLIP_HORIZONTAL_CHROMIUM:
return gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL;
case GL_OVERLAY_TRANSFORM_FLIP_VERTICAL_CHROMIUM:
return gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL;
case GL_OVERLAY_TRANSFORM_ROTATE_90_CHROMIUM:
return gfx::OVERLAY_TRANSFORM_ROTATE_90;
case GL_OVERLAY_TRANSFORM_ROTATE_180_CHROMIUM:
return gfx::OVERLAY_TRANSFORM_ROTATE_180;
case GL_OVERLAY_TRANSFORM_ROTATE_270_CHROMIUM:
return gfx::OVERLAY_TRANSFORM_ROTATE_270;
default:
return gfx::OVERLAY_TRANSFORM_INVALID;
}
}
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: ProfileSyncService::ProfileSyncService(ProfileSyncComponentsFactory* factory,
Profile* profile,
SigninManager* signin_manager,
StartBehavior start_behavior)
: last_auth_error_(AuthError::None()),
passphrase_required_reason_(sync_api::REASON_PASSPHRASE_NOT_REQUIRED),
factory_(factory),
profile_(profile),
sync_prefs_(profile_ ? profile_->GetPrefs() : NULL),
sync_service_url_(kDevServerUrl),
backend_initialized_(false),
is_auth_in_progress_(false),
signin_(signin_manager),
unrecoverable_error_detected_(false),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
expect_sync_configuration_aborted_(false),
clear_server_data_state_(CLEAR_NOT_STARTED),
encrypted_types_(browser_sync::Cryptographer::SensitiveTypes()),
encrypt_everything_(false),
encryption_pending_(false),
auto_start_enabled_(start_behavior == AUTO_START),
failed_datatypes_handler_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
configure_status_(DataTypeManager::UNKNOWN),
setup_in_progress_(false) {
#if defined(OS_ANDROID)
chrome::VersionInfo version_info;
if (version_info.IsOfficialBuild()) {
sync_service_url_ = GURL(kSyncServerUrl);
}
#else
base::ThreadRestrictions::ScopedAllowIO allow_io;
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
channel == chrome::VersionInfo::CHANNEL_BETA) {
sync_service_url_ = GURL(kSyncServerUrl);
}
#endif
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static __u8 *sp_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 107 && rdesc[104] == 0x26 && rdesc[105] == 0x80 &&
rdesc[106] == 0x03) {
hid_info(hdev, "fixing up Sunplus Wireless Desktop report descriptor\n");
rdesc[105] = rdesc[110] = 0x03;
rdesc[106] = rdesc[111] = 0x21;
}
return rdesc;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void TabStripGtk::ExecuteCommandForTab(
TabStripModel::ContextMenuCommand command_id, TabGtk* tab) {
int index = GetIndexOfTab(tab);
if (model_->ContainsIndex(index))
model_->ExecuteContextMenuCommand(index, command_id);
}
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: des_init_local(struct php_crypt_extended_data *data)
{
data->old_rawkey0 = data->old_rawkey1 = 0;
data->saltbits = 0;
data->old_salt = 0;
data->initialized = 1;
}
CWE ID: CWE-310
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: RenderFrameImpl::RenderFrameImpl(const CreateParams& params)
: frame_(NULL),
is_subframe_(false),
is_local_root_(false),
render_view_(params.render_view->AsWeakPtr()),
routing_id_(params.routing_id),
is_swapped_out_(false),
render_frame_proxy_(NULL),
is_detaching_(false),
proxy_routing_id_(MSG_ROUTING_NONE),
#if defined(ENABLE_PLUGINS)
plugin_power_saver_helper_(NULL),
#endif
cookie_jar_(this),
selection_text_offset_(0),
selection_range_(gfx::Range::InvalidRange()),
handling_select_range_(false),
notification_permission_dispatcher_(NULL),
web_user_media_client_(NULL),
media_permission_dispatcher_(NULL),
midi_dispatcher_(NULL),
#if defined(OS_ANDROID)
media_player_manager_(NULL),
#endif
#if defined(ENABLE_BROWSER_CDMS)
cdm_manager_(NULL),
#endif
#if defined(VIDEO_HOLE)
contains_media_player_(false),
#endif
has_played_media_(false),
devtools_agent_(nullptr),
geolocation_dispatcher_(NULL),
push_messaging_dispatcher_(NULL),
presentation_dispatcher_(NULL),
screen_orientation_dispatcher_(NULL),
manifest_manager_(NULL),
accessibility_mode_(AccessibilityModeOff),
renderer_accessibility_(NULL),
weak_factory_(this) {
std::pair<RoutingIDFrameMap::iterator, bool> result =
g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
CHECK(result.second) << "Inserting a duplicate item.";
RenderThread::Get()->AddRoute(routing_id_, this);
render_view_->RegisterRenderFrame(this);
#if defined(OS_ANDROID)
new GinJavaBridgeDispatcher(this);
#endif
#if defined(ENABLE_PLUGINS)
plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
#endif
manifest_manager_ = new ManifestManager(this);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: create_lwfn_name( char* ps_name,
Str255 lwfn_file_name )
{
int max = 5, count = 0;
FT_Byte* p = lwfn_file_name;
FT_Byte* q = (FT_Byte*)ps_name;
lwfn_file_name[0] = 0;
while ( *q )
{
if ( ft_isupper( *q ) )
{
if ( count )
max = 3;
count = 0;
}
if ( count < max && ( ft_isalnum( *q ) || *q == '_' ) )
{
*++p = *q;
lwfn_file_name[0]++;
count++;
}
q++;
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int khugepaged(void *none)
{
struct mm_slot *mm_slot;
set_freezable();
set_user_nice(current, 19);
/* serialize with start_khugepaged() */
mutex_lock(&khugepaged_mutex);
for (;;) {
mutex_unlock(&khugepaged_mutex);
VM_BUG_ON(khugepaged_thread != current);
khugepaged_loop();
VM_BUG_ON(khugepaged_thread != current);
mutex_lock(&khugepaged_mutex);
if (!khugepaged_enabled())
break;
if (unlikely(kthread_should_stop()))
break;
}
spin_lock(&khugepaged_mm_lock);
mm_slot = khugepaged_scan.mm_slot;
khugepaged_scan.mm_slot = NULL;
if (mm_slot)
collect_mm_slot(mm_slot);
spin_unlock(&khugepaged_mm_lock);
khugepaged_thread = NULL;
mutex_unlock(&khugepaged_mutex);
return 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: static inline long decode_twos_comp(ulong c, int prec)
{
long result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1)));
return result;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void kvm_exit(void)
{
debugfs_remove_recursive(kvm_debugfs_dir);
misc_deregister(&kvm_dev);
kmem_cache_destroy(kvm_vcpu_cache);
kvm_async_pf_deinit();
unregister_syscore_ops(&kvm_syscore_ops);
unregister_reboot_notifier(&kvm_reboot_notifier);
cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
on_each_cpu(hardware_disable_nolock, NULL, 1);
kvm_arch_hardware_unsetup();
kvm_arch_exit();
kvm_irqfd_exit();
free_cpumask_var(cpus_hardware_enabled);
kvm_vfio_ops_exit();
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void usage()
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: pnm2png [options] <file>.<pnm> [<file>.png]\n");
fprintf (stderr, " or: ... | pnm2png [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -i[nterlace] write png-file with interlacing on\n");
fprintf (stderr, " -a[lpha] <file>.pgm read PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt, int is_vp7)
{
VP8Context *s = avctx->priv_data;
int ret, i, referenced, num_jobs;
enum AVDiscard skip_thresh;
VP8Frame *av_uninit(curframe), *prev_frame;
if (is_vp7)
ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size);
else
ret = vp8_decode_frame_header(s, avpkt->data, avpkt->size);
if (ret < 0)
goto err;
prev_frame = s->framep[VP56_FRAME_CURRENT];
referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT ||
s->update_altref == VP56_FRAME_CURRENT;
skip_thresh = !referenced ? AVDISCARD_NONREF
: !s->keyframe ? AVDISCARD_NONKEY
: AVDISCARD_ALL;
if (avctx->skip_frame >= skip_thresh) {
s->invisible = 1;
memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);
goto skip_decode;
}
s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;
for (i = 0; i < 5; i++)
if (s->frames[i].tf.f->data[0] &&
&s->frames[i] != prev_frame &&
&s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
&s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&
&s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])
vp8_release_frame(s, &s->frames[i]);
curframe = s->framep[VP56_FRAME_CURRENT] = vp8_find_free_buffer(s);
if (!s->colorspace)
avctx->colorspace = AVCOL_SPC_BT470BG;
if (s->fullrange)
avctx->color_range = AVCOL_RANGE_JPEG;
else
avctx->color_range = AVCOL_RANGE_MPEG;
/* Given that arithmetic probabilities are updated every frame, it's quite
* likely that the values we have on a random interframe are complete
* junk if we didn't start decode on a keyframe. So just don't display
* anything rather than junk. */
if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||
!s->framep[VP56_FRAME_GOLDEN] ||
!s->framep[VP56_FRAME_GOLDEN2])) {
av_log(avctx, AV_LOG_WARNING,
"Discarding interframe without a prior keyframe!\n");
ret = AVERROR_INVALIDDATA;
goto err;
}
curframe->tf.f->key_frame = s->keyframe;
curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
: AV_PICTURE_TYPE_P;
if ((ret = vp8_alloc_frame(s, curframe, referenced)) < 0)
goto err;
if (s->update_altref != VP56_FRAME_NONE)
s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];
else
s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2];
if (s->update_golden != VP56_FRAME_NONE)
s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];
else
s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN];
if (s->update_last)
s->next_framep[VP56_FRAME_PREVIOUS] = curframe;
else
s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS];
s->next_framep[VP56_FRAME_CURRENT] = curframe;
if (avctx->codec->update_thread_context)
ff_thread_finish_setup(avctx);
s->linesize = curframe->tf.f->linesize[0];
s->uvlinesize = curframe->tf.f->linesize[1];
memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz));
/* Zero macroblock structures for top/top-left prediction
* from outside the frame. */
if (!s->mb_layout)
memset(s->macroblocks + s->mb_height * 2 - 1, 0,
(s->mb_width + 1) * sizeof(*s->macroblocks));
if (!s->mb_layout && s->keyframe)
memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4);
memset(s->ref_count, 0, sizeof(s->ref_count));
if (s->mb_layout == 1) {
if (prev_frame && s->segmentation.enabled &&
!s->segmentation.update_map)
ff_thread_await_progress(&prev_frame->tf, 1, 0);
if (is_vp7)
vp7_decode_mv_mb_modes(avctx, curframe, prev_frame);
else
vp8_decode_mv_mb_modes(avctx, curframe, prev_frame);
}
if (avctx->active_thread_type == FF_THREAD_FRAME)
num_jobs = 1;
else
num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count);
s->num_jobs = num_jobs;
s->curframe = curframe;
s->prev_frame = prev_frame;
s->mv_bounds.mv_min.y = -MARGIN;
s->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;
for (i = 0; i < MAX_THREADS; i++) {
VP8ThreadData *td = &s->thread_data[i];
atomic_init(&td->thread_mb_pos, 0);
atomic_init(&td->wait_mb_pos, INT_MAX);
}
if (is_vp7)
avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL,
num_jobs);
else
avctx->execute2(avctx, vp8_decode_mb_row_sliced, s->thread_data, NULL,
num_jobs);
ff_thread_report_progress(&curframe->tf, INT_MAX, 0);
memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4);
skip_decode:
if (!s->update_probabilities)
s->prob[0] = s->prob[1];
if (!s->invisible) {
if ((ret = av_frame_ref(data, curframe->tf.f)) < 0)
return ret;
*got_frame = 1;
}
return avpkt->size;
err:
memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int BackendImpl::Init(const CompletionCallback& callback) {
background_queue_.Init(callback);
return net::ERR_IO_PENDING;
}
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 TrayCast::DestroyDetailedView() {
detailed_ = nullptr;
}
CWE ID: CWE-79
Output: | 0 |
Here are some example code snippets. Analyze the following 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 gemsafe_get_cert_len(sc_card_t *card)
{
int r;
u8 ibuf[GEMSAFE_MAX_OBJLEN];
u8 *iptr;
struct sc_path path;
struct sc_file *file;
size_t objlen, certlen;
unsigned int ind, i=0;
sc_format_path(GEMSAFE_PATH, &path);
r = sc_select_file(card, &path, &file);
if (r != SC_SUCCESS || !file)
return SC_ERROR_INTERNAL;
/* Initial read */
r = sc_read_binary(card, 0, ibuf, GEMSAFE_READ_QUANTUM, 0);
if (r < 0)
return SC_ERROR_INTERNAL;
/* Actual stored object size is encoded in first 2 bytes
* (allocated EF space is much greater!)
*/
objlen = (((size_t) ibuf[0]) << 8) | ibuf[1];
sc_log(card->ctx, "Stored object is of size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
if (objlen < 1 || objlen > GEMSAFE_MAX_OBJLEN) {
sc_log(card->ctx, "Invalid object size: %"SC_FORMAT_LEN_SIZE_T"u",
objlen);
return SC_ERROR_INTERNAL;
}
/* It looks like the first thing in the block is a table of
* which keys are allocated. The table is small and is in the
* first 248 bytes. Example for a card with 10 key containers:
* 01 f0 00 03 03 b0 00 03 <= 1st key unallocated
* 01 f0 00 04 03 b0 00 04 <= 2nd key unallocated
* 01 fe 14 00 05 03 b0 00 05 <= 3rd key allocated
* 01 fe 14 01 06 03 b0 00 06 <= 4th key allocated
* 01 f0 00 07 03 b0 00 07 <= 5th key unallocated
* ...
* 01 f0 00 0c 03 b0 00 0c <= 10th key unallocated
* For allocated keys, the fourth byte seems to indicate the
* default key and the fifth byte indicates the key_ref of
* the private key.
*/
ind = 2; /* skip length */
while (ibuf[ind] == 0x01) {
if (ibuf[ind+1] == 0xFE) {
gemsafe_prkeys[i].ref = ibuf[ind+4];
sc_log(card->ctx, "Key container %d is allocated and uses key_ref %d",
i+1, gemsafe_prkeys[i].ref);
ind += 9;
}
else {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
sc_log(card->ctx, "Key container %d is unallocated", i+1);
ind += 8;
}
i++;
}
/* Delete additional key containers from the data structures if
* this card can't accommodate them.
*/
for (; i < gemsafe_cert_max; i++) {
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
/* Read entire file, then dissect in memory.
* Gemalto ClassicClient seems to do it the same way.
*/
iptr = ibuf + GEMSAFE_READ_QUANTUM;
while ((size_t)(iptr - ibuf) < objlen) {
r = sc_read_binary(card, iptr - ibuf, iptr,
MIN(GEMSAFE_READ_QUANTUM, objlen - (iptr - ibuf)), 0);
if (r < 0) {
sc_log(card->ctx, "Could not read cert object");
return SC_ERROR_INTERNAL;
}
iptr += GEMSAFE_READ_QUANTUM;
}
/* Search buffer for certificates, they start with 0x3082. */
i = 0;
while (ind < objlen - 1) {
if (ibuf[ind] == 0x30 && ibuf[ind+1] == 0x82) {
/* Find next allocated key container */
while (i < gemsafe_cert_max && gemsafe_cert[i].label == NULL)
i++;
if (i == gemsafe_cert_max) {
sc_log(card->ctx, "Warning: Found orphaned certificate at offset %d", ind);
return SC_SUCCESS;
}
/* DER cert len is encoded this way */
if (ind+3 >= sizeof ibuf)
return SC_ERROR_INVALID_DATA;
certlen = ((((size_t) ibuf[ind+2]) << 8) | ibuf[ind+3]) + 4;
sc_log(card->ctx,
"Found certificate of key container %d at offset %d, len %"SC_FORMAT_LEN_SIZE_T"u",
i+1, ind, certlen);
gemsafe_cert[i].index = ind;
gemsafe_cert[i].count = certlen;
ind += certlen;
i++;
} else
ind++;
}
/* Delete additional key containers from the data structures if
* they're missing on the card.
*/
for (; i < gemsafe_cert_max; i++) {
if (gemsafe_cert[i].label) {
sc_log(card->ctx, "Warning: Certificate of key container %d is missing", i+1);
gemsafe_prkeys[i].label = NULL;
gemsafe_cert[i].label = NULL;
}
}
return SC_SUCCESS;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: _tiffMapProc(thandle_t fd, tdata_t* pbase, toff_t* psize)
{
return (0);
}
CWE ID: CWE-369
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ssize_t pipe_get_pages(struct iov_iter *i,
struct page **pages, size_t maxsize, unsigned maxpages,
size_t *start)
{
unsigned npages;
size_t capacity;
int idx;
if (!maxsize)
return 0;
if (!sanity(i))
return -EFAULT;
data_start(i, &idx, start);
/* some of this one + all after this one */
npages = ((i->pipe->curbuf - idx - 1) & (i->pipe->buffers - 1)) + 1;
capacity = min(npages,maxpages) * PAGE_SIZE - *start;
return __pipe_get_pages(i, min(maxsize, capacity), pages, idx, start);
}
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 UINT drdynvc_process_close_request(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
int value;
UINT error;
UINT32 ChannelId;
wStream* data_out;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
WLog_Print(drdynvc->log, WLOG_DEBUG, "process_close_request: Sp=%d cbChId=%d, ChannelId=%"PRIu32"",
Sp,
cbChId, ChannelId);
if ((error = dvcman_close_channel(drdynvc->channel_mgr, ChannelId)))
{
WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", error);
return error;
}
data_out = Stream_New(NULL, 4);
if (!data_out)
{
WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!");
return CHANNEL_RC_NO_MEMORY;
}
value = (CLOSE_REQUEST_PDU << 4) | (cbChId & 0x03);
Stream_Write_UINT8(data_out, value);
drdynvc_write_variable_uint(data_out, ChannelId);
error = drdynvc_send(drdynvc, data_out);
if (error)
WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]",
WTSErrorToString(error), error);
return error;
}
CWE ID:
Target: 1
Example 2:
Code: bool omx_vdec::ts_arr_list::reset_ts_list()
{
bool ret = true;
int idx = 0;
DEBUG_PRINT_LOW("reset_ts_list(): Resetting timestamp array list");
for ( ; idx < MAX_NUM_INPUT_OUTPUT_BUFFERS; idx++) {
m_ts_arr_list[idx].valid = false;
}
return ret;
}
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 check_subprogs(struct bpf_verifier_env *env)
{
int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
struct bpf_subprog_info *subprog = env->subprog_info;
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
/* Add entry function. */
ret = add_subprog(env, 0);
if (ret < 0)
return ret;
/* determine subprog starts. The end is one before the next starts */
for (i = 0; i < insn_cnt; i++) {
if (insn[i].code != (BPF_JMP | BPF_CALL))
continue;
if (insn[i].src_reg != BPF_PSEUDO_CALL)
continue;
if (!env->allow_ptr_leaks) {
verbose(env, "function calls to other bpf functions are allowed for root only\n");
return -EPERM;
}
if (bpf_prog_is_dev_bound(env->prog->aux)) {
verbose(env, "function calls in offloaded programs are not supported yet\n");
return -EINVAL;
}
ret = add_subprog(env, i + insn[i].imm + 1);
if (ret < 0)
return ret;
}
/* Add a fake 'exit' subprog which could simplify subprog iteration
* logic. 'subprog_cnt' should not be increased.
*/
subprog[env->subprog_cnt].start = insn_cnt;
if (env->log.level > 1)
for (i = 0; i < env->subprog_cnt; i++)
verbose(env, "func#%d @%d\n", i, subprog[i].start);
/* now check that all jumps are within the same subprog */
subprog_start = subprog[cur_subprog].start;
subprog_end = subprog[cur_subprog + 1].start;
for (i = 0; i < insn_cnt; i++) {
u8 code = insn[i].code;
if (BPF_CLASS(code) != BPF_JMP)
goto next;
if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
goto next;
off = i + insn[i].off + 1;
if (off < subprog_start || off >= subprog_end) {
verbose(env, "jump out of range from insn %d to %d\n", i, off);
return -EINVAL;
}
next:
if (i == subprog_end - 1) {
/* to avoid fall-through from one subprog into another
* the last insn of the subprog should be either exit
* or unconditional jump back
*/
if (code != (BPF_JMP | BPF_EXIT) &&
code != (BPF_JMP | BPF_JA)) {
verbose(env, "last insn is not an exit or jmp\n");
return -EINVAL;
}
subprog_start = subprog_end;
cur_subprog++;
if (cur_subprog < env->subprog_cnt)
subprog_end = subprog[cur_subprog + 1].start;
}
}
return 0;
}
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: int copy_creds(struct task_struct *p, unsigned long clone_flags)
{
#ifdef CONFIG_KEYS
struct thread_group_cred *tgcred;
#endif
struct cred *new;
int ret;
if (
#ifdef CONFIG_KEYS
!p->cred->thread_keyring &&
#endif
clone_flags & CLONE_THREAD
) {
p->real_cred = get_cred(p->cred);
get_cred(p->cred);
alter_cred_subscribers(p->cred, 2);
kdebug("share_creds(%p{%d,%d})",
p->cred, atomic_read(&p->cred->usage),
read_cred_subscribers(p->cred));
atomic_inc(&p->cred->user->processes);
return 0;
}
new = prepare_creds();
if (!new)
return -ENOMEM;
if (clone_flags & CLONE_NEWUSER) {
ret = create_user_ns(new);
if (ret < 0)
goto error_put;
}
/* cache user_ns in cred. Doesn't need a refcount because it will
* stay pinned by cred->user
*/
new->user_ns = new->user->user_ns;
#ifdef CONFIG_KEYS
/* new threads get their own thread keyrings if their parent already
* had one */
if (new->thread_keyring) {
key_put(new->thread_keyring);
new->thread_keyring = NULL;
if (clone_flags & CLONE_THREAD)
install_thread_keyring_to_cred(new);
}
/* we share the process and session keyrings between all the threads in
* a process - this is slightly icky as we violate COW credentials a
* bit */
if (!(clone_flags & CLONE_THREAD)) {
tgcred = kmalloc(sizeof(*tgcred), GFP_KERNEL);
if (!tgcred) {
ret = -ENOMEM;
goto error_put;
}
atomic_set(&tgcred->usage, 1);
spin_lock_init(&tgcred->lock);
tgcred->process_keyring = NULL;
tgcred->session_keyring = key_get(new->tgcred->session_keyring);
release_tgcred(new);
new->tgcred = tgcred;
}
#endif
atomic_inc(&new->user->processes);
p->cred = p->real_cred = get_cred(new);
alter_cred_subscribers(new, 2);
validate_creds(new);
return 0;
error_put:
put_cred(new);
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
tTcpIpPacketParsingResult res = _res;
ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader);
res.TcpUdp = ppresIsUDP;
res.XxpIpHeaderSize = udpDataStart;
if (len >= udpDataStart)
{
UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
USHORT datagramLength = swap_short(pUdpHeader->udp_length);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength));
}
else
{
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
{
int i;
VncDisplay *vd = ds->opaque;
struct VncSurface *s = &vd->guest;
h += y;
two 16-pixel blocks but we only mark the first as dirty
*/
w += (x % 16);
x -= (x % 16);
w += (x % 16);
x -= (x % 16);
x = MIN(x, s->ds->width);
y = MIN(y, s->ds->height);
w = MIN(x + w, s->ds->width) - x;
h = MIN(h, s->ds->height);
for (; y < h; y++)
for (i = 0; i < w; i += 16)
void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
int32_t encoding)
{
vnc_write_u16(vs, x);
vnc_write_u16(vs, y);
vnc_write_u16(vs, w);
vnc_write_u16(vs, h);
vnc_write_s32(vs, encoding);
}
void buffer_reserve(Buffer *buffer, size_t len)
{
if ((buffer->capacity - buffer->offset) < len) {
buffer->capacity += (len + 1024);
buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
if (buffer->buffer == NULL) {
fprintf(stderr, "vnc: out of memory\n");
exit(1);
}
}
}
int buffer_empty(Buffer *buffer)
{
return buffer->offset == 0;
}
uint8_t *buffer_end(Buffer *buffer)
{
return buffer->buffer + buffer->offset;
}
void buffer_reset(Buffer *buffer)
{
buffer->offset = 0;
}
void buffer_free(Buffer *buffer)
{
g_free(buffer->buffer);
buffer->offset = 0;
buffer->capacity = 0;
buffer->buffer = NULL;
}
void buffer_append(Buffer *buffer, const void *data, size_t len)
{
memcpy(buffer->buffer + buffer->offset, data, len);
buffer->offset += len;
}
static void vnc_desktop_resize(VncState *vs)
{
DisplayState *ds = vs->ds;
if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
return;
}
if (vs->client_width == ds_get_width(ds) &&
vs->client_height == ds_get_height(ds)) {
return;
}
vs->client_width = ds_get_width(ds);
vs->client_height = ds_get_height(ds);
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1); /* number of rects */
vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
VNC_ENCODING_DESKTOPRESIZE);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void vnc_abort_display_jobs(VncDisplay *vd)
{
VncState *vs;
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_lock_output(vs);
vs->abort = true;
vnc_unlock_output(vs);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_jobs_join(vs);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_lock_output(vs);
vs->abort = false;
vnc_unlock_output(vs);
}
}
}
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 simulate_sync(struct pt_regs *regs, unsigned int opcode)
{
if ((opcode & OPCODE) == SPEC0 && (opcode & FUNC) == SYNC) {
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
1, 0, regs, 0);
return 0;
}
return -1; /* Must be something else ... */
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void kvm_set_mmio_spte_mask(void)
{
u64 mask;
int maxphyaddr = boot_cpu_data.x86_phys_bits;
/*
* Set the reserved bits and the present bit of an paging-structure
* entry to generate page fault with PFER.RSV = 1.
*/
/* Mask the reserved physical address bits. */
mask = rsvd_bits(maxphyaddr, 51);
/* Bit 62 is always reserved for 32bit host. */
mask |= 0x3ull << 62;
/* Set the present bit. */
mask |= 1ull;
#ifdef CONFIG_X86_64
/*
* If reserved bit is not supported, clear the present bit to disable
* mmio page fault.
*/
if (maxphyaddr == 52)
mask &= ~1ull;
#endif
kvm_mmu_set_mmio_spte_mask(mask);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool inode_capable(const struct inode *inode, int cap)
{
struct user_namespace *ns = current_user_ns();
return ns_capable(ns, cap) && kuid_has_mapping(ns, inode->i_uid);
}
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: jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
int i, j;
int w, h;
int leftbyte, rightbyte;
int shift;
uint8_t *s, *ss;
uint8_t *d, *dd;
uint8_t mask, rightmask;
if (op != JBIG2_COMPOSE_OR) {
/* hand off the the general routine */
return jbig2_image_compose_unopt(ctx, dst, src, x, y, op);
}
/* clip */
w = src->width;
h = src->height;
ss = src->data;
if (x < 0) {
w += x;
x = 0;
}
if (y < 0) {
h += y;
y = 0;
}
w = (x + w < dst->width) ? w : dst->width - x;
h = (y + h < dst->height) ? h : dst->height - y;
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping\n", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
#if 0
/* special case complete/strip replacement */
/* disabled because it's only safe to do when the destination
buffer is all-blank. */
if ((x == 0) && (w == src->width)) {
memcpy(dst->data + y * dst->stride, src->data, h * src->stride);
return 0;
}
#endif
leftbyte = x >> 3;
rightbyte = (x + w - 1) >> 3;
shift = x & 7;
/* general OR case */
s = ss;
d = dd = dst->data + y * dst->stride + leftbyte;
if (d < dst->data || leftbyte > dst->stride || h * dst->stride < 0 || d - leftbyte + h * dst->stride > dst->data + dst->height * dst->stride) {
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "preventing heap overflow in jbig2_image_compose");
}
if (leftbyte == rightbyte) {
mask = 0x100 - (0x100 >> w);
for (j = 0; j < h; j++) {
*d |= (*s & mask) >> shift;
d += dst->stride;
s += src->stride;
}
} else if (shift == 0) {
rightmask = (w & 7) ? 0x100 - (1 << (8 - (w & 7))) : 0xFF;
for (j = 0; j < h; j++) {
for (i = leftbyte; i < rightbyte; i++)
*d++ |= *s++;
*d |= *s & rightmask;
d = (dd += dst->stride);
s = (ss += src->stride);
}
} else {
bool overlap = (((w + 7) >> 3) < ((x + w + 7) >> 3) - (x >> 3));
mask = 0x100 - (1 << shift);
if (overlap)
rightmask = (0x100 - (0x100 >> ((x + w) & 7))) >> (8 - shift);
else
rightmask = 0x100 - (0x100 >> (w & 7));
for (j = 0; j < h; j++) {
*d++ |= (*s & mask) >> shift;
for (i = leftbyte; i < rightbyte - 1; i++) {
*d |= ((*s++ & ~mask) << (8 - shift));
*d++ |= ((*s & mask) >> shift);
}
if (overlap)
*d |= (*s & rightmask) << (8 - shift);
else
*d |= ((s[0] & ~mask) << (8 - shift)) | ((s[1] & rightmask) >> shift);
d = (dd += dst->stride);
s = (ss += src->stride);
}
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool RilSapSocket::SocketExists(const char *socketName) {
RilSapSocketList* current = head;
while(NULL != current) {
if(strcmp(current->socket->name, socketName) == 0) {
return true;
}
current = current->next;
}
return false;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void closedCallback(WebKitWebInspector*, InspectorTest* test)
{
return test->closed();
}
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 AllocateDataSet(cmsIT8* it8)
{
TABLE* t = GetTable(it8);
if (t -> Data) return; // Already allocated
t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*));
if (t->Data == NULL) {
SynError(it8, "AllocateDataSet: Unable to allocate data array");
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static bool tracing_record_taskinfo_skip(int flags)
{
if (unlikely(!(flags & (TRACE_RECORD_CMDLINE | TRACE_RECORD_TGID))))
return true;
if (atomic_read(&trace_record_taskinfo_disabled) || !tracing_is_on())
return true;
if (!__this_cpu_read(trace_taskinfo_save))
return true;
return false;
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AppLauncherHandler::HandleCreateAppShortcut(const base::ListValue* args) {
std::string extension_id;
CHECK(args->GetString(0, &extension_id));
const Extension* extension =
extension_service_->GetExtensionById(extension_id, true);
if (!extension)
return;
Browser* browser = chrome::FindBrowserWithWebContents(
web_ui()->GetWebContents());
chrome::ShowCreateChromeAppShortcutsDialog(
browser->window()->GetNativeWindow(), browser->profile(), extension,
base::Callback<void(bool)>());
}
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: png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
{
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
png_debug(1, "in png_do_write_interlace");
/* We don't have to do anything on the last pass (6) */
#ifdef PNG_USELESS_TESTS_SUPPORTED
if (row != NULL && row_info != NULL && pass < 6)
#else
if (pass < 6)
#endif
{
/* Each pixel depth is handled separately */
switch (row_info->pixel_depth)
{
case 1:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
d = 0;
shift = 7;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 3);
value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
d |= (value << shift);
if (shift == 0)
{
shift = 7;
*dp++ = (png_byte)d;
d = 0;
}
else
shift--;
}
if (shift != 7)
*dp = (png_byte)d;
break;
}
case 2:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
shift = 6;
d = 0;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 2);
value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
d |= (value << shift);
if (shift == 0)
{
shift = 6;
*dp++ = (png_byte)d;
d = 0;
}
else
shift -= 2;
}
if (shift != 6)
*dp = (png_byte)d;
break;
}
case 4:
{
png_bytep sp;
png_bytep dp;
int shift;
int d;
int value;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
dp = row;
shift = 4;
d = 0;
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
sp = row + (png_size_t)(i >> 1);
value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
d |= (value << shift);
if (shift == 0)
{
shift = 4;
*dp++ = (png_byte)d;
d = 0;
}
else
shift -= 4;
}
if (shift != 4)
*dp = (png_byte)d;
break;
}
default:
{
png_bytep sp;
png_bytep dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
png_size_t pixel_bytes;
/* Start at the beginning */
dp = row;
/* Find out how many bytes each pixel takes up */
pixel_bytes = (row_info->pixel_depth >> 3);
/* Loop through the row, only looking at the pixels that
matter */
for (i = png_pass_start[pass]; i < row_width;
i += png_pass_inc[pass])
{
/* Find out where the original pixel is */
sp = row + (png_size_t)i * pixel_bytes;
/* Move the pixel */
if (dp != sp)
png_memcpy(dp, sp, pixel_bytes);
/* Next pixel */
dp += pixel_bytes;
}
break;
}
}
/* Set new row width */
row_info->width = (row_info->width +
png_pass_inc[pass] - 1 -
png_pass_start[pass]) /
png_pass_inc[pass];
row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
row_info->width);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: __weak void perf_callchain_kernel(struct perf_callchain_entry *entry,
struct pt_regs *regs)
{
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void cm_format_rep(struct cm_rep_msg *rep_msg,
struct cm_id_private *cm_id_priv,
struct ib_cm_rep_param *param)
{
cm_format_mad_hdr(&rep_msg->hdr, CM_REP_ATTR_ID, cm_id_priv->tid);
rep_msg->local_comm_id = cm_id_priv->id.local_id;
rep_msg->remote_comm_id = cm_id_priv->id.remote_id;
cm_rep_set_starting_psn(rep_msg, cpu_to_be32(param->starting_psn));
rep_msg->resp_resources = param->responder_resources;
cm_rep_set_target_ack_delay(rep_msg,
cm_id_priv->av.port->cm_dev->ack_delay);
cm_rep_set_failover(rep_msg, param->failover_accepted);
cm_rep_set_rnr_retry_count(rep_msg, param->rnr_retry_count);
rep_msg->local_ca_guid = cm_id_priv->id.device->node_guid;
if (cm_id_priv->qp_type != IB_QPT_XRC_TGT) {
rep_msg->initiator_depth = param->initiator_depth;
cm_rep_set_flow_ctrl(rep_msg, param->flow_control);
cm_rep_set_srq(rep_msg, param->srq);
cm_rep_set_local_qpn(rep_msg, cpu_to_be32(param->qp_num));
} else {
cm_rep_set_srq(rep_msg, 1);
cm_rep_set_local_eecn(rep_msg, cpu_to_be32(param->qp_num));
}
if (param->private_data && param->private_data_len)
memcpy(rep_msg->private_data, param->private_data,
param->private_data_len);
}
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 dump_boot(DOS_FS * fs, struct boot_sector *b, unsigned lss)
{
unsigned short sectors;
printf("Boot sector contents:\n");
if (!atari_format) {
char id[9];
strncpy(id, (const char *)b->system_id, 8);
id[8] = 0;
printf("System ID \"%s\"\n", id);
} else {
/* On Atari, a 24 bit serial number is stored at offset 8 of the boot
* sector */
printf("Serial number 0x%x\n",
b->system_id[5] | (b->system_id[6] << 8) | (b->
system_id[7] << 16));
}
printf("Media byte 0x%02x (%s)\n", b->media, get_media_descr(b->media));
printf("%10d bytes per logical sector\n", GET_UNALIGNED_W(b->sector_size));
printf("%10d bytes per cluster\n", fs->cluster_size);
printf("%10d reserved sector%s\n", le16toh(b->reserved),
le16toh(b->reserved) == 1 ? "" : "s");
printf("First FAT starts at byte %llu (sector %llu)\n",
(unsigned long long)fs->fat_start,
(unsigned long long)fs->fat_start / lss);
printf("%10d FATs, %d bit entries\n", b->fats, fs->fat_bits);
printf("%10d bytes per FAT (= %u sectors)\n", fs->fat_size,
fs->fat_size / lss);
if (!fs->root_cluster) {
printf("Root directory starts at byte %llu (sector %llu)\n",
(unsigned long long)fs->root_start,
(unsigned long long)fs->root_start / lss);
printf("%10d root directory entries\n", fs->root_entries);
} else {
printf("Root directory start at cluster %lu (arbitrary size)\n",
(unsigned long)fs->root_cluster);
}
printf("Data area starts at byte %llu (sector %llu)\n",
(unsigned long long)fs->data_start,
(unsigned long long)fs->data_start / lss);
printf("%10lu data clusters (%llu bytes)\n",
(unsigned long)fs->data_clusters,
(unsigned long long)fs->data_clusters * fs->cluster_size);
printf("%u sectors/track, %u heads\n", le16toh(b->secs_track),
le16toh(b->heads));
printf("%10u hidden sectors\n", atari_format ?
/* On Atari, the hidden field is only 16 bit wide and unused */
(((unsigned char *)&b->hidden)[0] |
((unsigned char *)&b->hidden)[1] << 8) : le32toh(b->hidden));
sectors = GET_UNALIGNED_W(b->sectors);
printf("%10u sectors total\n", sectors ? sectors : le32toh(b->total_sect));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int kvm_get_dirty_log(struct kvm *kvm,
struct kvm_dirty_log *log, int *is_dirty)
{
struct kvm_memslots *slots;
struct kvm_memory_slot *memslot;
int i, as_id, id;
unsigned long n;
unsigned long any = 0;
as_id = log->slot >> 16;
id = (u16)log->slot;
if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
return -EINVAL;
slots = __kvm_memslots(kvm, as_id);
memslot = id_to_memslot(slots, id);
if (!memslot->dirty_bitmap)
return -ENOENT;
n = kvm_dirty_bitmap_bytes(memslot);
for (i = 0; !any && i < n/sizeof(long); ++i)
any = memslot->dirty_bitmap[i];
if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
return -EFAULT;
if (any)
*is_dirty = 1;
return 0;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool ExecuteMoveToEndOfDocument(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
frame.Selection().Modify(
SelectionModifyAlteration::kMove, SelectionModifyDirection::kForward,
TextGranularity::kDocumentBoundary, SetSelectionBy::kUser);
return true;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl2", CVAR_ARCHIVE | CVAR_LATCH);
Com_sprintf(dllName, sizeof(dllName), "renderer_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_opengl2_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
ri.Malloc = CL_RefMalloc;
ri.Free = Z_Free;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_SetDescription = Cvar_SetDescription;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
#if defined __USEA3D && defined __A3D_GEOM
hA3Dg_ExportRenderGeom (ret);
#endif
Com_Printf( "-------------------------------\n");
if ( !ret ) {
Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Cvar_Set( "cl_paused", "0" );
}
CWE ID: CWE-269
Target: 1
Example 2:
Code: ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb,
AVStream *st, RMStream *ast, int len, AVPacket *pkt,
int *seq, int flags, int64_t timestamp)
{
RMDemuxContext *rm = s->priv_data;
int ret;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
rm->current_stream= st->id;
ret = rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq, ×tamp);
if(ret)
return ret < 0 ? ret : -1; //got partial frame or error
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
if ((ast->deint_id == DEINT_ID_GENR) ||
(ast->deint_id == DEINT_ID_INT4) ||
(ast->deint_id == DEINT_ID_SIPR)) {
int x;
int sps = ast->sub_packet_size;
int cfs = ast->coded_framesize;
int h = ast->sub_packet_h;
int y = ast->sub_packet_cnt;
int w = ast->audio_framesize;
if (flags & 2)
y = ast->sub_packet_cnt = 0;
if (!y)
ast->audiotimestamp = timestamp;
switch (ast->deint_id) {
case DEINT_ID_INT4:
for (x = 0; x < h/2; x++)
readfull(s, pb, ast->pkt.data+x*2*w+y*cfs, cfs);
break;
case DEINT_ID_GENR:
for (x = 0; x < w/sps; x++)
readfull(s, pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
break;
case DEINT_ID_SIPR:
readfull(s, pb, ast->pkt.data + y * w, w);
break;
}
if (++(ast->sub_packet_cnt) < h)
return -1;
if (ast->deint_id == DEINT_ID_SIPR)
ff_rm_reorder_sipr_data(ast->pkt.data, h, w);
ast->sub_packet_cnt = 0;
rm->audio_stream_num = st->index;
if (st->codecpar->block_align <= 0) {
av_log(s, AV_LOG_ERROR, "Invalid block alignment %d\n", st->codecpar->block_align);
return AVERROR_INVALIDDATA;
}
rm->audio_pkt_cnt = h * w / st->codecpar->block_align;
} else if ((ast->deint_id == DEINT_ID_VBRF) ||
(ast->deint_id == DEINT_ID_VBRS)) {
int x;
rm->audio_stream_num = st->index;
ast->sub_packet_cnt = (avio_rb16(pb) & 0xf0) >> 4;
if (ast->sub_packet_cnt) {
for (x = 0; x < ast->sub_packet_cnt; x++)
ast->sub_packet_lengths[x] = avio_rb16(pb);
rm->audio_pkt_cnt = ast->sub_packet_cnt;
ast->audiotimestamp = timestamp;
} else
return -1;
} else {
ret = av_get_packet(pb, pkt, len);
if (ret < 0)
return ret;
rm_ac3_swap_bytes(st, pkt);
}
} else {
ret = av_get_packet(pb, pkt, len);
if (ret < 0)
return ret;
}
pkt->stream_index = st->index;
pkt->pts = timestamp;
if (flags & 2)
pkt->flags |= AV_PKT_FLAG_KEY;
return st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ? rm->audio_pkt_cnt : 0;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const char* AutofillDialogViews::SectionContainer::GetClassName() const {
return kSectionContainerClassName;
}
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 LoadingStatsCollectorTest::TestRedirectStatusHistogram(
const std::string& initial_url,
const std::string& prediction_url,
const std::string& navigation_url,
RedirectStatus expected_status) {
const std::string& script_url = "https://cdn.google.com/script.js";
PreconnectPrediction prediction = CreatePreconnectPrediction(
GURL(prediction_url).host(), initial_url != prediction_url,
{{GURL(script_url).GetOrigin(), 1, net::NetworkIsolationKey()}});
EXPECT_CALL(*mock_predictor_, PredictPreconnectOrigins(GURL(initial_url), _))
.WillOnce(DoAll(SetArgPointee<1>(prediction), Return(true)));
std::vector<content::mojom::ResourceLoadInfoPtr> resources;
resources.push_back(
CreateResourceLoadInfoWithRedirects({initial_url, navigation_url}));
resources.push_back(
CreateResourceLoadInfo(script_url, content::ResourceType::kScript));
PageRequestSummary summary =
CreatePageRequestSummary(navigation_url, initial_url, resources);
stats_collector_->RecordPageRequestSummary(summary);
histogram_tester_->ExpectUniqueSample(
internal::kLoadingPredictorPreconnectLearningRedirectStatus,
static_cast<int>(expected_status), 1);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void jbd2_journal_lock_updates(journal_t *journal)
{
DEFINE_WAIT(wait);
write_lock(&journal->j_state_lock);
++journal->j_barrier_count;
/* Wait until there are no running updates */
while (1) {
transaction_t *transaction = journal->j_running_transaction;
if (!transaction)
break;
spin_lock(&transaction->t_handle_lock);
prepare_to_wait(&journal->j_wait_updates, &wait,
TASK_UNINTERRUPTIBLE);
if (!atomic_read(&transaction->t_updates)) {
spin_unlock(&transaction->t_handle_lock);
finish_wait(&journal->j_wait_updates, &wait);
break;
}
spin_unlock(&transaction->t_handle_lock);
write_unlock(&journal->j_state_lock);
schedule();
finish_wait(&journal->j_wait_updates, &wait);
write_lock(&journal->j_state_lock);
}
write_unlock(&journal->j_state_lock);
/*
* We have now established a barrier against other normal updates, but
* we also need to barrier against other jbd2_journal_lock_updates() calls
* to make sure that we serialise special journal-locked operations
* too.
*/
mutex_lock(&journal->j_barrier);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int skcipher_walk_first(struct skcipher_walk *walk)
{
walk->nbytes = 0;
if (WARN_ON_ONCE(in_irq()))
return -EDEADLK;
if (unlikely(!walk->total))
return 0;
walk->buffer = NULL;
if (unlikely(((unsigned long)walk->iv & walk->alignmask))) {
int err = skcipher_copy_iv(walk);
if (err)
return err;
}
walk->page = NULL;
walk->nbytes = walk->total;
return skcipher_walk_next(walk);
}
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: handle_associated_event(struct cpu_hw_events *cpuc,
int idx, struct perf_sample_data *data, struct pt_regs *regs)
{
struct perf_event *event = cpuc->events[idx];
struct hw_perf_event *hwc = &event->hw;
mipspmu_event_update(event, hwc, idx);
data->period = event->hw.last_period;
if (!mipspmu_event_set_period(event, hwc, idx))
return;
if (perf_event_overflow(event, 0, data, regs))
mipspmu->disable_event(idx);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: int blkg_print_stat_bytes(struct seq_file *sf, void *v)
{
blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
blkg_prfill_rwstat_field, (void *)seq_cft(sf)->private,
offsetof(struct blkcg_gq, stat_bytes), true);
return 0;
}
CWE ID: CWE-415
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: rad_acct_open(void)
{
struct rad_handle *h;
h = rad_open();
if (h != NULL)
h->type = RADIUS_ACCT;
return h;
}
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 AppControllerImpl::BindRequest(mojom::AppControllerRequest request) {
bindings_.AddBinding(this, std::move(request));
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: bool Editor::Command::IsEnabled(Event* triggering_event) const {
if (!IsSupported() || !frame_)
return false;
return command_->is_enabled(*frame_, triggering_event, source_);
}
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 GraphicsContext::setLineCap(LineCap)
{
notImplemented();
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: EncodedJSValue JSC_HOST_CALL jsTestObjConstructorFunctionClassMethod2(ExecState* exec)
{
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
return JSValue::encode(JSTestObj::classMethod2(exec));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void FrameView::setTracksPaintInvalidations(bool trackPaintInvalidations)
{
if (trackPaintInvalidations == m_isTrackingPaintInvalidations)
return;
for (Frame* frame = m_frame->tree().top(); frame; frame = frame->tree().traverseNext()) {
if (!frame->isLocalFrame())
continue;
if (RenderView* renderView = toLocalFrame(frame)->contentRenderer())
renderView->compositor()->setTracksPaintInvalidations(trackPaintInvalidations);
}
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"),
"FrameView::setTracksPaintInvalidations", "enabled", trackPaintInvalidations);
resetTrackedPaintInvalidations();
m_isTrackingPaintInvalidations = trackPaintInvalidations;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int main(int argc, char *argv[])
{
FILE *fp_rd = stdin;
FILE *fp_wr = stdout;
FILE *fp_al = NULL;
BOOL raw = TRUE;
BOOL alpha = FALSE;
int argi;
for (argi = 1; argi < argc; argi++)
{
if (argv[argi][0] == '-')
{
switch (argv[argi][1])
{
case 'n':
raw = FALSE;
break;
case 'r':
raw = TRUE;
break;
case 'a':
alpha = TRUE;
argi++;
if ((fp_al = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNM2PNG\n");
fprintf (stderr, "Error: can not create alpha-channel file %s\n", argv[argi]);
exit (1);
}
break;
case 'h':
case '?':
usage();
exit(0);
break;
default:
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unknown option %s\n", argv[argi]);
usage();
exit(1);
break;
} /* end switch */
}
else if (fp_rd == stdin)
{
if ((fp_rd = fopen (argv[argi], "rb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: file %s does not exist\n", argv[argi]);
exit (1);
}
}
else if (fp_wr == stdout)
{
if ((fp_wr = fopen (argv[argi], "wb")) == NULL)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: can not create file %s\n", argv[argi]);
exit (1);
}
}
else
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: too many parameters\n");
usage();
exit(1);
}
} /* end for */
#ifdef __TURBOC__
/* set stdin/stdout if required to binary */
if (fp_rd == stdin)
{
setmode (STDIN, O_BINARY);
}
if ((raw) && (fp_wr == stdout))
{
setmode (STDOUT, O_BINARY);
}
#endif
/* call the conversion program itself */
if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE)
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, "Error: unsuccessful conversion of PNG-image\n");
exit(1);
}
/* close input file */
fclose (fp_rd);
/* close output file */
fclose (fp_wr);
/* close alpha file */
if (alpha)
fclose (fp_al);
return 0;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool TradQT_Manager::ParseCachedBoxes ( const MOOV_Manager & moovMgr )
{
MOOV_Manager::BoxInfo udtaInfo;
MOOV_Manager::BoxRef udtaRef = moovMgr.GetBox ( "moov/udta", &udtaInfo );
if ( udtaRef == 0 ) return false;
for ( XMP_Uns32 i = 0; i < udtaInfo.childCount; ++i ) {
MOOV_Manager::BoxInfo currInfo;
MOOV_Manager::BoxRef currRef = moovMgr.GetNthChild ( udtaRef, i, &currInfo );
if ( currRef == 0 ) break; // Sanity check, should not happen.
if ( (currInfo.boxType >> 24) != 0xA9 ) continue;
if ( currInfo.contentSize < 2+2+1 ) continue; // Want enough for a non-empty value.
InfoMapPos newInfo = this->parsedBoxes.insert ( this->parsedBoxes.end(),
InfoMap::value_type ( currInfo.boxType, ParsedBoxInfo ( currInfo.boxType ) ) );
std::vector<ValueInfo> * newValues = &newInfo->second.values;
XMP_Uns8 * boxPtr = (XMP_Uns8*) currInfo.content;
XMP_Uns8 * boxEnd = boxPtr + currInfo.contentSize;
XMP_Uns16 miniLen, macLang;
for ( ; boxPtr < boxEnd-4; boxPtr += miniLen ) {
miniLen = 4 + GetUns16BE ( boxPtr ); // ! Include header in local miniLen.
macLang = GetUns16BE ( boxPtr+2);
if ( (miniLen <= 4) || (miniLen > (boxEnd - boxPtr)) ) continue; // Ignore bad or empty values.
XMP_StringPtr valuePtr = (char*)(boxPtr+4);
size_t valueLen = miniLen - 4;
newValues->push_back ( ValueInfo() );
ValueInfo * newValue = &newValues->back();
newValue->macLang = macLang;
if ( IsMacLangKnown ( macLang ) ) newValue->xmpLang = GetXMPLang ( macLang );
newValue->macValue.assign ( valuePtr, valueLen );
}
}
return (! this->parsedBoxes.empty());
} // TradQT_Manager::ParseCachedBoxes
CWE ID: CWE-835
Target: 1
Example 2:
Code: void OmniboxPopupViewGtk::Show(size_t num_results) {
gint origin_x, origin_y;
GdkWindow* gdk_window = gtk_widget_get_window(location_bar_);
gdk_window_get_origin(gdk_window, &origin_x, &origin_y);
GtkAllocation allocation;
gtk_widget_get_allocation(location_bar_, &allocation);
int horizontal_offset = 1;
gtk_window_move(GTK_WINDOW(window_),
origin_x + allocation.x - kBorderThickness + horizontal_offset,
origin_y + allocation.y + allocation.height - kBorderThickness - 1 +
kVerticalOffset);
gtk_widget_set_size_request(window_,
allocation.width + (kBorderThickness * 2) - (horizontal_offset * 2),
(num_results * kHeightPerResult) + (kBorderThickness * 2));
gtk_widget_show(window_);
StackWindow();
opened_ = true;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void tv_details_row_activated(
GtkTreeView *tree_view,
GtkTreePath *tree_path_UNUSED,
GtkTreeViewColumn *column,
gpointer user_data)
{
gchar *item_name;
struct problem_item *item = get_current_problem_item_or_NULL(tree_view, &item_name);
if (!item || !(item->flags & CD_FLAG_TXT))
goto ret;
if (!strchr(item->content, '\n')) /* one line? */
goto ret; /* yes */
gint exitcode;
gchar *arg[3];
arg[0] = (char *) "xdg-open";
arg[1] = concat_path_file(g_dump_dir_name, item_name);
arg[2] = NULL;
const gboolean spawn_ret = g_spawn_sync(NULL, arg, NULL,
G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL,
NULL, NULL, NULL, NULL, &exitcode, NULL);
if (spawn_ret == FALSE || exitcode != EXIT_SUCCESS)
{
GtkWidget *dialog = gtk_dialog_new_with_buttons(_("View/edit a text file"),
GTK_WINDOW(g_wnd_assistant),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
NULL, NULL);
GtkWidget *vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL);
GtkWidget *textview = gtk_text_view_new();
gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Save"), GTK_RESPONSE_OK);
gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0);
gtk_widget_set_size_request(scrolled, 640, 480);
gtk_widget_show(scrolled);
#if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 7) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 7 && GTK_MICRO_VERSION < 8))
/* http://developer.gnome.org/gtk3/unstable/GtkScrolledWindow.html#gtk-scrolled-window-add-with-viewport */
/* gtk_scrolled_window_add_with_viewport has been deprecated since version 3.8 and should not be used in newly-written code. */
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), textview);
#else
/* gtk_container_add() will now automatically add a GtkViewport if the child doesn't implement GtkScrollable. */
gtk_container_add(GTK_CONTAINER(scrolled), textview);
#endif
gtk_widget_show(textview);
load_text_to_text_view(GTK_TEXT_VIEW(textview), item_name);
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK)
save_text_from_text_view(GTK_TEXT_VIEW(textview), item_name);
gtk_widget_destroy(textview);
gtk_widget_destroy(scrolled);
gtk_widget_destroy(dialog);
}
free(arg[1]);
ret:
g_free(item_name);
}
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: AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage(
const gpu::Mailbox& mailbox,
const gpu::SyncToken& sync_token,
unsigned texture_id,
base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&
context_provider_wrapper,
IntSize mailbox_size)
: paint_image_content_id_(cc::PaintImage::GetNextContentId()) {
texture_holder_ = std::make_unique<MailboxTextureHolder>(
mailbox, sync_token, texture_id, std::move(context_provider_wrapper),
mailbox_size);
thread_checker_.DetachFromThread();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct cm_timewait_info * cm_insert_remote_id(struct cm_timewait_info
*timewait_info)
{
struct rb_node **link = &cm.remote_id_table.rb_node;
struct rb_node *parent = NULL;
struct cm_timewait_info *cur_timewait_info;
__be64 remote_ca_guid = timewait_info->remote_ca_guid;
__be32 remote_id = timewait_info->work.remote_id;
while (*link) {
parent = *link;
cur_timewait_info = rb_entry(parent, struct cm_timewait_info,
remote_id_node);
if (be32_lt(remote_id, cur_timewait_info->work.remote_id))
link = &(*link)->rb_left;
else if (be32_gt(remote_id, cur_timewait_info->work.remote_id))
link = &(*link)->rb_right;
else if (be64_lt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
link = &(*link)->rb_left;
else if (be64_gt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
link = &(*link)->rb_right;
else
return cur_timewait_info;
}
timewait_info->inserted_remote_id = 1;
rb_link_node(&timewait_info->remote_id_node, parent, link);
rb_insert_color(&timewait_info->remote_id_node, &cm.remote_id_table);
return NULL;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void VaapiVideoDecodeAccelerator::NotifyError(Error error) {
if (!task_runner_->BelongsToCurrentThread()) {
DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread());
task_runner_->PostTask(FROM_HERE,
base::Bind(&VaapiVideoDecodeAccelerator::NotifyError,
weak_this_, error));
return;
}
task_runner_->PostTask(
FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::Cleanup, weak_this_));
VLOGF(1) << "Notifying of error " << error;
if (client_) {
client_->NotifyError(error);
client_ptr_factory_.reset();
}
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BrowserPolicyConnector::DeviceStopAutoRetry() {
#if defined(OS_CHROMEOS)
if (device_cloud_policy_subsystem_.get())
device_cloud_policy_subsystem_->StopAutoRetry();
#endif
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void ExtensionDevToolsClientHost::InfoBarDestroyed() {
infobar_delegate_ = NULL;
SendDetachedEvent();
Close();
}
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 RenderWidgetHostViewAura::AcceleratedSurfaceNew(
int32 width_in_pixel,
int32 height_in_pixel,
uint64 surface_handle) {
ImageTransportFactory* factory = ImageTransportFactory::GetInstance();
scoped_refptr<ui::Texture> surface(factory->CreateTransportClient(
gfx::Size(width_in_pixel, height_in_pixel), device_scale_factor_,
surface_handle));
if (!surface) {
LOG(ERROR) << "Failed to create ImageTransport texture";
return;
}
image_transport_clients_[surface_handle] = surface;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void *hashtable_iter_at(hashtable_t *hashtable, const char *key)
{
pair_t *pair;
size_t hash;
bucket_t *bucket;
hash = hash_str(key);
bucket = &hashtable->buckets[hash % num_buckets(hashtable)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
return NULL;
return &pair->list;
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: static void unkeep_all_packs(void)
{
static char name[PATH_MAX];
int k;
for (k = 0; k < pack_id; k++) {
struct packed_git *p = all_packs[k];
snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
get_object_directory(), sha1_to_hex(p->sha1));
unlink_or_warn(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: test_bson_validate (void)
{
char filename[64];
size_t offset;
bson_t *b;
int i;
bson_error_t error;
for (i = 1; i <= 38; i++) {
bson_snprintf (filename, sizeof filename, "test%u.bson", i);
b = get_bson (filename);
BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));
bson_destroy (b);
}
b = get_bson ("codewscope.bson");
BSON_ASSERT (bson_validate (b, BSON_VALIDATE_NONE, &offset));
bson_destroy (b);
b = get_bson ("empty_key.bson");
BSON_ASSERT (bson_validate (b,
BSON_VALIDATE_NONE | BSON_VALIDATE_UTF8 |
BSON_VALIDATE_DOLLAR_KEYS |
BSON_VALIDATE_DOT_KEYS,
&offset));
bson_destroy (b);
#define VALIDATE_TEST(_filename, _flags, _offset, _flag, _msg) \
b = get_bson (_filename); \
BSON_ASSERT (!bson_validate (b, _flags, &offset)); \
ASSERT_CMPSIZE_T (offset, ==, (size_t) _offset); \
BSON_ASSERT (!bson_validate_with_error (b, _flags, &error)); \
ASSERT_ERROR_CONTAINS (error, BSON_ERROR_INVALID, _flag, _msg); \
bson_destroy (b)
VALIDATE_TEST ("overflow2.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("trailingnull.bson",
BSON_VALIDATE_NONE,
14,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("dollarquery.bson",
BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,
4,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$query\"");
VALIDATE_TEST ("dotquery.bson",
BSON_VALIDATE_DOLLAR_KEYS | BSON_VALIDATE_DOT_KEYS,
4,
BSON_VALIDATE_DOT_KEYS,
"keys cannot contain \".\": \"abc.def\"");
VALIDATE_TEST ("overflow3.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
/* same outcome as above, despite different flags */
VALIDATE_TEST ("overflow3.bson",
BSON_VALIDATE_UTF8,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("overflow4.bson",
BSON_VALIDATE_NONE,
9,
BSON_VALIDATE_NONE,
"corrupt BSON");
VALIDATE_TEST ("empty_key.bson",
BSON_VALIDATE_EMPTY_KEYS,
4,
BSON_VALIDATE_EMPTY_KEYS,
"empty key");
VALIDATE_TEST (
"test40.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test41.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test42.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test43.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test44.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test45.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test46.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test47.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test48.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test49.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST ("test50.bson",
BSON_VALIDATE_NONE,
10,
BSON_VALIDATE_NONE,
"corrupt code-with-scope");
VALIDATE_TEST ("test51.bson",
BSON_VALIDATE_NONE,
10,
BSON_VALIDATE_NONE,
"corrupt code-with-scope");
VALIDATE_TEST (
"test52.bson", BSON_VALIDATE_NONE, 9, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST (
"test53.bson", BSON_VALIDATE_NONE, 6, BSON_VALIDATE_NONE, "corrupt BSON");
VALIDATE_TEST ("test54.bson",
BSON_VALIDATE_NONE,
12,
BSON_VALIDATE_NONE,
"corrupt BSON");
/* DBRef validation */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"$id",
BCON_INT32 (1),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
bson_destroy (b);
/* needs "$ref" before "$id" */
b = BCON_NEW ("my_dbref", "{", "$id", BCON_INT32 (1), "}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$id\"");
bson_destroy (b);
/* two $refs */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"$ref",
BCON_UTF8 ("collection"),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"keys cannot begin with \"$\": \"$ref\"");
bson_destroy (b);
/* must not contain invalid key like "extra" */
b = BCON_NEW ("my_dbref",
"{",
"$ref",
BCON_UTF8 ("collection"),
"extra",
BCON_INT32 (2),
"$id",
BCON_INT32 (1),
"}");
BSON_ASSERT (bson_validate_with_error (b, BSON_VALIDATE_NONE, &error));
BSON_ASSERT (
!bson_validate_with_error (b, BSON_VALIDATE_DOLLAR_KEYS, &error));
ASSERT_ERROR_CONTAINS (error,
BSON_ERROR_INVALID,
BSON_VALIDATE_DOLLAR_KEYS,
"invalid key within DBRef subdocument: \"extra\"");
bson_destroy (b);
#undef VALIDATE_TEST
}
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: print_bacp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case BACPOPT_FPEER:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|bacp]"));
return 0;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void bio_disassociate_task(struct bio *bio)
{
if (bio->bi_ioc) {
put_io_context(bio->bi_ioc);
bio->bi_ioc = NULL;
}
if (bio->bi_css) {
css_put(bio->bi_css);
bio->bi_css = NULL;
}
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nfc_llcp_wks_sap(char *service_name, size_t service_name_len)
{
int sap, num_wks;
pr_debug("%s\n", service_name);
if (service_name == NULL)
return -EINVAL;
num_wks = ARRAY_SIZE(wks);
for (sap = 0; sap < num_wks; sap++) {
if (wks[sap] == NULL)
continue;
if (strncmp(wks[sap], service_name, service_name_len) == 0)
return sap;
}
return -EINVAL;
}
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: CmdBufferImageTransportFactory::CreateSharedSurfaceHandle() {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return gfx::GLSurfaceHandle();
}
gfx::GLSurfaceHandle handle = gfx::GLSurfaceHandle(
gfx::kNullPluginWindow, true);
handle.parent_gpu_process_id = context_->GetGPUProcessID();
handle.parent_client_id = context_->GetChannelID();
handle.parent_context_id = context_->GetContextID();
handle.parent_texture_id[0] = context_->createTexture();
handle.parent_texture_id[1] = context_->createTexture();
handle.sync_point = context_->insertSyncPoint();
context_->flush();
return handle;
}
CWE ID:
Target: 1
Example 2:
Code: static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
{
int i, stream_no;
const char *type = "unknown";
char parameters[64];
LayeredAVStream *st;
AVCodec *codec;
stream_no = stream->nb_streams;
avio_printf(pb, "<table><tr><th>Stream<th>"
"type<th>kbit/s<th>codec<th>"
"Parameters\n");
for (i = 0; i < stream_no; i++) {
st = stream->streams[i];
codec = avcodec_find_encoder(st->codecpar->codec_id);
parameters[0] = 0;
switch(st->codecpar->codec_type) {
case AVMEDIA_TYPE_AUDIO:
type = "audio";
snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
st->codecpar->channels, st->codecpar->sample_rate);
break;
case AVMEDIA_TYPE_VIDEO:
type = "video";
snprintf(parameters, sizeof(parameters),
"%dx%d, q=%d-%d, fps=%d", st->codecpar->width,
st->codecpar->height, st->codec->qmin, st->codec->qmax,
st->time_base.den / st->time_base.num);
break;
default:
abort();
}
avio_printf(pb, "<tr><td>%d<td>%s<td>%"PRId64
"<td>%s<td>%s\n",
i, type, (int64_t)st->codecpar->bit_rate/1000,
codec ? codec->name : "", parameters);
}
avio_printf(pb, "</table>\n");
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static uint32_t GetMaxIndex(JSObject* receiver, FixedArrayBase* elements) {
if (receiver->IsJSArray()) {
DCHECK(JSArray::cast(receiver)->length()->IsSmi());
return static_cast<uint32_t>(
Smi::cast(JSArray::cast(receiver)->length())->value());
}
return Subclass::GetCapacityImpl(receiver, elements);
}
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: METHODDEF(JDIMENSION)
get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register unsigned int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
*ptr++ = rescale[temp];
}
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: xsltCurrentFunction(xmlXPathParserContextPtr ctxt, int nargs){
xsltTransformContextPtr tctxt;
if (nargs != 0) {
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"current() : function uses no argument\n");
ctxt->error = XPATH_INVALID_ARITY;
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
if (tctxt == NULL) {
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"current() : internal error tctxt == NULL\n");
valuePush(ctxt, xmlXPathNewNodeSet(NULL));
} else {
valuePush(ctxt, xmlXPathNewNodeSet(tctxt->node)); /* current */
}
}
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 NETJOIN_REC *netjoin_add(IRC_SERVER_REC *server, const char *nick,
GSList *channels)
{
NETJOIN_REC *rec;
NETJOIN_SERVER_REC *srec;
g_return_val_if_fail(server != NULL, NULL);
g_return_val_if_fail(nick != NULL, NULL);
rec = g_new0(NETJOIN_REC, 1);
rec->nick = g_strdup(nick);
while (channels != NULL) {
NETSPLIT_CHAN_REC *channel = channels->data;
rec->old_channels = g_slist_append(rec->old_channels,
g_strdup(channel->name));
channels = channels->next;
}
srec = netjoin_find_server(server);
if (srec == NULL) {
srec = g_new0(NETJOIN_SERVER_REC, 1);
srec->server = server;
joinservers = g_slist_append(joinservers, srec);
}
srec->last_netjoin = time(NULL);
srec->netjoins = g_slist_append(srec->netjoins, rec);
return rec;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)
{
ulonglong tmp;
if (jas_iccgetuint(in, 4, &tmp))
return -1;
*val = tmp;
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static void ib_uverbs_remove_one(struct ib_device *device, void *client_data)
{
struct ib_uverbs_device *uverbs_dev = client_data;
int wait_clients = 1;
if (!uverbs_dev)
return;
dev_set_drvdata(uverbs_dev->dev, NULL);
device_destroy(uverbs_class, uverbs_dev->cdev.dev);
cdev_del(&uverbs_dev->cdev);
if (uverbs_dev->devnum < IB_UVERBS_MAX_DEVICES)
clear_bit(uverbs_dev->devnum, dev_map);
else
clear_bit(uverbs_dev->devnum - IB_UVERBS_MAX_DEVICES, overflow_map);
if (device->disassociate_ucontext) {
/* We disassociate HW resources and immediately return.
* Userspace will see a EIO errno for all future access.
* Upon returning, ib_device may be freed internally and is not
* valid any more.
* uverbs_device is still available until all clients close
* their files, then the uverbs device ref count will be zero
* and its resources will be freed.
* Note: At this point no more files can be opened since the
* cdev was deleted, however active clients can still issue
* commands and close their open files.
*/
rcu_assign_pointer(uverbs_dev->ib_dev, NULL);
ib_uverbs_free_hw_resources(uverbs_dev, device);
wait_clients = 0;
}
if (atomic_dec_and_test(&uverbs_dev->refcount))
ib_uverbs_comp_dev(uverbs_dev);
if (wait_clients)
wait_for_completion(&uverbs_dev->comp);
kobject_put(&uverbs_dev->kobj);
}
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: X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param, const unsigned char *ip,
size_t iplen)
{
if (iplen != 0 && iplen != 4 && iplen != 16)
return 0;
return int_x509_param_set1((char **)¶m->id->ip, ¶m->id->iplen,
(char *)ip, iplen);
}
CWE ID: CWE-295
Output: | 0 |
Here are some example code snippets. Analyze the following 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 sc_file_set_sec_attr(sc_file_t *file, const u8 *sec_attr,
size_t sec_attr_len)
{
u8 *tmp;
if (!sc_file_valid(file)) {
return SC_ERROR_INVALID_ARGUMENTS;
}
if (sec_attr == NULL) {
if (file->sec_attr != NULL)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return 0;
}
tmp = (u8 *) realloc(file->sec_attr, sec_attr_len);
if (!tmp) {
if (file->sec_attr)
free(file->sec_attr);
file->sec_attr = NULL;
file->sec_attr_len = 0;
return SC_ERROR_OUT_OF_MEMORY;
}
file->sec_attr = tmp;
memcpy(file->sec_attr, sec_attr, sec_attr_len);
file->sec_attr_len = sec_attr_len;
return 0;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: static void _notify_slurmctld_prolog_fini(
uint32_t job_id, uint32_t prolog_return_code)
{
int rc;
slurm_msg_t req_msg;
complete_prolog_msg_t req;
slurm_msg_t_init(&req_msg);
req.job_id = job_id;
req.prolog_rc = prolog_return_code;
req_msg.msg_type= REQUEST_COMPLETE_PROLOG;
req_msg.data = &req;
if ((slurm_send_recv_controller_rc_msg(&req_msg, &rc) < 0) ||
(rc != SLURM_SUCCESS))
error("Error sending prolog completion notification: %m");
}
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: qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
u32 level, const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (!(qedi_dbg_log & level))
goto ret;
if (likely(qedi) && likely(qedi->pdev))
pr_info("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev),
nfunc, line, qedi->host_no, &vaf);
else
pr_info("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
ret:
va_end(va);
}
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: VideoTrack::VideoTrack(
Segment* pSegment,
long long element_start,
long long element_size) :
Track(pSegment, element_start, element_size)
{
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ExtensionResource Extension::GetResource(
const std::string& relative_path) const {
#if defined(OS_POSIX)
FilePath relative_file_path(relative_path);
#elif defined(OS_WIN)
FilePath relative_file_path(UTF8ToWide(relative_path));
#endif
return ExtensionResource(id(), path(), relative_file_path);
}
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 ptrace_triggered(struct perf_event *bp, int nmi,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct perf_event_attr attr;
/*
* Disable the breakpoint request here since ptrace has defined a
* one-shot behaviour for breakpoint exceptions.
*/
attr = bp->attr;
attr.disabled = true;
modify_user_hw_breakpoint(bp, &attr);
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
u16 selector, int seg, u8 cpl,
enum x86_transfer_type transfer,
struct desc_struct *desc)
{
struct desc_struct seg_desc, old_desc;
u8 dpl, rpl;
unsigned err_vec = GP_VECTOR;
u32 err_code = 0;
bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
ulong desc_addr;
int ret;
u16 dummy;
u32 base3 = 0;
memset(&seg_desc, 0, sizeof seg_desc);
if (ctxt->mode == X86EMUL_MODE_REAL) {
/* set real mode segment descriptor (keep limit etc. for
* unreal mode) */
ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
set_desc_base(&seg_desc, selector << 4);
goto load;
} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
/* VM86 needs a clean new segment descriptor */
set_desc_base(&seg_desc, selector << 4);
set_desc_limit(&seg_desc, 0xffff);
seg_desc.type = 3;
seg_desc.p = 1;
seg_desc.s = 1;
seg_desc.dpl = 3;
goto load;
}
rpl = selector & 3;
/* NULL selector is not valid for TR, CS and SS (except for long mode) */
if ((seg == VCPU_SREG_CS
|| (seg == VCPU_SREG_SS
&& (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl))
|| seg == VCPU_SREG_TR)
&& null_selector)
goto exception;
/* TR should be in GDT only */
if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
goto exception;
if (null_selector) /* for NULL selector skip all following checks */
goto load;
ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
if (ret != X86EMUL_CONTINUE)
return ret;
err_code = selector & 0xfffc;
err_vec = (transfer == X86_TRANSFER_TASK_SWITCH) ? TS_VECTOR :
GP_VECTOR;
/* can't load system descriptor into segment selector */
if (seg <= VCPU_SREG_GS && !seg_desc.s) {
if (transfer == X86_TRANSFER_CALL_JMP)
return X86EMUL_UNHANDLEABLE;
goto exception;
}
if (!seg_desc.p) {
err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
goto exception;
}
dpl = seg_desc.dpl;
switch (seg) {
case VCPU_SREG_SS:
/*
* segment is not a writable data segment or segment
* selector's RPL != CPL or segment selector's RPL != CPL
*/
if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
goto exception;
break;
case VCPU_SREG_CS:
if (!(seg_desc.type & 8))
goto exception;
if (seg_desc.type & 4) {
/* conforming */
if (dpl > cpl)
goto exception;
} else {
/* nonconforming */
if (rpl > cpl || dpl != cpl)
goto exception;
}
/* in long-mode d/b must be clear if l is set */
if (seg_desc.d && seg_desc.l) {
u64 efer = 0;
ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
if (efer & EFER_LMA)
goto exception;
}
/* CS(RPL) <- CPL */
selector = (selector & 0xfffc) | cpl;
break;
case VCPU_SREG_TR:
if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
goto exception;
old_desc = seg_desc;
seg_desc.type |= 2; /* busy */
ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
sizeof(seg_desc), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
break;
case VCPU_SREG_LDTR:
if (seg_desc.s || seg_desc.type != 2)
goto exception;
break;
default: /* DS, ES, FS, or GS */
/*
* segment is not a data or readable code segment or
* ((segment is a data or nonconforming code segment)
* and (both RPL and CPL > DPL))
*/
if ((seg_desc.type & 0xa) == 0x8 ||
(((seg_desc.type & 0xc) != 0xc) &&
(rpl > dpl && cpl > dpl)))
goto exception;
break;
}
if (seg_desc.s) {
/* mark segment as accessed */
if (!(seg_desc.type & 1)) {
seg_desc.type |= 1;
ret = write_segment_descriptor(ctxt, selector,
&seg_desc);
if (ret != X86EMUL_CONTINUE)
return ret;
}
} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3,
sizeof(base3), &ctxt->exception);
if (ret != X86EMUL_CONTINUE)
return ret;
if (is_noncanonical_address(get_desc_base(&seg_desc) |
((u64)base3 << 32)))
return emulate_gp(ctxt, 0);
}
load:
ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
if (desc)
*desc = seg_desc;
return X86EMUL_CONTINUE;
exception:
return emulate_exception(ctxt, err_vec, err_code, true);
}
CWE ID:
Target: 1
Example 2:
Code: explicit DeferredTaskPopupListSelectSingle(WebPagePrivate* webPagePrivate, int index)
: DeferredTaskType(webPagePrivate)
{
webPagePrivate->m_cachedPopupListSelectedIndex = index;
}
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: fix_transited_encoding(krb5_context context,
krb5_kdc_configuration *config,
krb5_boolean check_policy,
const TransitedEncoding *tr,
EncTicketPart *et,
const char *client_realm,
const char *server_realm,
const char *tgt_realm)
{
krb5_error_code ret = 0;
char **realms, **tmp;
unsigned int num_realms;
size_t i;
switch (tr->tr_type) {
case DOMAIN_X500_COMPRESS:
break;
case 0:
/*
* Allow empty content of type 0 because that is was Microsoft
* generates in their TGT.
*/
if (tr->contents.length == 0)
break;
kdc_log(context, config, 0,
"Transited type 0 with non empty content");
return KRB5KDC_ERR_TRTYPE_NOSUPP;
default:
kdc_log(context, config, 0,
"Unknown transited type: %u", tr->tr_type);
return KRB5KDC_ERR_TRTYPE_NOSUPP;
}
ret = krb5_domain_x500_decode(context,
tr->contents,
&realms,
&num_realms,
client_realm,
server_realm);
if(ret){
krb5_warn(context, ret,
"Decoding transited encoding");
return ret;
}
if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) {
/* not us, so add the previous realm to transited set */
if (num_realms + 1 > UINT_MAX/sizeof(*realms)) {
ret = ERANGE;
goto free_realms;
}
tmp = realloc(realms, (num_realms + 1) * sizeof(*realms));
if(tmp == NULL){
ret = ENOMEM;
goto free_realms;
}
realms = tmp;
realms[num_realms] = strdup(tgt_realm);
if(realms[num_realms] == NULL){
ret = ENOMEM;
goto free_realms;
}
num_realms++;
}
if(num_realms == 0) {
if(strcmp(client_realm, server_realm))
kdc_log(context, config, 0,
"cross-realm %s -> %s", client_realm, server_realm);
} else {
size_t l = 0;
char *rs;
for(i = 0; i < num_realms; i++)
l += strlen(realms[i]) + 2;
rs = malloc(l);
if(rs != NULL) {
*rs = '\0';
for(i = 0; i < num_realms; i++) {
if(i > 0)
strlcat(rs, ", ", l);
strlcat(rs, realms[i], l);
}
kdc_log(context, config, 0,
"cross-realm %s -> %s via [%s]",
client_realm, server_realm, rs);
free(rs);
}
}
if(check_policy) {
ret = krb5_check_transited(context, client_realm,
server_realm,
realms, num_realms, NULL);
if(ret) {
krb5_warn(context, ret, "cross-realm %s -> %s",
client_realm, server_realm);
goto free_realms;
}
et->flags.transited_policy_checked = 1;
}
et->transited.tr_type = DOMAIN_X500_COMPRESS;
ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents);
if(ret)
krb5_warn(context, ret, "Encoding transited encoding");
free_realms:
for(i = 0; i < num_realms; i++)
free(realms[i]);
free(realms);
return ret;
}
CWE ID: CWE-295
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: inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) {
debug(D_WEB_CLIENT, "%llu: API v1 data with URL '%s'", w->id, url);
int ret = 400;
BUFFER *dimensions = NULL;
buffer_flush(w->response.data);
char *google_version = "0.6",
*google_reqId = "0",
*google_sig = "0",
*google_out = "json",
*responseHandler = NULL,
*outFileName = NULL;
time_t last_timestamp_in_data = 0, google_timestamp = 0;
char *chart = NULL
, *before_str = NULL
, *after_str = NULL
, *group_time_str = NULL
, *points_str = NULL;
int group = RRDR_GROUPING_AVERAGE;
uint32_t format = DATASOURCE_JSON;
uint32_t options = 0x00000000;
while(url) {
char *value = mystrsep(&url, "?&");
if(!value || !*value) continue;
char *name = mystrsep(&value, "=");
if(!name || !*name) continue;
if(!value || !*value) continue;
debug(D_WEB_CLIENT, "%llu: API v1 data query param '%s' with value '%s'", w->id, name, value);
if(!strcmp(name, "chart")) chart = value;
else if(!strcmp(name, "dimension") || !strcmp(name, "dim") || !strcmp(name, "dimensions") || !strcmp(name, "dims")) {
if(!dimensions) dimensions = buffer_create(100);
buffer_strcat(dimensions, "|");
buffer_strcat(dimensions, value);
}
else if(!strcmp(name, "after")) after_str = value;
else if(!strcmp(name, "before")) before_str = value;
else if(!strcmp(name, "points")) points_str = value;
else if(!strcmp(name, "gtime")) group_time_str = value;
else if(!strcmp(name, "group")) {
group = web_client_api_request_v1_data_group(value, RRDR_GROUPING_AVERAGE);
}
else if(!strcmp(name, "format")) {
format = web_client_api_request_v1_data_format(value);
}
else if(!strcmp(name, "options")) {
options |= web_client_api_request_v1_data_options(value);
}
else if(!strcmp(name, "callback")) {
responseHandler = value;
}
else if(!strcmp(name, "filename")) {
outFileName = value;
}
else if(!strcmp(name, "tqx")) {
char *tqx_name, *tqx_value;
while(value) {
tqx_value = mystrsep(&value, ";");
if(!tqx_value || !*tqx_value) continue;
tqx_name = mystrsep(&tqx_value, ":");
if(!tqx_name || !*tqx_name) continue;
if(!tqx_value || !*tqx_value) continue;
if(!strcmp(tqx_name, "version"))
google_version = tqx_value;
else if(!strcmp(tqx_name, "reqId"))
google_reqId = tqx_value;
else if(!strcmp(tqx_name, "sig")) {
google_sig = tqx_value;
google_timestamp = strtoul(google_sig, NULL, 0);
}
else if(!strcmp(tqx_name, "out")) {
google_out = tqx_value;
format = web_client_api_request_v1_data_google_format(google_out);
}
else if(!strcmp(tqx_name, "responseHandler"))
responseHandler = tqx_value;
else if(!strcmp(tqx_name, "outFileName"))
outFileName = tqx_value;
}
}
}
if(!chart || !*chart) {
buffer_sprintf(w->response.data, "No chart id is given at the request.");
goto cleanup;
}
RRDSET *st = rrdset_find(host, chart);
if(!st) st = rrdset_find_byname(host, chart);
if(!st) {
buffer_strcat(w->response.data, "Chart is not found: ");
buffer_strcat_htmlescape(w->response.data, chart);
ret = 404;
goto cleanup;
}
st->last_accessed_time = now_realtime_sec();
long long before = (before_str && *before_str)?str2l(before_str):0;
long long after = (after_str && *after_str) ?str2l(after_str):0;
int points = (points_str && *points_str)?str2i(points_str):0;
long group_time = (group_time_str && *group_time_str)?str2l(group_time_str):0;
debug(D_WEB_CLIENT, "%llu: API command 'data' for chart '%s', dimensions '%s', after '%lld', before '%lld', points '%d', group '%d', format '%u', options '0x%08x'"
, w->id
, chart
, (dimensions)?buffer_tostring(dimensions):""
, after
, before
, points
, group
, format
, options
);
if(outFileName && *outFileName) {
buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
}
if(format == DATASOURCE_DATATABLE_JSONP) {
if(responseHandler == NULL)
responseHandler = "google.visualization.Query.setResponse";
debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'ok',sig:'%ld',table:",
responseHandler, google_version, google_reqId, st->last_updated.tv_sec);
}
else if(format == DATASOURCE_JSONP) {
if(responseHandler == NULL)
responseHandler = "callback";
buffer_strcat(w->response.data, responseHandler);
buffer_strcat(w->response.data, "(");
}
ret = rrdset2anything_api_v1(st, w->response.data, dimensions, format, points, after, before, group, group_time
, options, &last_timestamp_in_data);
if(format == DATASOURCE_DATATABLE_JSONP) {
if(google_timestamp < last_timestamp_in_data)
buffer_strcat(w->response.data, "});");
else {
buffer_flush(w->response.data);
buffer_sprintf(w->response.data,
"%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
responseHandler, google_version, google_reqId);
}
}
else if(format == DATASOURCE_JSONP)
buffer_strcat(w->response.data, ");");
cleanup:
buffer_free(dimensions);
return ret;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int __init macvlan_init_module(void)
{
int err;
register_netdevice_notifier(&macvlan_notifier_block);
err = macvlan_link_register(&macvlan_link_ops);
if (err < 0)
goto err1;
return 0;
err1:
unregister_netdevice_notifier(&macvlan_notifier_block);
return err;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void die_codec(vpx_codec_ctx_t *ctx, const char *s) {
const char *detail = vpx_codec_error_detail(ctx);
printf("%s: %s\n", s, vpx_codec_error(ctx));
if(detail)
printf(" %s\n",detail);
exit(EXIT_FAILURE);
}
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 AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) {
DCHECK(message_loop()->BelongsToCurrentThread());
if (!stream_id_)
return;
if (state == AudioOutputIPCDelegate::kError) {
DLOG(WARNING) << "AudioOutputDevice::OnStateChanged(kError)";
base::AutoLock auto_lock_(audio_thread_lock_);
if (audio_thread_.get() && !audio_thread_->IsStopped())
callback_->OnRenderError();
}
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: ZSTD_CStream* ZSTD_createCStream(void)
{
DEBUGLOG(3, "ZSTD_createCStream");
return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
}
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 zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC)
{
zend_object_value new_obj_val;
zend_object *old_object;
zend_object *new_object;
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
spl_filesystem_object *intern;
spl_filesystem_object *source;
int index, skip_dots;
old_object = zend_objects_get_address(zobject TSRMLS_CC);
source = (spl_filesystem_object*)old_object;
new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC);
new_object = &intern->std;
intern->flags = source->flags;
switch (source->type) {
case SPL_FS_INFO:
intern->_path_len = source->_path_len;
intern->_path = estrndup(source->_path, source->_path_len);
intern->file_name_len = source->file_name_len;
intern->file_name = estrndup(source->file_name, intern->file_name_len);
break;
case SPL_FS_DIR:
spl_filesystem_dir_open(intern, source->_path TSRMLS_CC);
/* read until we hit the position in which we were before */
skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS);
for(index = 0; index < source->u.dir.index; ++index) {
do {
spl_filesystem_dir_read(intern TSRMLS_CC);
} while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name));
}
intern->u.dir.index = index;
break;
case SPL_FS_FILE:
php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name);
break;
}
intern->file_class = source->file_class;
intern->info_class = source->info_class;
intern->oth = source->oth;
intern->oth_handler = source->oth_handler;
zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC);
if (intern->oth_handler && intern->oth_handler->clone) {
intern->oth_handler->clone(source, intern TSRMLS_CC);
}
return new_obj_val;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: parse_asntime_into_isotime (unsigned char const **buf, size_t *len,
ksba_isotime_t isotime)
{
struct tag_info ti;
gpg_error_t err;
err = _ksba_ber_parse_tl (buf, len, &ti);
if (err)
;
else if ( !(ti.class == CLASS_UNIVERSAL
&& (ti.tag == TYPE_UTC_TIME || ti.tag == TYPE_GENERALIZED_TIME)
&& !ti.is_constructed) )
err = gpg_error (GPG_ERR_INV_OBJ);
else if (!(err = _ksba_asntime_to_iso (*buf, ti.length,
ti.tag == TYPE_UTC_TIME, isotime)))
parse_skip (buf, len, &ti);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: const GPUInfo& GpuDataManager::gpu_info() const {
base::AutoLock auto_lock(gpu_info_lock_);
return gpu_info_;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int x509_crt_check_parent( const mbedtls_x509_crt *child,
const mbedtls_x509_crt *parent,
int top, int bottom )
{
int need_ca_bit;
/* Parent must be the issuer */
if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
return( -1 );
/* Parent must have the basicConstraints CA bit set as a general rule */
need_ca_bit = 1;
/* Exception: v1/v2 certificates that are locally trusted. */
if( top && parent->version < 3 )
need_ca_bit = 0;
/* Exception: self-signed end-entity certs that are locally trusted. */
if( top && bottom &&
child->raw.len == parent->raw.len &&
memcmp( child->raw.p, parent->raw.p, child->raw.len ) == 0 )
{
need_ca_bit = 0;
}
if( need_ca_bit && ! parent->ca_istrue )
return( -1 );
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( need_ca_bit &&
mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
{
return( -1 );
}
#endif
return( 0 );
}
CWE ID: CWE-287
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
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_err("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-119
Target: 1
Example 2:
Code: bool ExternalProtocolDialog::Accept() {
UMA_HISTOGRAM_LONG_TIMES("clickjacking.launch_url",
base::TimeTicks::Now() - creation_time_);
const bool remember = remember_decision_checkbox_->checked();
ExternalProtocolHandler::RecordHandleStateMetrics(
remember, ExternalProtocolHandler::DONT_BLOCK);
delegate_->DoAccept(delegate_->url(), remember);
return true;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void NavigationControllerImpl::InsertEntriesFrom(
const NavigationControllerImpl& source,
int max_index) {
DCHECK_LE(max_index, source.GetEntryCount());
size_t insert_index = 0;
for (int i = 0; i < max_index; i++) {
if (source.entries_[i]->GetPageType() != PAGE_TYPE_INTERSTITIAL) {
entries_.insert(entries_.begin() + insert_index++,
source.entries_[i]->Clone());
}
}
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: jp2_box_t *jp2_box_get(jas_stream_t *in)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
jas_stream_t *tmpstream;
uint_fast32_t len;
uint_fast64_t extlen;
bool dataflag;
box = 0;
tmpstream = 0;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
goto error;
}
box->ops = &jp2_boxinfo_unk.ops;
if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) {
goto error;
}
boxinfo = jp2_boxinfolookup(box->type);
box->info = boxinfo;
box->len = len;
JAS_DBGLOG(10, (
"preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n",
'"', boxinfo->name, '"', box->type, box->len
));
if (box->len == 1) {
if (jp2_getuint64(in, &extlen)) {
goto error;
}
if (extlen > 0xffffffffUL) {
jas_eprintf("warning: cannot handle large 64-bit box length\n");
extlen = 0xffffffffUL;
}
box->len = extlen;
box->datalen = extlen - JP2_BOX_HDRLEN(true);
} else {
box->datalen = box->len - JP2_BOX_HDRLEN(false);
}
if (box->len != 0 && box->len < 8) {
goto error;
}
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (jas_stream_copy(tmpstream, in, box->datalen)) {
jas_eprintf("cannot copy box data\n");
goto error;
}
jas_stream_rewind(tmpstream);
box->ops = &boxinfo->ops;
if (box->ops->getdata) {
if ((*box->ops->getdata)(box, tmpstream)) {
jas_eprintf("cannot parse box data\n");
goto error;
}
}
jas_stream_close(tmpstream);
}
if (jas_getdbglevel() >= 1) {
jp2_box_dump(box, stderr);
}
return box;
error:
if (box) {
jp2_box_destroy(box);
}
if (tmpstream) {
jas_stream_close(tmpstream);
}
return 0;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: void OnPrintPreview(const DictionaryValue& dict) {
PrintWebViewHelper* print_web_view_helper = PrintWebViewHelper::Get(view_);
print_web_view_helper->OnInitiatePrintPreview();
print_web_view_helper->OnPrintPreview(dict);
}
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 xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb)
{
struct skb_shared_info *shinfo = skb_shinfo(skb);
int nr_frags = shinfo->nr_frags;
int i;
for (i = 0; i < nr_frags; i++) {
skb_frag_t *frag = shinfo->frags + i;
struct xen_netif_tx_request *txp;
struct page *page;
u16 pending_idx;
pending_idx = frag_get_pending_idx(frag);
txp = &netbk->pending_tx_info[pending_idx].req;
page = virt_to_page(idx_to_kaddr(netbk, pending_idx));
__skb_fill_page_desc(skb, i, page, txp->offset, txp->size);
skb->len += txp->size;
skb->data_len += txp->size;
skb->truesize += txp->size;
/* Take an extra reference to offset xen_netbk_idx_release */
get_page(netbk->mmap_pages[pending_idx]);
xen_netbk_idx_release(netbk, pending_idx);
}
}
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: CURLcode Curl_urldecode(struct SessionHandle *data,
const char *string, size_t length,
char **ostring, size_t *olen,
bool reject_ctrl)
{
size_t alloc = (length?length:strlen(string))+1;
char *ns = malloc(alloc);
unsigned char in;
size_t strindex=0;
unsigned long hex;
CURLcode res;
if(!ns)
return CURLE_OUT_OF_MEMORY;
while(--alloc > 0) {
in = *string;
if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
/* this is two hexadecimal digits following a '%' */
char hexstr[3];
char *ptr;
hexstr[0] = string[1];
hexstr[1] = string[2];
hexstr[2] = 0;
hex = strtoul(hexstr, &ptr, 16);
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
res = Curl_convert_from_network(data, &in, 1);
if(res) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return res;
}
string+=2;
alloc-=2;
}
if(reject_ctrl && (in < 0x20)) {
free(ns);
return CURLE_URL_MALFORMAT;
}
ns[strindex++] = in;
string++;
}
ns[strindex]=0; /* terminate it */
if(olen)
/* store output size */
*olen = strindex;
if(ostring)
/* store output string */
*ostring = ns;
return CURLE_OK;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int spl_object_storage_contains(spl_SplObjectStorage *intern, zval *this, zval *obj TSRMLS_DC) /* {{{ */
{
int hash_len, found;
char *hash = spl_object_storage_get_hash(intern, this, obj, &hash_len TSRMLS_CC);
if (!hash) {
return 0;
}
found = zend_hash_exists(&intern->storage, hash, hash_len);
spl_object_storage_free_hash(intern, hash);
return found;
} /* }}} */
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 RenderFrameImpl::SendFindReply(int request_id,
int match_count,
int ordinal,
const WebRect& selection_rect,
bool final_status_update) {
DCHECK_GE(ordinal, -1);
WebRect converted_rect = selection_rect;
GetRenderWidget()->ConvertViewportToWindow(&converted_rect);
Send(new FrameHostMsg_Find_Reply(routing_id_,
request_id,
match_count,
converted_rect,
ordinal,
final_status_update));
}
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: zend_op_array *compile_string(zval *source_string, char *filename TSRMLS_DC)
{
zend_lex_state original_lex_state;
zend_op_array *op_array = (zend_op_array *) emalloc(sizeof(zend_op_array));
zend_op_array *original_active_op_array = CG(active_op_array);
zend_op_array *retval;
zval tmp;
int compiler_result;
zend_bool original_in_compilation = CG(in_compilation);
if (source_string->value.str.len==0) {
efree(op_array);
return NULL;
}
CG(in_compilation) = 1;
tmp = *source_string;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
source_string = &tmp;
zend_save_lexical_state(&original_lex_state TSRMLS_CC);
if (zend_prepare_string_for_scanning(source_string, filename TSRMLS_CC)==FAILURE) {
efree(op_array);
retval = NULL;
} else {
zend_bool orig_interactive = CG(interactive);
CG(interactive) = 0;
init_op_array(op_array, ZEND_EVAL_CODE, INITIAL_OP_ARRAY_SIZE TSRMLS_CC);
CG(interactive) = orig_interactive;
CG(active_op_array) = op_array;
zend_stack_push(&CG(context_stack), (void *) &CG(context), sizeof(CG(context)));
zend_init_compiler_context(TSRMLS_C);
BEGIN(ST_IN_SCRIPTING);
compiler_result = zendparse(TSRMLS_C);
if (SCNG(script_filtered)) {
efree(SCNG(script_filtered));
SCNG(script_filtered) = NULL;
}
if (compiler_result==1) {
CG(active_op_array) = original_active_op_array;
CG(unclean_shutdown)=1;
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
retval = NULL;
} else {
zend_do_return(NULL, 0 TSRMLS_CC);
CG(active_op_array) = original_active_op_array;
pass_two(op_array TSRMLS_CC);
zend_release_labels(0 TSRMLS_CC);
retval = op_array;
}
}
zend_restore_lexical_state(&original_lex_state TSRMLS_CC);
zval_dtor(&tmp);
CG(in_compilation) = original_in_compilation;
return retval;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
int len, void *val)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
int r;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
r = __kvm_io_bus_read(vcpu, bus, &range, val);
return r < 0 ? r : 0;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void perf_event_print_debug(void)
{
u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
u64 pebs;
struct cpu_hw_events *cpuc;
unsigned long flags;
int cpu, idx;
if (!x86_pmu.num_counters)
return;
local_irq_save(flags);
cpu = smp_processor_id();
cpuc = &per_cpu(cpu_hw_events, cpu);
if (x86_pmu.version >= 2) {
rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
pr_info("\n");
pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
pr_info("CPU#%d: status: %016llx\n", cpu, status);
pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
}
pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
rdmsrl(x86_pmu_event_addr(idx), pmc_count);
prev_left = per_cpu(pmc_prev_left[idx], cpu);
pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
cpu, idx, pmc_ctrl);
pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
cpu, idx, pmc_count);
pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
cpu, idx, prev_left);
}
for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
cpu, idx, pmc_count);
}
local_irq_restore(flags);
}
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: php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zval ** fields,
unsigned int field_count, const MYSQLND_FIELD * fields_metadata,
zend_bool as_int_or_float, zend_bool copy_data, MYSQLND_STATS * stats TSRMLS_DC)
{
unsigned int i;
zend_bool last_field_was_string = FALSE;
zval **current_field, **end_field, **start_field;
zend_uchar * p = row_buffer->ptr;
size_t data_size = row_buffer->app;
zend_uchar * bit_area = (zend_uchar*) row_buffer->ptr + data_size + 1; /* we allocate from here */
DBG_ENTER("php_mysqlnd_rowp_read_text_protocol_aux");
if (!fields) {
DBG_RETURN(FAIL);
}
end_field = (start_field = fields) + field_count;
for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {
DBG_INF("Directly creating zval");
MAKE_STD_ZVAL(*current_field);
if (!*current_field) {
DBG_RETURN(FAIL);
}
}
for (i = 0, current_field = start_field; current_field < end_field; current_field++, i++) {
/* Don't reverse the order. It is significant!*/
zend_uchar *this_field_len_pos = p;
/* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */
unsigned long len = php_mysqlnd_net_field_length(&p);
if (copy_data == FALSE && current_field > start_field && last_field_was_string) {
/*
Normal queries:
We have to put \0 now to the end of the previous field, if it was
a string. IS_NULL doesn't matter. Because we have already read our
length, then we can overwrite it in the row buffer.
This statement terminates the previous field, not the current one.
NULL_LENGTH is encoded in one byte, so we can stick a \0 there.
Any string's length is encoded in at least one byte, so we can stick
a \0 there.
*/
*this_field_len_pos = '\0';
}
/* NULL or NOT NULL, this is the question! */
if (len == MYSQLND_NULL_LENGTH) {
ZVAL_NULL(*current_field);
last_field_was_string = FALSE;
} else {
#if defined(MYSQLND_STRING_TO_INT_CONVERSION)
struct st_mysqlnd_perm_bind perm_bind =
mysqlnd_ps_fetch_functions[fields_metadata[i].type];
#endif
if (MYSQLND_G(collect_statistics)) {
enum_mysqlnd_collected_stats statistic;
switch (fields_metadata[i].type) {
case MYSQL_TYPE_DECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;
case MYSQL_TYPE_TINY: statistic = STAT_TEXT_TYPE_FETCHED_INT8; break;
case MYSQL_TYPE_SHORT: statistic = STAT_TEXT_TYPE_FETCHED_INT16; break;
case MYSQL_TYPE_LONG: statistic = STAT_TEXT_TYPE_FETCHED_INT32; break;
case MYSQL_TYPE_FLOAT: statistic = STAT_TEXT_TYPE_FETCHED_FLOAT; break;
case MYSQL_TYPE_DOUBLE: statistic = STAT_TEXT_TYPE_FETCHED_DOUBLE; break;
case MYSQL_TYPE_NULL: statistic = STAT_TEXT_TYPE_FETCHED_NULL; break;
case MYSQL_TYPE_TIMESTAMP: statistic = STAT_TEXT_TYPE_FETCHED_TIMESTAMP; break;
case MYSQL_TYPE_LONGLONG: statistic = STAT_TEXT_TYPE_FETCHED_INT64; break;
case MYSQL_TYPE_INT24: statistic = STAT_TEXT_TYPE_FETCHED_INT24; break;
case MYSQL_TYPE_DATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break;
case MYSQL_TYPE_TIME: statistic = STAT_TEXT_TYPE_FETCHED_TIME; break;
case MYSQL_TYPE_DATETIME: statistic = STAT_TEXT_TYPE_FETCHED_DATETIME; break;
case MYSQL_TYPE_YEAR: statistic = STAT_TEXT_TYPE_FETCHED_YEAR; break;
case MYSQL_TYPE_NEWDATE: statistic = STAT_TEXT_TYPE_FETCHED_DATE; break;
case MYSQL_TYPE_VARCHAR: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break;
case MYSQL_TYPE_BIT: statistic = STAT_TEXT_TYPE_FETCHED_BIT; break;
case MYSQL_TYPE_NEWDECIMAL: statistic = STAT_TEXT_TYPE_FETCHED_DECIMAL; break;
case MYSQL_TYPE_ENUM: statistic = STAT_TEXT_TYPE_FETCHED_ENUM; break;
case MYSQL_TYPE_SET: statistic = STAT_TEXT_TYPE_FETCHED_SET; break;
case MYSQL_TYPE_JSON: statistic = STAT_TEXT_TYPE_FETCHED_JSON; break;
case MYSQL_TYPE_TINY_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;
case MYSQL_TYPE_MEDIUM_BLOB:statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;
case MYSQL_TYPE_LONG_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;
case MYSQL_TYPE_BLOB: statistic = STAT_TEXT_TYPE_FETCHED_BLOB; break;
case MYSQL_TYPE_VAR_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break;
case MYSQL_TYPE_STRING: statistic = STAT_TEXT_TYPE_FETCHED_STRING; break;
case MYSQL_TYPE_GEOMETRY: statistic = STAT_TEXT_TYPE_FETCHED_GEOMETRY; break;
default: statistic = STAT_TEXT_TYPE_FETCHED_OTHER; break;
}
MYSQLND_INC_CONN_STATISTIC_W_VALUE2(stats, statistic, 1, STAT_BYTES_RECEIVED_PURE_DATA_TEXT, len);
}
#ifdef MYSQLND_STRING_TO_INT_CONVERSION
if (as_int_or_float && perm_bind.php_type == IS_LONG) {
zend_uchar save = *(p + len);
/* We have to make it ASCIIZ temporarily */
*(p + len) = '\0';
if (perm_bind.pack_len < SIZEOF_LONG) {
/* direct conversion */
int64_t v =
#ifndef PHP_WIN32
atoll((char *) p);
#else
_atoi64((char *) p);
#endif
ZVAL_LONG(*current_field, (long) v); /* the cast is safe */
} else {
uint64_t v =
#ifndef PHP_WIN32
(uint64_t) atoll((char *) p);
#else
(uint64_t) _atoi64((char *) p);
#endif
zend_bool uns = fields_metadata[i].flags & UNSIGNED_FLAG? TRUE:FALSE;
/* We have to make it ASCIIZ temporarily */
#if SIZEOF_LONG==8
if (uns == TRUE && v > 9223372036854775807L)
#elif SIZEOF_LONG==4
if ((uns == TRUE && v > L64(2147483647)) ||
(uns == FALSE && (( L64(2147483647) < (int64_t) v) ||
(L64(-2147483648) > (int64_t) v))))
#else
#error Need fix for this architecture
#endif /* SIZEOF */
{
ZVAL_STRINGL(*current_field, (char *)p, len, 0);
} else {
ZVAL_LONG(*current_field, (long) v); /* the cast is safe */
}
}
*(p + len) = save;
} else if (as_int_or_float && perm_bind.php_type == IS_DOUBLE) {
zend_uchar save = *(p + len);
/* We have to make it ASCIIZ temporarily */
*(p + len) = '\0';
ZVAL_DOUBLE(*current_field, atof((char *) p));
*(p + len) = save;
} else
#endif /* MYSQLND_STRING_TO_INT_CONVERSION */
if (fields_metadata[i].type == MYSQL_TYPE_BIT) {
/*
BIT fields are specially handled. As they come as bit mask, we have
to convert it to human-readable representation. As the bits take
less space in the protocol than the numbers they represent, we don't
have enough space in the packet buffer to overwrite inside.
Thus, a bit more space is pre-allocated at the end of the buffer,
see php_mysqlnd_rowp_read(). And we add the strings at the end.
Definitely not nice, _hackish_ :(, but works.
*/
zend_uchar *start = bit_area;
ps_fetch_from_1_to_8_bytes(*current_field, &(fields_metadata[i]), 0, &p, len TSRMLS_CC);
/*
We have advanced in ps_fetch_from_1_to_8_bytes. We should go back because
later in this function there will be an advancement.
*/
p -= len;
if (Z_TYPE_PP(current_field) == IS_LONG) {
bit_area += 1 + sprintf((char *)start, "%ld", Z_LVAL_PP(current_field));
ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);
} else if (Z_TYPE_PP(current_field) == IS_STRING){
memcpy(bit_area, Z_STRVAL_PP(current_field), Z_STRLEN_PP(current_field));
bit_area += Z_STRLEN_PP(current_field);
*bit_area++ = '\0';
zval_dtor(*current_field);
ZVAL_STRINGL(*current_field, (char *) start, bit_area - start - 1, copy_data);
}
} else {
ZVAL_STRINGL(*current_field, (char *)p, len, copy_data);
}
p += len;
last_field_was_string = TRUE;
}
}
if (copy_data == FALSE && last_field_was_string) {
/* Normal queries: The buffer has one more byte at the end, because we need it */
row_buffer->ptr[data_size] = '\0';
}
DBG_RETURN(PASS);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int pt_removexattr(FsContext *ctx, const char *path, const char *name)
{
return local_removexattr_nofollow(ctx, path, name);
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SoundChannel* SoundPool::allocateChannel_l(int priority)
{
List<SoundChannel*>::iterator iter;
SoundChannel* channel = NULL;
if (!mChannels.empty()) {
iter = mChannels.begin();
if (priority >= (*iter)->priority()) {
channel = *iter;
mChannels.erase(iter);
ALOGV("Allocated active channel");
}
}
if (channel) {
channel->setPriority(priority);
for (iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
if (priority < (*iter)->priority()) {
break;
}
}
mChannels.insert(iter, channel);
}
return channel;
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool InitSkBitmapFromData(SkBitmap* bitmap,
const char* pixels,
size_t pixels_size) const {
if (!bitmap->tryAllocPixels(
SkImageInfo::Make(width, height, color_type, alpha_type)))
return false;
if (pixels_size != bitmap->computeByteSize())
return false;
memcpy(bitmap->getPixels(), pixels, pixels_size);
return true;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void set_task_comm(struct task_struct *tsk, char *buf)
{
task_lock(tsk);
trace_task_rename(tsk, buf);
/*
* Threads may access current->comm without holding
* the task lock, so write the string carefully.
* Readers without a lock may see incomplete new
* names but are safe from non-terminating string reads.
*/
memset(tsk->comm, 0, TASK_COMM_LEN);
wmb();
strlcpy(tsk->comm, buf, sizeof(tsk->comm));
task_unlock(tsk);
perf_event_comm(tsk);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_midi *midi = func_to_midi(f);
unsigned i;
int err;
/* we only set alt for MIDIStreaming interface */
if (intf != midi->ms_id)
return 0;
err = f_midi_start_ep(midi, f, midi->in_ep);
if (err)
return err;
err = f_midi_start_ep(midi, f, midi->out_ep);
if (err)
return err;
/* pre-allocate write usb requests to use on f_midi_transmit. */
while (kfifo_avail(&midi->in_req_fifo)) {
struct usb_request *req =
midi_alloc_ep_req(midi->in_ep, midi->buflen);
if (req == NULL)
return -ENOMEM;
req->length = 0;
req->complete = f_midi_complete;
kfifo_put(&midi->in_req_fifo, req);
}
/* allocate a bunch of read buffers and queue them all at once. */
for (i = 0; i < midi->qlen && err == 0; i++) {
struct usb_request *req =
midi_alloc_ep_req(midi->out_ep, midi->buflen);
if (req == NULL)
return -ENOMEM;
req->complete = f_midi_complete;
err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);
if (err) {
ERROR(midi, "%s: couldn't enqueue request: %d\n",
midi->out_ep->name, err);
free_ep_req(midi->out_ep, req);
return err;
}
}
return 0;
}
CWE ID: CWE-415
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void xfrm6_tunnel_spi_fini(void)
{
kmem_cache_destroy(xfrm6_tunnel_spi_kmem);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static LayoutObject* nearestCommonHoverAncestor(LayoutObject* obj1, LayoutObject* obj2)
{
if (!obj1 || !obj2)
return 0;
for (LayoutObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
for (LayoutObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
if (currObj1 == currObj2)
return currObj1;
}
}
return 0;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DiceResponseHandler::OnTokenExchangeSuccess(
DiceTokenFetcher* token_fetcher,
const std::string& refresh_token,
bool is_under_advanced_protection) {
const std::string& email = token_fetcher->email();
const std::string& gaia_id = token_fetcher->gaia_id();
if (!CanGetTokenForAccount(gaia_id, email))
return;
VLOG(1) << "[Dice] OAuth success for email " << email;
bool should_enable_sync = token_fetcher->should_enable_sync();
std::string account_id =
account_tracker_service_->SeedAccountInfo(gaia_id, email);
account_tracker_service_->SetIsAdvancedProtectionAccount(
account_id, is_under_advanced_protection);
token_service_->UpdateCredentials(account_id, refresh_token);
about_signin_internals_->OnRefreshTokenReceived(
base::StringPrintf("Successful (%s)", account_id.c_str()));
if (should_enable_sync)
token_fetcher->delegate()->EnableSync(account_id);
DeleteTokenFetcher(token_fetcher);
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int socket_accept(int fd, uint16_t port)
{
#ifdef WIN32
int addr_len;
#else
socklen_t addr_len;
#endif
int result;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
addr_len = sizeof(addr);
result = accept(fd, (struct sockaddr*)&addr, &addr_len);
return result;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: int dev_open(struct net_device *dev)
{
int ret;
if (dev->flags & IFF_UP)
return 0;
ret = __dev_open(dev);
if (ret < 0)
return ret;
rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
call_netdevice_notifiers(NETDEV_UP, dev);
return ret;
}
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: netdev_features_t passthru_features_check(struct sk_buff *skb,
struct net_device *dev,
netdev_features_t features)
{
return features;
}
CWE ID: CWE-400
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool CustomButton::AcceleratorPressed(const ui::Accelerator& accelerator) {
SetState(STATE_NORMAL);
ui::MouseEvent synthetic_event(
ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON);
NotifyClick(synthetic_event);
return true;
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: StyleResolver* Document::styleResolver() const
{
return m_styleEngine->resolver();
}
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: nlmsvc_unlock(struct net *net, struct nlm_file *file, struct nlm_lock *lock)
{
int error;
dprintk("lockd: nlmsvc_unlock(%s/%ld, pi=%d, %Ld-%Ld)\n",
file_inode(file->f_file)->i_sb->s_id,
file_inode(file->f_file)->i_ino,
lock->fl.fl_pid,
(long long)lock->fl.fl_start,
(long long)lock->fl.fl_end);
/* First, cancel any lock that might be there */
nlmsvc_cancel_blocked(net, file, lock);
lock->fl.fl_type = F_UNLCK;
error = vfs_lock_file(file->f_file, F_SETLK, &lock->fl, NULL);
return (error < 0)? nlm_lck_denied_nolocks : nlm_granted;
}
CWE ID: CWE-404
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool SyncManager::SyncInternal::Init(
const FilePath& database_location,
const WeakHandle<JsEventHandler>& event_handler,
const std::string& sync_server_and_path,
int port,
bool use_ssl,
const scoped_refptr<base::TaskRunner>& blocking_task_runner,
HttpPostProviderFactory* post_factory,
ModelSafeWorkerRegistrar* model_safe_worker_registrar,
browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor,
ChangeDelegate* change_delegate,
const std::string& user_agent,
const SyncCredentials& credentials,
bool enable_sync_tabs_for_other_clients,
sync_notifier::SyncNotifier* sync_notifier,
const std::string& restored_key_for_bootstrapping,
TestingMode testing_mode,
Encryptor* encryptor,
UnrecoverableErrorHandler* unrecoverable_error_handler,
ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
CHECK(!initialized_);
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << "Starting SyncInternal initialization.";
weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr());
blocking_task_runner_ = blocking_task_runner;
registrar_ = model_safe_worker_registrar;
change_delegate_ = change_delegate;
testing_mode_ = testing_mode;
enable_sync_tabs_for_other_clients_ = enable_sync_tabs_for_other_clients;
sync_notifier_.reset(sync_notifier);
AddObserver(&js_sync_manager_observer_);
SetJsEventHandler(event_handler);
AddObserver(&debug_info_event_listener_);
database_path_ = database_location.Append(
syncable::Directory::kSyncDatabaseFilename);
encryptor_ = encryptor;
unrecoverable_error_handler_ = unrecoverable_error_handler;
report_unrecoverable_error_function_ = report_unrecoverable_error_function;
share_.directory.reset(
new syncable::Directory(encryptor_,
unrecoverable_error_handler_,
report_unrecoverable_error_function_));
connection_manager_.reset(new SyncAPIServerConnectionManager(
sync_server_and_path, port, use_ssl, user_agent, post_factory));
net::NetworkChangeNotifier::AddIPAddressObserver(this);
observing_ip_address_changes_ = true;
connection_manager()->AddListener(this);
if (testing_mode_ == NON_TEST) {
DVLOG(1) << "Sync is bringing up SyncSessionContext.";
std::vector<SyncEngineEventListener*> listeners;
listeners.push_back(&allstatus_);
listeners.push_back(this);
SyncSessionContext* context = new SyncSessionContext(
connection_manager_.get(),
directory(),
model_safe_worker_registrar,
extensions_activity_monitor,
listeners,
&debug_info_event_listener_,
&traffic_recorder_);
context->set_account_name(credentials.email);
scheduler_.reset(new SyncScheduler(name_, context, new Syncer()));
}
bool signed_in = SignIn(credentials);
if (signed_in) {
if (scheduler()) {
scheduler()->Start(
browser_sync::SyncScheduler::CONFIGURATION_MODE, base::Closure());
}
initialized_ = true;
ReadTransaction trans(FROM_HERE, GetUserShare());
trans.GetCryptographer()->Bootstrap(restored_key_for_bootstrapping);
trans.GetCryptographer()->AddObserver(this);
}
FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
OnInitializationComplete(
MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
signed_in));
if (!signed_in && testing_mode_ == NON_TEST)
return false;
sync_notifier_->AddObserver(this);
return signed_in;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: OMX_ERRORTYPE omx_video::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex ;
DEBUG_PRINT_LOW("ETB: buffer = %p, buffer->pBuffer[%p]", buffer, buffer->pBuffer);
if (m_state != OMX_StateExecuting &&
m_state != OMX_StatePause &&
m_state != OMX_StateIdle) {
DEBUG_PRINT_ERROR("ERROR: Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL || (buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) {
DEBUG_PRINT_ERROR("ERROR: omx_video::etb--> buffer is null or buffer size is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) {
DEBUG_PRINT_ERROR("ERROR: omx_video::etb--> OMX Version Invalid");
return OMX_ErrorVersionMismatch;
}
if (buffer->nInputPortIndex != (OMX_U32)PORT_INDEX_IN) {
DEBUG_PRINT_ERROR("ERROR: Bad port index to call empty_this_buffer");
return OMX_ErrorBadPortIndex;
}
if (!m_sInPortDef.bEnabled) {
DEBUG_PRINT_ERROR("ERROR: Cannot call empty_this_buffer while I/P port is disabled");
return OMX_ErrorIncorrectStateOperation;
}
nBufferIndex = buffer - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr);
if (nBufferIndex > m_sInPortDef.nBufferCountActual ) {
DEBUG_PRINT_ERROR("ERROR: ETB: Invalid buffer index[%d]", nBufferIndex);
return OMX_ErrorBadParameter;
}
m_etb_count++;
DEBUG_PRINT_LOW("DBG: i/p nTimestamp = %u", (unsigned)buffer->nTimeStamp);
post_event ((unsigned long)hComp,(unsigned long)buffer,m_input_msg_id);
return OMX_ErrorNone;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags = mrb_obj_ptr(self)->flags;
return clone;
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int asepcos_parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf,
size_t len)
{
const u8 *p = buf;
while (len != 0) {
unsigned int amode, tlen = 3;
if (len < 5 && p[0] != 0x80 && p[1] != 0x01) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid access mode encoding");
return SC_ERROR_INTERNAL;
}
amode = p[2];
if (p[3] == 0x90 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NONE);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0x97 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NEVER);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0xA0 && len >= 4U + p[4]) {
/* TODO: support OR expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else if (p[3] == 0xAF && len >= 4U + p[4]) {
/* TODO: support AND expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid security condition");
return SC_ERROR_INTERNAL;
}
p += tlen;
len -= tlen;
}
return SC_SUCCESS;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void checkAppendMsg(
IntegrityCk *pCheck,
const char *zFormat,
...
){
va_list ap;
if( !pCheck->mxErr ) return;
pCheck->mxErr--;
pCheck->nErr++;
va_start(ap, zFormat);
if( pCheck->errMsg.nChar ){
sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
}
if( pCheck->zPfx ){
sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
}
sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
va_end(ap);
if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
pCheck->mallocFailed = 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: gsm_xsmp_client_connect (GsmXSMPClient *client,
SmsConn conn,
unsigned long *mask_ret,
SmsCallbacks *callbacks_ret)
{
client->priv->conn = conn;
if (client->priv->protocol_timeout) {
g_source_remove (client->priv->protocol_timeout);
client->priv->protocol_timeout = 0;
}
g_debug ("GsmXSMPClient: Initializing client %s", client->priv->description);
*mask_ret = 0;
*mask_ret |= SmsRegisterClientProcMask;
callbacks_ret->register_client.callback = register_client_callback;
callbacks_ret->register_client.manager_data = client;
*mask_ret |= SmsInteractRequestProcMask;
callbacks_ret->interact_request.callback = interact_request_callback;
callbacks_ret->interact_request.manager_data = client;
*mask_ret |= SmsInteractDoneProcMask;
callbacks_ret->interact_done.callback = interact_done_callback;
callbacks_ret->interact_done.manager_data = client;
*mask_ret |= SmsSaveYourselfRequestProcMask;
callbacks_ret->save_yourself_request.callback = save_yourself_request_callback;
callbacks_ret->save_yourself_request.manager_data = client;
*mask_ret |= SmsSaveYourselfP2RequestProcMask;
callbacks_ret->save_yourself_phase2_request.callback = save_yourself_phase2_request_callback;
callbacks_ret->save_yourself_phase2_request.manager_data = client;
*mask_ret |= SmsSaveYourselfDoneProcMask;
callbacks_ret->save_yourself_done.callback = save_yourself_done_callback;
callbacks_ret->save_yourself_done.manager_data = client;
*mask_ret |= SmsCloseConnectionProcMask;
callbacks_ret->close_connection.callback = close_connection_callback;
callbacks_ret->close_connection.manager_data = client;
*mask_ret |= SmsSetPropertiesProcMask;
callbacks_ret->set_properties.callback = set_properties_callback;
callbacks_ret->set_properties.manager_data = client;
*mask_ret |= SmsDeletePropertiesProcMask;
callbacks_ret->delete_properties.callback = delete_properties_callback;
callbacks_ret->delete_properties.manager_data = client;
*mask_ret |= SmsGetPropertiesProcMask;
callbacks_ret->get_properties.callback = get_properties_callback;
callbacks_ret->get_properties.manager_data = client;
}
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: NodeIterator::NodeIterator(PassRefPtrWillBeRawPtr<Node> rootNode, unsigned whatToShow, PassRefPtrWillBeRawPtr<NodeFilter> filter)
: NodeIteratorBase(rootNode, whatToShow, filter)
, m_referenceNode(root(), true)
{
root()->document().attachNodeIterator(this);
}
CWE ID:
Target: 1
Example 2:
Code: static int PNGSetExifProfile(Image *image,png_size_t size,png_byte *data,
ExceptionInfo *exception)
{
StringInfo
*profile;
unsigned char
*p;
png_byte
*s;
size_t
i;
profile=BlobToStringInfo((const void *) NULL,size+6);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
return(-1);
}
p=GetStringInfoDatum(profile);
/* Initialize profile with "Exif\0\0" */
*p++ ='E';
*p++ ='x';
*p++ ='i';
*p++ ='f';
*p++ ='\0';
*p++ ='\0';
s=data;
i=0;
if (size > 6)
{
/* Skip first 6 bytes if "Exif\0\0" is
already present by accident
*/
if (s[0] == 'E' && s[1] == 'x' && s[2] == 'i' &&
s[3] == 'f' && s[4] == '\0' && s[5] == '\0')
{
s+=6;
i=6;
SetStringInfoLength(profile,size);
p=GetStringInfoDatum(profile);
}
}
/* copy chunk->data to profile */
for (; i<size; i++)
*p++ = *s++;
(void) SetImageProfile(image,"exif",profile,exception);
profile=DestroyStringInfo(profile);
return(1);
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool HTMLFormControlElement::isAutofocusable() const
{
if (!fastHasAttribute(autofocusAttr))
return false;
if (hasTagName(inputTag))
return !toHTMLInputElement(this)->isInputTypeHidden();
if (hasTagName(selectTag))
return true;
if (hasTagName(keygenTag))
return true;
if (hasTagName(buttonTag))
return true;
if (hasTagName(textareaTag))
return true;
return false;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool GDataRootDirectory::ParseFromString(const std::string& serialized_proto) {
scoped_ptr<GDataRootDirectoryProto> proto(
new GDataRootDirectoryProto());
bool ok = proto->ParseFromString(serialized_proto);
if (ok) {
const std::string& title = proto->gdata_directory().gdata_entry().title();
if (title != "drive") {
LOG(ERROR) << "Incompatible proto detected: " << title;
return false;
}
FromProto(*proto.get());
set_origin(FROM_CACHE);
set_refresh_time(base::Time::Now());
}
return ok;
}
CWE ID:
Target: 1
Example 2:
Code: static bool can_checksum_protocol(unsigned long features, __be16 protocol)
{
return ((features & NETIF_F_GEN_CSUM) ||
((features & NETIF_F_IP_CSUM) &&
protocol == htons(ETH_P_IP)) ||
((features & NETIF_F_IPV6_CSUM) &&
protocol == htons(ETH_P_IPV6)) ||
((features & NETIF_F_FCOE_CRC) &&
protocol == htons(ETH_P_FCOE)));
}
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: safe_fprintf(FILE *f, const char *fmt, ...)
{
char fmtbuff_stack[256]; /* Place to format the printf() string. */
char outbuff[256]; /* Buffer for outgoing characters. */
char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */
int fmtbuff_length;
int length, n;
va_list ap;
const char *p;
unsigned i;
wchar_t wc;
char try_wc;
/* Use a stack-allocated buffer if we can, for speed and safety. */
fmtbuff_heap = NULL;
fmtbuff_length = sizeof(fmtbuff_stack);
fmtbuff = fmtbuff_stack;
/* Try formatting into the stack buffer. */
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
/* If the result was too large, allocate a buffer on the heap. */
while (length < 0 || length >= fmtbuff_length) {
if (length >= fmtbuff_length)
fmtbuff_length = length+1;
else if (fmtbuff_length < 8192)
fmtbuff_length *= 2;
else if (fmtbuff_length < 1000000)
fmtbuff_length += fmtbuff_length / 4;
else {
length = fmtbuff_length;
fmtbuff_heap[length-1] = '\0';
break;
}
free(fmtbuff_heap);
fmtbuff_heap = malloc(fmtbuff_length);
/* Reformat the result into the heap buffer if we can. */
if (fmtbuff_heap != NULL) {
fmtbuff = fmtbuff_heap;
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
} else {
/* Leave fmtbuff pointing to the truncated
* string in fmtbuff_stack. */
length = sizeof(fmtbuff_stack) - 1;
break;
}
}
/* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
* more portable, so we use that here instead. */
if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */
/* mbtowc() should never fail in practice, but
* handle the theoretical error anyway. */
free(fmtbuff_heap);
return;
}
/* Write data, expanding unprintable characters. */
p = fmtbuff;
i = 0;
try_wc = 1;
while (*p != '\0') {
/* Convert to wide char, test if the wide
* char is printable in the current locale. */
if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
length -= n;
if (iswprint(wc) && wc != L'\\') {
/* Printable, copy the bytes through. */
while (n-- > 0)
outbuff[i++] = *p++;
} else {
/* Not printable, format the bytes. */
while (n-- > 0)
i += (unsigned)bsdtar_expand_char(
outbuff, i, *p++);
}
} else {
/* After any conversion failure, don't bother
* trying to convert the rest. */
i += (unsigned)bsdtar_expand_char(outbuff, i, *p++);
try_wc = 0;
}
/* If our output buffer is full, dump it and keep going. */
if (i > (sizeof(outbuff) - 20)) {
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
i = 0;
}
}
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
/* If we allocated a heap-based formatting buffer, free it now. */
free(fmtbuff_heap);
}
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 inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return -ENOMEM;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum = 0;
}
err = skb_append_datato_frags(sk,skb, getfrag, from,
(length - transhdrlen));
if (!err) {
struct frag_hdr fhdr;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
__skb_queue_tail(&sk->sk_write_queue, skb);
return 0;
}
/* There is not enough support do UPD LSO,
* so follow normal path
*/
kfree_skb(skb);
return err;
}
CWE ID:
Target: 1
Example 2:
Code: static int __init ipc_init(void)
{
sem_init();
msg_init();
shm_init();
return 0;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebViewTestClient::DidFocus() {
test_runner()->SetFocus(web_view_test_proxy_base_->web_view(), true);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void iov_iter_pipe(struct iov_iter *i, int direction,
struct pipe_inode_info *pipe,
size_t count)
{
BUG_ON(direction != ITER_PIPE);
i->type = direction;
i->pipe = pipe;
i->idx = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
i->iov_offset = 0;
i->count = count;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: PasswordAutofillAgent::ExtractFormStructureInfo(const FormData& form_data) {
FormStructureInfo result;
result.unique_renderer_id = form_data.unique_renderer_id;
result.fields.resize(form_data.fields.size());
for (size_t i = 0; i < form_data.fields.size(); ++i) {
const FormFieldData& form_field = form_data.fields[i];
FormFieldInfo& field_info = result.fields[i];
field_info.unique_renderer_id = form_field.unique_renderer_id;
field_info.form_control_type = form_field.form_control_type;
field_info.autocomplete_attribute = form_field.autocomplete_attribute;
field_info.is_focusable = form_field.is_focusable;
}
return result;
}
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 __init idt_setup_early_handler(void)
{
int i;
for (i = 0; i < NUM_EXCEPTION_VECTORS; i++)
set_intr_gate(i, early_idt_handler_array[i]);
#ifdef CONFIG_X86_32
for ( ; i < NR_VECTORS; i++)
set_intr_gate(i, early_ignore_irq);
#endif
load_idt(&idt_descr);
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: 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)
{
size_t ss = CDF_SHORT_SEC_SIZE(h);
size_t pos = CDF_SHORT_SEC_POS(h, id);
assert(ss == len);
if (pos > CDF_SEC_SIZE(h) * sst->sst_len) {
DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %"
SIZE_T_FORMAT "u\n",
pos, CDF_SEC_SIZE(h) * sst->sst_len));
return -1;
}
(void)memcpy(((char *)buf) + offs,
((const char *)sst->sst_tab) + pos, len);
return len;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: handle_table_stats_request(struct ofconn *ofconn,
const struct ofp_header *request)
{
struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
struct ofputil_table_features *features;
struct ofputil_table_stats *stats;
struct ofpbuf *reply;
size_t i;
query_tables(ofproto, &features, &stats);
reply = ofputil_encode_table_stats_reply(request);
for (i = 0; i < ofproto->n_tables; i++) {
if (!(ofproto->tables[i].flags & OFTABLE_HIDDEN)) {
ofputil_append_table_stats_reply(reply, &stats[i], &features[i]);
}
}
ofconn_send_reply(ofconn, reply);
free(features);
free(stats);
return 0;
}
CWE ID: CWE-617
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct ewah_bitmap *lookup_stored_bitmap(struct stored_bitmap *st)
{
struct ewah_bitmap *parent;
struct ewah_bitmap *composed;
if (st->xor == NULL)
return st->root;
composed = ewah_pool_new();
parent = lookup_stored_bitmap(st->xor);
ewah_xor(st->root, parent, composed);
ewah_pool_free(st->root);
st->root = composed;
st->xor = NULL;
return composed;
}
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 cypress_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct cypress_private *priv = usb_get_serial_port_data(port);
struct usb_serial *serial = port->serial;
unsigned long flags;
int result = 0;
if (!priv->comm_is_ok)
return -EIO;
/* clear halts before open */
usb_clear_halt(serial->dev, 0x81);
usb_clear_halt(serial->dev, 0x02);
spin_lock_irqsave(&priv->lock, flags);
/* reset read/write statistics */
priv->bytes_in = 0;
priv->bytes_out = 0;
priv->cmd_count = 0;
priv->rx_flags = 0;
spin_unlock_irqrestore(&priv->lock, flags);
/* Set termios */
cypress_send(port);
if (tty)
cypress_set_termios(tty, port, &priv->tmp_termios);
/* setup the port and start reading from the device */
if (!port->interrupt_in_urb) {
dev_err(&port->dev, "%s - interrupt_in_urb is empty!\n",
__func__);
return -1;
}
usb_fill_int_urb(port->interrupt_in_urb, serial->dev,
usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress),
port->interrupt_in_urb->transfer_buffer,
port->interrupt_in_urb->transfer_buffer_length,
cypress_read_int_callback, port, priv->read_urb_interval);
result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
if (result) {
dev_err(&port->dev,
"%s - failed submitting read urb, error %d\n",
__func__, result);
cypress_set_dead(port);
}
return result;
} /* cypress_open */
CWE ID:
Target: 1
Example 2:
Code: partition_table_create_device_changed_cb (Daemon *daemon,
const char *object_path,
gpointer user_data)
{
CreatePartitionTableData *data = user_data;
Device *device;
device = daemon_local_find_by_object_path (daemon, object_path);
if (device == data->device)
{
if (g_strcmp0 (device->priv->partition_table_scheme, data->scheme) == 0 || (device->priv->partition_table_scheme
== NULL && g_strcmp0 (data->scheme, "none") == 0))
{
dbus_g_method_return (data->context);
g_signal_handler_disconnect (daemon, data->device_changed_signal_handler_id);
g_source_remove (data->device_changed_timeout_id);
partition_table_create_data_unref (data);
}
}
}
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 GraphicsContext::clipOut(const Path&)
{
notImplemented();
}
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: log2vis_unicode (PyObject * unicode, FriBidiParType base_direction, int clean, int reordernsm)
{
PyObject *logical = NULL; /* input string encoded in utf-8 */
PyObject *visual = NULL; /* output string encoded in utf-8 */
PyObject *result = NULL; /* unicode output string */
int length = PyUnicode_GET_SIZE (unicode);
logical = PyUnicode_AsUTF8String (unicode);
if (logical == NULL)
goto cleanup;
visual = log2vis_utf8 (logical, length, base_direction, clean, reordernsm);
if (visual == NULL)
goto cleanup;
result = PyUnicode_DecodeUTF8 (PyString_AS_STRING (visual),
PyString_GET_SIZE (visual), "strict");
cleanup:
Py_XDECREF (logical);
Py_XDECREF (visual);
return result;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void vmxnet3_rx_need_csum_calculate(struct NetRxPkt *pkt,
const void *pkt_data,
size_t pkt_len)
{
struct virtio_net_hdr *vhdr;
bool isip4, isip6, istcp, isudp;
uint8_t *data;
int len;
if (!net_rx_pkt_has_virt_hdr(pkt)) {
return;
}
vhdr = net_rx_pkt_get_vhdr(pkt);
if (!VMXNET_FLAG_IS_SET(vhdr->flags, VIRTIO_NET_HDR_F_NEEDS_CSUM)) {
return;
}
net_rx_pkt_get_protocols(pkt, &isip4, &isip6, &isudp, &istcp);
if (!(isip4 || isip6) || !(istcp || isudp)) {
return;
}
vmxnet3_dump_virt_hdr(vhdr);
/* Validate packet len: csum_start + scum_offset + length of csum field */
if (pkt_len < (vhdr->csum_start + vhdr->csum_offset + 2)) {
VMW_PKPRN("packet len:%zu < csum_start(%d) + csum_offset(%d) + 2, "
"cannot calculate checksum",
pkt_len, vhdr->csum_start, vhdr->csum_offset);
return;
}
data = (uint8_t *)pkt_data + vhdr->csum_start;
len = pkt_len - vhdr->csum_start;
/* Put the checksum obtained into the packet */
stw_be_p(data + vhdr->csum_offset, net_raw_checksum(data, len));
vhdr->flags &= ~VIRTIO_NET_HDR_F_NEEDS_CSUM;
vhdr->flags |= VIRTIO_NET_HDR_F_DATA_VALID;
}
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: get_table_width(struct table *t, short *orgwidth, short *cellwidth, int flag)
{
#ifdef __GNUC__
short newwidth[t->maxcol + 1];
#else /* not __GNUC__ */
short newwidth[MAXCOL];
#endif /* not __GNUC__ */
int i;
int swidth;
struct table_cell *cell = &t->cell;
int rulewidth = table_rule_width(t);
for (i = 0; i <= t->maxcol; i++)
newwidth[i] = max(orgwidth[i], 0);
if (flag & CHECK_FIXED) {
#ifdef __GNUC__
short ccellwidth[cell->maxcell + 1];
#else /* not __GNUC__ */
short ccellwidth[MAXCELL];
#endif /* not __GNUC__ */
for (i = 0; i <= t->maxcol; i++) {
if (newwidth[i] < t->fixed_width[i])
newwidth[i] = t->fixed_width[i];
}
for (i = 0; i <= cell->maxcell; i++) {
ccellwidth[i] = cellwidth[i];
if (ccellwidth[i] < cell->fixed_width[i])
ccellwidth[i] = cell->fixed_width[i];
}
check_cell_width(newwidth, ccellwidth, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
}
else {
check_cell_width(newwidth, cellwidth, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
}
if (flag & CHECK_MINIMUM)
check_minimum_width(t, newwidth);
swidth = 0;
for (i = 0; i <= t->maxcol; i++) {
swidth += ceil_at_intervals(newwidth[i], rulewidth);
}
swidth += table_border_width(t);
return swidth;
}
CWE ID: CWE-835
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool SyncManager::ReceivedExperiment(browser_sync::Experiments* experiments)
const {
ReadTransaction trans(FROM_HERE, GetUserShare());
ReadNode node(&trans);
if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) {
DVLOG(1) << "Couldn't find Nigori node.";
return false;
}
bool found_experiment = false;
if (node.GetNigoriSpecifics().sync_tabs()) {
experiments->sync_tabs = true;
found_experiment = true;
}
if (node.GetNigoriSpecifics().sync_tab_favicons()) {
experiments->sync_tab_favicons = true;
found_experiment = true;
}
return found_experiment;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int update_raid_disks(struct mddev *mddev, int raid_disks)
{
int rv;
struct md_rdev *rdev;
/* change the number of raid disks */
if (mddev->pers->check_reshape == NULL)
return -EINVAL;
if (mddev->ro)
return -EROFS;
if (raid_disks <= 0 ||
(mddev->max_disks && raid_disks >= mddev->max_disks))
return -EINVAL;
if (mddev->sync_thread ||
test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
mddev->reshape_position != MaxSector)
return -EBUSY;
rdev_for_each(rdev, mddev) {
if (mddev->raid_disks < raid_disks &&
rdev->data_offset < rdev->new_data_offset)
return -EINVAL;
if (mddev->raid_disks > raid_disks &&
rdev->data_offset > rdev->new_data_offset)
return -EINVAL;
}
mddev->delta_disks = raid_disks - mddev->raid_disks;
if (mddev->delta_disks < 0)
mddev->reshape_backwards = 1;
else if (mddev->delta_disks > 0)
mddev->reshape_backwards = 0;
rv = mddev->pers->check_reshape(mddev);
if (rv < 0) {
mddev->delta_disks = 0;
mddev->reshape_backwards = 0;
}
return rv;
}
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: status_t OMXNodeInstance::enableNativeBuffers(
OMX_U32 portIndex, OMX_BOOL graphic, OMX_BOOL enable) {
Mutex::Autolock autoLock(mLock);
CLOG_CONFIG(enableNativeBuffers, "%s:%u%s, %d", portString(portIndex), portIndex,
graphic ? ", graphic" : "", enable);
OMX_STRING name = const_cast<OMX_STRING>(
graphic ? "OMX.google.android.index.enableAndroidNativeBuffers"
: "OMX.google.android.index.allocateNativeHandle");
OMX_INDEXTYPE index;
OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index);
if (err == OMX_ErrorNone) {
EnableAndroidNativeBuffersParams params;
InitOMXParams(¶ms);
params.nPortIndex = portIndex;
params.enable = enable;
err = OMX_SetParameter(mHandle, index, ¶ms);
CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d", name, index,
portString(portIndex), portIndex, enable);
if (!graphic) {
if (err == OMX_ErrorNone) {
mSecureBufferType[portIndex] =
enable ? kSecureBufferTypeNativeHandle : kSecureBufferTypeOpaque;
} else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) {
mSecureBufferType[portIndex] = kSecureBufferTypeOpaque;
}
}
} else {
CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name);
if (!graphic) {
char value[PROPERTY_VALUE_MAX];
if (property_get("media.mediadrmservice.enable", value, NULL)
&& (!strcmp("1", value) || !strcasecmp("true", value))) {
CLOG_CONFIG(enableNativeBuffers, "system property override: using native-handles");
mSecureBufferType[portIndex] = kSecureBufferTypeNativeHandle;
} else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) {
mSecureBufferType[portIndex] = kSecureBufferTypeOpaque;
}
err = OMX_ErrorNone;
}
}
return StatusFromOMXError(err);
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int accept_server_socket(int sfd)
{
struct sockaddr_un remote;
struct pollfd pfd;
int fd;
socklen_t len = sizeof(struct sockaddr_un);
BTIF_TRACE_EVENT("accept fd %d", sfd);
/* make sure there is data to process */
pfd.fd = sfd;
pfd.events = POLLIN;
if (poll(&pfd, 1, 0) == 0)
{
BTIF_TRACE_EVENT("accept poll timeout");
return -1;
}
if ((fd = accept(sfd, (struct sockaddr *)&remote, &len)) == -1)
{
BTIF_TRACE_ERROR("sock accept failed (%s)", strerror(errno));
return -1;
}
return fd;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: read_fatal (void)
{
pfatal ("read error");
}
CWE ID: CWE-22
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DevToolsUIBindings::SetDevicesUpdatesEnabled(bool enabled) {
if (devices_updates_enabled_ == enabled)
return;
devices_updates_enabled_ = enabled;
if (enabled) {
remote_targets_handler_ = DevToolsTargetsUIHandler::CreateForAdb(
base::Bind(&DevToolsUIBindings::DevicesUpdated,
base::Unretained(this)),
profile_);
pref_change_registrar_.Init(profile_->GetPrefs());
pref_change_registrar_.Add(prefs::kDevToolsDiscoverUsbDevicesEnabled,
base::Bind(&DevToolsUIBindings::DevicesDiscoveryConfigUpdated,
base::Unretained(this)));
pref_change_registrar_.Add(prefs::kDevToolsPortForwardingEnabled,
base::Bind(&DevToolsUIBindings::DevicesDiscoveryConfigUpdated,
base::Unretained(this)));
pref_change_registrar_.Add(prefs::kDevToolsPortForwardingConfig,
base::Bind(&DevToolsUIBindings::DevicesDiscoveryConfigUpdated,
base::Unretained(this)));
port_status_serializer_.reset(new PortForwardingStatusSerializer(
base::Bind(&DevToolsUIBindings::SendPortForwardingStatus,
base::Unretained(this)),
profile_));
DevicesDiscoveryConfigUpdated();
} else {
remote_targets_handler_.reset();
port_status_serializer_.reset();
pref_change_registrar_.RemoveAll();
SendPortForwardingStatus(base::DictionaryValue());
}
}
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: int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
{
int r;
/* Assume we're using HV mode when the HV module is loaded */
int hv_enabled = kvmppc_hv_ops ? 1 : 0;
if (kvm) {
/*
* Hooray - we know which VM type we're running on. Depend on
* that rather than the guess above.
*/
hv_enabled = is_kvmppc_hv_enabled(kvm);
}
switch (ext) {
#ifdef CONFIG_BOOKE
case KVM_CAP_PPC_BOOKE_SREGS:
case KVM_CAP_PPC_BOOKE_WATCHDOG:
case KVM_CAP_PPC_EPR:
#else
case KVM_CAP_PPC_SEGSTATE:
case KVM_CAP_PPC_HIOR:
case KVM_CAP_PPC_PAPR:
#endif
case KVM_CAP_PPC_UNSET_IRQ:
case KVM_CAP_PPC_IRQ_LEVEL:
case KVM_CAP_ENABLE_CAP:
case KVM_CAP_ENABLE_CAP_VM:
case KVM_CAP_ONE_REG:
case KVM_CAP_IOEVENTFD:
case KVM_CAP_DEVICE_CTRL:
case KVM_CAP_IMMEDIATE_EXIT:
r = 1;
break;
case KVM_CAP_PPC_PAIRED_SINGLES:
case KVM_CAP_PPC_OSI:
case KVM_CAP_PPC_GET_PVINFO:
#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC)
case KVM_CAP_SW_TLB:
#endif
/* We support this only for PR */
r = !hv_enabled;
break;
#ifdef CONFIG_KVM_MPIC
case KVM_CAP_IRQ_MPIC:
r = 1;
break;
#endif
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_CAP_SPAPR_TCE:
case KVM_CAP_SPAPR_TCE_64:
/* fallthrough */
case KVM_CAP_SPAPR_TCE_VFIO:
case KVM_CAP_PPC_RTAS:
case KVM_CAP_PPC_FIXUP_HCALL:
case KVM_CAP_PPC_ENABLE_HCALL:
#ifdef CONFIG_KVM_XICS
case KVM_CAP_IRQ_XICS:
#endif
r = 1;
break;
case KVM_CAP_PPC_ALLOC_HTAB:
r = hv_enabled;
break;
#endif /* CONFIG_PPC_BOOK3S_64 */
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_SMT:
r = 0;
if (kvm) {
if (kvm->arch.emul_smt_mode > 1)
r = kvm->arch.emul_smt_mode;
else
r = kvm->arch.smt_mode;
} else if (hv_enabled) {
if (cpu_has_feature(CPU_FTR_ARCH_300))
r = 1;
else
r = threads_per_subcore;
}
break;
case KVM_CAP_PPC_SMT_POSSIBLE:
r = 1;
if (hv_enabled) {
if (!cpu_has_feature(CPU_FTR_ARCH_300))
r = ((threads_per_subcore << 1) - 1);
else
/* P9 can emulate dbells, so allow any mode */
r = 8 | 4 | 2 | 1;
}
break;
case KVM_CAP_PPC_RMA:
r = 0;
break;
case KVM_CAP_PPC_HWRNG:
r = kvmppc_hwrng_present();
break;
case KVM_CAP_PPC_MMU_RADIX:
r = !!(hv_enabled && radix_enabled());
break;
case KVM_CAP_PPC_MMU_HASH_V3:
r = !!(hv_enabled && !radix_enabled() &&
cpu_has_feature(CPU_FTR_ARCH_300));
break;
#endif
case KVM_CAP_SYNC_MMU:
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
r = hv_enabled;
#elif defined(KVM_ARCH_WANT_MMU_NOTIFIER)
r = 1;
#else
r = 0;
#endif
break;
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_HTAB_FD:
r = hv_enabled;
break;
#endif
case KVM_CAP_NR_VCPUS:
/*
* Recommending a number of CPUs is somewhat arbitrary; we
* return the number of present CPUs for -HV (since a host
* will have secondary threads "offline"), and for other KVM
* implementations just count online CPUs.
*/
if (hv_enabled)
r = num_present_cpus();
else
r = num_online_cpus();
break;
case KVM_CAP_NR_MEMSLOTS:
r = KVM_USER_MEM_SLOTS;
break;
case KVM_CAP_MAX_VCPUS:
r = KVM_MAX_VCPUS;
break;
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_CAP_PPC_GET_SMMU_INFO:
r = 1;
break;
case KVM_CAP_SPAPR_MULTITCE:
r = 1;
break;
case KVM_CAP_SPAPR_RESIZE_HPT:
/* Disable this on POWER9 until code handles new HPTE format */
r = !!hv_enabled && !cpu_has_feature(CPU_FTR_ARCH_300);
break;
#endif
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_FWNMI:
r = hv_enabled;
break;
#endif
case KVM_CAP_PPC_HTM:
r = cpu_has_feature(CPU_FTR_TM_COMP) &&
is_kvmppc_hv_enabled(kvm);
break;
default:
r = 0;
break;
}
return r;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void parser_reset(struct jv_parser* p) {
if ((p->flags & JV_PARSE_STREAMING)) {
jv_free(p->path);
p->path = jv_array();
p->stacklen = 0;
}
p->last_seen = JV_LAST_NONE;
jv_free(p->output);
p->output = jv_invalid();
jv_free(p->next);
p->next = jv_invalid();
for (int i=0; i<p->stackpos; i++)
jv_free(p->stack[i]);
p->stackpos = 0;
p->tokenpos = 0;
p->st = JV_PARSER_NORMAL;
}
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: XFixesSelectCursorInput(ClientPtr pClient, WindowPtr pWindow, CARD32 eventMask)
{
CursorEventPtr *prev, e;
void *val;
int rc;
for (prev = &cursorEvents; (e = *prev); prev = &e->next) {
if (e->pClient == pClient && e->pWindow == pWindow) {
break;
}
}
if (!eventMask) {
if (e) {
FreeResource(e->clientResource, 0);
}
return Success;
}
if (!e) {
e = (CursorEventPtr) malloc(sizeof(CursorEventRec));
if (!e)
return BadAlloc;
e->next = 0;
e->pClient = pClient;
e->pWindow = pWindow;
e->clientResource = FakeClientID(pClient->index);
/*
* Add a resource hanging from the window to
* catch window destroy
*/
rc = dixLookupResourceByType(&val, pWindow->drawable.id,
CursorWindowType, serverClient,
DixGetAttrAccess);
if (rc != Success)
if (!AddResource(pWindow->drawable.id, CursorWindowType,
(void *) pWindow)) {
free(e);
return BadAlloc;
}
if (!AddResource(e->clientResource, CursorClientType, (void *) e))
return BadAlloc;
*prev = e;
}
e->eventMask = eventMask;
return Success;
}
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: PrintingContextCairo::PrintingContextCairo(const std::string& app_locale)
#if defined(OS_CHROMEOS)
: PrintingContext(app_locale) {
#else
: PrintingContext(app_locale),
print_dialog_(NULL) {
#endif
}
PrintingContextCairo::~PrintingContextCairo() {
ReleaseContext();
#if !defined(OS_CHROMEOS)
if (print_dialog_)
print_dialog_->ReleaseDialog();
#endif
}
#if !defined(OS_CHROMEOS)
void PrintingContextCairo::SetCreatePrintDialogFunction(
PrintDialogGtkInterface* (*create_dialog_func)(
PrintingContextCairo* context)) {
DCHECK(create_dialog_func);
DCHECK(!create_dialog_func_);
create_dialog_func_ = create_dialog_func;
}
void PrintingContextCairo::PrintDocument(const Metafile* metafile) {
DCHECK(print_dialog_);
DCHECK(metafile);
print_dialog_->PrintDocument(metafile, document_name_);
}
#endif // !defined(OS_CHROMEOS)
void PrintingContextCairo::AskUserForSettings(
gfx::NativeView parent_view,
int max_pages,
bool has_selection,
PrintSettingsCallback* callback) {
#if defined(OS_CHROMEOS)
callback->Run(OK);
#else
print_dialog_->ShowDialog(callback);
#endif // defined(OS_CHROMEOS)
}
PrintingContext::Result PrintingContextCairo::UseDefaultSettings() {
DCHECK(!in_print_job_);
ResetSettings();
#if defined(OS_CHROMEOS)
int dpi = 300;
gfx::Size physical_size_device_units;
gfx::Rect printable_area_device_units;
int32_t width = 0;
int32_t height = 0;
UErrorCode error = U_ZERO_ERROR;
ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);
if (error != U_ZERO_ERROR) {
LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: "
<< error;
width = static_cast<int>(8.5 * dpi);
height = static_cast<int>(11 * dpi);
} else {
width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi);
height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi);
}
physical_size_device_units.SetSize(width, height);
printable_area_device_units.SetRect(
static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),
static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),
width - (PrintSettingsInitializerGtk::kLeftMarginInInch +
PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,
height - (PrintSettingsInitializerGtk::kTopMarginInInch +
PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);
settings_.set_dpi(dpi);
settings_.SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
#else
if (!print_dialog_) {
print_dialog_ = create_dialog_func_(this);
print_dialog_->AddRefToDialog();
}
print_dialog_->UseDefaultSettings();
#endif // defined(OS_CHROMEOS)
return OK;
}
PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings(
const DictionaryValue& job_settings, const PageRanges& ranges) {
#if defined(OS_CHROMEOS)
bool landscape = false;
if (!job_settings.GetBoolean(kSettingLandscape, &landscape))
return OnError();
settings_.SetOrientation(landscape);
settings_.ranges = ranges;
return OK;
#else
DCHECK(!in_print_job_);
if (!print_dialog_->UpdateSettings(job_settings, ranges))
return OnError();
return OK;
#endif
}
PrintingContext::Result PrintingContextCairo::InitWithSettings(
const PrintSettings& settings) {
DCHECK(!in_print_job_);
settings_ = settings;
return OK;
}
PrintingContext::Result PrintingContextCairo::NewDocument(
const string16& document_name) {
DCHECK(!in_print_job_);
in_print_job_ = true;
#if !defined(OS_CHROMEOS)
document_name_ = document_name;
#endif // !defined(OS_CHROMEOS)
return OK;
}
PrintingContext::Result PrintingContextCairo::NewPage() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
return OK;
}
PrintingContext::Result PrintingContextCairo::PageDone() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
return OK;
}
PrintingContext::Result PrintingContextCairo::DocumentDone() {
if (abort_printing_)
return CANCEL;
DCHECK(in_print_job_);
ResetSettings();
return OK;
}
void PrintingContextCairo::Cancel() {
abort_printing_ = true;
in_print_job_ = false;
}
void PrintingContextCairo::ReleaseContext() {
}
gfx::NativeDrawingContext PrintingContextCairo::context() const {
return NULL;
}
} // namespace printing
CWE ID: CWE-399
Target: 1
Example 2:
Code: mm_sshpam_query(void *ctx, char **name, char **info,
u_int *num, char ***prompts, u_int **echo_on)
{
Buffer m;
u_int i;
int ret;
debug3("%s", __func__);
buffer_init(&m);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_QUERY, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_QUERY", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_QUERY, &m);
ret = buffer_get_int(&m);
debug3("%s: pam_query returned %d", __func__, ret);
*name = buffer_get_string(&m, NULL);
*info = buffer_get_string(&m, NULL);
*num = buffer_get_int(&m);
if (*num > PAM_MAX_NUM_MSG)
fatal("%s: recieved %u PAM messages, expected <= %u",
__func__, *num, PAM_MAX_NUM_MSG);
*prompts = xcalloc((*num + 1), sizeof(char *));
*echo_on = xcalloc((*num + 1), sizeof(u_int));
for (i = 0; i < *num; ++i) {
(*prompts)[i] = buffer_get_string(&m, NULL);
(*echo_on)[i] = buffer_get_int(&m);
}
buffer_free(&m);
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: PHP_FUNCTION(imagetypes)
{
int ret=0;
#ifdef HAVE_GD_GIF_CREATE
ret = 1;
#endif
#ifdef HAVE_GD_JPG
ret |= 2;
#endif
#ifdef HAVE_GD_PNG
ret |= 4;
#endif
#ifdef HAVE_GD_WBMP
ret |= 8;
#endif
#if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED)
ret |= 16;
#endif
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(ret);
}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const Cluster* Segment::GetNext(const Cluster* pCurr) {
assert(pCurr);
assert(pCurr != &m_eos);
assert(m_clusters);
long idx = pCurr->m_index;
if (idx >= 0) {
assert(m_clusterCount > 0);
assert(idx < m_clusterCount);
assert(pCurr == m_clusters[idx]);
++idx;
if (idx >= m_clusterCount)
return &m_eos; // caller will LoadCluster as desired
Cluster* const pNext = m_clusters[idx];
assert(pNext);
assert(pNext->m_index >= 0);
assert(pNext->m_index == idx);
return pNext;
}
assert(m_clusterPreloadCount > 0);
long long pos = pCurr->m_element_start;
assert(m_size >= 0); // TODO
const long long stop = m_start + m_size; // end of segment
{
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); // TODO
if (result != 0)
return NULL;
const long long id = ReadUInt(m_pReader, pos, len);
assert(id == 0x0F43B675); // Cluster ID
if (id != 0x0F43B675)
return NULL;
pos += len; // consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); // TODO
assert((pos + len) <= stop); // TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size > 0); // TODO
pos += len; // consume length of size of element
assert((pos + size) <= stop); // TODO
pos += size; // consume payload
}
long long off_next = 0;
while (pos < stop) {
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); // TODO
if (result != 0)
return NULL;
const long long idpos = pos; // pos of next (potential) cluster
const long long id = ReadUInt(m_pReader, idpos, len);
assert(id > 0); // TODO
pos += len; // consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); // TODO
assert((pos + len) <= stop); // TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size >= 0); // TODO
pos += len; // consume length of size of element
assert((pos + size) <= stop); // TODO
if (size == 0) // weird
continue;
if (id == 0x0F43B675) { // Cluster ID
const long long off_next_ = idpos - m_start;
long long pos_;
long len_;
const long status = Cluster::HasBlockEntries(this, off_next_, pos_, len_);
assert(status >= 0);
if (status > 0) {
off_next = off_next_;
break;
}
}
pos += size; // consume payload
}
if (off_next <= 0)
return 0;
Cluster** const ii = m_clusters + m_clusterCount;
Cluster** i = ii;
Cluster** const jj = ii + m_clusterPreloadCount;
Cluster** j = jj;
while (i < j) {
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pNext = *k;
assert(pNext);
assert(pNext->m_index < 0);
pos = pNext->GetPosition();
if (pos < off_next)
i = k + 1;
else if (pos > off_next)
j = k;
else
return pNext;
}
assert(i == j);
Cluster* const pNext = Cluster::Create(this, -1, off_next);
assert(pNext);
const ptrdiff_t idx_next = i - m_clusters; // insertion position
PreloadCluster(pNext, idx_next);
assert(m_clusters);
assert(idx_next < m_clusterSize);
assert(m_clusters[idx_next] == pNext);
return pNext;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static ssize_t shrink_store(struct kmem_cache *s,
const char *buf, size_t length)
{
if (buf[0] == '1') {
int rc = kmem_cache_shrink(s);
if (rc)
return rc;
} else
return -EINVAL;
return length;
}
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 SecureProxyChecker::OnURLLoadComplete(
std::unique_ptr<std::string> response_body) {
std::string response;
if (response_body)
response = std::move(*response_body);
int response_code = -1;
if (url_loader_->ResponseInfo() && url_loader_->ResponseInfo()->headers)
response_code = url_loader_->ResponseInfo()->headers->response_code();
OnURLLoadCompleteOrRedirect(response, url_loader_->NetError(), response_code);
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void jp2_box_dump(jp2_box_t *box, FILE *out)
{
jp2_boxinfo_t *boxinfo;
boxinfo = jp2_boxinfolookup(box->type);
assert(boxinfo);
fprintf(out, "JP2 box: ");
fprintf(out, "type=%c%s%c (0x%08"PRIxFAST32"); length=%"PRIuFAST32"\n", '"', boxinfo->name,
'"', box->type, box->len);
if (box->ops->dumpdata) {
(*box->ops->dumpdata)(box, out);
}
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: void espruino_snprintf_cb(const char *str, void *userdata) {
espruino_snprintf_data *d = (espruino_snprintf_data*)userdata;
while (*str) {
if (d->idx < d->len) d->outPtr[d->idx] = *str;
d->idx++;
str++;
}
}
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: ft_var_apply_tuple( GX_Blend blend,
FT_UShort tupleIndex,
FT_Fixed* tuple_coords,
FT_Fixed* im_start_coords,
FT_Fixed* im_end_coords )
{
FT_UInt i;
FT_Fixed apply;
FT_Fixed temp;
apply = 0x10000L;
for ( i = 0; i < blend->num_axis; ++i )
{
if ( tuple_coords[i] == 0 )
/* It's not clear why (for intermediate tuples) we don't need */
/* to check against start/end -- the documentation says we don't. */
/* Similarly, it's unclear why we don't need to scale along the */
/* axis. */
continue;
else if ( blend->normalizedcoords[i] == 0 ||
( blend->normalizedcoords[i] < 0 && tuple_coords[i] > 0 ) ||
( blend->normalizedcoords[i] > 0 && tuple_coords[i] < 0 ) )
{
apply = 0;
break;
}
else if ( !( tupleIndex & GX_TI_INTERMEDIATE_TUPLE ) )
/* not an intermediate tuple */
apply = FT_MulDiv( apply,
blend->normalizedcoords[i] > 0
? blend->normalizedcoords[i]
: -blend->normalizedcoords[i],
0x10000L );
else if ( blend->normalizedcoords[i] <= im_start_coords[i] ||
blend->normalizedcoords[i] >= im_end_coords[i] )
{
apply = 0;
break;
}
else if ( blend->normalizedcoords[i] < tuple_coords[i] )
{
temp = FT_MulDiv( blend->normalizedcoords[i] - im_start_coords[i],
0x10000L,
tuple_coords[i] - im_start_coords[i]);
apply = FT_MulDiv( apply, temp, 0x10000L );
}
else
{
temp = FT_MulDiv( im_end_coords[i] - blend->normalizedcoords[i],
0x10000L,
im_end_coords[i] - tuple_coords[i] );
apply = FT_MulDiv( apply, temp, 0x10000L );
}
}
return apply;
}
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 bdt_enable(void)
{
bdt_log("ENABLE BT");
if (bt_enabled) {
bdt_log("Bluetooth is already enabled");
return;
}
status = sBtInterface->enable();
check_return_status(status);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int mailimf_broken_date_parse(const char * message, size_t length,
size_t * indx,
int * pday, int * pmonth, int * pyear)
{
size_t cur_token;
int day;
int month;
int year;
int r;
cur_token = * indx;
month = 1;
r = mailimf_month_parse(message, length, &cur_token, &month);
if (r != MAILIMF_NO_ERROR)
return r;
day = 1;
r = mailimf_day_parse(message, length, &cur_token, &day);
if (r != MAILIMF_NO_ERROR)
return r;
year = 2001;
r = mailimf_year_parse(message, length, &cur_token, &year);
if (r != MAILIMF_NO_ERROR)
return r;
* pday = day;
* pmonth = month;
* pyear = year;
* indx = cur_token;
return MAILIMF_NO_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: SERVER* dup_serve(const SERVER *const s) {
SERVER *serve = NULL;
serve=g_new0(SERVER, 1);
if(serve == NULL)
return NULL;
if(s->exportname)
serve->exportname = g_strdup(s->exportname);
serve->expected_size = s->expected_size;
if(s->listenaddr)
serve->listenaddr = g_strdup(s->listenaddr);
serve->port = s->port;
if(s->authname)
serve->authname = strdup(s->authname);
serve->flags = s->flags;
serve->socket = s->socket;
serve->socket_family = s->socket_family;
serve->virtstyle = s->virtstyle;
serve->cidrlen = s->cidrlen;
if(s->prerun)
serve->prerun = g_strdup(s->prerun);
if(s->postrun)
serve->postrun = g_strdup(s->postrun);
if(s->transactionlog)
serve->transactionlog = g_strdup(s->transactionlog);
if(s->servename)
serve->servename = g_strdup(s->servename);
serve->max_connections = s->max_connections;
return serve;
}
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: ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt,
int newtype,
struct ipv6_opt_hdr __user *newopt, int newoptlen)
{
int tot_len = 0;
char *p;
struct ipv6_txoptions *opt2;
int err;
if (opt) {
if (newtype != IPV6_HOPOPTS && opt->hopopt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->hopopt));
if (newtype != IPV6_RTHDRDSTOPTS && opt->dst0opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst0opt));
if (newtype != IPV6_RTHDR && opt->srcrt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->srcrt));
if (newtype != IPV6_DSTOPTS && opt->dst1opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst1opt));
}
if (newopt && newoptlen)
tot_len += CMSG_ALIGN(newoptlen);
if (!tot_len)
return NULL;
tot_len += sizeof(*opt2);
opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC);
if (!opt2)
return ERR_PTR(-ENOBUFS);
memset(opt2, 0, tot_len);
opt2->tot_len = tot_len;
p = (char *)(opt2 + 1);
err = ipv6_renew_option(opt ? opt->hopopt : NULL, newopt, newoptlen,
newtype != IPV6_HOPOPTS,
&opt2->hopopt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->dst0opt : NULL, newopt, newoptlen,
newtype != IPV6_RTHDRDSTOPTS,
&opt2->dst0opt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->srcrt : NULL, newopt, newoptlen,
newtype != IPV6_RTHDR,
(struct ipv6_opt_hdr **)&opt2->srcrt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->dst1opt : NULL, newopt, newoptlen,
newtype != IPV6_DSTOPTS,
&opt2->dst1opt, &p);
if (err)
goto out;
opt2->opt_nflen = (opt2->hopopt ? ipv6_optlen(opt2->hopopt) : 0) +
(opt2->dst0opt ? ipv6_optlen(opt2->dst0opt) : 0) +
(opt2->srcrt ? ipv6_optlen(opt2->srcrt) : 0);
opt2->opt_flen = (opt2->dst1opt ? ipv6_optlen(opt2->dst1opt) : 0);
return opt2;
out:
sock_kfree_s(sk, opt2, opt2->tot_len);
return ERR_PTR(err);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void oz_usb_farewell(struct oz_pd *pd, u8 ep_num, u8 *data, u8 len)
{
struct oz_usb_ctx *usb_ctx;
spin_lock_bh(&pd->app_lock[OZ_APPID_USB]);
usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB];
if (usb_ctx)
oz_usb_get(usb_ctx);
spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]);
if (usb_ctx == NULL)
return; /* Context has gone so nothing to do. */
if (!usb_ctx->stopped) {
oz_dbg(ON, "Farewell indicated ep = 0x%x\n", ep_num);
oz_hcd_data_ind(usb_ctx->hport, ep_num, data, len);
}
oz_usb_put(usb_ctx);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int fill_thread_core_info(struct elf_thread_core_info *t,
const struct user_regset_view *view,
long signr, size_t *total)
{
unsigned int i;
/*
* NT_PRSTATUS is the one special case, because the regset data
* goes into the pr_reg field inside the note contents, rather
* than being the whole note contents. We fill the reset in here.
* We assume that regset 0 is NT_PRSTATUS.
*/
fill_prstatus(&t->prstatus, t->task, signr);
(void) view->regsets[0].get(t->task, &view->regsets[0],
0, sizeof(t->prstatus.pr_reg),
&t->prstatus.pr_reg, NULL);
fill_note(&t->notes[0], "CORE", NT_PRSTATUS,
sizeof(t->prstatus), &t->prstatus);
*total += notesize(&t->notes[0]);
do_thread_regset_writeback(t->task, &view->regsets[0]);
/*
* Each other regset might generate a note too. For each regset
* that has no core_note_type or is inactive, we leave t->notes[i]
* all zero and we'll know to skip writing it later.
*/
for (i = 1; i < view->n; ++i) {
const struct user_regset *regset = &view->regsets[i];
do_thread_regset_writeback(t->task, regset);
if (regset->core_note_type &&
(!regset->active || regset->active(t->task, regset))) {
int ret;
size_t size = regset->n * regset->size;
void *data = kmalloc(size, GFP_KERNEL);
if (unlikely(!data))
return 0;
ret = regset->get(t->task, regset,
0, size, data, NULL);
if (unlikely(ret))
kfree(data);
else {
if (regset->core_note_type != NT_PRFPREG)
fill_note(&t->notes[i], "LINUX",
regset->core_note_type,
size, data);
else {
t->prstatus.pr_fpvalid = 1;
fill_note(&t->notes[i], "CORE",
NT_PRFPREG, size, data);
}
*total += notesize(&t->notes[i]);
}
}
}
return 1;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::string SanitizeRemoteBase(const std::string& value) {
GURL url(value);
std::string path = url.path();
std::vector<std::string> parts = base::SplitString(
path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
std::string revision = parts.size() > 2 ? parts[2] : "";
revision = SanitizeRevision(revision);
path = base::StringPrintf("/%s/%s/", kRemoteFrontendPath, revision.c_str());
return SanitizeFrontendURL(url, url::kHttpsScheme,
kRemoteFrontendDomain, path, false).spec();
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: server_read_httpchunks(struct bufferevent *bev, void *arg)
{
struct client *clt = arg;
struct evbuffer *src = EVBUFFER_INPUT(bev);
char *line;
long long llval;
size_t size;
getmonotime(&clt->clt_tv_last);
size = EVBUFFER_LENGTH(src);
DPRINTF("%s: session %d: size %lu, to read %lld", __func__,
clt->clt_id, size, clt->clt_toread);
if (!size)
return;
if (clt->clt_toread > 0) {
/* Read chunk data */
if ((off_t)size > clt->clt_toread) {
size = clt->clt_toread;
if (server_bufferevent_write_chunk(clt, src, size)
== -1)
goto fail;
clt->clt_toread = 0;
} else {
if (server_bufferevent_write_buffer(clt, src) == -1)
goto fail;
clt->clt_toread -= size;
}
DPRINTF("%s: done, size %lu, to read %lld", __func__,
size, clt->clt_toread);
}
switch (clt->clt_toread) {
case TOREAD_HTTP_CHUNK_LENGTH:
line = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF_STRICT);
if (line == NULL) {
/* Ignore empty line, continue */
bufferevent_enable(bev, EV_READ);
return;
}
if (strlen(line) == 0) {
free(line);
goto next;
}
/*
* Read prepended chunk size in hex, ignore the trailer.
* The returned signed value must not be negative.
*/
if (sscanf(line, "%llx", &llval) != 1 || llval < 0) {
free(line);
server_close(clt, "invalid chunk size");
return;
}
if (server_bufferevent_print(clt, line) == -1 ||
server_bufferevent_print(clt, "\r\n") == -1) {
free(line);
goto fail;
}
free(line);
if ((clt->clt_toread = llval) == 0) {
DPRINTF("%s: last chunk", __func__);
clt->clt_toread = TOREAD_HTTP_CHUNK_TRAILER;
}
break;
case TOREAD_HTTP_CHUNK_TRAILER:
/* Last chunk is 0 bytes followed by trailer and empty line */
line = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF_STRICT);
if (line == NULL) {
/* Ignore empty line, continue */
bufferevent_enable(bev, EV_READ);
return;
}
if (server_bufferevent_print(clt, line) == -1 ||
server_bufferevent_print(clt, "\r\n") == -1) {
free(line);
goto fail;
}
if (strlen(line) == 0) {
/* Switch to HTTP header mode */
clt->clt_toread = TOREAD_HTTP_HEADER;
bev->readcb = server_read_http;
}
free(line);
break;
case 0:
/* Chunk is terminated by an empty newline */
line = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF_STRICT);
free(line);
if (server_bufferevent_print(clt, "\r\n") == -1)
goto fail;
clt->clt_toread = TOREAD_HTTP_CHUNK_LENGTH;
break;
}
next:
if (clt->clt_done)
goto done;
if (EVBUFFER_LENGTH(src))
bev->readcb(bev, arg);
bufferevent_enable(bev, EV_READ);
return;
done:
server_close(clt, "last http chunk read (done)");
return;
fail:
server_close(clt, strerror(errno));
}
CWE ID: CWE-770
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GLuint GetServiceId(const OBJECT_TYPE* object) {
return object ? object->service_id() : 0;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void mk_request_free(struct session_request *sr)
{
if (sr->fd_file > 0) {
mk_vhost_close(sr);
}
if (sr->headers.location) {
mk_mem_free(sr->headers.location);
}
if (sr->uri_processed.data != sr->uri.data) {
mk_ptr_free(&sr->uri_processed);
}
if (sr->real_path.data != sr->real_path_static) {
mk_ptr_free(&sr->real_path);
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int skcipher_encrypt_blkcipher(struct skcipher_request *req)
{
struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
struct crypto_tfm *tfm = crypto_skcipher_tfm(skcipher);
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
return skcipher_crypt_blkcipher(req, alg->encrypt);
}
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: bool InspectorPageAgent::deviceMetricsOverrideEnabled()
{
return m_enabled && m_deviceMetricsOverridden;
}
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 PlatformSensorProviderBase::CreateSensor(
mojom::SensorType type,
const CreateSensorCallback& callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!CreateSharedBufferIfNeeded()) {
callback.Run(nullptr);
return;
}
mojo::ScopedSharedBufferMapping mapping = MapSharedBufferForType(type);
if (!mapping) {
callback.Run(nullptr);
return;
}
auto it = requests_map_.find(type);
if (it != requests_map_.end()) {
it->second.push_back(callback);
} else { // This is the first CreateSensor call.
requests_map_[type] = CallbackQueue({callback});
CreateSensorInternal(
type, std::move(mapping),
base::Bind(&PlatformSensorProviderBase::NotifySensorCreated,
base::Unretained(this), type));
}
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: static inline struct sockaddr *cma_src_addr(struct rdma_id_private *id_priv)
{
return (struct sockaddr *) &id_priv->id.route.addr.src_addr;
}
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 ServiceWorkerHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_ = process_host;
if (!process_host) {
ClearForceUpdate();
context_ = nullptr;
return;
}
StoragePartition* partition = process_host->GetStoragePartition();
DCHECK(partition);
context_ = static_cast<ServiceWorkerContextWrapper*>(
partition->GetServiceWorkerContext());
}
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 ScrollHitTestDisplayItem::PropertiesAsJSON(JSONObject& json) const {
DisplayItem::PropertiesAsJSON(json);
json.SetString("scrollOffsetNode",
String::Format("%p", scroll_offset_node_.get()));
}
CWE ID:
Target: 1
Example 2:
Code: virtual ~TestSiteInstance() {
(*delete_counter_)++;
}
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 TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener,
int start_index) const {
DCHECK(opener);
DCHECK(ContainsIndex(start_index));
for (int i = contents_data_.size() - 1; i > start_index; --i) {
if (contents_data_[i]->opener == opener)
return i;
}
return kNoTab;
}
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 PHP_FUNCTION(xmlwriter_open_uri)
{
char *valid_file = NULL;
xmlwriter_object *intern;
xmlTextWriterPtr ptr;
char *source;
char resolved_path[MAXPATHLEN + 1];
int source_len;
#ifdef ZEND_ENGINE_2
zval *this = getThis();
ze_xmlwriter_object *ze_obj = NULL;
#endif
#ifndef ZEND_ENGINE_2
xmlOutputBufferPtr out_buffer;
void *ioctx;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &source, &source_len) == FAILURE) {
return;
}
#ifdef ZEND_ENGINE_2
if (this) {
/* We do not use XMLWRITER_FROM_OBJECT, xmlwriter init function here */
ze_obj = (ze_xmlwriter_object*) zend_object_store_get_object(this TSRMLS_CC);
}
#endif
if (source_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string as source");
RETURN_FALSE;
}
valid_file = _xmlwriter_get_valid_file_path(source, resolved_path, MAXPATHLEN TSRMLS_CC);
if (!valid_file) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to resolve file path");
RETURN_FALSE;
}
/* TODO: Fix either the PHP stream or libxml APIs: it can then detect when a given
path is valid and not report out of memory error. Once it is done, remove the
directory check in _xmlwriter_get_valid_file_path */
#ifndef ZEND_ENGINE_2
ioctx = php_xmlwriter_streams_IO_open_write_wrapper(valid_file TSRMLS_CC);
if (ioctx == NULL) {
RETURN_FALSE;
}
out_buffer = xmlOutputBufferCreateIO(php_xmlwriter_streams_IO_write,
php_xmlwriter_streams_IO_close, ioctx, NULL);
if (out_buffer == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create output buffer");
RETURN_FALSE;
}
ptr = xmlNewTextWriter(out_buffer);
#else
ptr = xmlNewTextWriterFilename(valid_file, 0);
#endif
if (!ptr) {
RETURN_FALSE;
}
intern = emalloc(sizeof(xmlwriter_object));
intern->ptr = ptr;
intern->output = NULL;
#ifndef ZEND_ENGINE_2
intern->uri_output = out_buffer;
#else
if (this) {
if (ze_obj->xmlwriter_ptr) {
xmlwriter_free_resource_ptr(ze_obj->xmlwriter_ptr TSRMLS_CC);
}
ze_obj->xmlwriter_ptr = intern;
RETURN_TRUE;
} else
#endif
{
ZEND_REGISTER_RESOURCE(return_value,intern,le_xmlwriter);
}
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static int exif_discard_imageinfo(image_info_type *ImageInfo)
{
int i;
EFREE_IF(ImageInfo->FileName);
EFREE_IF(ImageInfo->UserComment);
EFREE_IF(ImageInfo->UserCommentEncoding);
EFREE_IF(ImageInfo->Copyright);
EFREE_IF(ImageInfo->CopyrightPhotographer);
EFREE_IF(ImageInfo->CopyrightEditor);
EFREE_IF(ImageInfo->Thumbnail.data);
EFREE_IF(ImageInfo->encode_unicode);
EFREE_IF(ImageInfo->decode_unicode_be);
EFREE_IF(ImageInfo->decode_unicode_le);
EFREE_IF(ImageInfo->encode_jis);
EFREE_IF(ImageInfo->decode_jis_be);
EFREE_IF(ImageInfo->decode_jis_le);
EFREE_IF(ImageInfo->make);
EFREE_IF(ImageInfo->model);
for (i=0; i<ImageInfo->xp_fields.count; i++) {
EFREE_IF(ImageInfo->xp_fields.list[i].value);
}
EFREE_IF(ImageInfo->xp_fields.list);
for (i=0; i<SECTION_COUNT; i++) {
exif_iif_free(ImageInfo, i);
}
exif_file_sections_free(ImageInfo);
memset(ImageInfo, 0, sizeof(*ImageInfo));
return TRUE;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: asmlinkage long compat_sys_ptrace(compat_long_t request, compat_long_t pid,
compat_long_t addr, compat_long_t data)
{
struct task_struct *child;
long ret;
if (request == PTRACE_TRACEME) {
ret = ptrace_traceme();
goto out;
}
child = ptrace_get_task_struct(pid);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
goto out;
}
if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) {
ret = ptrace_attach(child, request, addr, data);
/*
* Some architectures need to do book-keeping after
* a ptrace attach.
*/
if (!ret)
arch_ptrace_attach(child);
goto out_put_task_struct;
}
ret = ptrace_check_attach(child, request == PTRACE_KILL ||
request == PTRACE_INTERRUPT);
if (!ret)
ret = compat_arch_ptrace(child, request, addr, data);
out_put_task_struct:
put_task_struct(child);
out:
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: PHP_MINIT_FUNCTION(spl_directory)
{
REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions);
memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone;
spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast;
spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info;
spl_ce_SplFileInfo->serialize = zend_class_serialize_deny;
spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny;
REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions);
zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator);
REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator);
spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "OTHER_MODE_MASK", SPL_FILE_DIR_OTHERS_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS);
spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions);
REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator);
memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers));
spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check;
#ifdef HAVE_GLOB
REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions);
REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable);
#endif
REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions);
REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator);
REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV);
REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions);
return SUCCESS;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int irda_data_indication(void *instance, void *sap, struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
int err;
IRDA_DEBUG(3, "%s()\n", __func__);
self = instance;
sk = instance;
err = sock_queue_rcv_skb(sk, skb);
if (err) {
IRDA_DEBUG(1, "%s(), error: no more mem!\n", __func__);
self->rx_flow = FLOW_STOP;
/* When we return error, TTP will need to requeue the skb */
return err;
}
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: cleanup_pathname(struct archive_write_disk *a)
{
char *dest, *src;
char separator = '\0';
dest = src = a->name;
if (*src == '\0') {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/') {
if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Path is absolute");
return (ARCHIVE_FAILED);
}
separator = *src++;
}
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == a->name) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
}
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: Page* ChromeClientImpl::CreateWindow(LocalFrame* frame,
const FrameLoadRequest& r,
const WebWindowFeatures& features,
NavigationPolicy navigation_policy,
SandboxFlags sandbox_flags) {
if (!web_view_->Client())
return nullptr;
if (!frame->GetPage() || frame->GetPage()->Paused())
return nullptr;
DCHECK(frame->GetDocument());
Fullscreen::FullyExitFullscreen(*frame->GetDocument());
const AtomicString& frame_name =
!EqualIgnoringASCIICase(r.FrameName(), "_blank") ? r.FrameName()
: g_empty_atom;
WebViewImpl* new_view =
static_cast<WebViewImpl*>(web_view_->Client()->CreateView(
WebLocalFrameImpl::FromFrame(frame),
WrappedResourceRequest(r.GetResourceRequest()), features, frame_name,
static_cast<WebNavigationPolicy>(navigation_policy),
r.GetShouldSetOpener() == kNeverSetOpener,
static_cast<WebSandboxFlags>(sandbox_flags)));
if (!new_view)
return nullptr;
return new_view->GetPage();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: PaymentHandlerWebFlowViewController::~PaymentHandlerWebFlowViewController() {}
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: const PropertyTreeState& PropertyTreeState::Root() {
DEFINE_STATIC_LOCAL(
std::unique_ptr<PropertyTreeState>, root,
(std::make_unique<PropertyTreeState>(TransformPaintPropertyNode::Root(),
ClipPaintPropertyNode::Root(),
EffectPaintPropertyNode::Root())));
return *root;
}
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 Chapters::Atom* Chapters::Edition::GetAtom(int index) const
{
if (index < 0)
return NULL;
if (index >= m_atoms_count)
return NULL;
return m_atoms + index;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void block_socket(SOCKETTYPE fd)
{
#ifndef WIN32
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
#else
u_long flags = 0;
ioctlsocket(fd, FIONBIO, &flags);
#endif
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void cpu_clock_event_read(struct perf_event *event)
{
cpu_clock_event_update(event);
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src)
{
flush_fp_to_thread(src);
flush_altivec_to_thread(src);
flush_vsx_to_thread(src);
flush_spe_to_thread(src);
*dst = *src;
clear_task_ebb(dst);
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: nfsd4_secinfo_no_name(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
struct nfsd4_secinfo_no_name *sin)
{
__be32 err;
switch (sin->sin_style) {
case NFS4_SECINFO_STYLE4_CURRENT_FH:
break;
case NFS4_SECINFO_STYLE4_PARENT:
err = nfsd4_do_lookupp(rqstp, &cstate->current_fh);
if (err)
return err;
break;
default:
return nfserr_inval;
}
sin->sin_exp = exp_get(cstate->current_fh.fh_export);
fh_put(&cstate->current_fh);
return nfs_ok;
}
CWE ID: CWE-404
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int here(JF)
{
return F->codelen;
}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void si_conn_send(struct connection *conn)
{
struct stream_interface *si = conn->owner;
struct channel *chn = si->ob;
int ret;
if (chn->pipe && conn->xprt->snd_pipe) {
ret = conn->xprt->snd_pipe(conn, chn->pipe);
if (ret > 0)
chn->flags |= CF_WRITE_PARTIAL;
if (!chn->pipe->data) {
put_pipe(chn->pipe);
chn->pipe = NULL;
}
if (conn->flags & CO_FL_ERROR)
return;
}
/* At this point, the pipe is empty, but we may still have data pending
* in the normal buffer.
*/
if (!chn->buf->o)
return;
/* when we're here, we already know that there is no spliced
* data left, and that there are sendable buffered data.
*/
if (!(conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH | CO_FL_DATA_WR_SH | CO_FL_WAIT_DATA | CO_FL_HANDSHAKE))) {
/* check if we want to inform the kernel that we're interested in
* sending more data after this call. We want this if :
* - we're about to close after this last send and want to merge
* the ongoing FIN with the last segment.
* - we know we can't send everything at once and must get back
* here because of unaligned data
* - there is still a finite amount of data to forward
* The test is arranged so that the most common case does only 2
* tests.
*/
unsigned int send_flag = 0;
if ((!(chn->flags & (CF_NEVER_WAIT|CF_SEND_DONTWAIT)) &&
((chn->to_forward && chn->to_forward != CHN_INFINITE_FORWARD) ||
(chn->flags & CF_EXPECT_MORE))) ||
((chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) == CF_SHUTW_NOW))
send_flag |= CO_SFL_MSG_MORE;
if (chn->flags & CF_STREAMER)
send_flag |= CO_SFL_STREAMER;
ret = conn->xprt->snd_buf(conn, chn->buf, send_flag);
if (ret > 0) {
chn->flags |= CF_WRITE_PARTIAL;
if (!chn->buf->o) {
/* Always clear both flags once everything has been sent, they're one-shot */
chn->flags &= ~(CF_EXPECT_MORE | CF_SEND_DONTWAIT);
}
/* if some data remain in the buffer, it's only because the
* system buffers are full, we will try next time.
*/
}
}
return;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void VaapiVideoDecodeAccelerator::Decode(
const BitstreamBuffer& bitstream_buffer) {
DCHECK(task_runner_->BelongsToCurrentThread());
TRACE_EVENT1("Video Decoder", "VAVDA::Decode", "Buffer id",
bitstream_buffer.id());
if (bitstream_buffer.id() < 0) {
if (base::SharedMemory::IsHandleValid(bitstream_buffer.handle()))
base::SharedMemory::CloseHandle(bitstream_buffer.handle());
VLOGF(1) << "Invalid bitstream_buffer, id: " << bitstream_buffer.id();
NotifyError(INVALID_ARGUMENT);
return;
}
if (bitstream_buffer.size() == 0) {
if (base::SharedMemory::IsHandleValid(bitstream_buffer.handle()))
base::SharedMemory::CloseHandle(bitstream_buffer.handle());
if (client_)
client_->NotifyEndOfBitstreamBuffer(bitstream_buffer.id());
return;
}
QueueInputBuffer(bitstream_buffer);
}
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: kdc_process_s4u2proxy_req(kdc_realm_t *kdc_active_realm,
krb5_kdc_req *request,
const krb5_enc_tkt_part *t2enc,
const krb5_db_entry *server,
krb5_const_principal server_princ,
krb5_const_principal proxy_princ,
const char **status)
{
krb5_error_code errcode;
/*
* Constrained delegation is mutually exclusive with renew/forward/etc.
* We can assert from this check that the header ticket was a TGT, as
* that is validated previously in validate_tgs_request().
*/
if (request->kdc_options & (NON_TGT_OPTION | KDC_OPT_ENC_TKT_IN_SKEY)) {
return KRB5KDC_ERR_BADOPTION;
}
/* Ensure that evidence ticket server matches TGT client */
if (!krb5_principal_compare(kdc_context,
server->princ, /* after canon */
server_princ)) {
return KRB5KDC_ERR_SERVER_NOMATCH;
}
if (!isflagset(t2enc->flags, TKT_FLG_FORWARDABLE)) {
*status = "EVIDENCE_TKT_NOT_FORWARDABLE";
return KRB5_TKT_NOT_FORWARDABLE;
}
/* Backend policy check */
errcode = check_allowed_to_delegate_to(kdc_context,
t2enc->client,
server,
proxy_princ);
if (errcode) {
*status = "NOT_ALLOWED_TO_DELEGATE";
return errcode;
}
return 0;
}
CWE ID: CWE-617
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 simple_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
if (type == ACL_TYPE_ACCESS) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return 0;
if (error == 0)
acl = NULL;
}
inode->i_ctime = current_time(inode);
set_cached_acl(inode, type, acl);
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: static int _TIFFFillStrilesInternal( TIFF *tif, int loadStripByteCount )
{
#if defined(DEFER_STRILE_LOAD)
register TIFFDirectory *td = &tif->tif_dir;
int return_value = 1;
if( td->td_stripoffset != NULL )
return 1;
if( td->td_stripoffset_entry.tdir_count == 0 )
return 0;
if (!TIFFFetchStripThing(tif,&(td->td_stripoffset_entry),
td->td_nstrips,&td->td_stripoffset))
{
return_value = 0;
}
if (loadStripByteCount &&
!TIFFFetchStripThing(tif,&(td->td_stripbytecount_entry),
td->td_nstrips,&td->td_stripbytecount))
{
return_value = 0;
}
_TIFFmemset( &(td->td_stripoffset_entry), 0, sizeof(TIFFDirEntry));
_TIFFmemset( &(td->td_stripbytecount_entry), 0, sizeof(TIFFDirEntry));
if (tif->tif_dir.td_nstrips > 1 && return_value == 1 ) {
uint32 strip;
tif->tif_dir.td_stripbytecountsorted = 1;
for (strip = 1; strip < tif->tif_dir.td_nstrips; strip++) {
if (tif->tif_dir.td_stripoffset[strip - 1] >
tif->tif_dir.td_stripoffset[strip]) {
tif->tif_dir.td_stripbytecountsorted = 0;
break;
}
}
}
return return_value;
#else /* !defined(DEFER_STRILE_LOAD) */
(void) tif;
(void) loadStripByteCount;
return 1;
#endif
}
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 WebContentsImpl::DidCancelLoading() {
controller_.DiscardNonCommittedEntries();
NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
}
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: cf2_initGlobalRegionBuffer( CFF_Decoder* decoder,
CF2_UInt idx,
CF2_Buffer buf )
{
FT_ASSERT( decoder && decoder->globals );
FT_ZERO( buf );
idx += decoder->globals_bias;
if ( idx >= decoder->num_globals )
return TRUE; /* error */
buf->start =
buf->ptr = decoder->globals[idx];
buf->end = decoder->globals[idx + 1];
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void InlineSigninHelper::ConfirmEmailAction(
content::WebContents* web_contents,
const std::string& refresh_token,
OneClickSigninSyncStarter::ConfirmationRequired confirmation_required,
OneClickSigninSyncStarter::StartSyncMode start_mode,
SigninEmailConfirmationDialog::Action action) {
Browser* browser = chrome::FindLastActiveWithProfile(profile_);
switch (action) {
case SigninEmailConfirmationDialog::CREATE_NEW_USER:
base::RecordAction(
base::UserMetricsAction("Signin_ImportDataPrompt_DontImport"));
CreateSyncStarter(browser, current_url_, refresh_token,
OneClickSigninSyncStarter::NEW_PROFILE, start_mode,
confirmation_required);
break;
case SigninEmailConfirmationDialog::START_SYNC:
base::RecordAction(
base::UserMetricsAction("Signin_ImportDataPrompt_ImportData"));
CreateSyncStarter(browser, current_url_, refresh_token,
OneClickSigninSyncStarter::CURRENT_PROFILE, start_mode,
confirmation_required);
break;
case SigninEmailConfirmationDialog::CLOSE:
base::RecordAction(
base::UserMetricsAction("Signin_ImportDataPrompt_Cancel"));
if (handler_) {
handler_->SyncStarterCallback(
OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
}
break;
default:
DCHECK(false) << "Invalid action";
}
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}
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: vbf_stp_fetchbody(struct worker *wrk, struct busyobj *bo)
{
ssize_t l;
uint8_t *ptr;
enum vfp_status vfps = VFP_ERROR;
ssize_t est;
struct vfp_ctx *vfc;
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
vfc = bo->vfc;
CHECK_OBJ_NOTNULL(vfc, VFP_CTX_MAGIC);
AN(vfc->vfp_nxt);
est = bo->htc->content_length;
if (est < 0)
est = 0;
do {
if (vfc->oc->flags & OC_F_ABANDON) {
/*
* A pass object and delivery was terminated
* We don't fail the fetch, in order for hit-for-pass
* objects to be created.
*/
AN(vfc->oc->flags & OC_F_PASS);
VSLb(wrk->vsl, SLT_FetchError,
"Pass delivery abandoned");
bo->htc->doclose = SC_RX_BODY;
break;
}
AZ(vfc->failed);
l = est;
assert(l >= 0);
if (VFP_GetStorage(vfc, &l, &ptr) != VFP_OK) {
bo->htc->doclose = SC_RX_BODY;
break;
}
AZ(vfc->failed);
vfps = VFP_Suck(vfc, ptr, &l);
if (l > 0 && vfps != VFP_ERROR) {
bo->acct.beresp_bodybytes += l;
VFP_Extend(vfc, l);
if (est >= l)
est -= l;
else
est = 0;
}
} while (vfps == VFP_OK);
if (vfc->failed) {
(void)VFP_Error(vfc, "Fetch pipeline failed to process");
bo->htc->doclose = SC_RX_BODY;
VFP_Close(vfc);
VDI_Finish(wrk, bo);
if (!bo->do_stream) {
assert(bo->fetch_objcore->boc->state < BOS_STREAM);
return (F_STP_ERROR);
} else {
wrk->stats->fetch_failed++;
return (F_STP_FAIL);
}
}
ObjTrimStore(wrk, vfc->oc);
return (F_STP_FETCHEND);
}
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: enum nss_status _nss_mymachines_getgrnam_r(
const char *name,
struct group *gr,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t gid;
size_t l;
int r;
assert(name);
assert(gr);
p = startswith(name, "vg-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
r = parse_gid(e + 1, &gid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineGroup",
&error,
&reply,
"su",
machine, (uint32_t) gid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_GROUP_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = sizeof(char*) + strlen(name) + 1;
if (buflen < l) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memzero(buffer, sizeof(char*));
strcpy(buffer + sizeof(char*), name);
gr->gr_name = buffer + sizeof(char*);
gr->gr_gid = gid;
gr->gr_passwd = (char*) "*"; /* locked */
gr->gr_mem = (char**) buffer;
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool DevToolsEventForwarder::KeyWhitelistingAllowed(int key_code,
int modifiers) {
return (ui::VKEY_F1 <= key_code && key_code <= ui::VKEY_F12) ||
modifiers != 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: g_utf8_normalize (const gchar * str, gssize len, GNormalizeMode mode)
{
gunichar *result_wc = _g_utf8_normalize_wc (str, len, mode);
gchar *result;
result = g_ucs4_to_utf8 (result_wc, -1, NULL, NULL);
g_free (result_wc);
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: void AppControllerImpl::SetClient(mojom::AppControllerClientPtr client) {
client_ = std::move(client);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void ShellContentBrowserClient::OpenURL(
BrowserContext* browser_context,
const OpenURLParams& params,
const base::Callback<void(WebContents*)>& callback) {
callback.Run(Shell::CreateNewWindow(browser_context,
params.url,
nullptr,
gfx::Size())->web_contents());
}
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 zend_object_value spl_object_storage_clone(zval *zobject TSRMLS_DC)
{
zend_object_value new_obj_val;
zend_object *old_object;
zend_object *new_object;
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
spl_SplObjectStorage *intern;
old_object = zend_objects_get_address(zobject TSRMLS_CC);
new_obj_val = spl_object_storage_new_ex(old_object->ce, &intern, zobject TSRMLS_CC);
new_object = &intern->std;
zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC);
return new_obj_val;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen,
int prediction_resistance,
const unsigned char *adin, size_t adinlen)
{
int reseed_required = 0;
if (drbg->state != DRBG_READY) {
rand_drbg_restart(drbg, NULL, 0, 0);
if (drbg->state == DRBG_ERROR) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE);
return 0;
}
if (drbg->state == DRBG_UNINITIALISED) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED);
return 0;
}
}
if (outlen > drbg->max_request) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG);
return 0;
}
if (adinlen > drbg->max_adinlen) {
RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG);
return 0;
return 0;
}
if (drbg->fork_count != rand_fork_count) {
drbg->fork_count = rand_fork_count;
reseed_required = 1;
}
}
CWE ID: CWE-330
Target: 1
Example 2:
Code: bool PDFiumEngine::OnRightMouseDown(const pp::MouseInputEvent& event) {
DCHECK_EQ(PP_INPUTEVENT_MOUSEBUTTON_RIGHT, event.GetButton());
pp::Point point = event.GetPosition();
int page_index = -1;
int char_index = -1;
int form_type = FPDF_FORMFIELD_UNKNOWN;
PDFiumPage::LinkTarget target;
PDFiumPage::Area area =
GetCharIndex(point, &page_index, &char_index, &form_type, &target);
DCHECK_GE(form_type, FPDF_FORMFIELD_UNKNOWN);
bool is_form_text_area = IsFormTextArea(area, form_type);
bool is_editable_form_text_area = false;
double page_x = -1;
double page_y = -1;
FPDF_PAGE page = nullptr;
if (is_form_text_area) {
DCHECK_NE(page_index, -1);
DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
page = pages_[page_index]->GetPage();
is_editable_form_text_area =
IsPointInEditableFormTextArea(page, page_x, page_y, form_type);
}
if (in_form_text_area_) {
if (is_form_text_area) {
FORM_OnFocus(form_, page, 0, page_x, page_y);
} else {
FORM_ForceToKillFocus(form_);
SetInFormTextArea(false);
}
return true;
}
if (is_form_text_area) {
{
SelectionChangeInvalidator selection_invalidator(this);
selection_.clear();
}
SetInFormTextArea(true);
editable_form_text_area_ = is_editable_form_text_area;
FORM_OnFocus(form_, page, 0, page_x, page_y);
return true;
}
if (selection_.empty())
return false;
std::vector<pp::Rect> selection_rect_vector;
GetAllScreenRectsUnion(&selection_, GetVisibleRect().point(),
&selection_rect_vector);
for (const auto& rect : selection_rect_vector) {
if (rect.Contains(point.x(), point.y()))
return false;
}
SelectionChangeInvalidator selection_invalidator(this);
selection_.clear();
return true;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static long aio_read_events_ring(struct kioctx *ctx,
struct io_event __user *event, long nr)
{
struct aio_ring *ring;
unsigned head, tail, pos;
long ret = 0;
int copy_ret;
mutex_lock(&ctx->ring_lock);
/* Access to ->ring_pages here is protected by ctx->ring_lock. */
ring = kmap_atomic(ctx->ring_pages[0]);
head = ring->head;
tail = ring->tail;
kunmap_atomic(ring);
pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
if (head == tail)
goto out;
while (ret < nr) {
long avail;
struct io_event *ev;
struct page *page;
avail = (head <= tail ? tail : ctx->nr_events) - head;
if (head == tail)
break;
avail = min(avail, nr - ret);
avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
pos = head + AIO_EVENTS_OFFSET;
page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
pos %= AIO_EVENTS_PER_PAGE;
ev = kmap(page);
copy_ret = copy_to_user(event + ret, ev + pos,
sizeof(*ev) * avail);
kunmap(page);
if (unlikely(copy_ret)) {
ret = -EFAULT;
goto out;
}
ret += avail;
head += avail;
head %= ctx->nr_events;
}
ring = kmap_atomic(ctx->ring_pages[0]);
ring->head = head;
kunmap_atomic(ring);
flush_dcache_page(ctx->ring_pages[0]);
pr_debug("%li h%u t%u\n", ret, head, tail);
out:
mutex_unlock(&ctx->ring_lock);
return ret;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderWidgetHostViewAura::AcceleratedSurfaceRelease(
uint64 surface_handle) {
DCHECK(image_transport_clients_.find(surface_handle) !=
image_transport_clients_.end());
if (current_surface_ == surface_handle) {
current_surface_ = 0;
UpdateExternalTexture();
}
image_transport_clients_.erase(surface_handle);
}
CWE ID:
Target: 1
Example 2:
Code: handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
{
struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
struct ofputil_switch_config config;
enum ofperr error;
error = ofputil_decode_set_config(oh, &config);
if (error) {
return error;
}
if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
|| ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
enum ofputil_frag_handling cur = ofproto->frag_handling;
enum ofputil_frag_handling next = config.frag;
if (cur != next) {
if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
ofproto->frag_handling = next;
} else {
VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
ofproto->name,
ofputil_frag_handling_to_string(next));
}
}
}
if (config.invalid_ttl_to_controller >= 0) {
ofconn_set_invalid_ttl_to_controller(ofconn,
config.invalid_ttl_to_controller);
}
ofconn_set_miss_send_len(ofconn, config.miss_send_len);
return 0;
}
CWE ID: CWE-617
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ProfilingProcessHost::Mode ProfilingProcessHost::GetCurrentMode() {
const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
#if BUILDFLAG(USE_ALLOCATOR_SHIM)
if (cmdline->HasSwitch(switches::kMemlog) ||
base::FeatureList::IsEnabled(kOOPHeapProfilingFeature)) {
if (cmdline->HasSwitch(switches::kEnableHeapProfiling)) {
LOG(ERROR) << "--" << switches::kEnableHeapProfiling
<< " specified with --" << switches::kMemlog
<< "which are not compatible. Memlog will be disabled.";
return Mode::kNone;
}
std::string mode;
if (cmdline->HasSwitch(switches::kMemlog)) {
mode = cmdline->GetSwitchValueASCII(switches::kMemlog);
} else {
mode = base::GetFieldTrialParamValueByFeature(
kOOPHeapProfilingFeature, kOOPHeapProfilingFeatureMode);
}
if (mode == switches::kMemlogModeAll)
return Mode::kAll;
if (mode == switches::kMemlogModeMinimal)
return Mode::kMinimal;
if (mode == switches::kMemlogModeBrowser)
return Mode::kBrowser;
if (mode == switches::kMemlogModeGpu)
return Mode::kGpu;
if (mode == switches::kMemlogModeRendererSampling)
return Mode::kRendererSampling;
DLOG(ERROR) << "Unsupported value: \"" << mode << "\" passed to --"
<< switches::kMemlog;
}
return Mode::kNone;
#else
LOG_IF(ERROR, cmdline->HasSwitch(switches::kMemlog))
<< "--" << switches::kMemlog
<< " specified but it will have no effect because the use_allocator_shim "
<< "is not available in this build.";
return Mode::kNone;
#endif
}
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int validate_camera_metadata_structure(const camera_metadata_t *metadata,
const size_t *expected_size) {
if (metadata == NULL) {
ALOGE("%s: metadata is null!", __FUNCTION__);
return ERROR;
}
{
static const struct {
const char *name;
size_t alignment;
} alignments[] = {
{
.name = "camera_metadata",
.alignment = METADATA_ALIGNMENT
},
{
.name = "camera_metadata_buffer_entry",
.alignment = ENTRY_ALIGNMENT
},
{
.name = "camera_metadata_data",
.alignment = DATA_ALIGNMENT
},
};
for (size_t i = 0; i < sizeof(alignments)/sizeof(alignments[0]); ++i) {
uintptr_t aligned_ptr = ALIGN_TO(metadata, alignments[i].alignment);
if ((uintptr_t)metadata != aligned_ptr) {
ALOGE("%s: Metadata pointer is not aligned (actual %p, "
"expected %p) to type %s",
__FUNCTION__, metadata,
(void*)aligned_ptr, alignments[i].name);
return ERROR;
}
}
}
/**
* Check that the metadata contents are correct
*/
if (expected_size != NULL && metadata->size > *expected_size) {
ALOGE("%s: Metadata size (%" PRIu32 ") should be <= expected size (%zu)",
__FUNCTION__, metadata->size, *expected_size);
return ERROR;
}
if (metadata->entry_count > metadata->entry_capacity) {
ALOGE("%s: Entry count (%" PRIu32 ") should be <= entry capacity "
"(%" PRIu32 ")",
__FUNCTION__, metadata->entry_count, metadata->entry_capacity);
return ERROR;
}
const metadata_uptrdiff_t entries_end =
metadata->entries_start + metadata->entry_capacity;
if (entries_end < metadata->entries_start || // overflow check
entries_end > metadata->data_start) {
ALOGE("%s: Entry start + capacity (%" PRIu32 ") should be <= data start "
"(%" PRIu32 ")",
__FUNCTION__,
(metadata->entries_start + metadata->entry_capacity),
metadata->data_start);
return ERROR;
}
const metadata_uptrdiff_t data_end =
metadata->data_start + metadata->data_capacity;
if (data_end < metadata->data_start || // overflow check
data_end > metadata->size) {
ALOGE("%s: Data start + capacity (%" PRIu32 ") should be <= total size "
"(%" PRIu32 ")",
__FUNCTION__,
(metadata->data_start + metadata->data_capacity),
metadata->size);
return ERROR;
}
const metadata_size_t entry_count = metadata->entry_count;
camera_metadata_buffer_entry_t *entries = get_entries(metadata);
for (size_t i = 0; i < entry_count; ++i) {
if ((uintptr_t)&entries[i] != ALIGN_TO(&entries[i], ENTRY_ALIGNMENT)) {
ALOGE("%s: Entry index %zu had bad alignment (address %p),"
" expected alignment %zu",
__FUNCTION__, i, &entries[i], ENTRY_ALIGNMENT);
return ERROR;
}
camera_metadata_buffer_entry_t entry = entries[i];
if (entry.type >= NUM_TYPES) {
ALOGE("%s: Entry index %zu had a bad type %d",
__FUNCTION__, i, entry.type);
return ERROR;
}
uint32_t tag_section = entry.tag >> 16;
int tag_type = get_camera_metadata_tag_type(entry.tag);
if (tag_type != (int)entry.type && tag_section < VENDOR_SECTION) {
ALOGE("%s: Entry index %zu had tag type %d, but the type was %d",
__FUNCTION__, i, tag_type, entry.type);
return ERROR;
}
size_t data_size =
calculate_camera_metadata_entry_data_size(entry.type,
entry.count);
if (data_size != 0) {
camera_metadata_data_t *data =
(camera_metadata_data_t*) (get_data(metadata) +
entry.data.offset);
if ((uintptr_t)data != ALIGN_TO(data, DATA_ALIGNMENT)) {
ALOGE("%s: Entry index %zu had bad data alignment (address %p),"
" expected align %zu, (tag name %s, data size %zu)",
__FUNCTION__, i, data, DATA_ALIGNMENT,
get_camera_metadata_tag_name(entry.tag) ?: "unknown",
data_size);
return ERROR;
}
size_t data_entry_end = entry.data.offset + data_size;
if (data_entry_end < entry.data.offset || // overflow check
data_entry_end > metadata->data_capacity) {
ALOGE("%s: Entry index %zu data ends (%zu) beyond the capacity "
"%" PRIu32, __FUNCTION__, i, data_entry_end,
metadata->data_capacity);
return ERROR;
}
} else if (entry.count == 0) {
if (entry.data.offset != 0) {
ALOGE("%s: Entry index %zu had 0 items, but offset was non-0 "
"(%" PRIu32 "), tag name: %s", __FUNCTION__, i, entry.data.offset,
get_camera_metadata_tag_name(entry.tag) ?: "unknown");
return ERROR;
}
} // else data stored inline, so we look at value which can be anything.
}
return OK;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: g_NP_GetValue(NPPVariable variable, void *value)
{
if (g_plugin_NP_GetValue == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
D(bugiI("NP_GetValue variable=%d [%s]\n", variable, string_of_NPPVariable(variable)));
NPError ret = g_plugin_NP_GetValue(NULL, variable, value);
D(bugiD("NP_GetValue return: %d\n", ret));
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 TabStrip::RemoveMessageLoopObserver() {
mouse_watcher_ = nullptr;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int picolcd_raw_event(struct hid_device *hdev,
struct hid_report *report, u8 *raw_data, int size)
{
struct picolcd_data *data = hid_get_drvdata(hdev);
unsigned long flags;
int ret = 0;
if (!data)
return 1;
if (report->id == REPORT_KEY_STATE) {
if (data->input_keys)
ret = picolcd_raw_keypad(data, report, raw_data+1, size-1);
} else if (report->id == REPORT_IR_DATA) {
ret = picolcd_raw_cir(data, report, raw_data+1, size-1);
} else {
spin_lock_irqsave(&data->lock, flags);
/*
* We let the caller of picolcd_send_and_wait() check if the
* report we got is one of the expected ones or not.
*/
if (data->pending) {
memcpy(data->pending->raw_data, raw_data+1, size-1);
data->pending->raw_size = size-1;
data->pending->in_report = report;
complete(&data->pending->ready);
}
spin_unlock_irqrestore(&data->lock, flags);
}
picolcd_debug_raw_event(data, hdev, report, raw_data, size);
return 1;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void DevToolsWindow::ActivateContents(WebContents* contents) {
if (is_docked_) {
WebContents* inspected_tab = GetInspectedWebContents();
if (inspected_tab)
inspected_tab->GetDelegate()->ActivateContents(inspected_tab);
} else if (browser_) {
browser_->window()->Activate();
}
}
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 struct nfs4_opendata *nfs4_opendata_alloc(struct path *path,
struct nfs4_state_owner *sp, int flags,
const struct iattr *attrs)
{
struct dentry *parent = dget_parent(path->dentry);
struct inode *dir = parent->d_inode;
struct nfs_server *server = NFS_SERVER(dir);
struct nfs4_opendata *p;
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL)
goto err;
p->o_arg.seqid = nfs_alloc_seqid(&sp->so_seqid);
if (p->o_arg.seqid == NULL)
goto err_free;
p->path.mnt = mntget(path->mnt);
p->path.dentry = dget(path->dentry);
p->dir = parent;
p->owner = sp;
atomic_inc(&sp->so_count);
p->o_arg.fh = NFS_FH(dir);
p->o_arg.open_flags = flags,
p->o_arg.clientid = server->nfs_client->cl_clientid;
p->o_arg.id = sp->so_owner_id.id;
p->o_arg.name = &p->path.dentry->d_name;
p->o_arg.server = server;
p->o_arg.bitmask = server->attr_bitmask;
p->o_arg.claim = NFS4_OPEN_CLAIM_NULL;
if (flags & O_EXCL) {
u32 *s = (u32 *) p->o_arg.u.verifier.data;
s[0] = jiffies;
s[1] = current->pid;
} else if (flags & O_CREAT) {
p->o_arg.u.attrs = &p->attrs;
memcpy(&p->attrs, attrs, sizeof(p->attrs));
}
p->c_arg.fh = &p->o_res.fh;
p->c_arg.stateid = &p->o_res.stateid;
p->c_arg.seqid = p->o_arg.seqid;
nfs4_init_opendata_res(p);
kref_init(&p->kref);
return p;
err_free:
kfree(p);
err:
dput(parent);
return NULL;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int atusb_get_and_show_build(struct atusb *atusb)
{
struct usb_device *usb_dev = atusb->usb_dev;
char build[ATUSB_BUILD_SIZE + 1];
int ret;
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_BUILD, ATUSB_REQ_FROM_DEV, 0, 0,
build, ATUSB_BUILD_SIZE, 1000);
if (ret >= 0) {
build[ret] = 0;
dev_info(&usb_dev->dev, "Firmware: build %s\n", build);
}
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: UNCURL_EXPORT int32_t uncurl_read_header(struct uncurl_conn *ucc)
{
int32_t e;
if (ucc->hin) http_free_header(ucc->hin);
ucc->hin = NULL;
char *header = NULL;
e = uncurl_read_header_(ucc, &header);
if (e == UNCURL_OK) {
ucc->hin = http_parse_header(header);
free(header);
}
return e;
}
CWE ID: CWE-352
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 CameraSource::signalBufferReturned(MediaBuffer *buffer) {
ALOGV("signalBufferReturned: %p", buffer->data());
Mutex::Autolock autoLock(mLock);
for (List<sp<IMemory> >::iterator it = mFramesBeingEncoded.begin();
it != mFramesBeingEncoded.end(); ++it) {
if ((*it)->pointer() == buffer->data()) {
releaseOneRecordingFrame((*it));
mFramesBeingEncoded.erase(it);
++mNumFramesEncoded;
buffer->setObserver(0);
buffer->release();
mFrameCompleteCondition.signal();
return;
}
}
CHECK(!"signalBufferReturned: bogus buffer");
}
CWE ID: CWE-200
Output: | 1 |
Subsets and Splits