text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void __skb_get_hash(struct sk_buff *skb) { struct flow_keys keys; u32 hash; __flow_hash_secret_init(); hash = ___skb_get_hash(skb, &keys, hashrnd); __skb_set_sw_hash(skb, hash, flow_keys_have_l4(&keys)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int hhf_init(struct Qdisc *sch, struct nlattr *opt, struct netlink_ext_ack *extack) { struct hhf_sched_data *q = qdisc_priv(sch); int i; sch->limit = 1000; q->quantum = psched_mtu(qdisc_dev(sch)); q->perturbation = prandom_u32(); INIT_LIST_HEAD(&q->new_buckets); INIT_LIST_HEAD(&q->old_buckets); /* Configurable HHF parameters */ q->hhf_reset_timeout = HZ / 25; /* 40 ms */ q->hhf_admit_bytes = 131072; /* 128 KB */ q->hhf_evict_timeout = HZ; /* 1 sec */ q->hhf_non_hh_weight = 2; if (opt) { int err = hhf_change(sch, opt, extack); if (err) return err; } if (!q->hh_flows) { /* Initialize heavy-hitter flow table. */ q->hh_flows = kvcalloc(HH_FLOWS_CNT, sizeof(struct list_head), GFP_KERNEL); if (!q->hh_flows) return -ENOMEM; for (i = 0; i < HH_FLOWS_CNT; i++) INIT_LIST_HEAD(&q->hh_flows[i]); /* Cap max active HHs at twice len of hh_flows table. */ q->hh_flows_limit = 2 * HH_FLOWS_CNT; q->hh_flows_overlimit = 0; q->hh_flows_total_cnt = 0; q->hh_flows_current_cnt = 0; /* Initialize heavy-hitter filter arrays. */ for (i = 0; i < HHF_ARRAYS_CNT; i++) { q->hhf_arrays[i] = kvcalloc(HHF_ARRAYS_LEN, sizeof(u32), GFP_KERNEL); if (!q->hhf_arrays[i]) { /* Note: hhf_destroy() will be called * by our caller. */ return -ENOMEM; } } q->hhf_arrays_reset_timestamp = hhf_time_stamp(); /* Initialize valid bits of heavy-hitter filter arrays. */ for (i = 0; i < HHF_ARRAYS_CNT; i++) { q->hhf_valid_bits[i] = kvzalloc(HHF_ARRAYS_LEN / BITS_PER_BYTE, GFP_KERNEL); if (!q->hhf_valid_bits[i]) { /* Note: hhf_destroy() will be called * by our caller. */ return -ENOMEM; } } /* Initialize Weighted DRR buckets. */ for (i = 0; i < WDRR_BUCKET_CNT; i++) { struct wdrr_bucket *bucket = q->buckets + i; INIT_LIST_HEAD(&bucket->bucketchain); } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: u32 __skb_get_hash_symmetric(const struct sk_buff *skb) { struct flow_keys keys; __flow_hash_secret_init(); memset(&keys, 0, sizeof(keys)); __skb_flow_dissect(NULL, skb, &flow_keys_dissector_symmetric, &keys, NULL, 0, 0, 0, FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL); return __flow_hash_from_keys(&keys, hashrnd); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static unsigned int sfq_hash(const struct sfq_sched_data *q, const struct sk_buff *skb) { return skb_get_hash_perturb(skb, q->perturbation) & (q->divisor - 1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline u32 ___skb_get_hash(const struct sk_buff *skb, struct flow_keys *keys, u32 keyval) { skb_flow_dissect_flow_keys(skb, keys, FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL); return __flow_hash_from_keys(keys, keyval); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __u32 skb_get_hash_perturb(const struct sk_buff *skb, u32 perturb) { struct flow_keys keys; return ___skb_get_hash(skb, &keys, perturb); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline u32 __flow_hash_from_keys(struct flow_keys *keys, u32 keyval) { u32 hash; __flow_hash_consistentify(keys); hash = __flow_hash_words(flow_keys_hash_start(keys), flow_keys_hash_length(keys), keyval); if (!hash) hash = 1; return hash; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int sfb_enqueue(struct sk_buff *skb, struct Qdisc *sch, struct sk_buff **to_free) { struct sfb_sched_data *q = qdisc_priv(sch); struct Qdisc *child = q->qdisc; struct tcf_proto *fl; int i; u32 p_min = ~0; u32 minqlen = ~0; u32 r, sfbhash; u32 slot = q->slot; int ret = NET_XMIT_SUCCESS | __NET_XMIT_BYPASS; if (unlikely(sch->q.qlen >= q->limit)) { qdisc_qstats_overlimit(sch); q->stats.queuedrop++; goto drop; } if (q->rehash_interval > 0) { unsigned long limit = q->rehash_time + q->rehash_interval; if (unlikely(time_after(jiffies, limit))) { sfb_swap_slot(q); q->rehash_time = jiffies; } else if (unlikely(!q->double_buffering && q->warmup_time > 0 && time_after(jiffies, limit - q->warmup_time))) { q->double_buffering = true; } } fl = rcu_dereference_bh(q->filter_list); if (fl) { u32 salt; /* If using external classifiers, get result and record it. */ if (!sfb_classify(skb, fl, &ret, &salt)) goto other_drop; sfbhash = jhash_1word(salt, q->bins[slot].perturbation); } else { sfbhash = skb_get_hash_perturb(skb, q->bins[slot].perturbation); } if (!sfbhash) sfbhash = 1; sfb_skb_cb(skb)->hashes[slot] = sfbhash; for (i = 0; i < SFB_LEVELS; i++) { u32 hash = sfbhash & SFB_BUCKET_MASK; struct sfb_bucket *b = &q->bins[slot].bins[i][hash]; sfbhash >>= SFB_BUCKET_SHIFT; if (b->qlen == 0) decrement_prob(b, q); else if (b->qlen >= q->bin_size) increment_prob(b, q); if (minqlen > b->qlen) minqlen = b->qlen; if (p_min > b->p_mark) p_min = b->p_mark; } slot ^= 1; sfb_skb_cb(skb)->hashes[slot] = 0; if (unlikely(minqlen >= q->max)) { qdisc_qstats_overlimit(sch); q->stats.bucketdrop++; goto drop; } if (unlikely(p_min >= SFB_MAX_PROB)) { /* Inelastic flow */ if (q->double_buffering) { sfbhash = skb_get_hash_perturb(skb, q->bins[slot].perturbation); if (!sfbhash) sfbhash = 1; sfb_skb_cb(skb)->hashes[slot] = sfbhash; for (i = 0; i < SFB_LEVELS; i++) { u32 hash = sfbhash & SFB_BUCKET_MASK; struct sfb_bucket *b = &q->bins[slot].bins[i][hash]; sfbhash >>= SFB_BUCKET_SHIFT; if (b->qlen == 0) decrement_prob(b, q); else if (b->qlen >= q->bin_size) increment_prob(b, q); } } if (sfb_rate_limit(skb, q)) { qdisc_qstats_overlimit(sch); q->stats.penaltydrop++; goto drop; } goto enqueue; } r = prandom_u32() & SFB_MAX_PROB; if (unlikely(r < p_min)) { if (unlikely(p_min > SFB_MAX_PROB / 2)) { /* If we're marking that many packets, then either * this flow is unresponsive, or we're badly congested. * In either case, we want to start dropping packets. */ if (r < (p_min - SFB_MAX_PROB / 2) * 2) { q->stats.earlydrop++; goto drop; } } if (INET_ECN_set_ce(skb)) { q->stats.marked++; } else { q->stats.earlydrop++; goto drop; } } enqueue: ret = qdisc_enqueue(skb, child, to_free); if (likely(ret == NET_XMIT_SUCCESS)) { qdisc_qstats_backlog_inc(sch, skb); sch->q.qlen++; increment_qlen(skb, q); } else if (net_xmit_drop_count(ret)) { q->stats.childdrop++; qdisc_qstats_drop(sch); } return ret; drop: qdisc_drop(skb, sch, to_free); return NET_XMIT_CN; other_drop: if (ret & __NET_XMIT_BYPASS) qdisc_qstats_drop(sch); kfree_skb(skb); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_last(struct nameidata *nd, struct file *file, const struct open_flags *op) { struct dentry *dir = nd->path.dentry; int open_flag = op->open_flag; bool will_truncate = (open_flag & O_TRUNC) != 0; bool got_write = false; int acc_mode = op->acc_mode; unsigned seq; struct inode *inode; struct path path; int error; nd->flags &= ~LOOKUP_PARENT; nd->flags |= op->intent; if (nd->last_type != LAST_NORM) { error = handle_dots(nd, nd->last_type); if (unlikely(error)) return error; goto finish_open; } if (!(open_flag & O_CREAT)) { if (nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; /* we _can_ be in RCU mode here */ error = lookup_fast(nd, &path, &inode, &seq); if (likely(error > 0)) goto finish_lookup; if (error < 0) return error; BUG_ON(nd->inode != dir->d_inode); BUG_ON(nd->flags & LOOKUP_RCU); } else { /* create side of things */ /* * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED * has been cleared when we got to the last component we are * about to look up */ error = complete_walk(nd); if (error) return error; audit_inode(nd->name, dir, AUDIT_INODE_PARENT); /* trailing slashes? */ if (unlikely(nd->last.name[nd->last.len])) return -EISDIR; } if (open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) { error = mnt_want_write(nd->path.mnt); if (!error) got_write = true; /* * do _not_ fail yet - we might not need that or fail with * a different error; let lookup_open() decide; we'll be * dropping this one anyway. */ } if (open_flag & O_CREAT) inode_lock(dir->d_inode); else inode_lock_shared(dir->d_inode); error = lookup_open(nd, &path, file, op, got_write); if (open_flag & O_CREAT) inode_unlock(dir->d_inode); else inode_unlock_shared(dir->d_inode); if (error) goto out; if (file->f_mode & FMODE_OPENED) { if ((file->f_mode & FMODE_CREATED) || !S_ISREG(file_inode(file)->i_mode)) will_truncate = false; audit_inode(nd->name, file->f_path.dentry, 0); goto opened; } if (file->f_mode & FMODE_CREATED) { /* Don't check for write permission, don't truncate */ open_flag &= ~O_TRUNC; will_truncate = false; acc_mode = 0; path_to_nameidata(&path, nd); goto finish_open_created; } /* * If atomic_open() acquired write access it is dropped now due to * possible mount and symlink following (this might be optimized away if * necessary...) */ if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } error = follow_managed(&path, nd); if (unlikely(error < 0)) return error; /* * create/update audit record if it already exists. */ audit_inode(nd->name, path.dentry, 0); if (unlikely((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))) { path_to_nameidata(&path, nd); return -EEXIST; } seq = 0; /* out of RCU mode, so the value doesn't matter */ inode = d_backing_inode(path.dentry); finish_lookup: error = step_into(nd, &path, 0, inode, seq); if (unlikely(error)) return error; finish_open: /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ error = complete_walk(nd); if (error) return error; audit_inode(nd->name, nd->path.dentry, 0); if (open_flag & O_CREAT) { error = -EISDIR; if (d_is_dir(nd->path.dentry)) goto out; error = may_create_in_sticky(dir, d_backing_inode(nd->path.dentry)); if (unlikely(error)) goto out; } error = -ENOTDIR; if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry)) goto out; if (!d_is_reg(nd->path.dentry)) will_truncate = false; if (will_truncate) { error = mnt_want_write(nd->path.mnt); if (error) goto out; got_write = true; } finish_open_created: error = may_open(&nd->path, acc_mode, open_flag); if (error) goto out; BUG_ON(file->f_mode & FMODE_OPENED); /* once it's opened, it's opened */ error = vfs_open(&nd->path, file); if (error) goto out; opened: error = ima_file_check(file, op->acc_mode); if (!error && will_truncate) error = handle_truncate(file); out: if (unlikely(error > 0)) { WARN_ON(1); error = -EINVAL; } if (got_write) mnt_drop_write(nd->path.mnt); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'do_last(): fetch directory ->i_mode and ->i_uid before it's too late may_create_in_sticky() call is done when we already have dropped the reference to dir. Fixes: 30aba6656f61e (namei: allow restricted O_CREAT of FIFOs and regular files) Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tgetpass(const char *prompt, int timeout, int flags, struct sudo_conv_callback *callback) { struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm; struct sigaction savetstp, savettin, savettou; char *pass; static const char *askpass; static char buf[SUDO_CONV_REPL_MAX + 1]; int i, input, output, save_errno, ttyfd; bool need_restart, neednl = false; enum tgetpass_errval errval; debug_decl(tgetpass, SUDO_DEBUG_CONV); (void) fflush(stdout); if (askpass == NULL) { askpass = getenv_unhooked("SUDO_ASKPASS"); if (askpass == NULL || *askpass == '\0') askpass = sudo_conf_askpass_path(); } restart: /* Try to open /dev/tty if we are going to be using it for I/O. */ ttyfd = -1; if (!ISSET(flags, TGP_STDIN|TGP_ASKPASS)) { ttyfd = open(_PATH_TTY, O_RDWR); /* If no tty present and we need to disable echo, try askpass. */ if (ttyfd == -1 && !ISSET(flags, TGP_ECHO|TGP_NOECHO_TRY)) { if (askpass == NULL || getenv_unhooked("DISPLAY") == NULL) { sudo_warnx(U_("a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper")); debug_return_str(NULL); } SET(flags, TGP_ASKPASS); } } /* If using a helper program to get the password, run it instead. */ if (ISSET(flags, TGP_ASKPASS)) { if (askpass == NULL || *askpass == '\0') sudo_fatalx(U_("no askpass program specified, try setting SUDO_ASKPASS")); debug_return_str_masked(sudo_askpass(askpass, prompt)); } /* Reset state. */ for (i = 0; i < NSIG; i++) signo[i] = 0; pass = NULL; save_errno = 0; need_restart = false; /* Use tty for reading/writing if available else use stdin/stderr. */ if (ttyfd == -1) { input = STDIN_FILENO; output = STDERR_FILENO; } else { input = ttyfd; output = ttyfd; } /* * If we are using a tty but are not the foreground pgrp this will * return EINTR. We send ourself SIGTTOU bracketed by callbacks. */ if (!ISSET(flags, TGP_ECHO)) { for (;;) { if (ISSET(flags, TGP_MASK)) neednl = sudo_term_cbreak(input); else neednl = sudo_term_noecho(input); if (neednl || errno != EINTR) break; /* Received SIGTTOU, suspend the process. */ if (suspend(SIGTTOU, callback) == -1) { if (input != STDIN_FILENO) (void) close(input); debug_return_ptr(NULL); } } } /* * Catch signals that would otherwise cause the user to end * up with echo turned off in the shell. */ memset(&sa, 0, sizeof(sa)); sigemptyset(&sa.sa_mask); sa.sa_flags = 0; /* don't restart system calls */ sa.sa_handler = tgetpass_handler; (void) sigaction(SIGALRM, &sa, &savealrm); (void) sigaction(SIGINT, &sa, &saveint); (void) sigaction(SIGHUP, &sa, &savehup); (void) sigaction(SIGQUIT, &sa, &savequit); (void) sigaction(SIGTERM, &sa, &saveterm); (void) sigaction(SIGTSTP, &sa, &savetstp); (void) sigaction(SIGTTIN, &sa, &savettin); (void) sigaction(SIGTTOU, &sa, &savettou); if (ISSET(flags, TGP_BELL) && output != STDERR_FILENO) { /* Ring the bell if requested and there is a tty. */ if (write(output, "\a", 1) == -1) goto restore; } if (prompt) { if (write(output, prompt, strlen(prompt)) == -1) goto restore; } if (timeout > 0) alarm(timeout); pass = getln(input, buf, sizeof(buf), ISSET(flags, TGP_MASK), &errval); alarm(0); save_errno = errno; if (neednl || pass == NULL) { if (write(output, "\n", 1) == -1) goto restore; } tgetpass_display_error(errval); restore: /* Restore old signal handlers. */ (void) sigaction(SIGALRM, &savealrm, NULL); (void) sigaction(SIGINT, &saveint, NULL); (void) sigaction(SIGHUP, &savehup, NULL); (void) sigaction(SIGQUIT, &savequit, NULL); (void) sigaction(SIGTERM, &saveterm, NULL); (void) sigaction(SIGTSTP, &savetstp, NULL); (void) sigaction(SIGTTIN, &savettin, NULL); (void) sigaction(SIGTTOU, &savettou, NULL); /* Restore old tty settings. */ if (!ISSET(flags, TGP_ECHO)) { /* Restore old tty settings if possible. */ (void) sudo_term_restore(input, true); } if (input != STDIN_FILENO) (void) close(input); /* * If we were interrupted by a signal, resend it to ourselves * now that we have restored the signal handlers. */ for (i = 0; i < NSIG; i++) { if (signo[i]) { switch (i) { case SIGALRM: break; case SIGTSTP: case SIGTTIN: case SIGTTOU: if (suspend(i, callback) == 0) need_restart = true; break; default: kill(getpid(), i); break; } } } if (need_restart) goto restart; if (save_errno) errno = save_errno; debug_return_str_masked(pass); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix a buffer overflow when pwfeedback is enabled and input is a not a tty. In getln() if the user enters ^U (erase line) and the write(2) fails, the remaining buffer size is reset but the current pointer is not. While here, fix an incorrect break for erase when write(2) fails. Also disable pwfeedback when input is not a tty as it cannot work. CVE-2019-18634 Credit: Joe Vennix from Apple Information Security.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: repodata_schema2id(Repodata *data, Id *schema, int create) { int h, len, i; Id *sp, cid; Id *schematahash; if (!*schema) return 0; /* XXX: allow empty schema? */ if ((schematahash = data->schematahash) == 0) { data->schematahash = schematahash = solv_calloc(256, sizeof(Id)); for (i = 1; i < data->nschemata; i++) { for (sp = data->schemadata + data->schemata[i], h = 0; *sp;) h = h * 7 + *sp++; h &= 255; schematahash[h] = i; } data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK); } for (sp = schema, len = 0, h = 0; *sp; len++) h = h * 7 + *sp++; h &= 255; len++; cid = schematahash[h]; if (cid) { if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; /* cache conflict, do a slow search */ for (cid = 1; cid < data->nschemata; cid++) if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id))) return cid; } /* a new one */ if (!create) return 0; data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK); data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK); /* add schema */ memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id)); data->schemata[data->nschemata] = data->schemadatalen; data->schemadatalen += len; schematahash[h] = data->nschemata; #if 0 fprintf(stderr, "schema2id: new schema\n"); #endif return data->nschemata++; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'repodata_schema2id: fix heap-buffer-overflow in memcmp When the length of last schema in data->schemadata is less than length of input schema, we got a read overflow in asan test. Signed-off-by: Zhipeng Xie <xiezhipeng1@huawei.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char* skipSpaces( char* ptr ) { bool is_eof = false; bool is_completed = false; while ( is_eof == false && is_completed == false ) { switch ( *ptr ) { /* comment */ case '/' : { ptr++; if ( *ptr == '\0' ) { ptr = fs->gets(); if( !ptr || !*ptr ) { is_eof = true; break; } } if ( *ptr == '/' ) { while ( *ptr != '\n' && *ptr != '\r' ) { if ( *ptr == '\0' ) { ptr = fs->gets(); if( !ptr || !*ptr ) { is_eof = true; break; } } else { ptr++; } } } else if ( *ptr == '*' ) { ptr++; for (;;) { if ( *ptr == '\0' ) { ptr = fs->gets(); if( !ptr || !*ptr ) { is_eof = true; break; } } else if ( *ptr == '*' ) { ptr++; if ( *ptr == '\0' ) { ptr = fs->gets(); if( !ptr || !*ptr ) { is_eof = true; break; } } if ( *ptr == '/' ) { ptr++; break; } } else { ptr++; } } } else { CV_PARSE_ERROR_CPP( "Not supported escape character" ); } } break; /* whitespace */ case '\t': case ' ' : { ptr++; } break; /* newline || end mark */ case '\0': case '\n': case '\r': { ptr = fs->gets(); if( !ptr || !*ptr ) { is_eof = true; break; } } break; /* other character */ default: { if( !cv_isprint(*ptr) ) CV_PARSE_ERROR_CPP( "Invalid character in the stream" ); is_completed = true; } break; } } if ( is_eof || !is_completed ) { ptr = fs->bufferStart(); *ptr = '\0'; fs->setEof(); if( !is_completed ) CV_PARSE_ERROR_CPP( "Abort at parse time" ); } return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char* parseValue( char* ptr, FileNode& node, int min_indent, bool is_parent_flow ) { char* endptr = 0; char c = ptr[0], d = ptr[1]; int value_type = FileNode::NONE; int len; bool is_binary_string = false; bool is_user = false; if( c == '!' ) // handle explicit type specification { if( d == '!' || d == '^' ) { ptr++; is_user = true; //value_type |= FileNode::USER; } if ( d == '<') //support of full type heading from YAML 1.2 { const char* yamlTypeHeading = "<tag:yaml.org,2002:"; const size_t headingLenght = strlen(yamlTypeHeading); char* typeEndPtr = ++ptr; do d = *++typeEndPtr; while( cv_isprint(d) && d != ' ' && d != '>' ); if ( d == '>' && (size_t)(typeEndPtr - ptr) > headingLenght ) { if ( memcmp(ptr, yamlTypeHeading, headingLenght) == 0 ) { *typeEndPtr = ' '; ptr += headingLenght - 1; is_user = true; //value_type |= FileNode::USER; } } } endptr = ptr++; do d = *++endptr; while( cv_isprint(d) && d != ' ' ); len = (int)(endptr - ptr); if( len == 0 ) CV_PARSE_ERROR_CPP( "Empty type name" ); d = *endptr; *endptr = '\0'; if( len == 3 && !is_user ) { if( memcmp( ptr, "str", 3 ) == 0 ) value_type = FileNode::STRING; else if( memcmp( ptr, "int", 3 ) == 0 ) value_type = FileNode::INT; else if( memcmp( ptr, "seq", 3 ) == 0 ) value_type = FileNode::SEQ; else if( memcmp( ptr, "map", 3 ) == 0 ) value_type = FileNode::MAP; } else if( len == 5 && !is_user ) { if( memcmp( ptr, "float", 5 ) == 0 ) value_type = FileNode::REAL; } else if (len == 6 && is_user) { if( memcmp( ptr, "binary", 6 ) == 0 ) { value_type = FileNode::SEQ; is_binary_string = true; /* for ignore '|' */ /**** operation with endptr ****/ *endptr = d; do { d = *++endptr; if (d == '|') break; } while (d == ' '); d = *++endptr; *endptr = '\0'; } } *endptr = d; ptr = skipSpaces( endptr, min_indent, INT_MAX ); c = *ptr; if( !is_user ) { if (value_type == FileNode::STRING && c != '\'' && c != '\"') goto force_string; if( value_type == FileNode::INT ) goto force_int; if( value_type == FileNode::REAL ) goto force_real; } } if (is_binary_string) { int indent = static_cast<int>(ptr - fs->bufferStart()); ptr = fs->parseBase64(ptr, indent, node); } else if( cv_isdigit(c) || ((c == '-' || c == '+') && (cv_isdigit(d) || d == '.')) || (c == '.' && cv_isalnum(d))) // a number { endptr = ptr + (c == '-' || c == '+'); while( cv_isdigit(*endptr) ) endptr++; if( *endptr == '.' || *endptr == 'e' ) { force_real: double fval = fs->strtod( ptr, &endptr ); node.setValue(FileNode::REAL, &fval); } else { force_int: int ival = (int)strtol( ptr, &endptr, 0 ); node.setValue(FileNode::INT, &ival); } if( !endptr || endptr == ptr ) CV_PARSE_ERROR_CPP( "Invalid numeric value (inconsistent explicit type specification?)" ); ptr = endptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); } else if( c == '\'' || c == '\"' ) // an explicit string { if( c == '\'' ) for( len = 0; len < CV_FS_MAX_LEN; ) { c = *++ptr; if( cv_isalnum(c) || (c != '\'' && cv_isprint(c))) buf[len++] = c; else if( c == '\'' ) { c = *++ptr; if( c != '\'' ) break; buf[len++] = c; } else CV_PARSE_ERROR_CPP( "Invalid character" ); } else for( len = 0; len < CV_FS_MAX_LEN; ) { c = *++ptr; if( cv_isalnum(c) || (c != '\\' && c != '\"' && cv_isprint(c))) buf[len++] = c; else if( c == '\"' ) { ++ptr; break; } else if( c == '\\' ) { d = *++ptr; if( d == '\'' ) buf[len++] = d; else if( d == '\"' || d == '\\' || d == '\'' ) buf[len++] = d; else if( d == 'n' ) buf[len++] = '\n'; else if( d == 'r' ) buf[len++] = '\r'; else if( d == 't' ) buf[len++] = '\t'; else if( d == 'x' || (cv_isdigit(d) && d < '8') ) { int val, is_hex = d == 'x'; c = ptr[3]; ptr[3] = '\0'; val = (int)strtol( ptr + is_hex, &endptr, is_hex ? 8 : 16 ); ptr[3] = c; if( endptr == ptr + is_hex ) buf[len++] = 'x'; else { buf[len++] = (char)val; ptr = endptr; } } } else CV_PARSE_ERROR_CPP( "Invalid character" ); } if( len >= CV_FS_MAX_LEN ) CV_PARSE_ERROR_CPP( "Too long string literal" ); node.setValue(FileNode::STRING, buf, len); } else if( c == '[' || c == '{' ) // collection as a flow { int new_min_indent = min_indent + !is_parent_flow; int struct_type = c == '{' ? FileNode::MAP : FileNode::SEQ; int nelems = 0; fs->convertToCollection(struct_type, node); d = c == '[' ? ']' : '}'; for( ++ptr ;; nelems++ ) { FileNode elem; ptr = skipSpaces( ptr, new_min_indent, INT_MAX ); if( *ptr == '}' || *ptr == ']' ) { if( *ptr != d ) CV_PARSE_ERROR_CPP( "The wrong closing bracket" ); ptr++; break; } if( nelems != 0 ) { if( *ptr != ',' ) CV_PARSE_ERROR_CPP( "Missing , between the elements" ); ptr = skipSpaces( ptr + 1, new_min_indent, INT_MAX ); } if( struct_type == FileNode::MAP ) { ptr = parseKey( ptr, node, elem ); ptr = skipSpaces( ptr, new_min_indent, INT_MAX ); } else { if( *ptr == ']' ) break; elem = fs->addNode(node, std::string(), FileNode::NONE); } ptr = parseValue( ptr, elem, new_min_indent, true ); } fs->finalizeCollection(node); } else { int indent, struct_type; if( is_parent_flow || c != '-' ) { // implicit (one-line) string or nested block-style collection if( !is_parent_flow ) { if( c == '?' ) CV_PARSE_ERROR_CPP( "Complex keys are not supported" ); if( c == '|' || c == '>' ) CV_PARSE_ERROR_CPP( "Multi-line text literals are not supported" ); } force_string: endptr = ptr - 1; do c = *++endptr; while( cv_isprint(c) && (!is_parent_flow || (c != ',' && c != '}' && c != ']')) && (is_parent_flow || c != ':' || value_type == FileNode::STRING)); if( endptr == ptr ) CV_PARSE_ERROR_CPP( "Invalid character" ); if( is_parent_flow || c != ':' ) { char* str_end = endptr; // strip spaces in the end of string do c = *--str_end; while( str_end > ptr && c == ' ' ); str_end++; node.setValue(FileNode::STRING, ptr, (int)(str_end - ptr)); ptr = endptr; return ptr; } struct_type = FileNode::MAP; } else struct_type = FileNode::SEQ; fs->convertToCollection( struct_type, node ); indent = (int)(ptr - fs->bufferStart()); for(;;) { FileNode elem; if( struct_type == FileNode::MAP ) { ptr = parseKey( ptr, node, elem ); } else { c = *ptr++; if( c != '-' ) CV_PARSE_ERROR_CPP( "Block sequence elements must be preceded with \'-\'" ); elem = fs->addNode(node, std::string(), FileNode::NONE); } ptr = skipSpaces( ptr, indent + 1, INT_MAX ); ptr = parseValue( ptr, elem, indent + 1, false ); ptr = skipSpaces( ptr, 0, INT_MAX ); if( ptr - fs->bufferStart() != indent ) { if( ptr - fs->bufferStart() < indent ) break; else CV_PARSE_ERROR_CPP( "Incorrect indentation" ); } if( memcmp( ptr, "...", 3 ) == 0 ) break; } fs->finalizeCollection(node); } return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool parse( char* ptr ) { ptr = skipSpaces( ptr ); if ( !ptr || !*ptr ) return false; FileNode root_collection(fs->getFS(), 0, 0); if( *ptr == '{' ) { FileNode root_node = fs->addNode(root_collection, std::string(), FileNode::MAP); parseMap( ptr, root_node ); } else if ( *ptr == '[' ) { FileNode root_node = fs->addNode(root_collection, std::string(), FileNode::SEQ); parseSeq( ptr, root_node ); } else { CV_PARSE_ERROR_CPP( "left-brace of top level is missing" ); } if( !ptr || !*ptr ) CV_PARSE_ERROR_CPP( "Unexpected End-Of-File" ); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool parse(char* ptr) { CV_Assert( fs != 0 ); std::string key, key2, type_name; int tag_type = 0; bool ok = false; // CV_XML_INSIDE_TAG is used to prohibit leading comments ptr = skipSpaces( ptr, CV_XML_INSIDE_TAG ); if( memcmp( ptr, "<?xml", 5 ) != 0 ) // FIXIT ptr[1..] - out of bounds read without check CV_PARSE_ERROR_CPP( "Valid XML should start with \'<?xml ...?>\'" ); ptr = parseTag( ptr, key, type_name, tag_type ); FileNode root_collection(fs->getFS(), 0, 0); while( ptr && *ptr != '\0' ) { ptr = skipSpaces( ptr, 0 ); if( *ptr != '\0' ) { ptr = parseTag( ptr, key, type_name, tag_type ); if( tag_type != CV_XML_OPENING_TAG || key != "opencv_storage" ) CV_PARSE_ERROR_CPP( "<opencv_storage> tag is missing" ); FileNode root = fs->addNode(root_collection, std::string(), FileNode::MAP, 0); ptr = parseValue( ptr, root ); ptr = parseTag( ptr, key2, type_name, tag_type ); if( tag_type != CV_XML_CLOSING_TAG || key != key2 ) CV_PARSE_ERROR_CPP( "</opencv_storage> tag is missing" ); ptr = skipSpaces( ptr, 0 ); ok = true; } } CV_Assert( fs->eof() ); return ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool getBase64Row(char* ptr, int indent, char* &beg, char* &end) { beg = end = ptr = skipSpaces(ptr, 0, INT_MAX); if (!ptr || !*ptr) return false; // end of file if (ptr - fs->bufferStart() != indent) return false; // end of base64 data /* find end */ while(cv_isprint(*ptr)) /* no check for base64 string */ ++ptr; if (*ptr == '\0') CV_PARSE_ERROR_CPP("Unexpected end of line"); end = ptr; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char* parseValue( char* ptr, FileNode& node ) { FileNode new_elem; bool have_space = true; int value_type = node.type(); std::string key, key2, type_name; for(;;) { char c = *ptr, d; char* endptr; // FIXIT ptr[1], ptr[2] - out of bounds read without check or data fetch (#11061) if( cv_isspace(c) || c == '\0' || (c == '<' && ptr[1] == '!' && ptr[2] == '-') ) { ptr = skipSpaces( ptr, 0 ); have_space = true; c = *ptr; } d = ptr[1]; // FIXIT ptr[1] - out of bounds read without check or data fetch (#11061) if( c =='<' || c == '\0' ) { int tag_type = 0; int elem_type = FileNode::NONE; if( d == '/' || c == '\0' ) break; ptr = parseTag( ptr, key, type_name, tag_type ); if( tag_type == CV_XML_DIRECTIVE_TAG ) CV_PARSE_ERROR_CPP( "Directive tags are not allowed here" ); if( tag_type == CV_XML_EMPTY_TAG ) CV_PARSE_ERROR_CPP( "Empty tags are not supported" ); CV_Assert(tag_type == CV_XML_OPENING_TAG); /* for base64 string */ bool binary_string = false; if( !type_name.empty() ) { const char* tn = type_name.c_str(); if( strcmp(tn, "str") == 0 ) elem_type = FileNode::STRING; else if( strcmp( tn, "map" ) == 0 ) elem_type = FileNode::MAP; else if( strcmp( tn, "seq" ) == 0 ) elem_type = FileNode::SEQ; else if( strcmp( tn, "binary") == 0) binary_string = true; } new_elem = fs->addNode(node, key, elem_type, 0); if (!binary_string) ptr = parseValue(ptr, new_elem); else { ptr = fs->parseBase64( ptr, 0, new_elem); ptr = skipSpaces( ptr, 0 ); } ptr = parseTag( ptr, key2, type_name, tag_type ); if( tag_type != CV_XML_CLOSING_TAG || key2 != key ) CV_PARSE_ERROR_CPP( "Mismatched closing tag" ); have_space = true; } else { if( !have_space ) CV_PARSE_ERROR_CPP( "There should be space between literals" ); FileNode* elem = &node; if( node.type() != FileNode::NONE ) { fs->convertToCollection( FileNode::SEQ, node ); new_elem = fs->addNode(node, std::string(), FileNode::NONE, 0); elem = &new_elem; } if( value_type != FileNode::STRING && (cv_isdigit(c) || ((c == '-' || c == '+') && (cv_isdigit(d) || d == '.')) || (c == '.' && cv_isalnum(d))) ) // a number { endptr = ptr + (c == '-' || c == '+'); while( cv_isdigit(*endptr) ) endptr++; if( *endptr == '.' || *endptr == 'e' ) { double fval = fs->strtod( ptr, &endptr ); elem->setValue(FileNode::REAL, &fval); } else { int ival = (int)strtol( ptr, &endptr, 0 ); elem->setValue(FileNode::INT, &ival); } if( endptr == ptr ) CV_PARSE_ERROR_CPP( "Invalid numeric value (inconsistent explicit type specification?)" ); ptr = endptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); } else { // string int i = 0, len, is_quoted = 0; if( c == '\"' ) is_quoted = 1; else --ptr; strbuf[0] = '\0'; for( ;; ) { c = *++ptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); if( !cv_isalnum(c) ) { if( c == '\"' ) { if( !is_quoted ) CV_PARSE_ERROR_CPP( "Literal \" is not allowed within a string. Use &quot;" ); ++ptr; break; } else if( !cv_isprint(c) || c == '<' || (!is_quoted && cv_isspace(c))) { if( is_quoted ) CV_PARSE_ERROR_CPP( "Closing \" is expected" ); break; } else if( c == '\'' || c == '>' ) { CV_PARSE_ERROR_CPP( "Literal \' or > are not allowed. Use &apos; or &gt;" ); } else if( c == '&' ) { if( *++ptr == '#' ) { int val, base = 10; ptr++; if( *ptr == 'x' ) { base = 16; ptr++; } val = (int)strtol( ptr, &endptr, base ); if( (unsigned)val > (unsigned)255 || !endptr || *endptr != ';' ) CV_PARSE_ERROR_CPP( "Invalid numeric value in the string" ); c = (char)val; } else { endptr = ptr; do c = *++endptr; while( cv_isalnum(c) ); if( c != ';' ) CV_PARSE_ERROR_CPP( "Invalid character in the symbol entity name" ); len = (int)(endptr - ptr); if( len == 2 && memcmp( ptr, "lt", len ) == 0 ) c = '<'; else if( len == 2 && memcmp( ptr, "gt", len ) == 0 ) c = '>'; else if( len == 3 && memcmp( ptr, "amp", len ) == 0 ) c = '&'; else if( len == 4 && memcmp( ptr, "apos", len ) == 0 ) c = '\''; else if( len == 4 && memcmp( ptr, "quot", len ) == 0 ) c = '\"'; else { memcpy( strbuf + i, ptr-1, len + 2 ); i += len + 2; } } ptr = endptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); } } strbuf[i++] = c; if( i >= CV_FS_MAX_LEN ) CV_PARSE_ERROR_CPP( "Too long string literal" ); } elem->setValue(FileNode::STRING, strbuf, i); } if( value_type != FileNode::NONE && value_type != FileNode::SEQ && value_type != FileNode::MAP ) break; have_space = false; } } fs->finalizeCollection(node); return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char* parseKey( char* ptr, FileNode& collection, FileNode& value_placeholder ) { if( *ptr != '"' ) CV_PARSE_ERROR_CPP( "Key must start with \'\"\'" ); char * beg = ptr + 1; do { ++ptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); } while( cv_isprint(*ptr) && *ptr != '"' ); if( *ptr != '"' ) CV_PARSE_ERROR_CPP( "Key must end with \'\"\'" ); const char * end = ptr; ptr++; ptr = skipSpaces( ptr ); if( !ptr || !*ptr ) return 0; if( *ptr != ':' ) CV_PARSE_ERROR_CPP( "Missing \':\' between key and value" ); /* [beg, end) */ if( end <= beg ) CV_PARSE_ERROR_CPP( "Key is empty" ); value_placeholder = fs->addNode(collection, std::string(beg, (size_t)(end - beg)), FileNode::NONE); return ++ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'core(persistence): added null ptr checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void * adminchild(struct clientparam* param) { int i, res; char * buf; char username[256]; char *sb; char *req = NULL; struct printparam pp; int contentlen = 0; int isform = 0; pp.inbuf = 0; pp.cp = param; buf = myalloc(LINESIZE); if(!buf) {RETURN(555);} i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]); if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') && (buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/'))) { RETURN(701); } buf[i] = 0; sb = strchr(buf+5, ' '); if(!sb){ RETURN(702); } *sb = 0; req = mystrdup(buf + ((*buf == 'P')? 6 : 5)); while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){ buf[i] = 0; if(i > 19 && (!strncasecmp(buf, "authorization", 13))){ sb = strchr(buf, ':'); if(!sb)continue; ++sb; while(isspace(*sb))sb++; if(!*sb || strncasecmp(sb, "basic", 5)){ continue; } sb+=5; while(isspace(*sb))sb++; i = de64((unsigned char *)sb, (unsigned char *)username, 255); if(i<=0)continue; username[i] = 0; sb = strchr((char *)username, ':'); if(sb){ *sb = 0; if(param->password)myfree(param->password); param->password = (unsigned char *)mystrdup(sb+1); } if(param->username) myfree(param->username); param->username = (unsigned char *)mystrdup(username); continue; } else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){ sb = buf + 15; while(isspace(*sb))sb++; contentlen = atoi(sb); } else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){ sb = buf + 13; while(isspace(*sb))sb++; if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1; } } param->operation = ADMIN; if(isform && contentlen) { printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n"); stdpr(&pp, NULL, 0); } res = (*param->srv->authfunc)(param); if(res && res != 10) { printstr(&pp, authreq); RETURN(res); } if(param->srv->singlepacket || param->redirected){ if(*req == 'C') req[1] = 0; else *req = 0; } sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:""); if(*req != 'S') printstr(&pp, buf); switch(*req){ case 'C': printstr(&pp, counters); { struct trafcount *cp; int num = 0; for(cp = conf.trafcounter; cp; cp = cp->next, num++){ int inbuf = 0; if(cp->ace && (param->srv->singlepacket || param->redirected)){ if(!ACLmatches(cp->ace, param))continue; } if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0; if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1; inbuf += sprintf(buf, "<tr>" "<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>", (cp->comment)?cp->comment:"&nbsp;", (cp->disabled)?'S':'D', num, (cp->disabled)?"NO":"YES" ); if(!cp->ace || !cp->ace->users){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->src){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->dst){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->ports){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n"); } if(cp->type == NONE) { inbuf += sprintf(buf+inbuf, "</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n" ); } else { inbuf += sprintf(buf+inbuf, "</td><td>%"PRINTF_INT64_MODIFIER"u</td>" "<td>MB%s</td>" "<td>%"PRINTF_INT64_MODIFIER"u</td>" "<td>%s</td>", cp->traflim64 / (1024 * 1024), rotations[cp->type], cp->traf64, cp->cleared?ctime(&cp->cleared):"never" ); inbuf += sprintf(buf + inbuf, "<td>%s</td>" "<td>%i</td>" "</tr>\r\n", cp->updated?ctime(&cp->updated):"never", cp->number ); } printstr(&pp, buf); } } printstr(&pp, counterstail); break; case 'R': conf.needreload = 1; printstr(&pp, "<h3>Reload scheduled</h3>"); break; case 'S': { if(req[1] == 'X'){ printstr(&pp, style); break; } printstr(&pp, xml); printval(conf.services, TYPE_SERVER, 0, &pp); printstr(&pp, postxml); } break; case 'F': { FILE *fp; char buf[256]; fp = confopen(); if(!fp){ printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>"); break; } printstr(&pp, "<h3>Please be careful editing config file remotely</h3>"); printstr(&pp, "<form method=\"POST\" action=\"/U\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">"); while(fgets(buf, 256, fp)){ printstr(&pp, buf); } if(!writable) fclose(fp); printstr(&pp, "</textarea><br><input type=\"Submit\"></form>"); break; } case 'U': { int l=0; int error = 0; if(!writable || fseek(writable, 0, 0)){ error = 1; } while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '+', conf.timeouts[STRING_S])) > 0){ if(i > (contentlen - l)) i = (contentlen - l); buf[i] = 0; if(!l){ if(strncasecmp(buf, "conffile=", 9)) error = 1; } if(!error){ decodeurl((unsigned char *)buf, 1); fprintf(writable, "%s", l? buf : buf + 9); } l += i; if(l >= contentlen) break; } if(writable && !error){ fflush(writable); #ifndef _WINCE ftruncate(fileno(writable), ftell(writable)); #endif } printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file": "<h3>Configuration updated</h3>"); } break; default: printstr(&pp, (char *)conf.stringtable[WEBBANNERS]); break; } if(*req != 'S') printstr(&pp, tail); CLEANRET: printstr(&pp, NULL); if(buf) myfree(buf); (*param->srv->logfunc)(param, (unsigned char *)req); if(req)myfree(req); freeparam(param); return (NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Fix: out-of-bounds write and few more bugs in 'admin' configuration upload'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mbfl_filt_conv_big5_wchar(int c, mbfl_convert_filter *filter) { int k; int c1, w, c2; switch (filter->status) { case 0: if (filter->from->no_encoding == mbfl_no_encoding_cp950) { c1 = 0x80; } else { c1 = 0xa0; } if (c >= 0 && c <= 0x80) { /* latin */ CK((*filter->output_function)(c, filter->data)); } else if (c == 0xff) { CK((*filter->output_function)(0xf8f8, filter->data)); } else if (c > c1 && c < 0xff) { /* dbcs lead byte */ filter->status = 1; filter->cache = c; } else { w = c & MBFL_WCSGROUP_MASK; w |= MBFL_WCSGROUP_THROUGH; CK((*filter->output_function)(w, filter->data)); } break; case 1: /* dbcs second byte */ filter->status = 0; c1 = filter->cache; if ((c > 0x39 && c < 0x7f) | (c > 0xa0 && c < 0xff)) { if (c < 0x7f){ w = (c1 - 0xa1)*157 + (c - 0x40); } else { w = (c1 - 0xa1)*157 + (c - 0xa1) + 0x3f; } if (w >= 0 && w < big5_ucs_table_size) { w = big5_ucs_table[w]; } else { w = 0; } if (filter->from->no_encoding == mbfl_no_encoding_cp950) { /* PUA for CP950 */ if (w <= 0 && (((c1 >= 0xfa && c1 <= 0xfe) || (c1 >= 0x8e && c1 <= 0xa0) || (c1 >= 0x81 && c1 <= 0x8d) ||(c1 >= 0xc7 && c1 <= 0xc8)) && ((c > 0x39 && c < 0x7f) || (c > 0xa0 && c < 0xff))) || ((c1 == 0xc6) && (c > 0xa0 && c < 0xff))) { c2 = c1 << 8 | c; for (k = 0; k < sizeof(cp950_pua_tbl)/(sizeof(unsigned short)*4); k++) { if (c2 >= cp950_pua_tbl[k][2] && c2 <= cp950_pua_tbl[k][3]) { break; } } if ((cp950_pua_tbl[k][2] & 0xff) == 0x40) { w = 157*(c1 - (cp950_pua_tbl[k][2]>>8)) + c - (c >= 0xa1 ? 0x62 : 0x40) + cp950_pua_tbl[k][0]; } else { w = c2 - cp950_pua_tbl[k][2] + cp950_pua_tbl[k][0]; } } } if (w <= 0) { w = (c1 << 8) | c; w &= MBFL_WCSPLANE_MASK; w |= MBFL_WCSPLANE_BIG5; } CK((*filter->output_function)(w, filter->data)); } else if ((c >= 0 && c < 0x21) || c == 0x7f) { /* CTLs */ CK((*filter->output_function)(c, filter->data)); } else { w = (c1 << 8) | c; w &= MBFL_WCSGROUP_MASK; w |= MBFL_WCSGROUP_THROUGH; CK((*filter->output_function)(w, filter->data)); } break; default: filter->status = 0; break; } return c; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #79037 (global buffer-overflow in `mbfl_filt_conv_big5_wchar`)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6, const struct sk_buff *skb, int flags, pol_lookup_t lookup) { struct rt6_info *rt; rt = lookup(net, net->ipv6.fib6_main_tbl, fl6, skb, flags); if (rt->dst.error == -EAGAIN) { ip6_rt_put_flags(rt, flags); rt = net->ipv6.ip6_null_entry; if (!(flags | RT6_LOOKUP_F_DST_NOREF)) dst_hold(&rt->dst); } return &rt->dst; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-755'], 'message': 'ipv6: fix a typo in fib6_rule_lookup() Yi Ren reported an issue discovered by syzkaller, and bisected to the cited commit. Many thanks to Yi, this trivial patch does not reflect the patient work that has been done. Fixes: d64a1f574a29 ("ipv6: honor RT6_LOOKUP_F_DST_NOREF in rule lookup logic") Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Wei Wang <weiwan@google.com> Bisected-and-reported-by: Yi Ren <c4tren@gmail.com> Signed-off-by: Jakub Kicinski <jakub.kicinski@netronome.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: read_fru_area_section(struct ipmi_intf * intf, struct fru_info *fru, uint8_t id, uint32_t offset, uint32_t length, uint8_t *frubuf) { static uint32_t fru_data_rqst_size = 20; uint32_t off = offset, tmp, finish; struct ipmi_rs * rsp; struct ipmi_rq req; uint8_t msg_data[4]; if (offset > fru->size) { lprintf(LOG_ERR, "Read FRU Area offset incorrect: %d > %d", offset, fru->size); return -1; } finish = offset + length; if (finish > fru->size) { finish = fru->size; lprintf(LOG_NOTICE, "Read FRU Area length %d too large, " "Adjusting to %d", offset + length, finish - offset); } memset(&req, 0, sizeof(req)); req.msg.netfn = IPMI_NETFN_STORAGE; req.msg.cmd = GET_FRU_DATA; req.msg.data = msg_data; req.msg.data_len = 4; #ifdef LIMIT_ALL_REQUEST_SIZE if (fru_data_rqst_size > 16) #else if (fru->access && fru_data_rqst_size > 16) #endif fru_data_rqst_size = 16; do { tmp = fru->access ? off >> 1 : off; msg_data[0] = id; msg_data[1] = (uint8_t)(tmp & 0xff); msg_data[2] = (uint8_t)(tmp >> 8); tmp = finish - off; if (tmp > fru_data_rqst_size) msg_data[3] = (uint8_t)fru_data_rqst_size; else msg_data[3] = (uint8_t)tmp; rsp = intf->sendrecv(intf, &req); if (!rsp) { lprintf(LOG_NOTICE, "FRU Read failed"); break; } if (rsp->ccode) { /* if we get C7 or C8 or CA return code then we requested too * many bytes at once so try again with smaller size */ if (fru_cc_rq2big(rsp->ccode) && (--fru_data_rqst_size > FRU_BLOCK_SZ)) { lprintf(LOG_INFO, "Retrying FRU read with request size %d", fru_data_rqst_size); continue; } lprintf(LOG_NOTICE, "FRU Read failed: %s", val2str(rsp->ccode, completion_code_vals)); break; } tmp = fru->access ? rsp->data[0] << 1 : rsp->data[0]; memcpy((frubuf + off)-offset, rsp->data + 1, tmp); off += tmp; /* sometimes the size returned in the Info command * is too large. return 0 so higher level function * still attempts to parse what was returned */ if (tmp == 0 && off < finish) return 0; } while (off < finish); if (off < finish) return -1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'fru: Fix buffer overflow vulnerabilities Partial fix for CVE-2020-5208, see https://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp The `read_fru_area_section` function only performs size validation of requested read size, and falsely assumes that the IPMI message will not respond with more than the requested amount of data; it uses the unvalidated response size to copy into `frubuf`. If the response is larger than the request, this can result in overflowing the buffer. The same issue affects the `read_fru_area` function.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ipmi_sdr_print_sensor_generic_locator(struct sdr_record_generic_locator *dev) { char desc[17]; memset(desc, 0, sizeof (desc)); snprintf(desc, (dev->id_code & 0x1f) + 1, "%s", dev->id_string); if (!verbose) { if (csv_output) printf("%s,00h,ns,%d.%d\n", dev->id_code ? desc : "", dev->entity.id, dev->entity.instance); else if (sdr_extended) printf ("%-16s | 00h | ns | %2d.%1d | Generic Device @%02Xh:%02Xh.%1d\n", dev->id_code ? desc : "", dev->entity.id, dev->entity.instance, dev->dev_access_addr, dev->dev_slave_addr, dev->oem); else printf("%-16s | Generic @%02X:%02X.%-2d | ok\n", dev->id_code ? desc : "", dev->dev_access_addr, dev->dev_slave_addr, dev->oem); return 0; } printf("Device ID : %s\n", dev->id_string); printf("Entity ID : %d.%d (%s)\n", dev->entity.id, dev->entity.instance, val2str(dev->entity.id, entity_id_vals)); printf("Device Access Address : %02Xh\n", dev->dev_access_addr); printf("Device Slave Address : %02Xh\n", dev->dev_slave_addr); printf("Address Span : %02Xh\n", dev->addr_span); printf("Channel Number : %01Xh\n", dev->channel_num); printf("LUN.Bus : %01Xh.%01Xh\n", dev->lun, dev->bus); printf("Device Type.Modifier : %01Xh.%01Xh (%s)\n", dev->dev_type, dev->dev_type_modifier, val2str(dev->dev_type << 8 | dev->dev_type_modifier, entity_device_type_vals)); printf("OEM : %02Xh\n", dev->oem); printf("\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'fru, sdr: Fix id_string buffer overflows Final part of the fixes for CVE-2020-5208, see https://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp 9 variants of stack buffer overflow when parsing `id_string` field of SDR records returned from `CMD_GET_SDR` command. SDR record structs have an `id_code` field, and an `id_string` `char` array. The length of `id_string` is calculated as `(id_code & 0x1f) + 1`, which can be larger than expected 16 characters (if `id_code = 0xff`, then length will be `(0xff & 0x1f) + 1 = 32`). In numerous places, this can cause stack buffer overflow when copying into fixed buffer of size `17` bytes from this calculated length.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ipmi_sdr_print_name_from_rawentry(uint16_t id, uint8_t type, uint8_t *raw) { union { struct sdr_record_full_sensor *full; struct sdr_record_compact_sensor *compact; struct sdr_record_eventonly_sensor *eventonly; struct sdr_record_generic_locator *genloc; struct sdr_record_fru_locator *fruloc; struct sdr_record_mc_locator *mcloc; struct sdr_record_entity_assoc *entassoc; struct sdr_record_oem *oem; } record; int rc =0; char desc[17]; memset(desc, ' ', sizeof (desc)); switch ( type) { case SDR_RECORD_TYPE_FULL_SENSOR: record.full = (struct sdr_record_full_sensor *) raw; snprintf(desc, (record.full->id_code & 0x1f) +1, "%s", (const char *)record.full->id_string); break; case SDR_RECORD_TYPE_COMPACT_SENSOR: record.compact = (struct sdr_record_compact_sensor *) raw ; snprintf(desc, (record.compact->id_code & 0x1f) +1, "%s", (const char *)record.compact->id_string); break; case SDR_RECORD_TYPE_EVENTONLY_SENSOR: record.eventonly = (struct sdr_record_eventonly_sensor *) raw ; snprintf(desc, (record.eventonly->id_code & 0x1f) +1, "%s", (const char *)record.eventonly->id_string); break; case SDR_RECORD_TYPE_MC_DEVICE_LOCATOR: record.mcloc = (struct sdr_record_mc_locator *) raw ; snprintf(desc, (record.mcloc->id_code & 0x1f) +1, "%s", (const char *)record.mcloc->id_string); break; default: rc = -1; break; } lprintf(LOG_INFO, "ID: 0x%04x , NAME: %-16s", id, desc); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'fru, sdr: Fix id_string buffer overflows Final part of the fixes for CVE-2020-5208, see https://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp 9 variants of stack buffer overflow when parsing `id_string` field of SDR records returned from `CMD_GET_SDR` command. SDR record structs have an `id_code` field, and an `id_string` `char` array. The length of `id_string` is calculated as `(id_code & 0x1f) + 1`, which can be larger than expected 16 characters (if `id_code = 0xff`, then length will be `(0xff & 0x1f) + 1 = 32`). In numerous places, this can cause stack buffer overflow when copying into fixed buffer of size `17` bytes from this calculated length.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ipmi_sdr_print_sensor_eventonly(struct ipmi_intf *intf, struct sdr_record_eventonly_sensor *sensor) { char desc[17]; if (!sensor) return -1; memset(desc, 0, sizeof (desc)); snprintf(desc, (sensor->id_code & 0x1f) + 1, "%s", sensor->id_string); if (verbose) { printf("Sensor ID : %s (0x%x)\n", sensor->id_code ? desc : "", sensor->keys.sensor_num); printf("Entity ID : %d.%d (%s)\n", sensor->entity.id, sensor->entity.instance, val2str(sensor->entity.id, entity_id_vals)); printf("Sensor Type : %s (0x%02x)\n", ipmi_get_sensor_type(intf, sensor->sensor_type), sensor->sensor_type); lprintf(LOG_DEBUG, "Event Type Code : 0x%02x", sensor->event_type); printf("\n"); } else { if (csv_output) printf("%s,%02Xh,ns,%d.%d,Event-Only\n", sensor->id_code ? desc : "", sensor->keys.sensor_num, sensor->entity.id, sensor->entity.instance); else if (sdr_extended) printf("%-16s | %02Xh | ns | %2d.%1d | Event-Only\n", sensor->id_code ? desc : "", sensor->keys.sensor_num, sensor->entity.id, sensor->entity.instance); else printf("%-16s | Event-Only | ns\n", sensor->id_code ? desc : ""); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'fru, sdr: Fix id_string buffer overflows Final part of the fixes for CVE-2020-5208, see https://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp 9 variants of stack buffer overflow when parsing `id_string` field of SDR records returned from `CMD_GET_SDR` command. SDR record structs have an `id_code` field, and an `id_string` `char` array. The length of `id_string` is calculated as `(id_code & 0x1f) + 1`, which can be larger than expected 16 characters (if `id_code = 0xff`, then length will be `(0xff & 0x1f) + 1 = 32`). In numerous places, this can cause stack buffer overflow when copying into fixed buffer of size `17` bytes from this calculated length.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ipmi_get_channel_cipher_suites(struct ipmi_intf *intf, const char *payload_type, uint8_t channel, struct cipher_suite_info *suites, size_t *count) { struct ipmi_rs *rsp; struct ipmi_rq req; uint8_t rqdata[3]; uint8_t list_index = 0; /* 0x40 sets * 16 bytes per set */ uint8_t cipher_suite_data[MAX_CIPHER_SUITE_RECORD_OFFSET * MAX_CIPHER_SUITE_DATA_LEN]; size_t offset = 0; size_t nr_suites = 0; if (!suites || !count || !*count) return -1; nr_suites = *count; *count = 0; memset(cipher_suite_data, 0, sizeof(cipher_suite_data)); memset(&req, 0, sizeof(req)); req.msg.netfn = IPMI_NETFN_APP; req.msg.cmd = IPMI_GET_CHANNEL_CIPHER_SUITES; req.msg.data = rqdata; req.msg.data_len = sizeof(rqdata); rqdata[0] = channel; rqdata[1] = ((strncmp(payload_type, "ipmi", 4) == 0)? 0: 1); do { /* Always ask for cipher suite format */ rqdata[2] = LIST_ALGORITHMS_BY_CIPHER_SUITE | list_index; rsp = intf->sendrecv(intf, &req); if (!rsp) { lprintf(LOG_ERR, "Unable to Get Channel Cipher Suites"); return -1; } if (rsp->ccode || rsp->data_len < 1) { lprintf(LOG_ERR, "Get Channel Cipher Suites failed: %s", val2str(rsp->ccode, completion_code_vals)); return -1; } /* * We got back cipher suite data -- store it. * printf("copying data to offset %d\n", offset); * printbuf(rsp->data + 1, rsp->data_len - 1, "this is the data"); */ memcpy(cipher_suite_data + offset, rsp->data + 1, rsp->data_len - 1); offset += rsp->data_len - 1; /* * Increment our list for the next call */ ++list_index; } while ((rsp->data_len == (sizeof(uint8_t) + MAX_CIPHER_SUITE_DATA_LEN)) && (list_index < MAX_CIPHER_SUITE_RECORD_OFFSET)); *count = parse_channel_cipher_suite_data(cipher_suite_data, offset, suites, nr_suites); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'channel: Fix buffer overflow Partial fix for CVE-2020-5208, see https://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp The `ipmi_get_channel_cipher_suites` function does not properly check the final response’s `data_len`, which can lead to stack buffer overflow on the final copy.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ipmi_spd_print_fru(struct ipmi_intf * intf, uint8_t id) { struct ipmi_rs * rsp; struct ipmi_rq req; struct fru_info fru; uint8_t *spd_data, msg_data[4]; int len, offset; msg_data[0] = id; memset(&req, 0, sizeof(req)); req.msg.netfn = IPMI_NETFN_STORAGE; req.msg.cmd = GET_FRU_INFO; req.msg.data = msg_data; req.msg.data_len = 1; rsp = intf->sendrecv(intf, &req); if (!rsp) { printf(" Device not present (No Response)\n"); return -1; } if (rsp->ccode) { printf(" Device not present (%s)\n", val2str(rsp->ccode, completion_code_vals)); return -1; } fru.size = (rsp->data[1] << 8) | rsp->data[0]; fru.access = rsp->data[2] & 0x1; lprintf(LOG_DEBUG, "fru.size = %d bytes (accessed by %s)", fru.size, fru.access ? "words" : "bytes"); if (fru.size < 1) { lprintf(LOG_ERR, " Invalid FRU size %d", fru.size); return -1; } spd_data = malloc(fru.size); if (!spd_data) { printf(" Unable to malloc memory for spd array of size=%d\n", fru.size); return -1; } memset(&req, 0, sizeof(req)); req.msg.netfn = IPMI_NETFN_STORAGE; req.msg.cmd = GET_FRU_DATA; req.msg.data = msg_data; req.msg.data_len = 4; offset = 0; memset(spd_data, 0, fru.size); do { msg_data[0] = id; msg_data[1] = offset & 0xFF; msg_data[2] = offset >> 8; msg_data[3] = FRU_DATA_RQST_SIZE; rsp = intf->sendrecv(intf, &req); if (!rsp) { printf(" Device not present (No Response)\n"); free(spd_data); spd_data = NULL; return -1; } if (rsp->ccode) { printf(" Device not present (%s)\n", val2str(rsp->ccode, completion_code_vals)); free(spd_data); spd_data = NULL; /* Timeouts are acceptable. No DIMM in the socket */ if (rsp->ccode == 0xc3) return 1; return -1; } len = rsp->data[0]; memcpy(&spd_data[offset], rsp->data + 1, len); offset += len; } while (offset < fru.size); /* now print spd info */ ipmi_spd_print(spd_data, offset); free(spd_data); spd_data = NULL; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'fru: Fix buffer overflow in ipmi_spd_print_fru Partial fix for CVE-2020-5208, see https://github.com/ipmitool/ipmitool/security/advisories/GHSA-g659-9qxw-p7cp The `ipmi_spd_print_fru` function has a similar issue as the one fixed by the previous commit in `read_fru_area_section`. An initial request is made to get the `fru.size`, which is used as the size for the allocation of `spd_data`. Inside a loop, further requests are performed to get the copy sizes which are not checked before being used as the size for a copy into the buffer.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int http_message_needs_eof (const http_parser *parser) { if (parser->type == HTTP_REQUEST) { return 0; } /* See RFC 2616 section 4.4 */ if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */ parser->status_code == 204 || /* No Content */ parser->status_code == 304 || /* Not Modified */ parser->flags & F_SKIPBODY) { /* response to a HEAD request */ return 0; } if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) { return 0; } return 1; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-444'], 'message': 'Support multi-coding Transfer-Encoding `Transfer-Encoding` header might have multiple codings in it. Even though llhttp cares only about `chunked`, it must check that `chunked` is the last coding (if present). ABNF from RFC 7230: ``` Transfer-Encoding = *( "," OWS ) transfer-coding *( OWS "," [ OWS transfer-coding ] ) transfer-coding = "chunked" / "compress" / "deflate" / "gzip" / transfer-extension transfer-extension = token *( OWS ";" OWS transfer-parameter ) transfer-parameter = token BWS "=" BWS ( token / quoted-string ) ``` However, if `chunked` is not last - llhttp must assume that the encoding and size of the body is unknown (according to 3.3.3 of RFC 7230) and read the response until EOF. For request - the error must be raised for an unknown `Transfer-Encoding`. Furthermore, 3.3.3 of RFC 7230 explicitly states that presence of both `Transfer-Encoding` and `Content-Length` indicates the smuggling attack and "ought to be handled as an error". For the lenient mode: * Unknown `Transfer-Encoding` in requests is not an error and request body is simply read until EOF (end of connection) * Only `Transfer-Encoding: chunked` together with `Content-Length` would result an error (just like before the patch) PR-URL: https://github.com/nodejs-private/http-parser-private/pull/4 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Sam Roberts <vieuxtech@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int llhttp_message_needs_eof(const llhttp_t* parser) { if (parser->type == HTTP_REQUEST) { return 0; } /* See RFC 2616 section 4.4 */ if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */ parser->status_code == 204 || /* No Content */ parser->status_code == 304 || /* Not Modified */ (parser->flags & F_SKIPBODY)) { /* response to a HEAD request */ return 0; } if (parser->flags & (F_CHUNKED | F_CONTENT_LENGTH)) { return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-444'], 'message': 'http: support multi-coding Transfer-Encoding `Transfer-Encoding` header might have multiple codings in it. Even though llhttp cares only about `chunked`, it must check that `chunked` is the last coding (if present). ABNF from RFC 7230: ``` Transfer-Encoding = *( "," OWS ) transfer-coding *( OWS "," [ OWS transfer-coding ] ) transfer-coding = "chunked" / "compress" / "deflate" / "gzip" / transfer-extension transfer-extension = token *( OWS ";" OWS transfer-parameter ) transfer-parameter = token BWS "=" BWS ( token / quoted-string ) ``` However, if `chunked` is not last - llhttp must assume that the encoding and size of the body is unknown (according to 3.3.3 of RFC 7230) and read the response until EOF. For request - the error must be raised for an unknown `Transfer-Encoding`. Furthermore, 3.3.3 of RFC 7230 explicitly states that presence of both `Transfer-Encoding` and `Content-Length` indicates the smuggling attack and "ought to be handled as an error". For the lenient mode: * Unknown `Transfer-Encoding` in requests is not an error and request body is simply read until EOF (end of connection) * Only `Transfer-Encoding: chunked` together with `Content-Length` would result an error (just like before the patch) PR-URL: https://github.com/nodejs-private/llhttp-private/pull/1 Reviewed-By: Sam Roberts <vieuxtech@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: eap_response(esp, inp, id, len) eap_state *esp; u_char *inp; int id; int len; { u_char typenum; u_char vallen; int secret_len; char secret[MAXSECRETLEN]; char rhostname[256]; MD5_CTX mdContext; u_char hash[MD5_SIGNATURE_SIZE]; #ifdef USE_SRP struct t_server *ts; struct t_num A; SHA1_CTX ctxt; u_char dig[SHA_DIGESTSIZE]; #endif /* USE_SRP */ if (esp->es_server.ea_id != id) { dbglog("EAP: discarding Response %d; expected ID %d", id, esp->es_server.ea_id); return; } esp->es_server.ea_responses++; if (len <= 0) { error("EAP: empty Response message discarded"); return; } GETCHAR(typenum, inp); len--; switch (typenum) { case EAPT_IDENTITY: if (esp->es_server.ea_state != eapIdentify) { dbglog("EAP discarding unwanted Identify \"%.q\"", len, inp); break; } info("EAP: unauthenticated peer name \"%.*q\"", len, inp); if (esp->es_server.ea_peer != NULL && esp->es_server.ea_peer != remote_name) free(esp->es_server.ea_peer); esp->es_server.ea_peer = malloc(len + 1); if (esp->es_server.ea_peer == NULL) { esp->es_server.ea_peerlen = 0; eap_figure_next_state(esp, 1); break; } BCOPY(inp, esp->es_server.ea_peer, len); esp->es_server.ea_peer[len] = '\0'; esp->es_server.ea_peerlen = len; eap_figure_next_state(esp, 0); break; case EAPT_NOTIFICATION: dbglog("EAP unexpected Notification; response discarded"); break; case EAPT_NAK: if (len < 1) { info("EAP: Nak Response with no suggested protocol"); eap_figure_next_state(esp, 1); break; } GETCHAR(vallen, inp); len--; if (!explicit_remote && esp->es_server.ea_state == eapIdentify){ /* Peer cannot Nak Identify Request */ eap_figure_next_state(esp, 1); break; } switch (vallen) { case EAPT_SRP: /* Run through SRP validator selection again. */ esp->es_server.ea_state = eapIdentify; eap_figure_next_state(esp, 0); break; case EAPT_MD5CHAP: esp->es_server.ea_state = eapMD5Chall; break; default: dbglog("EAP: peer requesting unknown Type %d", vallen); switch (esp->es_server.ea_state) { case eapSRP1: case eapSRP2: case eapSRP3: esp->es_server.ea_state = eapMD5Chall; break; case eapMD5Chall: case eapSRP4: esp->es_server.ea_state = eapIdentify; eap_figure_next_state(esp, 0); break; default: break; } break; } break; case EAPT_MD5CHAP: if (esp->es_server.ea_state != eapMD5Chall) { error("EAP: unexpected MD5-Response"); eap_figure_next_state(esp, 1); break; } if (len < 1) { error("EAP: received MD5-Response with no data"); eap_figure_next_state(esp, 1); break; } GETCHAR(vallen, inp); len--; if (vallen != 16 || vallen > len) { error("EAP: MD5-Response with bad length %d", vallen); eap_figure_next_state(esp, 1); break; } /* Not so likely to happen. */ if (vallen >= len + sizeof (rhostname)) { dbglog("EAP: trimming really long peer name down"); BCOPY(inp + vallen, rhostname, sizeof (rhostname) - 1); rhostname[sizeof (rhostname) - 1] = '\0'; } else { BCOPY(inp + vallen, rhostname, len - vallen); rhostname[len - vallen] = '\0'; } /* In case the remote doesn't give us his name. */ if (explicit_remote || (remote_name[0] != '\0' && vallen == len)) strlcpy(rhostname, remote_name, sizeof (rhostname)); /* * Get the secret for authenticating the specified * host. */ if (!get_secret(esp->es_unit, rhostname, esp->es_server.ea_name, secret, &secret_len, 1)) { dbglog("EAP: no MD5 secret for auth of %q", rhostname); eap_send_failure(esp); break; } MD5_Init(&mdContext); MD5_Update(&mdContext, &esp->es_server.ea_id, 1); MD5_Update(&mdContext, (u_char *)secret, secret_len); BZERO(secret, sizeof (secret)); MD5_Update(&mdContext, esp->es_challenge, esp->es_challen); MD5_Final(hash, &mdContext); if (BCMP(hash, inp, MD5_SIGNATURE_SIZE) != 0) { eap_send_failure(esp); break; } esp->es_server.ea_type = EAPT_MD5CHAP; eap_send_success(esp); eap_figure_next_state(esp, 0); if (esp->es_rechallenge != 0) TIMEOUT(eap_rechallenge, esp, esp->es_rechallenge); break; #ifdef USE_SRP case EAPT_SRP: if (len < 1) { error("EAP: empty SRP Response"); eap_figure_next_state(esp, 1); break; } GETCHAR(typenum, inp); len--; switch (typenum) { case EAPSRP_CKEY: if (esp->es_server.ea_state != eapSRP1) { error("EAP: unexpected SRP Subtype 1 Response"); eap_figure_next_state(esp, 1); break; } A.data = inp; A.len = len; ts = (struct t_server *)esp->es_server.ea_session; assert(ts != NULL); esp->es_server.ea_skey = t_servergetkey(ts, &A); if (esp->es_server.ea_skey == NULL) { /* Client's A value is bogus; terminate now */ error("EAP: bogus A value from client"); eap_send_failure(esp); } else { eap_figure_next_state(esp, 0); } break; case EAPSRP_CVALIDATOR: if (esp->es_server.ea_state != eapSRP2) { error("EAP: unexpected SRP Subtype 2 Response"); eap_figure_next_state(esp, 1); break; } if (len < sizeof (u_int32_t) + SHA_DIGESTSIZE) { error("EAP: M1 length %d < %d", len, sizeof (u_int32_t) + SHA_DIGESTSIZE); eap_figure_next_state(esp, 1); break; } GETLONG(esp->es_server.ea_keyflags, inp); ts = (struct t_server *)esp->es_server.ea_session; assert(ts != NULL); if (t_serververify(ts, inp)) { info("EAP: unable to validate client identity"); eap_send_failure(esp); break; } eap_figure_next_state(esp, 0); break; case EAPSRP_ACK: if (esp->es_server.ea_state != eapSRP3) { error("EAP: unexpected SRP Subtype 3 Response"); eap_send_failure(esp); break; } esp->es_server.ea_type = EAPT_SRP; eap_send_success(esp); eap_figure_next_state(esp, 0); if (esp->es_rechallenge != 0) TIMEOUT(eap_rechallenge, esp, esp->es_rechallenge); if (esp->es_lwrechallenge != 0) TIMEOUT(srp_lwrechallenge, esp, esp->es_lwrechallenge); break; case EAPSRP_LWRECHALLENGE: if (esp->es_server.ea_state != eapSRP4) { info("EAP: unexpected SRP Subtype 4 Response"); return; } if (len != SHA_DIGESTSIZE) { error("EAP: bad Lightweight rechallenge " "response"); return; } SHA1Init(&ctxt); vallen = id; SHA1Update(&ctxt, &vallen, 1); SHA1Update(&ctxt, esp->es_server.ea_skey, SESSION_KEY_LEN); SHA1Update(&ctxt, esp->es_challenge, esp->es_challen); SHA1Update(&ctxt, esp->es_server.ea_peer, esp->es_server.ea_peerlen); SHA1Final(dig, &ctxt); if (BCMP(dig, inp, SHA_DIGESTSIZE) != 0) { error("EAP: failed Lightweight rechallenge"); eap_send_failure(esp); break; } esp->es_server.ea_state = eapOpen; if (esp->es_lwrechallenge != 0) TIMEOUT(srp_lwrechallenge, esp, esp->es_lwrechallenge); break; } break; #endif /* USE_SRP */ default: /* This can't happen. */ error("EAP: unknown Response type %d; ignored", typenum); return; } if (esp->es_server.ea_timeout > 0) { UNTIMEOUT(eap_server_timeout, (void *)esp); } if (esp->es_server.ea_state != eapBadAuth && esp->es_server.ea_state != eapOpen) { esp->es_server.ea_id++; eap_send_request(esp); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'pppd: Fix bounds check in EAP code Given that we have just checked vallen < len, it can never be the case that vallen >= len + sizeof(rhostname). This fixes the check so we actually avoid overflowing the rhostname array. Reported-by: Ilja Van Sprundel <ivansprundel@ioactive.com> Signed-off-by: Paul Mackerras <paulus@ozlabs.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_options(argc, argv) int argc; char *argv[]; { int i, l; /* * Process options. */ while (argc > 1 && argv[1][0] == '-') { argv++; argc--; l = (int) strlen(*argv); /* must supply at least 4 chars to match "-XXXgraphics" */ if (l < 4) l = 4; switch (argv[0][1]) { case 'D': case 'd': if ((argv[0][1] == 'D' && !argv[0][2]) || !strcmpi(*argv, "-debug")) { wizard = TRUE, discover = FALSE; } else if (!strncmpi(*argv, "-DECgraphics", l)) { load_symset("DECGraphics", PRIMARY); switch_symbols(TRUE); } else { raw_printf("Unknown option: %s", *argv); } break; case 'X': discover = TRUE, wizard = FALSE; break; #ifdef NEWS case 'n': iflags.news = FALSE; break; #endif case 'u': if (argv[0][2]) { (void) strncpy(plname, argv[0] + 2, sizeof plname - 1); } else if (argc > 1) { argc--; argv++; (void) strncpy(plname, argv[0], sizeof plname - 1); } else { raw_print("Player name expected after -u"); } break; case 'I': case 'i': if (!strncmpi(*argv, "-IBMgraphics", l)) { load_symset("IBMGraphics", PRIMARY); load_symset("RogueIBM", ROGUESET); switch_symbols(TRUE); } else { raw_printf("Unknown option: %s", *argv); } break; case 'p': /* profession (role) */ if (argv[0][2]) { if ((i = str2role(&argv[0][2])) >= 0) flags.initrole = i; } else if (argc > 1) { argc--; argv++; if ((i = str2role(argv[0])) >= 0) flags.initrole = i; } break; case 'r': /* race */ if (argv[0][2]) { if ((i = str2race(&argv[0][2])) >= 0) flags.initrace = i; } else if (argc > 1) { argc--; argv++; if ((i = str2race(argv[0])) >= 0) flags.initrace = i; } break; case 'w': /* windowtype */ config_error_init(FALSE, "command line", FALSE); choose_windows(&argv[0][2]); config_error_done(); break; case '@': flags.randomall = 1; break; default: if ((i = str2role(&argv[0][1])) >= 0) { flags.initrole = i; break; } /* else raw_printf("Unknown option: %s", *argv); */ } } #ifdef SYSCF if (argc > 1) raw_printf("MAXPLAYERS are set in sysconf file.\n"); #else /* XXX This is deprecated in favor of SYSCF with MAXPLAYERS */ if (argc > 1) locknum = atoi(argv[1]); #endif #ifdef MAX_NR_OF_PLAYERS /* limit to compile-time limit */ if (!locknum || locknum > MAX_NR_OF_PLAYERS) locknum = MAX_NR_OF_PLAYERS; #endif #ifdef SYSCF /* let syscf override compile-time limit */ if (!locknum || (sysopt.maxplayers && locknum > sysopt.maxplayers)) locknum = sysopt.maxplayers; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-269'], 'message': 'command line triggered buffer overruns Prevent extremely long command line arguments from overflowing local buffers in raw_printf or config_error_add. The increased buffer sizes they recently got to deal with long configuration file values aren't sufficient to handle command line induced overflows. choose_windows(core): copy and truncate the window_type argument in case it gets passed to config_error_add(). process_options(unix): report bad values with "%.60s" so that vsprintf will implicitly truncate when formatted by raw_printf().'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ int i; WhereConst *pConst; if( pExpr->op!=TK_COLUMN ) return WRC_Continue; if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue; pConst = pWalker->u.pConst; for(i=0; i<pConst->nConst; i++){ Expr *pColumn = pConst->apExpr[i*2]; if( pColumn==pExpr ) continue; if( pColumn->iTable!=pExpr->iTable ) continue; if( pColumn->iColumn!=pExpr->iColumn ) continue; /* A match is found. Add the EP_FixedCol property */ pConst->nChng++; ExprClearProperty(pExpr, EP_Leaf); ExprSetProperty(pExpr, EP_FixedCol); assert( pExpr->pLeft==0 ); pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); break; } return WRC_Prune; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Do not allow the constant-propagation optimization to apple to ON/USING clause terms as it does not help and it might cause downstream problems. FossilOrigin-Name: 1bc783da63d58b05c690468b569cb2787846357b63c1100d11777666c5787bf4'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: archive_wstring_append_from_mbs(struct archive_wstring *dest, const char *p, size_t len) { return archive_wstring_append_from_mbs_in_codepage(dest, p, len, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Bugfix and optimize archive_wstring_append_from_mbs() The cal to mbrtowc() or mbtowc() should read up to mbs_length bytes and not wcs_length. This avoids out-of-bounds reads. mbrtowc() and mbtowc() return (size_t)-1 wit errno EILSEQ when they encounter an invalid multibyte character and (size_t)-2 when they they encounter an incomplete multibyte character. As we return failure and all our callers error out it makes no sense to continue parsing mbs. As we allocate `len` wchars at the beginning and each wchar has at least one byte, there will never be need to grow the buffer, so the code can be left out. On the other hand, we are always allocatng more memory than we need. As long as wcs_length == mbs_length == len we can omit wcs_length. We keep the old code commented if we decide to save memory and use autoexpanding wcs_length in the future. Fixes #1276'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport void DestroyXResources(void) { register int i; unsigned int number_windows; XWindowInfo *magick_windows[MaxXWindows]; XWindows *windows; DestroyXWidget(); windows=XSetWindows((XWindows *) ~0); if ((windows == (XWindows *) NULL) || (windows->display == (Display *) NULL)) return; number_windows=0; magick_windows[number_windows++]=(&windows->context); magick_windows[number_windows++]=(&windows->group_leader); magick_windows[number_windows++]=(&windows->backdrop); magick_windows[number_windows++]=(&windows->icon); magick_windows[number_windows++]=(&windows->image); magick_windows[number_windows++]=(&windows->info); magick_windows[number_windows++]=(&windows->magnify); magick_windows[number_windows++]=(&windows->pan); magick_windows[number_windows++]=(&windows->command); magick_windows[number_windows++]=(&windows->widget); magick_windows[number_windows++]=(&windows->popup); for (i=0; i < (int) number_windows; i++) { if (magick_windows[i]->mapped != MagickFalse) { (void) XWithdrawWindow(windows->display,magick_windows[i]->id, magick_windows[i]->screen); magick_windows[i]->mapped=MagickFalse; } if (magick_windows[i]->name != (char *) NULL) magick_windows[i]->name=(char *) RelinquishMagickMemory(magick_windows[i]->name); if (magick_windows[i]->icon_name != (char *) NULL) magick_windows[i]->icon_name=(char *) RelinquishMagickMemory(magick_windows[i]->icon_name); if (magick_windows[i]->cursor != (Cursor) NULL) { (void) XFreeCursor(windows->display,magick_windows[i]->cursor); magick_windows[i]->cursor=(Cursor) NULL; } if (magick_windows[i]->busy_cursor != (Cursor) NULL) { (void) XFreeCursor(windows->display,magick_windows[i]->busy_cursor); magick_windows[i]->busy_cursor=(Cursor) NULL; } if (magick_windows[i]->highlight_stipple != (Pixmap) NULL) { (void) XFreePixmap(windows->display, magick_windows[i]->highlight_stipple); magick_windows[i]->highlight_stipple=(Pixmap) NULL; } if (magick_windows[i]->shadow_stipple != (Pixmap) NULL) { (void) XFreePixmap(windows->display,magick_windows[i]->shadow_stipple); magick_windows[i]->shadow_stipple=(Pixmap) NULL; } if (magick_windows[i]->ximage != (XImage *) NULL) { XDestroyImage(magick_windows[i]->ximage); magick_windows[i]->ximage=(XImage *) NULL; } if (magick_windows[i]->pixmap != (Pixmap) NULL) { (void) XFreePixmap(windows->display,magick_windows[i]->pixmap); magick_windows[i]->pixmap=(Pixmap) NULL; } if (magick_windows[i]->id != (Window) NULL) { (void) XDestroyWindow(windows->display,magick_windows[i]->id); magick_windows[i]->id=(Window) NULL; } if (magick_windows[i]->destroy != MagickFalse) { if (magick_windows[i]->image != (Image *) NULL) { magick_windows[i]->image=DestroyImage(magick_windows[i]->image); magick_windows[i]->image=NewImageList(); } if (magick_windows[i]->matte_pixmap != (Pixmap) NULL) { (void) XFreePixmap(windows->display, magick_windows[i]->matte_pixmap); magick_windows[i]->matte_pixmap=(Pixmap) NULL; } } if (magick_windows[i]->segment_info != (void *) NULL) { #if defined(MAGICKCORE_HAVE_SHARED_MEMORY) XShmSegmentInfo *segment_info; segment_info=(XShmSegmentInfo *) magick_windows[i]->segment_info; if (segment_info != (XShmSegmentInfo *) NULL) if (segment_info[0].shmid >= 0) { if (segment_info[0].shmaddr != NULL) (void) shmdt(segment_info[0].shmaddr); (void) shmctl(segment_info[0].shmid,IPC_RMID,0); segment_info[0].shmaddr=NULL; segment_info[0].shmid=(-1); } #endif magick_windows[i]->segment_info=(void *) RelinquishMagickMemory( magick_windows[i]->segment_info); } } windows->icon_resources=(XResourceInfo *) RelinquishMagickMemory(windows->icon_resources); if (windows->icon_pixel != (XPixelInfo *) NULL) { if (windows->icon_pixel->pixels != (unsigned long *) NULL) windows->icon_pixel->pixels=(unsigned long *) RelinquishMagickMemory(windows->icon_pixel->pixels); if (windows->icon_pixel->annotate_context != (GC) NULL) XFreeGC(windows->display,windows->icon_pixel->annotate_context); windows->icon_pixel=(XPixelInfo *) RelinquishMagickMemory(windows->icon_pixel); } if (windows->pixel_info != (XPixelInfo *) NULL) { if (windows->pixel_info->pixels != (unsigned long *) NULL) windows->pixel_info->pixels=(unsigned long *) RelinquishMagickMemory(windows->pixel_info->pixels); if (windows->pixel_info->annotate_context != (GC) NULL) XFreeGC(windows->display,windows->pixel_info->annotate_context); if (windows->pixel_info->widget_context != (GC) NULL) XFreeGC(windows->display,windows->pixel_info->widget_context); if (windows->pixel_info->highlight_context != (GC) NULL) XFreeGC(windows->display,windows->pixel_info->highlight_context); windows->pixel_info=(XPixelInfo *) RelinquishMagickMemory(windows->pixel_info); } if (windows->font_info != (XFontStruct *) NULL) { XFreeFont(windows->display,windows->font_info); windows->font_info=(XFontStruct *) NULL; } if (windows->class_hints != (XClassHint *) NULL) { if (windows->class_hints->res_name != (char *) NULL) windows->class_hints->res_name=DestroyString( windows->class_hints->res_name); if (windows->class_hints->res_class != (char *) NULL) windows->class_hints->res_class=DestroyString( windows->class_hints->res_class); XFree(windows->class_hints); windows->class_hints=(XClassHint *) NULL; } if (windows->manager_hints != (XWMHints *) NULL) { XFree(windows->manager_hints); windows->manager_hints=(XWMHints *) NULL; } if (windows->map_info != (XStandardColormap *) NULL) { XFree(windows->map_info); windows->map_info=(XStandardColormap *) NULL; } if (windows->icon_map != (XStandardColormap *) NULL) { XFree(windows->icon_map); windows->icon_map=(XStandardColormap *) NULL; } if (windows->visual_info != (XVisualInfo *) NULL) { XFree(windows->visual_info); windows->visual_info=(XVisualInfo *) NULL; } if (windows->icon_visual != (XVisualInfo *) NULL) { XFree(windows->icon_visual); windows->icon_visual=(XVisualInfo *) NULL; } (void) XSetWindows((XWindows *) NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1531'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char command[MaxTextExtent]; const char *option; graph_t *graph; Image *image; ImageInfo *read_info; MagickBooleanType status; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(graphic_context != (GVC_t *) NULL); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return((Image *) NULL); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) CopyMagickString(read_info->magick,"SVG",MaxTextExtent); (void) AcquireUniqueFilename(read_info->filename); (void) FormatLocaleString(command,MaxTextExtent,"-Tsvg -o%s %s", read_info->filename,image_info->filename); #if !defined(WITH_CGRAPH) graph=agread(GetBlobFileHandle(image)); #else graph=agread(GetBlobFileHandle(image),(Agdisc_t *) NULL); #endif if (graph == (graph_t *) NULL) { (void) RelinquishUniqueFileResource(read_info->filename); return ((Image *) NULL); } option=GetImageOption(image_info,"dot:layout-engine"); if (option == (const char *) NULL) gvLayout(graphic_context,graph,(char *) "dot"); else gvLayout(graphic_context,graph,(char *) option); gvRenderFilename(graphic_context,graph,(char *) "svg",read_info->filename); gvFreeLayout(graphic_context,graph); agclose(graph); /* Read SVG graph. */ (void) CopyMagickString(read_info->magick,"SVG",MaxTextExtent); image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (image == (Image *) NULL) return((Image *) NULL); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1528'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WritePS2Image(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { static const char *const PostscriptProlog[]= { "%%%%BeginProlog", "%%", "%% Display a color image. The image is displayed in color on", "%% Postscript viewers or printers that support color, otherwise", "%% it is displayed as grayscale.", "%%", "/DirectClassImage", "{", " %%", " %% Display a DirectClass image.", " %%", " colorspace 0 eq", " {", " /DeviceRGB setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /Decode [0 1 0 1 0 1]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " compression 0 gt", " { /DataSource pixel_stream %s }", " { /DataSource pixel_stream %s } ifelse", " >> image", " }", " {", " /DeviceCMYK setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /Decode [1 0 1 0 1 0 1 0]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " compression 0 gt", " { /DataSource pixel_stream %s }", " { /DataSource pixel_stream %s } ifelse", " >> image", " } ifelse", "} bind def", "", "/PseudoClassImage", "{", " %%", " %% Display a PseudoClass image.", " %%", " %% Parameters:", " %% colors: number of colors in the colormap.", " %%", " currentfile buffer readline pop", " token pop /colors exch def pop", " colors 0 eq", " {", " %%", " %% Image is grayscale.", " %%", " currentfile buffer readline pop", " token pop /bits exch def pop", " /DeviceGray setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent bits", " /Decode [0 1]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " compression 0 gt", " { /DataSource pixel_stream %s }", " {", " /DataSource pixel_stream %s", " <<", " /K " CCITTParam, " /Columns columns", " /Rows rows", " >> /CCITTFaxDecode filter", " } ifelse", " >> image", " }", " {", " %%", " %% Parameters:", " %% colormap: red, green, blue color packets.", " %%", " /colormap colors 3 mul string def", " currentfile colormap readhexstring pop pop", " currentfile buffer readline pop", " [ /Indexed /DeviceRGB colors 1 sub colormap ] setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /Decode [0 255]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " compression 0 gt", " { /DataSource pixel_stream %s }", " { /DataSource pixel_stream %s } ifelse", " >> image", " } ifelse", "} bind def", "", "/DisplayImage", "{", " %%", " %% Display a DirectClass or PseudoClass image.", " %%", " %% Parameters:", " %% x & y translation.", " %% x & y scale.", " %% label pointsize.", " %% image label.", " %% image columns & rows.", " %% class: 0-DirectClass or 1-PseudoClass.", " %% colorspace: 0-RGB or 1-CMYK.", " %% compression: 0-RLECompression or 1-NoCompression.", " %% hex color packets.", " %%", " gsave", " /buffer 512 string def", " /pixel_stream currentfile def", "", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " x y translate", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " currentfile buffer readline pop", " token pop /pointsize exch def pop", (const char *) NULL }, *const PostscriptEpilog[]= { " x y scale", " currentfile buffer readline pop", " token pop /columns exch def", " token pop /rows exch def pop", " currentfile buffer readline pop", " token pop /class exch def pop", " currentfile buffer readline pop", " token pop /colorspace exch def pop", " currentfile buffer readline pop", " token pop /compression exch def pop", " class 0 gt { PseudoClassImage } { DirectClassImage } ifelse", " grestore", (const char *) NULL }; char buffer[MagickPathExtent], date[MagickPathExtent], page_geometry[MagickPathExtent], **labels; CompressionType compression; const char *const *q, *value; double pointsize; GeometryInfo geometry_info; MagickOffsetType scene, start, stop; MagickBooleanType progress, status; MagickOffsetType offset; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register ssize_t x; register ssize_t i; SegmentInfo bounds; size_t imageListLength, length, page, text_size; ssize_t j, y; time_t timer; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif default: break; } (void) memset(&bounds,0,sizeof(bounds)); page=1; scene=0; imageListLength=GetImageListLength(image); do { /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(size_t) (100.0*2.54*resolution.x+0.5)/100.0; resolution.y=(size_t) (100.0*2.54*resolution.y+0.5)/100.0; } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PS") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MagickPathExtent); (void) ConcatenateMagickString(page_geometry,">",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); if (page == 1) { /* Output Postscript header. */ if (LocaleCompare(image_info->magick,"PS2") == 0) (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MagickPathExtent); else (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%Creator: (ImageMagick)\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"%%%%Title: (%s)\n", image->filename); (void) WriteBlobString(image,buffer); timer=time((time_t *) NULL); (void) FormatMagickTime(timer,MagickPathExtent,date); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%CreationDate: (%s)\n",date); (void) WriteBlobString(image,buffer); bounds.x1=(double) geometry.x; bounds.y1=(double) geometry.y; bounds.x2=(double) geometry.x+geometry.width; bounds.y2=(double) geometry.y+geometry.height+text_size; if ((image_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) (void) CopyMagickString(buffer,"%%BoundingBox: (atend)\n", MagickPathExtent); else { (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1, bounds.y1,bounds.x2,bounds.y2); } (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) WriteBlobString(image, "%%DocumentNeededResources: font Helvetica\n"); (void) WriteBlobString(image,"%%LanguageLevel: 2\n"); if (LocaleCompare(image_info->magick,"PS2") != 0) (void) WriteBlobString(image,"%%Pages: 1\n"); else { (void) WriteBlobString(image,"%%Orientation: Portrait\n"); (void) WriteBlobString(image,"%%PageOrder: Ascend\n"); if (image_info->adjoin == MagickFalse) (void) CopyMagickString(buffer,"%%Pages: 1\n",MagickPathExtent); else (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%Pages: %.20g\n",(double) imageListLength); (void) WriteBlobString(image,buffer); } if (image->colorspace == CMYKColorspace) (void) WriteBlobString(image, "%%DocumentProcessColors: Cyan Magenta Yellow Black\n"); (void) WriteBlobString(image,"%%EndComments\n"); (void) WriteBlobString(image,"\n%%BeginDefaults\n"); (void) WriteBlobString(image,"%%EndDefaults\n\n"); /* Output Postscript commands. */ for (q=PostscriptProlog; *q; q++) { switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,*q, "/ASCII85Decode filter"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,*q, "/DCTDecode filter"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,*q, "/LZWDecode filter"); break; } case FaxCompression: case Group4Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,*q," "); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,*q, "/RunLengthDecode filter"); break; } } (void) WriteBlobString(image,buffer); (void) WriteBlobByte(image,'\n'); } value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) { (void) WriteBlobString(image, " /Helvetica findfont pointsize scalefont setfont\n"); for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--) { (void) WriteBlobString(image," /label 512 string def\n"); (void) WriteBlobString(image, " currentfile label readline pop\n"); (void) FormatLocaleString(buffer,MagickPathExtent, " 0 y %g add moveto label show pop\n",j*pointsize+12); (void) WriteBlobString(image,buffer); } } for (q=PostscriptEpilog; *q; q++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%s\n",*q); (void) WriteBlobString(image,buffer); } if (LocaleCompare(image_info->magick,"PS2") == 0) (void) WriteBlobString(image," showpage\n"); (void) WriteBlobString(image,"} bind def\n"); (void) WriteBlobString(image,"%%EndProlog\n"); } (void) FormatLocaleString(buffer,MagickPathExtent,"%%%%Page: 1 %.20g\n", (double) page++); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x, (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double) (geometry.height+text_size)); (void) WriteBlobString(image,buffer); if ((double) geometry.x < bounds.x1) bounds.x1=(double) geometry.x; if ((double) geometry.y < bounds.y1) bounds.y1=(double) geometry.y; if ((double) (geometry.x+geometry.width-1) > bounds.x2) bounds.x2=(double) geometry.x+geometry.width-1; if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2) bounds.y2=(double) geometry.y+(geometry.height+text_size)-1; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) (void) WriteBlobString(image,"%%PageResources: font Helvetica\n"); if (LocaleCompare(image_info->magick,"PS2") != 0) (void) WriteBlobString(image,"userdict begin\n"); start=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BeginData:%13ld %s Bytes\n",0L, compression == NoCompression ? "ASCII" : "Binary"); (void) WriteBlobString(image,buffer); stop=TellBlob(image); (void) WriteBlobString(image,"DisplayImage\n"); /* Output image data. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n%g %g\n%g\n",(double) geometry.x,(double) geometry.y, scale.x,scale.y,pointsize); (void) WriteBlobString(image,buffer); labels=(char **) NULL; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { for (i=0; labels[i] != (char *) NULL; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%s \n", labels[i]); (void) WriteBlobString(image,buffer); labels[i]=DestroyString(labels[i]); } labels=(char **) RelinquishMagickMemory(labels); } number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != (MagickSizeType) ((size_t) number_pixels)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n1\n%d\n",(double) image->columns,(double) image->rows, (int) (image->colorspace == CMYKColorspace)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%d\n",(int) ((compression != FaxCompression) && (compression != Group4Compression))); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"0\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"%d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; register unsigned char *q; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (progress == MagickFalse) break; } length=(size_t) (q-pixels); if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (image->alpha_trait != UndefinedPixelTrait)) { (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n0\n%d\n",(double) image->columns,(double) image->rows, (int) (image->colorspace == CMYKColorspace)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%d\n", (int) (compression == NoCompression)); (void) WriteBlobString(image,buffer); switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; register unsigned char *q; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((image->alpha_trait != UndefinedPixelTrait) && (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)) { *q++=ScaleQuantumToChar(QuantumRange); *q++=ScaleQuantumToChar(QuantumRange); *q++=ScaleQuantumToChar(QuantumRange); } else if (image->colorspace != CMYKColorspace) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); } else { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); } p+=GetPixelChannels(image); } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } length=(size_t) (q-pixels); if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } pixel_info=RelinquishVirtualMemory(pixel_info); break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((image->alpha_trait != UndefinedPixelTrait) && (GetPixelAlpha(image,p) == (Quantum) TransparentAlpha)) { Ascii85Encode(image,ScaleQuantumToChar((Quantum) QuantumRange)); Ascii85Encode(image,ScaleQuantumToChar((Quantum) QuantumRange)); Ascii85Encode(image,ScaleQuantumToChar((Quantum) QuantumRange)); } else if (image->colorspace != CMYKColorspace) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(image,p))); } else { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); } p+=GetPixelChannels(image); } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } Ascii85Flush(image); break; } } } else { /* Dump number of colors and colormap. */ (void) FormatLocaleString(buffer,MagickPathExtent, "%.20g %.20g\n1\n%d\n",(double) image->columns,(double) image->rows, (int) (image->colorspace == CMYKColorspace)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%d\n", (int) (compression == NoCompression)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) image->colors); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) image->colors; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%02X%02X%02X\n", ScaleQuantumToChar(image->colormap[i].red), ScaleQuantumToChar(image->colormap[i].green), ScaleQuantumToChar(image->colormap[i].blue)); (void) WriteBlobString(image,buffer); } switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; register unsigned char *q; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } length=(size_t) (q-pixels); if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } Ascii85Flush(image); break; } } } (void) WriteBlobByte(image,'\n'); length=(size_t) (TellBlob(image)-stop); stop=TellBlob(image); offset=SeekBlob(image,start,SEEK_SET); if (offset < 0) ThrowWriterException(CorruptImageError,"ImproperImageHeader"); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BeginData:%13ld %s Bytes\n",(long) length, compression == NoCompression ? "ASCII" : "Binary"); (void) WriteBlobString(image,buffer); offset=SeekBlob(image,stop,SEEK_SET); (void) WriteBlobString(image,"%%EndData\n"); if (LocaleCompare(image_info->magick,"PS2") != 0) (void) WriteBlobString(image,"end\n"); (void) WriteBlobString(image,"%%PageTrailer\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"%%Trailer\n"); if (page > 1) { (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EOF\n"); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1542'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadDOTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char command[MagickPathExtent]; const char *option; graph_t *graph; Image *image; ImageInfo *read_info; MagickBooleanType status; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(graphic_context != (GVC_t *) NULL); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) CopyMagickString(read_info->magick,"SVG",MagickPathExtent); (void) AcquireUniqueFilename(read_info->filename); (void) FormatLocaleString(command,MagickPathExtent,"-Tsvg -o%s %s", read_info->filename,image_info->filename); #if !defined(WITH_CGRAPH) graph=agread(GetBlobFileHandle(image)); #else graph=agread(GetBlobFileHandle(image),(Agdisc_t *) NULL); #endif if (graph == (graph_t *) NULL) { (void) RelinquishUniqueFileResource(read_info->filename); return ((Image *) NULL); } option=GetImageOption(image_info,"dot:layout-engine"); if (option == (const char *) NULL) gvLayout(graphic_context,graph,(char *) "dot"); else gvLayout(graphic_context,graph,(char *) option); gvRenderFilename(graphic_context,graph,(char *) "svg",read_info->filename); gvFreeLayout(graphic_context,graph); agclose(graph); /* Read SVG graph. */ (void) CopyMagickString(read_info->magick,"SVG",MaxTextExtent); image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (image == (Image *) NULL) return((Image *) NULL); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fixed memory leak reported in #1558 and fixed other leak.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void aes_ctr_cleanup(struct ssh_cipher_struct *cipher){ explicit_bzero(cipher->aes_key, sizeof(*cipher->aes_key)); SAFE_FREE(cipher->aes_key); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'CVE-2020-1730: Fix a possible segfault when zeroing AES-CTR key Fixes T213 Signed-off-by: Andreas Schneider <asn@cryptomilk.org> Reviewed-by: Anderson Toshiyuki Sasaki <ansasaki@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: forward_search(regex_t* reg, const UChar* str, const UChar* end, UChar* start, UChar* range, UChar** low, UChar** high, UChar** low_prev) { UChar *p, *pprev = (UChar* )NULL; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "forward_search: str: %p, end: %p, start: %p, range: %p\n", str, end, start, range); #endif p = start; if (reg->dist_min > 0) { if (ONIGENC_IS_SINGLEBYTE(reg->enc)) { p += reg->dist_min; } else { UChar *q = p + reg->dist_min; if (q >= end) return 0; /* fail */ while (p < q) p += enclen(reg->enc, p); } } retry: switch (reg->optimize) { case OPTIMIZE_STR: p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range); break; case OPTIMIZE_STR_CASE_FOLD: p = slow_search_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, p, end, range); break; case OPTIMIZE_STR_FAST: p = sunday_quick_search(reg, reg->exact, reg->exact_end, p, end, range); break; case OPTIMIZE_STR_FAST_STEP_FORWARD: p = sunday_quick_search_step_forward(reg, reg->exact, reg->exact_end, p, end, range); break; case OPTIMIZE_MAP: p = map_search(reg->enc, reg->map, p, range); break; } if (p && p < range) { if (p - reg->dist_min < start) { retry_gate: pprev = p; p += enclen(reg->enc, p); goto retry; } if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; } break; case ANCR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = (UChar* )onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) goto retry_gate; break; } } if (reg->dist_max == 0) { *low = p; if (low_prev) { if (*low > start) *low_prev = onigenc_get_prev_char_head(reg->enc, start, p); else *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); } } else { if (reg->dist_max != INFINITE_LEN) { if (p - str < reg->dist_max) { *low = (UChar* )str; if (low_prev) *low_prev = onigenc_get_prev_char_head(reg->enc, str, *low); } else { *low = p - reg->dist_max; if (*low > start) { *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, start, *low, (const UChar** )low_prev); } else { if (low_prev) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), *low); } } } } /* no needs to adjust *high, *high is used as range check only */ *high = p - reg->dist_min; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "forward_search success: low: %d, high: %d, dmin: %d, dmax: %d\n", (int )(*low - str), (int )(*high - str), reg->dist_min, reg->dist_max); #endif return 1; /* success */ } return 0; /* fail */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix #164: Integer overflow related to reg->dmax in search_in_range()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: backward_search(regex_t* reg, const UChar* str, const UChar* end, UChar* s, const UChar* range, UChar* adjrange, UChar** low, UChar** high) { UChar *p; if (range == 0) goto fail; range += reg->dist_min; p = s; retry: switch (reg->optimize) { case OPTIMIZE_STR: exact_method: p = slow_search_backward(reg->enc, reg->exact, reg->exact_end, range, adjrange, end, p); break; case OPTIMIZE_STR_CASE_FOLD: p = slow_search_backward_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, range, adjrange, end, p); break; case OPTIMIZE_STR_FAST: case OPTIMIZE_STR_FAST_STEP_FORWARD: goto exact_method; break; case OPTIMIZE_MAP: p = map_search_backward(reg->enc, reg->map, range, adjrange, p); break; } if (p) { if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, str, p); if (IS_NOT_NULL(prev) && !ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) { p = prev; goto retry; } } break; case ANCR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = onigenc_get_prev_char_head(reg->enc, adjrange, p); if (IS_NULL(prev)) goto fail; if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) { p = prev; goto retry; } #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) { p = onigenc_get_prev_char_head(reg->enc, adjrange, p); if (IS_NULL(p)) goto fail; goto retry; } break; } } /* no needs to adjust *high, *high is used as range check only */ if (reg->dist_max != INFINITE_LEN) { *low = p - reg->dist_max; *high = p - reg->dist_min; *high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high); } #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "backward_search: low: %d, high: %d\n", (int )(*low - str), (int )(*high - str)); #endif return 1; /* success */ } fail: #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "backward_search: fail.\n"); #endif return 0; /* fail */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix #164: Integer overflow related to reg->dmax in search_in_range()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: forward_search(regex_t* reg, const UChar* str, const UChar* end, UChar* start, UChar* range, UChar** low, UChar** high, UChar** low_prev) { UChar *p, *pprev = (UChar* )NULL; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "forward_search: str: %p, end: %p, start: %p, range: %p\n", str, end, start, range); #endif p = start; if (reg->dist_min != 0) { if ((ptrdiff_t )(end - p) <= (ptrdiff_t )reg->dist_min) return 0; /* fail */ if (ONIGENC_IS_SINGLEBYTE(reg->enc)) { p += reg->dist_min; } else { UChar *q = p + reg->dist_min; while (p < q) p += enclen(reg->enc, p); } } retry: switch (reg->optimize) { case OPTIMIZE_STR: p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range); break; case OPTIMIZE_STR_CASE_FOLD: p = slow_search_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, p, end, range); break; case OPTIMIZE_STR_FAST: p = sunday_quick_search(reg, reg->exact, reg->exact_end, p, end, range); break; case OPTIMIZE_STR_FAST_STEP_FORWARD: p = sunday_quick_search_step_forward(reg, reg->exact, reg->exact_end, p, end, range); break; case OPTIMIZE_MAP: p = map_search(reg->enc, reg->map, p, range); break; } if (p && p < range) { if ((ptrdiff_t )(p - start) < (ptrdiff_t )reg->dist_min) { retry_gate: pprev = p; p += enclen(reg->enc, p); goto retry; } if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; } break; case ANCR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = (UChar* )onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) goto retry_gate; break; } } if (reg->dist_max == 0) { *low = p; if (low_prev) { if (*low > start) *low_prev = onigenc_get_prev_char_head(reg->enc, start, p); else *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); } *high = p; } else { if (reg->dist_max != INFINITE_LEN) { if ((ptrdiff_t )(p - str) < (ptrdiff_t )reg->dist_max) { *low = (UChar* )str; if (low_prev) *low_prev = onigenc_get_prev_char_head(reg->enc, str, *low); } else { *low = p - reg->dist_max; if (*low > start) { *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, start, *low, (const UChar** )low_prev); } else { if (low_prev) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), *low); } } } /* no needs to adjust *high, *high is used as range check only */ if ((ptrdiff_t )(p - str) < (ptrdiff_t )reg->dist_min) *high = (UChar* )str; else *high = p - reg->dist_min; } #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "forward_search success: low: %d, high: %d, dmin: %d, dmax: %d\n", (int )(*low - str), (int )(*high - str), reg->dist_min, reg->dist_max); #endif return 1; /* success */ } return 0; /* fail */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix #164: Integer overflow related to reg->dmax in search_in_range()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: backward_search(regex_t* reg, const UChar* str, const UChar* end, UChar* s, const UChar* range, UChar* adjrange, UChar** low, UChar** high) { UChar *p; p = s; retry: switch (reg->optimize) { case OPTIMIZE_STR: exact_method: p = slow_search_backward(reg->enc, reg->exact, reg->exact_end, range, adjrange, end, p); break; case OPTIMIZE_STR_CASE_FOLD: p = slow_search_backward_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, range, adjrange, end, p); break; case OPTIMIZE_STR_FAST: case OPTIMIZE_STR_FAST_STEP_FORWARD: goto exact_method; break; case OPTIMIZE_MAP: p = map_search_backward(reg->enc, reg->map, range, adjrange, p); break; } if (p) { if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, str, p); if (IS_NOT_NULL(prev) && !ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) { p = prev; goto retry; } } break; case ANCR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = onigenc_get_prev_char_head(reg->enc, adjrange, p); if (IS_NULL(prev)) goto fail; if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) { p = prev; goto retry; } #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) { p = onigenc_get_prev_char_head(reg->enc, adjrange, p); if (IS_NULL(p)) goto fail; goto retry; } break; } } if (reg->dist_max != INFINITE_LEN) { if ((ptrdiff_t )(p - str) < (ptrdiff_t )reg->dist_max) *low = (UChar* )str; else *low = p - reg->dist_max; if (reg->dist_min != 0) { if ((ptrdiff_t )(p - str) < (ptrdiff_t )reg->dist_min) *high = (UChar* )str; else *high = p - reg->dist_min; } else { *high = p; } *high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high); } #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "backward_search: low: %d, high: %d\n", (int )(*low - str), (int )(*high - str)); #endif return 1; /* success */ } fail: #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "backward_search: fail.\n"); #endif return 0; /* fail */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix #164: Integer overflow related to reg->dmax in search_in_range()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { #define ASCII_LIMIT 127 int c, r; int ascii_mode; const OnigCodePoint *ranges; OnigCodePoint limit; OnigCodePoint sb_out; OnigEncoding enc = env->enc; ascii_mode = IS_ASCII_MODE_CTYPE_OPTION(ctype, env->options); r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { if (ascii_mode == 0) r = add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); else r = add_ctype_to_cc_by_range_limit(cc, ctype, not, env->enc, sb_out, ranges, ASCII_LIMIT); return r; } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; limit = ascii_mode ? ASCII_LIMIT : SINGLE_BYTE_SIZE; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < (int )limit; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } for (c = limit; c < SINGLE_BYTE_SIZE; c++) { BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < (int )limit; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: case ONIGENC_CTYPE_WORD: if (not != 0) { for (c = 0; c < (int )limit; c++) { if (ONIGENC_CODE_TO_MBCLEN(enc, c) > 0 /* check invalid code point */ && ! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } for (c = limit; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < (int )limit; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } if (ascii_mode == 0) ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; default: return ONIGERR_PARSER_BUG; break; } return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix #163: heap-buffer-overflow in gb18030_mbc_enc_len'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; const OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } else { onig_syntax_warn(env, "invalid Unicode Property \\%c", c); } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 0, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev, end) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 0, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, 4, enc); if (num < -1) return ONIGERR_TOO_SHORT_DIGITS; else if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case 'o': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) { PINC; num = scan_unsigned_octal_number(&p, end, 11, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_DIGIT(enc, c2) && c2 < '8') return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev, end) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 8; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0 || 0xff < num) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env); if (num < 0) return num; if (tok->u.c != num) { tok->u.code = (OnigCodePoint )num; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bug: Fix out of bounds read Add boundary check before PFETCH. Based on the following commits on https://github.com/kkos/oniguruma , but not the same. * 68c395576813b3f9812427f94d272bcffaca316c * dc0a23eb16961f98d2a5a2128d18bd4602058a10 * 5186c7c706a7f280110e6a0b060f87d0f7d790ce * 562bf4825b301693180c674994bf708b28b00592 * 162cf9124ba3bfaa21d53ebc506f3d9354bfa99b'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r = 0, num; Node *target, *work1 = NULL, *work2 = NULL; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; # ifdef USE_CAPITAL_P_NAMED_GROUP case 'P': /* (?P<name>...) */ if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_CAPITAL_P_NAMED_GROUP)) { PFETCH(c); if (c == '<') goto named_group1; } return ONIGERR_UNDEFINED_GROUP_OPTION; break; # endif #endif case '<': /* look behind (?<=...), (?<!...) */ PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { /* (?<name>...) */ if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; if (num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; case '(': /* conditional expression: (?(cond)yes), (?(cond)yes|no) */ if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LPAREN_CONDITION)) { UChar *name = NULL; UChar *name_end; PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { /* (n) */ PUNFETCH; r = fetch_name((OnigCodePoint )'(', &p, end, &name_end, env, &num, 1); if (r < 0) return r; #if 0 /* Relative number is not currently supported. (same as Perl) */ if (num < 0) { num = BACKREF_REL_TO_ABS(num, env); if (num <= 0) return ONIGERR_INVALID_BACKREF; } #endif if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } } #ifdef USE_NAMED_GROUP else if (c == '<' || c == '\'') { /* (<name>), ('name') */ int nums; int *backs; name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; PFETCH(c); if (c != ')') return ONIGERR_UNDEFINED_GROUP_OPTION; nums = onig_name_to_group_numbers(env->reg, name, name_end, &backs); if (nums <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, name, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < nums; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } num = backs[0]; /* XXX: use left most named group as Perl */ } #endif else return ONIGERR_INVALID_CONDITION_PATTERN; *np = node_new_enclose(ENCLOSE_CONDITION); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (IS_NOT_NULL(name)) NENCLOSE(*np)->state |= NST_NAME_REF; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #if 0 case '|': /* branch reset: (?|...) */ if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_VBAR_BRANCH_RESET)) { /* TODO */ } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '^': /* loads default options */ if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { /* d-imsx */ ONOFF(option, ONIG_OPTION_ASCII_RANGE, 1); ONOFF(option, ONIG_OPTION_IGNORECASE, 1); ONOFF(option, ONIG_OPTION_SINGLELINE, 0); ONOFF(option, ONIG_OPTION_MULTILINE, 1); ONOFF(option, ONIG_OPTION_EXTEND, 1); PFETCH(c); } #if 0 else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { /* d-imx */ ONOFF(option, ONIG_OPTION_ASCII_RANGE, 0); ONOFF(option, ONIG_OPTION_POSIX_BRACKET_ALL_RANGE, 0); ONOFF(option, ONIG_OPTION_WORD_BOUND_ALL_RANGE, 0); ONOFF(option, ONIG_OPTION_IGNORECASE, 1); ONOFF(option, ONIG_OPTION_MULTILINE, 1); ONOFF(option, ONIG_OPTION_EXTEND, 1); PFETCH(c); } #endif else { return ONIGERR_UNDEFINED_GROUP_OPTION; } /* fall through */ #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': case 'a': case 'd': case 'l': case 'u': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif case 'a': /* limits \d, \s, \w and POSIX brackets to ASCII range */ if ((IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL) || IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) && (neg == 0)) { ONOFF(option, ONIG_OPTION_ASCII_RANGE, 0); ONOFF(option, ONIG_OPTION_POSIX_BRACKET_ALL_RANGE, 1); ONOFF(option, ONIG_OPTION_WORD_BOUND_ALL_RANGE, 1); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'u': if ((IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL) || IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) && (neg == 0)) { ONOFF(option, ONIG_OPTION_ASCII_RANGE, 1); ONOFF(option, ONIG_OPTION_POSIX_BRACKET_ALL_RANGE, 1); ONOFF(option, ONIG_OPTION_WORD_BOUND_ALL_RANGE, 1); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'd': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL) && (neg == 0)) { ONOFF(option, ONIG_OPTION_ASCII_RANGE, 1); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY) && (neg == 0)) { ONOFF(option, ONIG_OPTION_ASCII_RANGE, 0); ONOFF(option, ONIG_OPTION_POSIX_BRACKET_ALL_RANGE, 0); ONOFF(option, ONIG_OPTION_WORD_BOUND_ALL_RANGE, 0); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'l': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL) && (neg == 0)) { ONOFF(option, ONIG_OPTION_ASCII_RANGE, 1); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) return r; *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } else if (NENCLOSE(*np)->type == ENCLOSE_CONDITION) { if (NTYPE(target) != NT_ALT) { /* convert (?(cond)yes) to (?(cond)yes|empty) */ work1 = node_new_empty(); if (IS_NULL(work1)) goto err; work2 = onig_node_new_alt(work1, NULL_NODE); if (IS_NULL(work2)) goto err; work1 = onig_node_new_alt(target, work2); if (IS_NULL(work1)) goto err; NENCLOSE(*np)->target = work1; } } } *src = p; return 0; err: onig_node_free(work1); onig_node_free(work2); onig_node_free(*np); *np = NULL; return ONIGERR_MEMORY; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bug: Fix out of bounds read Add boundary check before PFETCH. Based on the following commits on https://github.com/kkos/oniguruma , but not the same. * 68c395576813b3f9812427f94d272bcffaca316c * dc0a23eb16961f98d2a5a2128d18bd4602058a10 * 5186c7c706a7f280110e6a0b060f87d0f7d790ce * 562bf4825b301693180c674994bf708b28b00592 * 162cf9124ba3bfaa21d53ebc506f3d9354bfa99b'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: irc_mode_channel_update (struct t_irc_server *server, struct t_irc_channel *channel, char set_flag, char chanmode, const char *argument) { char *pos_args, *str_modes, **argv, *pos, *ptr_arg; char *new_modes, *new_args, str_mode[2], *str_temp; int argc, current_arg, chanmode_found, length; if (!channel->modes) channel->modes = strdup ("+"); if (!channel->modes) return; argc = 0; argv = NULL; pos_args = strchr (channel->modes, ' '); if (pos_args) { str_modes = weechat_strndup (channel->modes, pos_args - channel->modes); if (!str_modes) return; pos_args++; while (pos_args[0] == ' ') pos_args++; argv = weechat_string_split (pos_args, " ", NULL, WEECHAT_STRING_SPLIT_STRIP_LEFT | WEECHAT_STRING_SPLIT_STRIP_RIGHT | WEECHAT_STRING_SPLIT_COLLAPSE_SEPS, 0, &argc); } else { str_modes = strdup (channel->modes); if (!str_modes) return; } new_modes = malloc (strlen (channel->modes) + 1 + 1); new_args = malloc (((pos_args) ? strlen (pos_args) : 0) + ((argument) ? 1 + strlen (argument) : 0) + 1); if (new_modes && new_args) { new_modes[0] = '\0'; new_args[0] = '\0'; /* loop on current modes and build "new_modes" + "new_args" */ current_arg = 0; chanmode_found = 0; pos = str_modes; while (pos && pos[0]) { if ((pos[0] == '+') || (pos[0] == '-')) { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); } else { ptr_arg = NULL; switch (irc_mode_get_chanmode_type (server, pos[0])) { case 'A': /* always argument */ case 'B': /* always argument */ case 'C': /* argument if set */ ptr_arg = (current_arg < argc) ? argv[current_arg] : NULL; break; case 'D': /* no argument */ break; } if (ptr_arg) current_arg++; if (pos[0] == chanmode) { chanmode_found = 1; if (set_flag == '+') { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (argument) { if (new_args[0]) strcat (new_args, " "); strcat (new_args, argument); } } } else { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (ptr_arg) { if (new_args[0]) strcat (new_args, " "); strcat (new_args, ptr_arg); } } } pos++; } if (!chanmode_found) { /* * chanmode was not in channel modes: if set_flag is '+', add * it to channel modes */ if (set_flag == '+') { if (argument) { /* add mode with argument at the end of modes */ str_mode[0] = chanmode; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (new_args[0]) strcat (new_args, " "); strcat (new_args, argument); } else { /* add mode without argument at the beginning of modes */ pos = new_modes; while (pos[0] == '+') pos++; memmove (pos + 1, pos, strlen (pos) + 1); pos[0] = chanmode; } } } if (new_args[0]) { length = strlen (new_modes) + 1 + strlen (new_args) + 1; str_temp = malloc (length); if (str_temp) { snprintf (str_temp, length, "%s %s", new_modes, new_args); if (channel->modes) free (channel->modes); channel->modes = str_temp; } } else { if (channel->modes) free (channel->modes); channel->modes = strdup (new_modes); } } if (new_modes) free (new_modes); if (new_args) free (new_args); if (str_modes) free (str_modes); if (argv) weechat_string_free_split (argv); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'irc: fix crash when receiving a malformed message 324 (channel mode) Thanks to Stuart Nevans Locke for reporting the issue.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength = oldLength + srcLength; // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'ICU-20958 Prevent SEGV_MAPERR in append See #971'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra) /* {{{ */ { php_session_rfc1867_progress *progress; int retval = SUCCESS; if (php_session_rfc1867_orig_callback) { retval = php_session_rfc1867_orig_callback(event, event_data, extra); } if (!PS(rfc1867_enabled)) { return retval; } progress = PS(rfc1867_progress); switch(event) { case MULTIPART_EVENT_START: { multipart_event_start *data = (multipart_event_start *) event_data; progress = ecalloc(1, sizeof(php_session_rfc1867_progress)); progress->content_length = data->content_length; progress->sname_len = strlen(PS(session_name)); PS(rfc1867_progress) = progress; } break; case MULTIPART_EVENT_FORMDATA: { multipart_event_formdata *data = (multipart_event_formdata *) event_data; size_t value_len; if (Z_TYPE(progress->sid) && progress->key.s) { break; } /* orig callback may have modified *data->newlength */ if (data->newlength) { value_len = *data->newlength; } else { value_len = data->length; } if (data->name && data->value && value_len) { size_t name_len = strlen(data->name); if (name_len == progress->sname_len && memcmp(data->name, PS(session_name), name_len) == 0) { zval_dtor(&progress->sid); ZVAL_STRINGL(&progress->sid, (*data->value), value_len); } else if (name_len == strlen(PS(rfc1867_name)) && memcmp(data->name, PS(rfc1867_name), name_len + 1) == 0) { smart_str_free(&progress->key); smart_str_appends(&progress->key, PS(rfc1867_prefix)); smart_str_appendl(&progress->key, *data->value, value_len); smart_str_0(&progress->key); progress->apply_trans_sid = APPLY_TRANS_SID; php_session_rfc1867_early_find_sid(progress); } } } break; case MULTIPART_EVENT_FILE_START: { multipart_event_file_start *data = (multipart_event_file_start *) event_data; /* Do nothing when $_POST["PHP_SESSION_UPLOAD_PROGRESS"] is not set * or when we have no session id */ if (!Z_TYPE(progress->sid) || !progress->key.s) { break; } /* First FILE_START event, initializing data */ if (Z_ISUNDEF(progress->data)) { if (PS(rfc1867_freq) >= 0) { progress->update_step = PS(rfc1867_freq); } else if (PS(rfc1867_freq) < 0) { /* % of total size */ progress->update_step = progress->content_length * -PS(rfc1867_freq) / 100; } progress->next_update = 0; progress->next_update_time = 0.0; array_init(&progress->data); array_init(&progress->files); add_assoc_long_ex(&progress->data, "start_time", sizeof("start_time") - 1, (zend_long)sapi_get_request_time()); add_assoc_long_ex(&progress->data, "content_length", sizeof("content_length") - 1, progress->content_length); add_assoc_long_ex(&progress->data, "bytes_processed", sizeof("bytes_processed") - 1, data->post_bytes_processed); add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 0); add_assoc_zval_ex(&progress->data, "files", sizeof("files") - 1, &progress->files); progress->post_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->data), "bytes_processed", sizeof("bytes_processed") - 1); php_rinit_session(0); PS(id) = zend_string_init(Z_STRVAL(progress->sid), Z_STRLEN(progress->sid), 0); if (progress->apply_trans_sid) { /* Enable trans sid by modifying flags */ PS(use_trans_sid) = 1; PS(use_only_cookies) = 0; } PS(send_cookie) = 0; } array_init(&progress->current_file); /* Each uploaded file has its own array. Trying to make it close to $_FILES entries. */ add_assoc_string_ex(&progress->current_file, "field_name", sizeof("field_name") - 1, data->name); add_assoc_string_ex(&progress->current_file, "name", sizeof("name") - 1, *data->filename); add_assoc_null_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1); add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, 0); add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 0); add_assoc_long_ex(&progress->current_file, "start_time", sizeof("start_time") - 1, (zend_long)time(NULL)); add_assoc_long_ex(&progress->current_file, "bytes_processed", sizeof("bytes_processed") - 1, 0); add_next_index_zval(&progress->files, &progress->current_file); progress->current_file_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->current_file), "bytes_processed", sizeof("bytes_processed") - 1); Z_LVAL_P(progress->current_file_bytes_processed) = data->post_bytes_processed; php_session_rfc1867_update(progress, 0); } break; case MULTIPART_EVENT_FILE_DATA: { multipart_event_file_data *data = (multipart_event_file_data *) event_data; if (!Z_TYPE(progress->sid) || !progress->key.s) { break; } Z_LVAL_P(progress->current_file_bytes_processed) = data->offset + data->length; Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed; php_session_rfc1867_update(progress, 0); } break; case MULTIPART_EVENT_FILE_END: { multipart_event_file_end *data = (multipart_event_file_end *) event_data; if (!Z_TYPE(progress->sid) || !progress->key.s) { break; } if (data->temp_filename) { add_assoc_string_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1, data->temp_filename); } add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, data->cancel_upload); add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 1); Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed; php_session_rfc1867_update(progress, 0); } break; case MULTIPART_EVENT_END: { multipart_event_end *data = (multipart_event_end *) event_data; if (Z_TYPE(progress->sid) && progress->key.s) { if (PS(rfc1867_cleanup)) { php_session_rfc1867_cleanup(progress); } else { SEPARATE_ARRAY(&progress->data); add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 1); Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed; php_session_rfc1867_update(progress, 1); } php_rshutdown_session_globals(); } if (!Z_ISUNDEF(progress->data)) { zval_ptr_dtor(&progress->data); } zval_ptr_dtor(&progress->sid); smart_str_free(&progress->key); efree(progress); progress = NULL; PS(rfc1867_progress) = NULL; } break; } if (progress && progress->cancel_upload) { return FAILURE; } return retval; } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #79221 - Null Pointer Dereference in PHP Session Upload Progress'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ati_2d_blt(ATIVGAState *s) { /* FIXME it is probably more complex than this and may need to be */ /* rewritten but for now as a start just to get some output: */ DisplaySurface *ds = qemu_console_surface(s->vga.con); DPRINTF("%p %u ds: %p %d %d rop: %x\n", s->vga.vram_ptr, s->vga.vbe_start_addr, surface_data(ds), surface_stride(ds), surface_bits_per_pixel(ds), (s->regs.dp_mix & GMC_ROP3_MASK) >> 16); int dst_x = (s->regs.dp_cntl & DST_X_LEFT_TO_RIGHT ? s->regs.dst_x : s->regs.dst_x + 1 - s->regs.dst_width); int dst_y = (s->regs.dp_cntl & DST_Y_TOP_TO_BOTTOM ? s->regs.dst_y : s->regs.dst_y + 1 - s->regs.dst_height); int bpp = ati_bpp_from_datatype(s); int dst_stride = DEFAULT_CNTL ? s->regs.dst_pitch : s->regs.default_pitch; uint8_t *dst_bits = s->vga.vram_ptr + (DEFAULT_CNTL ? s->regs.dst_offset : s->regs.default_offset); if (s->dev_id == PCI_DEVICE_ID_ATI_RAGE128_PF) { dst_bits += s->regs.crtc_offset & 0x07ffffff; dst_stride *= bpp; } uint8_t *end = s->vga.vram_ptr + s->vga.vram_size; if (dst_bits >= end || dst_bits + dst_x + (dst_y + s->regs.dst_height) * dst_stride >= end) { qemu_log_mask(LOG_UNIMP, "blt outside vram not implemented\n"); return; } DPRINTF("%d %d %d, %d %d %d, (%d,%d) -> (%d,%d) %dx%d %c %c\n", s->regs.src_offset, s->regs.dst_offset, s->regs.default_offset, s->regs.src_pitch, s->regs.dst_pitch, s->regs.default_pitch, s->regs.src_x, s->regs.src_y, s->regs.dst_x, s->regs.dst_y, s->regs.dst_width, s->regs.dst_height, (s->regs.dp_cntl & DST_X_LEFT_TO_RIGHT ? '>' : '<'), (s->regs.dp_cntl & DST_Y_TOP_TO_BOTTOM ? 'v' : '^')); switch (s->regs.dp_mix & GMC_ROP3_MASK) { case ROP3_SRCCOPY: { int src_x = (s->regs.dp_cntl & DST_X_LEFT_TO_RIGHT ? s->regs.src_x : s->regs.src_x + 1 - s->regs.dst_width); int src_y = (s->regs.dp_cntl & DST_Y_TOP_TO_BOTTOM ? s->regs.src_y : s->regs.src_y + 1 - s->regs.dst_height); int src_stride = DEFAULT_CNTL ? s->regs.src_pitch : s->regs.default_pitch; uint8_t *src_bits = s->vga.vram_ptr + (DEFAULT_CNTL ? s->regs.src_offset : s->regs.default_offset); if (s->dev_id == PCI_DEVICE_ID_ATI_RAGE128_PF) { src_bits += s->regs.crtc_offset & 0x07ffffff; src_stride *= bpp; } if (src_bits >= end || src_bits + src_x + (src_y + s->regs.dst_height) * src_stride >= end) { qemu_log_mask(LOG_UNIMP, "blt outside vram not implemented\n"); return; } src_stride /= sizeof(uint32_t); dst_stride /= sizeof(uint32_t); DPRINTF("pixman_blt(%p, %p, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)\n", src_bits, dst_bits, src_stride, dst_stride, bpp, bpp, src_x, src_y, dst_x, dst_y, s->regs.dst_width, s->regs.dst_height); if (s->regs.dp_cntl & DST_X_LEFT_TO_RIGHT && s->regs.dp_cntl & DST_Y_TOP_TO_BOTTOM) { pixman_blt((uint32_t *)src_bits, (uint32_t *)dst_bits, src_stride, dst_stride, bpp, bpp, src_x, src_y, dst_x, dst_y, s->regs.dst_width, s->regs.dst_height); } else { /* FIXME: We only really need a temporary if src and dst overlap */ int llb = s->regs.dst_width * (bpp / 8); int tmp_stride = DIV_ROUND_UP(llb, sizeof(uint32_t)); uint32_t *tmp = g_malloc(tmp_stride * sizeof(uint32_t) * s->regs.dst_height); pixman_blt((uint32_t *)src_bits, tmp, src_stride, tmp_stride, bpp, bpp, src_x, src_y, 0, 0, s->regs.dst_width, s->regs.dst_height); pixman_blt(tmp, (uint32_t *)dst_bits, tmp_stride, dst_stride, bpp, bpp, 0, 0, dst_x, dst_y, s->regs.dst_width, s->regs.dst_height); g_free(tmp); } if (dst_bits >= s->vga.vram_ptr + s->vga.vbe_start_addr && dst_bits < s->vga.vram_ptr + s->vga.vbe_start_addr + s->vga.vbe_regs[VBE_DISPI_INDEX_YRES] * s->vga.vbe_line_offset) { memory_region_set_dirty(&s->vga.vram, s->vga.vbe_start_addr + s->regs.dst_offset + dst_y * surface_stride(ds), s->regs.dst_height * surface_stride(ds)); } s->regs.dst_x += s->regs.dst_width; s->regs.dst_y += s->regs.dst_height; break; } case ROP3_PATCOPY: case ROP3_BLACKNESS: case ROP3_WHITENESS: { uint32_t filler = 0; switch (s->regs.dp_mix & GMC_ROP3_MASK) { case ROP3_PATCOPY: filler = s->regs.dp_brush_frgd_clr; break; case ROP3_BLACKNESS: filler = 0xffUL << 24 | rgb_to_pixel32(s->vga.palette[0], s->vga.palette[1], s->vga.palette[2]); break; case ROP3_WHITENESS: filler = 0xffUL << 24 | rgb_to_pixel32(s->vga.palette[3], s->vga.palette[4], s->vga.palette[5]); break; } dst_stride /= sizeof(uint32_t); DPRINTF("pixman_fill(%p, %d, %d, %d, %d, %d, %d, %x)\n", dst_bits, dst_stride, bpp, s->regs.dst_x, s->regs.dst_y, s->regs.dst_width, s->regs.dst_height, filler); pixman_fill((uint32_t *)dst_bits, dst_stride, bpp, s->regs.dst_x, s->regs.dst_y, s->regs.dst_width, s->regs.dst_height, filler); if (dst_bits >= s->vga.vram_ptr + s->vga.vbe_start_addr && dst_bits < s->vga.vram_ptr + s->vga.vbe_start_addr + s->vga.vbe_regs[VBE_DISPI_INDEX_YRES] * s->vga.vbe_line_offset) { memory_region_set_dirty(&s->vga.vram, s->vga.vbe_start_addr + s->regs.dst_offset + dst_y * surface_stride(ds), s->regs.dst_height * surface_stride(ds)); } s->regs.dst_y += s->regs.dst_height; break; } default: qemu_log_mask(LOG_UNIMP, "Unimplemented ati_2d blt op %x\n", (s->regs.dp_mix & GMC_ROP3_MASK) >> 16); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'ati-vga: Fix checks in ati_2d_blt() to avoid crash In some corner cases (that never happen during normal operation but a malicious guest could program wrong values) pixman functions were called with parameters that result in a crash. Fix this and add more checks to disallow such cases. Reported-by: Ziming Zhang <ezrakiez@gmail.com> Signed-off-by: BALATON Zoltan <balaton@eik.bme.hu> Message-id: 20200406204029.19559747D5D@zero.eik.bme.hu Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void *zrle_convert_fb(VncState *vs, int x, int y, int w, int h, int bpp) { Buffer tmp; buffer_reset(&vs->zrle.fb); buffer_reserve(&vs->zrle.fb, w * h * bpp + bpp); tmp = vs->output; vs->output = vs->zrle.fb; vnc_raw_send_framebuffer_update(vs, x, y, w, h); vs->zrle.fb = vs->output; vs->output = tmp; return vs->zrle.fb.buffer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void write_png_palette(int idx, uint32_t pix, void *opaque) { struct palette_cb_priv *priv = opaque; VncState *vs = priv->vs; png_colorp color = &priv->png_palette[idx]; if (vs->tight.pixel24) { color->red = (pix >> vs->client_pf.rshift) & vs->client_pf.rmax; color->green = (pix >> vs->client_pf.gshift) & vs->client_pf.gmax; color->blue = (pix >> vs->client_pf.bshift) & vs->client_pf.bmax; } else { int red, green, blue; red = (pix >> vs->client_pf.rshift) & vs->client_pf.rmax; green = (pix >> vs->client_pf.gshift) & vs->client_pf.gmax; blue = (pix >> vs->client_pf.bshift) & vs->client_pf.bmax; color->red = ((red * 255 + vs->client_pf.rmax / 2) / vs->client_pf.rmax); color->green = ((green * 255 + vs->client_pf.gmax / 2) / vs->client_pf.gmax); color->blue = ((blue * 255 + vs->client_pf.bmax / 2) / vs->client_pf.bmax); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int vnc_zrle_send_framebuffer_update(VncState *vs, int x, int y, int w, int h) { vs->zrle.type = VNC_ENCODING_ZRLE; return zrle_send_framebuffer_update(vs, x, y, w, h); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static boolean jpeg_empty_output_buffer(j_compress_ptr cinfo) { VncState *vs = cinfo->client_data; Buffer *buffer = &vs->tight.jpeg; buffer->offset = buffer->capacity; buffer_reserve(buffer, 2048); jpeg_init_destination(cinfo); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void png_write_data(png_structp png_ptr, png_bytep data, png_size_t length) { VncState *vs = png_get_io_ptr(png_ptr); buffer_reserve(&vs->tight.png, vs->tight.png.offset + length); memcpy(vs->tight.png.buffer + vs->tight.png.offset, data, length); vs->tight.png.offset += length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tight_detect_smooth_image24(VncState *vs, int w, int h) { int off; int x, y, d, dx; unsigned int c; unsigned int stats[256]; int pixels = 0; int pix, left[3]; unsigned int errors; unsigned char *buf = vs->tight.tight.buffer; /* * If client is big-endian, color samples begin from the second * byte (offset 1) of a 32-bit pixel value. */ off = vs->client_be; memset(stats, 0, sizeof (stats)); for (y = 0, x = 0; y < h && x < w;) { for (d = 0; d < h - y && d < w - x - VNC_TIGHT_DETECT_SUBROW_WIDTH; d++) { for (c = 0; c < 3; c++) { left[c] = buf[((y+d)*w+x+d)*4+off+c] & 0xFF; } for (dx = 1; dx <= VNC_TIGHT_DETECT_SUBROW_WIDTH; dx++) { for (c = 0; c < 3; c++) { pix = buf[((y+d)*w+x+d+dx)*4+off+c] & 0xFF; stats[abs(pix - left[c])]++; left[c] = pix; } pixels++; } } if (w > h) { x += h; y = 0; } else { x = 0; y += w; } } if (pixels == 0) { return 0; } /* 95% smooth or more ... */ if (stats[0] * 33 / pixels >= 95) { return 0; } errors = 0; for (c = 1; c < 8; c++) { errors += stats[c] * (c * c); if (stats[c] == 0 || stats[c] > stats[c-1] * 2) { return 0; } } for (; c < 256; c++) { errors += stats[c] * (c * c); } errors /= (pixels * 3 - stats[0]); return errors; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int send_full_color_rect(VncState *vs, int x, int y, int w, int h) { int stream = 0; ssize_t bytes; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { return send_png_rect(vs, x, y, w, h, NULL); } #endif vnc_write_u8(vs, stream << 4); /* no flushing, no filter */ if (vs->tight.pixel24) { tight_pack24(vs, vs->tight.tight.buffer, w * h, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->client_pf.bytes_per_pixel; } bytes = tight_compress_data(vs, stream, w * h * bytes, tight_conf[vs->tight.compression].raw_zlib_level, Z_DEFAULT_STRATEGY); return (bytes >= 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void jpeg_term_destination(j_compress_ptr cinfo) { VncState *vs = cinfo->client_data; Buffer *buffer = &vs->tight.jpeg; buffer->offset = buffer->capacity - cinfo->dest->free_in_buffer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int send_rect_simple(VncState *vs, int x, int y, int w, int h, bool split) { int max_size, max_width; int max_sub_width, max_sub_height; int dx, dy; int rw, rh; int n = 0; max_size = tight_conf[vs->tight.compression].max_rect_size; max_width = tight_conf[vs->tight.compression].max_rect_width; if (split && (w > max_width || w * h > max_size)) { max_sub_width = (w > max_width) ? max_width : w; max_sub_height = max_size / max_sub_width; for (dy = 0; dy < h; dy += max_sub_height) { for (dx = 0; dx < w; dx += max_width) { rw = MIN(max_sub_width, w - dx); rh = MIN(max_sub_height, h - dy); n += send_sub_rect(vs, x+dx, y+dy, rw, rh); } } } else { n += send_sub_rect(vs, x, y, w, h); } return n; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h) { uint32_t *buf32; uint32_t pix32; int shift[3]; int *prev; int here[3], upper[3], left[3], upperleft[3]; int prediction; int x, y, c; buf32 = (uint32_t *)buf; memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int)); if (1 /* FIXME */) { shift[0] = vs->client_pf.rshift; shift[1] = vs->client_pf.gshift; shift[2] = vs->client_pf.bshift; } else { shift[0] = 24 - vs->client_pf.rshift; shift[1] = 24 - vs->client_pf.gshift; shift[2] = 24 - vs->client_pf.bshift; } for (y = 0; y < h; y++) { for (c = 0; c < 3; c++) { upper[c] = 0; here[c] = 0; } prev = (int *)vs->tight.gradient.buffer; for (x = 0; x < w; x++) { pix32 = *buf32++; for (c = 0; c < 3; c++) { upperleft[c] = upper[c]; left[c] = here[c]; upper[c] = *prev; here[c] = (int)(pix32 >> shift[c] & 0xFF); *prev++ = here[c]; prediction = left[c] + upper[c] - upperleft[c]; if (prediction < 0) { prediction = 0; } else if (prediction > 0xFF) { prediction = 0xFF; } *buf++ = (char)(here[c] - prediction); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void vnc_tight_start(VncState *vs) { buffer_reset(&vs->tight.tight); // make the output buffer be the zlib buffer, so we can compress it later vs->tight.tmp = vs->output; vs->output = vs->tight.tight; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int send_sub_rect_jpeg(VncState *vs, int x, int y, int w, int h, int bg, int fg, int colors, VncPalette *palette, bool force) { int ret; if (colors == 0) { if (force || (tight_jpeg_conf[vs->tight.quality].jpeg_full && tight_detect_smooth_image(vs, w, h))) { int quality = tight_conf[vs->tight.quality].jpeg_quality; ret = send_jpeg_rect(vs, x, y, w, h, quality); } else { ret = send_full_color_rect(vs, x, y, w, h); } } else if (colors == 1) { ret = send_solid_rect(vs); } else if (colors == 2) { ret = send_mono_rect(vs, x, y, w, h, bg, fg); } else if (colors <= 256) { if (force || (colors > 96 && tight_jpeg_conf[vs->tight.quality].jpeg_idx && tight_detect_smooth_image(vs, w, h))) { int quality = tight_conf[vs->tight.quality].jpeg_quality; ret = send_jpeg_rect(vs, x, y, w, h, quality); } else { ret = send_palette_rect(vs, x, y, w, h, palette); } } else { ret = 0; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void vnc_zrle_clear(VncState *vs) { if (vs->zrle.stream.opaque) { deflateEnd(&vs->zrle.stream); } buffer_free(&vs->zrle.zrle); buffer_free(&vs->zrle.fb); buffer_free(&vs->zrle.zlib); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int zrle_compress_data(VncState *vs, int level) { z_streamp zstream = &vs->zrle.stream; buffer_reset(&vs->zrle.zlib); if (zstream->opaque != vs) { int err; zstream->zalloc = vnc_zlib_zalloc; zstream->zfree = vnc_zlib_zfree; err = deflateInit2(zstream, level, Z_DEFLATED, MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); if (err != Z_OK) { fprintf(stderr, "VNC: error initializing zlib\n"); return -1; } zstream->opaque = vs; } /* reserve memory in output buffer */ buffer_reserve(&vs->zrle.zlib, vs->zrle.zrle.offset + 64); /* set pointers */ zstream->next_in = vs->zrle.zrle.buffer; zstream->avail_in = vs->zrle.zrle.offset; zstream->next_out = vs->zrle.zlib.buffer + vs->zrle.zlib.offset; zstream->avail_out = vs->zrle.zlib.capacity - vs->zrle.zlib.offset; zstream->data_type = Z_BINARY; /* start encoding */ if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) { fprintf(stderr, "VNC: error during zrle compression\n"); return -1; } vs->zrle.zlib.offset = vs->zrle.zlib.capacity - zstream->avail_out; return vs->zrle.zlib.offset; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int send_solid_rect(VncState *vs) { size_t bytes; vnc_write_u8(vs, VNC_TIGHT_FILL << 4); /* no flushing, no filter */ if (vs->tight.pixel24) { tight_pack24(vs, vs->tight.tight.buffer, 1, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->client_pf.bytes_per_pixel; } vnc_write(vs, vs->tight.tight.buffer, bytes); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void vnc_tight_stop(VncState *vs) { // switch back to normal output/zlib buffers vs->tight.tight = vs->output; vs->output = vs->tight.tmp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc, bool skipauth, bool websocket) { VncState *vs = g_new0(VncState, 1); bool first_client = QTAILQ_EMPTY(&vd->clients); int i; trace_vnc_client_connect(vs, sioc); vs->magic = VNC_MAGIC; vs->sioc = sioc; object_ref(OBJECT(vs->sioc)); vs->ioc = QIO_CHANNEL(sioc); object_ref(OBJECT(vs->ioc)); vs->vd = vd; buffer_init(&vs->input, "vnc-input/%p", sioc); buffer_init(&vs->output, "vnc-output/%p", sioc); buffer_init(&vs->jobs_buffer, "vnc-jobs_buffer/%p", sioc); buffer_init(&vs->tight.tight, "vnc-tight/%p", sioc); buffer_init(&vs->tight.zlib, "vnc-tight-zlib/%p", sioc); buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc); #ifdef CONFIG_VNC_JPEG buffer_init(&vs->tight.jpeg, "vnc-tight-jpeg/%p", sioc); #endif #ifdef CONFIG_VNC_PNG buffer_init(&vs->tight.png, "vnc-tight-png/%p", sioc); #endif buffer_init(&vs->zlib.zlib, "vnc-zlib/%p", sioc); buffer_init(&vs->zrle.zrle, "vnc-zrle/%p", sioc); buffer_init(&vs->zrle.fb, "vnc-zrle-fb/%p", sioc); buffer_init(&vs->zrle.zlib, "vnc-zrle-zlib/%p", sioc); if (skipauth) { vs->auth = VNC_AUTH_NONE; vs->subauth = VNC_AUTH_INVALID; } else { if (websocket) { vs->auth = vd->ws_auth; vs->subauth = VNC_AUTH_INVALID; } else { vs->auth = vd->auth; vs->subauth = vd->subauth; } } VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n", sioc, websocket, vs->auth, vs->subauth); vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect)); for (i = 0; i < VNC_STAT_ROWS; ++i) { vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS); } VNC_DEBUG("New client on socket %p\n", vs->sioc); update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE); qio_channel_set_blocking(vs->ioc, false, NULL); if (vs->ioc_tag) { g_source_remove(vs->ioc_tag); } if (websocket) { vs->websocket = 1; if (vd->tlscreds) { vs->ioc_tag = qio_channel_add_watch( vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL); } else { vs->ioc_tag = qio_channel_add_watch( vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL); } } else { vs->ioc_tag = qio_channel_add_watch( vs->ioc, G_IO_IN, vnc_client_io, vs, NULL); } vnc_client_cache_addr(vs); vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED); vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING); vs->last_x = -1; vs->last_y = -1; vs->as.freq = 44100; vs->as.nchannels = 2; vs->as.fmt = AUDIO_FORMAT_S16; vs->as.endianness = 0; qemu_mutex_init(&vs->output_mutex); vs->bh = qemu_bh_new(vnc_jobs_bh, vs); QTAILQ_INSERT_TAIL(&vd->clients, vs, next); if (first_client) { vnc_update_server_surface(vd); } graphic_hw_update(vd->dcl.con); if (!vs->websocket) { vnc_start_protocol(vs); } if (vd->num_connecting > vd->connections_limit) { QTAILQ_FOREACH(vs, &vd->clients, next) { if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) { vnc_disconnect_start(vs); return; } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int send_sub_rect_solid(VncState *vs, int x, int y, int w, int h) { vnc_framebuffer_update(vs, x, y, w, h, vs->tight.type); vnc_tight_start(vs); vnc_raw_send_framebuffer_update(vs, x, y, w, h); vnc_tight_stop(vs); return send_solid_rect(vs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int zrle_send_framebuffer_update(VncState *vs, int x, int y, int w, int h) { bool be = vs->client_be; size_t bytes; int zywrle_level; if (vs->zrle.type == VNC_ENCODING_ZYWRLE) { if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1 || vs->tight.quality == 9) { zywrle_level = 0; vs->zrle.type = VNC_ENCODING_ZRLE; } else if (vs->tight.quality < 3) { zywrle_level = 3; } else if (vs->tight.quality < 6) { zywrle_level = 2; } else { zywrle_level = 1; } } else { zywrle_level = 0; } vnc_zrle_start(vs); switch (vs->client_pf.bytes_per_pixel) { case 1: zrle_encode_8ne(vs, x, y, w, h, zywrle_level); break; case 2: if (vs->client_pf.gmax > 0x1F) { if (be) { zrle_encode_16be(vs, x, y, w, h, zywrle_level); } else { zrle_encode_16le(vs, x, y, w, h, zywrle_level); } } else { if (be) { zrle_encode_15be(vs, x, y, w, h, zywrle_level); } else { zrle_encode_15le(vs, x, y, w, h, zywrle_level); } } break; case 4: { bool fits_in_ls3bytes; bool fits_in_ms3bytes; fits_in_ls3bytes = ((vs->client_pf.rmax << vs->client_pf.rshift) < (1 << 24) && (vs->client_pf.gmax << vs->client_pf.gshift) < (1 << 24) && (vs->client_pf.bmax << vs->client_pf.bshift) < (1 << 24)); fits_in_ms3bytes = (vs->client_pf.rshift > 7 && vs->client_pf.gshift > 7 && vs->client_pf.bshift > 7); if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) { if (be) { zrle_encode_24abe(vs, x, y, w, h, zywrle_level); } else { zrle_encode_24ale(vs, x, y, w, h, zywrle_level); } } else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) { if (be) { zrle_encode_24bbe(vs, x, y, w, h, zywrle_level); } else { zrle_encode_24ble(vs, x, y, w, h, zywrle_level); } } else { if (be) { zrle_encode_32be(vs, x, y, w, h, zywrle_level); } else { zrle_encode_32le(vs, x, y, w, h, zywrle_level); } } } break; } vnc_zrle_stop(vs); bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION); vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type); vnc_write_u32(vs, bytes); vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int send_jpeg_rect(VncState *vs, int x, int y, int w, int h, int quality) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; struct jpeg_destination_mgr manager; pixman_image_t *linebuf; JSAMPROW row[1]; uint8_t *buf; int dy; if (surface_bytes_per_pixel(vs->vd->ds) == 1) { return send_full_color_rect(vs, x, y, w, h); } buffer_reserve(&vs->tight.jpeg, 2048); cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); cinfo.client_data = vs; cinfo.image_width = w; cinfo.image_height = h; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, true); manager.init_destination = jpeg_init_destination; manager.empty_output_buffer = jpeg_empty_output_buffer; manager.term_destination = jpeg_term_destination; cinfo.dest = &manager; jpeg_start_compress(&cinfo, true); linebuf = qemu_pixman_linebuf_create(PIXMAN_BE_r8g8b8, w); buf = (uint8_t *)pixman_image_get_data(linebuf); row[0] = buf; for (dy = 0; dy < h; dy++) { qemu_pixman_linebuf_fill(linebuf, vs->vd->server, w, x, y + dy); jpeg_write_scanlines(&cinfo, row, 1); } qemu_pixman_image_unref(linebuf); jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); vnc_write_u8(vs, VNC_TIGHT_JPEG << 4); tight_send_compact_size(vs, vs->tight.jpeg.offset); vnc_write(vs, vs->tight.jpeg.buffer, vs->tight.jpeg.offset); buffer_reset(&vs->tight.jpeg); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ZRLE_ENCODE_TILE(VncState *vs, ZRLE_PIXEL *data, int w, int h, int zywrle_level) { VncPalette *palette = &vs->zrle.palette; int runs = 0; int single_pixels = 0; bool use_rle; bool use_palette; int i; ZRLE_PIXEL *ptr = data; ZRLE_PIXEL *end = ptr + h * w; *end = ~*(end-1); /* one past the end is different so the while loop ends */ /* Real limit is 127 but we wan't a way to know if there is more than 127 */ palette_init(palette, 256, ZRLE_BPP); while (ptr < end) { ZRLE_PIXEL pix = *ptr; if (*++ptr != pix) { /* FIXME */ single_pixels++; } else { while (*++ptr == pix) ; runs++; } palette_put(palette, pix); } /* Solid tile is a special case */ if (palette_size(palette) == 1) { bool found; vnc_write_u8(vs, 1); ZRLE_WRITE_PIXEL(vs, palette_color(palette, 0, &found)); return; } zrle_choose_palette_rle(vs, w, h, palette, ZRLE_BPP_OUT, runs, single_pixels, zywrle_level, &use_rle, &use_palette); if (!use_palette) { vnc_write_u8(vs, (use_rle ? 128 : 0)); } else { uint32_t colors[VNC_PALETTE_MAX_SIZE]; size_t size = palette_size(palette); vnc_write_u8(vs, (use_rle ? 128 : 0) | size); palette_fill(palette, colors); for (i = 0; i < size; i++) { ZRLE_WRITE_PIXEL(vs, colors[i]); } } if (use_rle) { ZRLE_PIXEL *ptr = data; ZRLE_PIXEL *end = ptr + w * h; ZRLE_PIXEL *run_start; ZRLE_PIXEL pix; while (ptr < end) { int len; int index = 0; run_start = ptr; pix = *ptr++; while (*ptr == pix && ptr < end) { ptr++; } len = ptr - run_start; if (use_palette) index = palette_idx(palette, pix); if (len <= 2 && use_palette) { if (len == 2) { vnc_write_u8(vs, index); } vnc_write_u8(vs, index); continue; } if (use_palette) { vnc_write_u8(vs, index | 128); } else { ZRLE_WRITE_PIXEL(vs, pix); } len -= 1; while (len >= 255) { vnc_write_u8(vs, 255); len -= 255; } vnc_write_u8(vs, len); } } else if (use_palette) { /* no RLE */ int bppp; ZRLE_PIXEL *ptr = data; /* packed pixels */ assert (palette_size(palette) < 17); bppp = bits_per_packed_pixel[palette_size(palette)-1]; for (i = 0; i < h; i++) { uint8_t nbits = 0; uint8_t byte = 0; ZRLE_PIXEL *eol = ptr + w; while (ptr < eol) { ZRLE_PIXEL pix = *ptr++; uint8_t index = palette_idx(palette, pix); byte = (byte << bppp) | index; nbits += bppp; if (nbits >= 8) { vnc_write_u8(vs, byte); nbits = 0; } } if (nbits > 0) { byte <<= 8 - nbits; vnc_write_u8(vs, byte); } } } else { /* raw */ #if ZRLE_BPP != 8 if (zywrle_level > 0 && !(zywrle_level & 0x80)) { ZYWRLE_ANALYZE(data, data, w, h, w, zywrle_level, vs->zywrle.buf); ZRLE_ENCODE_TILE(vs, data, w, h, zywrle_level | 0x80); } else #endif { #ifdef ZRLE_COMPACT_PIXEL ZRLE_PIXEL *ptr; for (ptr = data; ptr < data + w * h; ptr++) { ZRLE_WRITE_PIXEL(vs, *ptr); } #else vnc_write(vs, data, w * h * (ZRLE_BPP / 8)); #endif } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'vnc: fix memory leak when vnc disconnect Currently when qemu receives a vnc connect, it creates a 'VncState' to represent this connection. In 'vnc_worker_thread_loop' it creates a local 'VncState'. The connection 'VcnState' and local 'VncState' exchange data in 'vnc_async_encoding_start' and 'vnc_async_encoding_end'. In 'zrle_compress_data' it calls 'deflateInit2' to allocate the libz library opaque data. The 'VncState' used in 'zrle_compress_data' is the local 'VncState'. In 'vnc_zrle_clear' it calls 'deflateEnd' to free the libz library opaque data. The 'VncState' used in 'vnc_zrle_clear' is the connection 'VncState'. In currently implementation there will be a memory leak when the vnc disconnect. Following is the asan output backtrack: Direct leak of 29760 byte(s) in 5 object(s) allocated from: 0 0xffffa67ef3c3 in __interceptor_calloc (/lib64/libasan.so.4+0xd33c3) 1 0xffffa65071cb in g_malloc0 (/lib64/libglib-2.0.so.0+0x571cb) 2 0xffffa5e968f7 in deflateInit2_ (/lib64/libz.so.1+0x78f7) 3 0xaaaacec58613 in zrle_compress_data ui/vnc-enc-zrle.c:87 4 0xaaaacec58613 in zrle_send_framebuffer_update ui/vnc-enc-zrle.c:344 5 0xaaaacec34e77 in vnc_send_framebuffer_update ui/vnc.c:919 6 0xaaaacec5e023 in vnc_worker_thread_loop ui/vnc-jobs.c:271 7 0xaaaacec5e5e7 in vnc_worker_thread ui/vnc-jobs.c:340 8 0xaaaacee4d3c3 in qemu_thread_start util/qemu-thread-posix.c:502 9 0xffffa544e8bb in start_thread (/lib64/libpthread.so.0+0x78bb) 10 0xffffa53965cb in thread_start (/lib64/libc.so.6+0xd55cb) This is because the opaque allocated in 'deflateInit2' is not freed in 'deflateEnd'. The reason is that the 'deflateEnd' calls 'deflateStateCheck' and in the latter will check whether 's->strm != strm'(libz's data structure). This check will be true so in 'deflateEnd' it just return 'Z_STREAM_ERROR' and not free the data allocated in 'deflateInit2'. The reason this happens is that the 'VncState' contains the whole 'VncZrle', so when calling 'deflateInit2', the 's->strm' will be the local address. So 's->strm != strm' will be true. To fix this issue, we need to make 'zrle' of 'VncState' to be a pointer. Then the connection 'VncState' and local 'VncState' exchange mechanism will work as expection. The 'tight' of 'VncState' has the same issue, let's also turn it to a pointer. Reported-by: Ying Fang <fangying1@huawei.com> Signed-off-by: Li Qiang <liq3ea@163.com> Message-id: 20190831153922.121308-1-liq3ea@163.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: handle_keywordonly_args(struct compiling *c, const node *n, int start, asdl_seq *kwonlyargs, asdl_seq *kwdefaults) { PyObject *argname; node *ch; expr_ty expression, annotation; arg_ty arg = NULL; int i = start; int j = 0; /* index for kwdefaults and kwonlyargs */ if (kwonlyargs == NULL) { ast_error(c, CHILD(n, start), "named arguments must follow bare *"); return -1; } assert(kwdefaults != NULL); while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { case vfpdef: case tfpdef: if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) goto error; asdl_seq_SET(kwdefaults, j, expression); i += 2; /* '=' and test */ } else { /* setting NULL if no default value exists */ asdl_seq_SET(kwdefaults, j, NULL); } if (NCH(ch) == 3) { /* ch is NAME ':' test */ annotation = ast_for_expr(c, CHILD(ch, 2)); if (!annotation) goto error; } else { annotation = NULL; } ch = CHILD(ch, 0); argname = NEW_IDENTIFIER(ch); if (!argname) goto error; if (forbidden_name(c, argname, ch, 0)) goto error; arg = arg(argname, annotation, NULL, LINENO(ch), ch->n_col_offset, ch->n_end_lineno, ch->n_end_col_offset, c->c_arena); if (!arg) goto error; asdl_seq_SET(kwonlyargs, j++, arg); i += 1; /* the name */ if (TYPE(CHILD(n, i)) == COMMA) i += 1; /* the comma, if present */ break; case TYPE_COMMENT: /* arg will be equal to the last argument processed */ arg->type_comment = NEW_TYPE_COMMENT(ch); if (!arg->type_comment) goto error; i += 1; break; case DOUBLESTAR: return i; default: ast_error(c, ch, "unexpected node"); goto error; } } return i; error: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-36495: Fix two out-of-bounds array reads (GH-12641) Research and fix by @bradlarsen.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: arg(identifier arg, expr_ty annotation, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena) { arg_ty p; if (!arg) { PyErr_SetString(PyExc_ValueError, "field arg is required for arg"); return NULL; } p = (arg_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->arg = arg; p->annotation = annotation; p->lineno = lineno; p->col_offset = col_offset; p->end_lineno = end_lineno; p->end_col_offset = end_col_offset; return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); /* expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) | ('=' (yield_expr|testlist_star_expr))*) annassign: ':' test ['=' test] testlist_star_expr: (test|star_expr) (',' test|star_expr)* [','] augassign: '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=' test: ... here starts the operator precedence dance */ if (NCH(n) == 1) { expr_ty e = ast_for_testlist(c, CHILD(n, 0)); if (!e) return NULL; return Expr(e, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else if (TYPE(CHILD(n, 1)) == augassign) { expr_ty expr1, expr2; operator_ty newoperator; node *ch = CHILD(n, 0); expr1 = ast_for_testlist(c, ch); if (!expr1) return NULL; if(!set_context(c, expr1, Store, ch)) return NULL; /* set_context checks that most expressions are not the left side. Augmented assignments can only have a name, a subscript, or an attribute on the left, though, so we have to explicitly check for those. */ switch (expr1->kind) { case Name_kind: case Attribute_kind: case Subscript_kind: break; default: ast_error(c, ch, "illegal expression for augmented assignment"); return NULL; } ch = CHILD(n, 2); if (TYPE(ch) == testlist) expr2 = ast_for_testlist(c, ch); else expr2 = ast_for_expr(c, ch); if (!expr2) return NULL; newoperator = ast_for_augassign(c, CHILD(n, 1)); if (!newoperator) return NULL; return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else if (TYPE(CHILD(n, 1)) == annassign) { expr_ty expr1, expr2, expr3; node *ch = CHILD(n, 0); node *deep, *ann = CHILD(n, 1); int simple = 1; /* we keep track of parens to qualify (x) as expression not name */ deep = ch; while (NCH(deep) == 1) { deep = CHILD(deep, 0); } if (NCH(deep) > 0 && TYPE(CHILD(deep, 0)) == LPAR) { simple = 0; } expr1 = ast_for_testlist(c, ch); if (!expr1) { return NULL; } switch (expr1->kind) { case Name_kind: if (forbidden_name(c, expr1->v.Name.id, n, 0)) { return NULL; } expr1->v.Name.ctx = Store; break; case Attribute_kind: if (forbidden_name(c, expr1->v.Attribute.attr, n, 1)) { return NULL; } expr1->v.Attribute.ctx = Store; break; case Subscript_kind: expr1->v.Subscript.ctx = Store; break; case List_kind: ast_error(c, ch, "only single target (not list) can be annotated"); return NULL; case Tuple_kind: ast_error(c, ch, "only single target (not tuple) can be annotated"); return NULL; default: ast_error(c, ch, "illegal target for annotation"); return NULL; } if (expr1->kind != Name_kind) { simple = 0; } ch = CHILD(ann, 1); expr2 = ast_for_expr(c, ch); if (!expr2) { return NULL; } if (NCH(ann) == 2) { return AnnAssign(expr1, expr2, NULL, simple, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else { ch = CHILD(ann, 3); if (TYPE(ch) == testlist) { expr3 = ast_for_testlist(c, ch); } else { expr3 = ast_for_expr(c, ch); } if (!expr3) { return NULL; } return AnnAssign(expr1, expr2, expr3, simple, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } } else { int i; asdl_seq *targets; node *value; expr_ty expression; /* a normal assignment */ REQ(CHILD(n, 1), EQUAL); targets = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena); if (!targets) return NULL; for (i = 0; i < NCH(n) - 2; i += 2) { expr_ty e; node *ch = CHILD(n, i); if (TYPE(ch) == yield_expr) { ast_error(c, ch, "assignment to yield expression not possible"); return NULL; } e = ast_for_testlist(c, ch); if (!e) return NULL; /* set context to assign */ if (!set_context(c, e, Store, CHILD(n, i))) return NULL; asdl_seq_SET(targets, i / 2, e); } value = CHILD(n, NCH(n) - 1); if (TYPE(value) == testlist_star_expr) expression = ast_for_testlist(c, value); else expression = ast_for_expr(c, value); if (!expression) return NULL; return Assign(targets, expression, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PyParser_AddToken(parser_state *ps, int type, char *str, int lineno, int col_offset, int end_lineno, int end_col_offset, int *expected_ret) { int ilabel; int err; D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); /* Find out which label this token is */ ilabel = classify(ps, type, str); if (ilabel < 0) return E_SYNTAX; /* Loop until the token is shifted or an error occurred */ for (;;) { /* Fetch the current dfa and state */ dfa *d = ps->p_stack.s_top->s_dfa; state *s = &d->d_state[ps->p_stack.s_top->s_state]; D(printf(" DFA '%s', state %d:", d->d_name, ps->p_stack.s_top->s_state)); /* Check accelerator */ if (s->s_lower <= ilabel && ilabel < s->s_upper) { int x = s->s_accel[ilabel - s->s_lower]; if (x != -1) { if (x & (1<<7)) { /* Push non-terminal */ int nt = (x >> 8) + NT_OFFSET; int arrow = x & ((1<<7)-1); dfa *d1 = PyGrammar_FindDFA( ps->p_grammar, nt); if ((err = push(&ps->p_stack, nt, d1, arrow, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: push\n")); return err; } D(printf(" Push ...\n")); continue; } /* Shift the token */ if ((err = shift(&ps->p_stack, type, str, x, lineno, col_offset, end_lineno, end_col_offset)) > 0) { D(printf(" MemError: shift.\n")); return err; } D(printf(" Shift.\n")); /* Pop while we are in an accept-only state */ while (s = &d->d_state [ps->p_stack.s_top->s_state], s->s_accept && s->s_narcs == 1) { D(printf(" DFA '%s', state %d: " "Direct pop.\n", d->d_name, ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif s_pop(&ps->p_stack); if (s_empty(&ps->p_stack)) { D(printf(" ACCEPT.\n")); return E_DONE; } d = ps->p_stack.s_top->s_dfa; } return E_OK; } } if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif /* Pop this dfa and try again */ s_pop(&ps->p_stack); D(printf(" Pop ...\n")); if (s_empty(&ps->p_stack)) { D(printf(" Error: bottom of stack.\n")); return E_SYNTAX; } continue; } /* Stuck, report syntax error */ D(printf(" Error.\n")); if (expected_ret) { if (s->s_lower == s->s_upper - 1) { /* Only one possible expected token */ *expected_ret = ps->p_grammar-> g_ll.ll_label[s->s_lower].lb_type; } else *expected_ret = -1; } return E_SYNTAX; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: num_stmts(const node *n) { int i, l; node *ch; switch (TYPE(n)) { case single_input: if (TYPE(CHILD(n, 0)) == NEWLINE) return 0; else return num_stmts(CHILD(n, 0)); case file_input: l = 0; for (i = 0; i < NCH(n); i++) { ch = CHILD(n, i); if (TYPE(ch) == stmt) l += num_stmts(ch); } return l; case stmt: return num_stmts(CHILD(n, 0)); case compound_stmt: return 1; case simple_stmt: return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */ case suite: if (NCH(n) == 1) return num_stmts(CHILD(n, 0)); else { l = 0; for (i = 2; i < (NCH(n) - 1); i++) l += num_stmts(CHILD(n, i)); return l; } default: { char buf[128]; sprintf(buf, "Non-statement found: %d %d", TYPE(n), NCH(n)); Py_FatalError(buf); } } Py_UNREACHABLE(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast2obj_stmt(void* _o) { stmt_ty o = (stmt_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_RETURN_NONE; } switch (o->kind) { case FunctionDef_kind: result = PyType_GenericNew(FunctionDef_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.FunctionDef.name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_arguments(o->v.FunctionDef.args); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_args, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.FunctionDef.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.FunctionDef.decorator_list, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_decorator_list, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.FunctionDef.returns); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_returns, value) == -1) goto failed; Py_DECREF(value); break; case AsyncFunctionDef_kind: result = PyType_GenericNew(AsyncFunctionDef_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.AsyncFunctionDef.name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_arguments(o->v.AsyncFunctionDef.args); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_args, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncFunctionDef.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncFunctionDef.decorator_list, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_decorator_list, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AsyncFunctionDef.returns); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_returns, value) == -1) goto failed; Py_DECREF(value); break; case ClassDef_kind: result = PyType_GenericNew(ClassDef_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.ClassDef.name); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_name, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ClassDef.bases, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_bases, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ClassDef.keywords, ast2obj_keyword); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_keywords, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ClassDef.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ClassDef.decorator_list, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_decorator_list, value) == -1) goto failed; Py_DECREF(value); break; case Return_kind: result = PyType_GenericNew(Return_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Return.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case Delete_kind: result = PyType_GenericNew(Delete_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Delete.targets, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_targets, value) == -1) goto failed; Py_DECREF(value); break; case Assign_kind: result = PyType_GenericNew(Assign_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Assign.targets, ast2obj_expr); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_targets, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Assign.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case AugAssign_kind: result = PyType_GenericNew(AugAssign_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.AugAssign.target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_operator(o->v.AugAssign.op); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_op, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AugAssign.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case AnnAssign_kind: result = PyType_GenericNew(AnnAssign_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.AnnAssign.target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AnnAssign.annotation); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_annotation, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AnnAssign.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_int(o->v.AnnAssign.simple); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_simple, value) == -1) goto failed; Py_DECREF(value); break; case For_kind: result = PyType_GenericNew(For_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.For.target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.For.iter); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_iter, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.For.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.For.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case AsyncFor_kind: result = PyType_GenericNew(AsyncFor_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.AsyncFor.target); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_target, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.AsyncFor.iter); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_iter, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncFor.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncFor.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case While_kind: result = PyType_GenericNew(While_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.While.test); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_test, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.While.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.While.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case If_kind: result = PyType_GenericNew(If_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.If.test); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_test, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.If.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.If.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); break; case With_kind: result = PyType_GenericNew(With_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.With.items, ast2obj_withitem); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_items, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.With.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case AsyncWith_kind: result = PyType_GenericNew(AsyncWith_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.AsyncWith.items, ast2obj_withitem); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_items, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.AsyncWith.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case Raise_kind: result = PyType_GenericNew(Raise_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Raise.exc); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_exc, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Raise.cause); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_cause, value) == -1) goto failed; Py_DECREF(value); break; case Try_kind: result = PyType_GenericNew(Try_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Try.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Try.handlers, ast2obj_excepthandler); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_handlers, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Try.orelse, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_orelse, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.Try.finalbody, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_finalbody, value) == -1) goto failed; Py_DECREF(value); break; case Assert_kind: result = PyType_GenericNew(Assert_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Assert.test); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_test, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_expr(o->v.Assert.msg); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_msg, value) == -1) goto failed; Py_DECREF(value); break; case Import_kind: result = PyType_GenericNew(Import_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Import.names, ast2obj_alias); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_names, value) == -1) goto failed; Py_DECREF(value); break; case ImportFrom_kind: result = PyType_GenericNew(ImportFrom_type, NULL, NULL); if (!result) goto failed; value = ast2obj_identifier(o->v.ImportFrom.module); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_module, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_list(o->v.ImportFrom.names, ast2obj_alias); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_names, value) == -1) goto failed; Py_DECREF(value); value = ast2obj_int(o->v.ImportFrom.level); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_level, value) == -1) goto failed; Py_DECREF(value); break; case Global_kind: result = PyType_GenericNew(Global_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Global.names, ast2obj_identifier); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_names, value) == -1) goto failed; Py_DECREF(value); break; case Nonlocal_kind: result = PyType_GenericNew(Nonlocal_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Nonlocal.names, ast2obj_identifier); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_names, value) == -1) goto failed; Py_DECREF(value); break; case Expr_kind: result = PyType_GenericNew(Expr_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Expr.value); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_value, value) == -1) goto failed; Py_DECREF(value); break; case Pass_kind: result = PyType_GenericNew(Pass_type, NULL, NULL); if (!result) goto failed; break; case Break_kind: result = PyType_GenericNew(Break_type, NULL, NULL); if (!result) goto failed; break; case Continue_kind: result = PyType_GenericNew(Continue_type, NULL, NULL); if (!result) goto failed; break; } value = ast2obj_int(o->lineno); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_lineno, value) < 0) goto failed; Py_DECREF(value); value = ast2obj_int(o->col_offset); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_col_offset, value) < 0) goto failed; Py_DECREF(value); value = ast2obj_int(o->end_lineno); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_end_lineno, value) < 0) goto failed; Py_DECREF(value); value = ast2obj_int(o->end_col_offset); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_end_col_offset, value) < 0) goto failed; Py_DECREF(value); return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PyInit__ast(void) { PyObject *m, *d; if (!init_types()) return NULL; m = PyModule_Create(&_astmodule); if (!m) return NULL; d = PyModule_GetDict(m); if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return NULL; if (PyModule_AddIntMacro(m, PyCF_ONLY_AST) < 0) return NULL; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return NULL; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) return NULL; if (PyDict_SetItemString(d, "Interactive", (PyObject*)Interactive_type) < 0) return NULL; if (PyDict_SetItemString(d, "Expression", (PyObject*)Expression_type) < 0) return NULL; if (PyDict_SetItemString(d, "Suite", (PyObject*)Suite_type) < 0) return NULL; if (PyDict_SetItemString(d, "stmt", (PyObject*)stmt_type) < 0) return NULL; if (PyDict_SetItemString(d, "FunctionDef", (PyObject*)FunctionDef_type) < 0) return NULL; if (PyDict_SetItemString(d, "AsyncFunctionDef", (PyObject*)AsyncFunctionDef_type) < 0) return NULL; if (PyDict_SetItemString(d, "ClassDef", (PyObject*)ClassDef_type) < 0) return NULL; if (PyDict_SetItemString(d, "Return", (PyObject*)Return_type) < 0) return NULL; if (PyDict_SetItemString(d, "Delete", (PyObject*)Delete_type) < 0) return NULL; if (PyDict_SetItemString(d, "Assign", (PyObject*)Assign_type) < 0) return NULL; if (PyDict_SetItemString(d, "AugAssign", (PyObject*)AugAssign_type) < 0) return NULL; if (PyDict_SetItemString(d, "AnnAssign", (PyObject*)AnnAssign_type) < 0) return NULL; if (PyDict_SetItemString(d, "For", (PyObject*)For_type) < 0) return NULL; if (PyDict_SetItemString(d, "AsyncFor", (PyObject*)AsyncFor_type) < 0) return NULL; if (PyDict_SetItemString(d, "While", (PyObject*)While_type) < 0) return NULL; if (PyDict_SetItemString(d, "If", (PyObject*)If_type) < 0) return NULL; if (PyDict_SetItemString(d, "With", (PyObject*)With_type) < 0) return NULL; if (PyDict_SetItemString(d, "AsyncWith", (PyObject*)AsyncWith_type) < 0) return NULL; if (PyDict_SetItemString(d, "Raise", (PyObject*)Raise_type) < 0) return NULL; if (PyDict_SetItemString(d, "Try", (PyObject*)Try_type) < 0) return NULL; if (PyDict_SetItemString(d, "Assert", (PyObject*)Assert_type) < 0) return NULL; if (PyDict_SetItemString(d, "Import", (PyObject*)Import_type) < 0) return NULL; if (PyDict_SetItemString(d, "ImportFrom", (PyObject*)ImportFrom_type) < 0) return NULL; if (PyDict_SetItemString(d, "Global", (PyObject*)Global_type) < 0) return NULL; if (PyDict_SetItemString(d, "Nonlocal", (PyObject*)Nonlocal_type) < 0) return NULL; if (PyDict_SetItemString(d, "Expr", (PyObject*)Expr_type) < 0) return NULL; if (PyDict_SetItemString(d, "Pass", (PyObject*)Pass_type) < 0) return NULL; if (PyDict_SetItemString(d, "Break", (PyObject*)Break_type) < 0) return NULL; if (PyDict_SetItemString(d, "Continue", (PyObject*)Continue_type) < 0) return NULL; if (PyDict_SetItemString(d, "expr", (PyObject*)expr_type) < 0) return NULL; if (PyDict_SetItemString(d, "BoolOp", (PyObject*)BoolOp_type) < 0) return NULL; if (PyDict_SetItemString(d, "NamedExpr", (PyObject*)NamedExpr_type) < 0) return NULL; if (PyDict_SetItemString(d, "BinOp", (PyObject*)BinOp_type) < 0) return NULL; if (PyDict_SetItemString(d, "UnaryOp", (PyObject*)UnaryOp_type) < 0) return NULL; if (PyDict_SetItemString(d, "Lambda", (PyObject*)Lambda_type) < 0) return NULL; if (PyDict_SetItemString(d, "IfExp", (PyObject*)IfExp_type) < 0) return NULL; if (PyDict_SetItemString(d, "Dict", (PyObject*)Dict_type) < 0) return NULL; if (PyDict_SetItemString(d, "Set", (PyObject*)Set_type) < 0) return NULL; if (PyDict_SetItemString(d, "ListComp", (PyObject*)ListComp_type) < 0) return NULL; if (PyDict_SetItemString(d, "SetComp", (PyObject*)SetComp_type) < 0) return NULL; if (PyDict_SetItemString(d, "DictComp", (PyObject*)DictComp_type) < 0) return NULL; if (PyDict_SetItemString(d, "GeneratorExp", (PyObject*)GeneratorExp_type) < 0) return NULL; if (PyDict_SetItemString(d, "Await", (PyObject*)Await_type) < 0) return NULL; if (PyDict_SetItemString(d, "Yield", (PyObject*)Yield_type) < 0) return NULL; if (PyDict_SetItemString(d, "YieldFrom", (PyObject*)YieldFrom_type) < 0) return NULL; if (PyDict_SetItemString(d, "Compare", (PyObject*)Compare_type) < 0) return NULL; if (PyDict_SetItemString(d, "Call", (PyObject*)Call_type) < 0) return NULL; if (PyDict_SetItemString(d, "FormattedValue", (PyObject*)FormattedValue_type) < 0) return NULL; if (PyDict_SetItemString(d, "JoinedStr", (PyObject*)JoinedStr_type) < 0) return NULL; if (PyDict_SetItemString(d, "Constant", (PyObject*)Constant_type) < 0) return NULL; if (PyDict_SetItemString(d, "Attribute", (PyObject*)Attribute_type) < 0) return NULL; if (PyDict_SetItemString(d, "Subscript", (PyObject*)Subscript_type) < 0) return NULL; if (PyDict_SetItemString(d, "Starred", (PyObject*)Starred_type) < 0) return NULL; if (PyDict_SetItemString(d, "Name", (PyObject*)Name_type) < 0) return NULL; if (PyDict_SetItemString(d, "List", (PyObject*)List_type) < 0) return NULL; if (PyDict_SetItemString(d, "Tuple", (PyObject*)Tuple_type) < 0) return NULL; if (PyDict_SetItemString(d, "expr_context", (PyObject*)expr_context_type) < 0) return NULL; if (PyDict_SetItemString(d, "Load", (PyObject*)Load_type) < 0) return NULL; if (PyDict_SetItemString(d, "Store", (PyObject*)Store_type) < 0) return NULL; if (PyDict_SetItemString(d, "Del", (PyObject*)Del_type) < 0) return NULL; if (PyDict_SetItemString(d, "AugLoad", (PyObject*)AugLoad_type) < 0) return NULL; if (PyDict_SetItemString(d, "AugStore", (PyObject*)AugStore_type) < 0) return NULL; if (PyDict_SetItemString(d, "Param", (PyObject*)Param_type) < 0) return NULL; if (PyDict_SetItemString(d, "NamedStore", (PyObject*)NamedStore_type) < 0) return NULL; if (PyDict_SetItemString(d, "slice", (PyObject*)slice_type) < 0) return NULL; if (PyDict_SetItemString(d, "Slice", (PyObject*)Slice_type) < 0) return NULL; if (PyDict_SetItemString(d, "ExtSlice", (PyObject*)ExtSlice_type) < 0) return NULL; if (PyDict_SetItemString(d, "Index", (PyObject*)Index_type) < 0) return NULL; if (PyDict_SetItemString(d, "boolop", (PyObject*)boolop_type) < 0) return NULL; if (PyDict_SetItemString(d, "And", (PyObject*)And_type) < 0) return NULL; if (PyDict_SetItemString(d, "Or", (PyObject*)Or_type) < 0) return NULL; if (PyDict_SetItemString(d, "operator", (PyObject*)operator_type) < 0) return NULL; if (PyDict_SetItemString(d, "Add", (PyObject*)Add_type) < 0) return NULL; if (PyDict_SetItemString(d, "Sub", (PyObject*)Sub_type) < 0) return NULL; if (PyDict_SetItemString(d, "Mult", (PyObject*)Mult_type) < 0) return NULL; if (PyDict_SetItemString(d, "MatMult", (PyObject*)MatMult_type) < 0) return NULL; if (PyDict_SetItemString(d, "Div", (PyObject*)Div_type) < 0) return NULL; if (PyDict_SetItemString(d, "Mod", (PyObject*)Mod_type) < 0) return NULL; if (PyDict_SetItemString(d, "Pow", (PyObject*)Pow_type) < 0) return NULL; if (PyDict_SetItemString(d, "LShift", (PyObject*)LShift_type) < 0) return NULL; if (PyDict_SetItemString(d, "RShift", (PyObject*)RShift_type) < 0) return NULL; if (PyDict_SetItemString(d, "BitOr", (PyObject*)BitOr_type) < 0) return NULL; if (PyDict_SetItemString(d, "BitXor", (PyObject*)BitXor_type) < 0) return NULL; if (PyDict_SetItemString(d, "BitAnd", (PyObject*)BitAnd_type) < 0) return NULL; if (PyDict_SetItemString(d, "FloorDiv", (PyObject*)FloorDiv_type) < 0) return NULL; if (PyDict_SetItemString(d, "unaryop", (PyObject*)unaryop_type) < 0) return NULL; if (PyDict_SetItemString(d, "Invert", (PyObject*)Invert_type) < 0) return NULL; if (PyDict_SetItemString(d, "Not", (PyObject*)Not_type) < 0) return NULL; if (PyDict_SetItemString(d, "UAdd", (PyObject*)UAdd_type) < 0) return NULL; if (PyDict_SetItemString(d, "USub", (PyObject*)USub_type) < 0) return NULL; if (PyDict_SetItemString(d, "cmpop", (PyObject*)cmpop_type) < 0) return NULL; if (PyDict_SetItemString(d, "Eq", (PyObject*)Eq_type) < 0) return NULL; if (PyDict_SetItemString(d, "NotEq", (PyObject*)NotEq_type) < 0) return NULL; if (PyDict_SetItemString(d, "Lt", (PyObject*)Lt_type) < 0) return NULL; if (PyDict_SetItemString(d, "LtE", (PyObject*)LtE_type) < 0) return NULL; if (PyDict_SetItemString(d, "Gt", (PyObject*)Gt_type) < 0) return NULL; if (PyDict_SetItemString(d, "GtE", (PyObject*)GtE_type) < 0) return NULL; if (PyDict_SetItemString(d, "Is", (PyObject*)Is_type) < 0) return NULL; if (PyDict_SetItemString(d, "IsNot", (PyObject*)IsNot_type) < 0) return NULL; if (PyDict_SetItemString(d, "In", (PyObject*)In_type) < 0) return NULL; if (PyDict_SetItemString(d, "NotIn", (PyObject*)NotIn_type) < 0) return NULL; if (PyDict_SetItemString(d, "comprehension", (PyObject*)comprehension_type) < 0) return NULL; if (PyDict_SetItemString(d, "excepthandler", (PyObject*)excepthandler_type) < 0) return NULL; if (PyDict_SetItemString(d, "ExceptHandler", (PyObject*)ExceptHandler_type) < 0) return NULL; if (PyDict_SetItemString(d, "arguments", (PyObject*)arguments_type) < 0) return NULL; if (PyDict_SetItemString(d, "arg", (PyObject*)arg_type) < 0) return NULL; if (PyDict_SetItemString(d, "keyword", (PyObject*)keyword_type) < 0) return NULL; if (PyDict_SetItemString(d, "alias", (PyObject*)alias_type) < 0) return NULL; if (PyDict_SetItemString(d, "withitem", (PyObject*)withitem_type) < 0) return NULL; return m; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: handle_keywordonly_args(struct compiling *c, const node *n, int start, asdl_seq *kwonlyargs, asdl_seq *kwdefaults) { PyObject *argname; node *ch; expr_ty expression, annotation; arg_ty arg; int i = start; int j = 0; /* index for kwdefaults and kwonlyargs */ if (kwonlyargs == NULL) { ast_error(c, CHILD(n, start), "named arguments must follow bare *"); return -1; } assert(kwdefaults != NULL); while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { case vfpdef: case tfpdef: if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) goto error; asdl_seq_SET(kwdefaults, j, expression); i += 2; /* '=' and test */ } else { /* setting NULL if no default value exists */ asdl_seq_SET(kwdefaults, j, NULL); } if (NCH(ch) == 3) { /* ch is NAME ':' test */ annotation = ast_for_expr(c, CHILD(ch, 2)); if (!annotation) goto error; } else { annotation = NULL; } ch = CHILD(ch, 0); argname = NEW_IDENTIFIER(ch); if (!argname) goto error; if (forbidden_name(c, argname, ch, 0)) goto error; arg = arg(argname, annotation, LINENO(ch), ch->n_col_offset, ch->n_end_lineno, ch->n_end_col_offset, c->c_arena); if (!arg) goto error; asdl_seq_SET(kwonlyargs, j++, arg); i += 2; /* the name and the comma */ break; case DOUBLESTAR: return i; default: ast_error(c, ch, "unexpected node"); goto error; } } return i; error: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Module(asdl_seq * body, PyArena *arena) { mod_ty p; p = (mod_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Module_kind; p->v.Module.body = body; return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PyParser_ParseStringObject(const char *s, PyObject *filename, grammar *g, int start, perrdetail *err_ret, int *flags) { struct tok_state *tok; int exec_input = start == file_input; if (initerr(err_ret, filename) < 0) return NULL; if (*flags & PyPARSE_IGNORE_COOKIE) tok = PyTokenizer_FromUTF8(s, exec_input); else tok = PyTokenizer_FromString(s, exec_input); if (tok == NULL) { err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; return NULL; } #ifndef PGEN Py_INCREF(err_ret->filename); tok->filename = err_ret->filename; #endif return parsetok(tok, g, start, err_ret, flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, int *flags) { parser_state *ps; node *n; int started = 0; int col_offset, end_col_offset; if ((ps = PyParser_New(g, start)) == NULL) { err_ret->error = E_NOMEM; PyTokenizer_Free(tok); return NULL; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (*flags & PyPARSE_BARRY_AS_BDFL) ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif for (;;) { char *a, *b; int type; size_t len; char *str; col_offset = -1; int lineno; const char *line_start; type = PyTokenizer_Get(tok, &a, &b); if (type == ERRORTOKEN) { err_ret->error = tok->done; break; } if (type == ENDMARKER && started) { type = NEWLINE; /* Add an extra newline */ started = 0; /* Add the right number of dedent tokens, except if a certain flag is given -- codeop.py uses this. */ if (tok->indent && !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) { tok->pendin = -tok->indent; tok->indent = 0; } } else started = 1; len = (a != NULL && b != NULL) ? b - a : 0; str = (char *) PyObject_MALLOC(len + 1); if (str == NULL) { err_ret->error = E_NOMEM; break; } if (len > 0) strncpy(str, a, len); str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (type == NOTEQUAL) { if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "!=")) { PyObject_FREE(str); err_ret->error = E_SYNTAX; break; } else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "<>")) { PyObject_FREE(str); err_ret->expected = NOTEQUAL; err_ret->error = E_SYNTAX; break; } } #endif /* Nodes of type STRING, especially multi line strings must be handled differently in order to get both the starting line number and the column offset right. (cf. issue 16806) */ lineno = type == STRING ? tok->first_lineno : tok->lineno; line_start = type == STRING ? tok->multi_line_start : tok->line_start; if (a != NULL && a >= line_start) { col_offset = Py_SAFE_DOWNCAST(a - line_start, intptr_t, int); } else { col_offset = -1; } if (b != NULL && b >= tok->line_start) { end_col_offset = Py_SAFE_DOWNCAST(b - tok->line_start, intptr_t, int); } else { end_col_offset = -1; } if ((err_ret->error = PyParser_AddToken(ps, (int)type, str, lineno, col_offset, tok->lineno, end_col_offset, &(err_ret->expected))) != E_OK) { if (err_ret->error != E_DONE) { PyObject_FREE(str); err_ret->token = type; } break; } } if (err_ret->error == E_DONE) { n = ps->p_tree; ps->p_tree = NULL; #ifndef PGEN /* Check that the source for a single input statement really is a single statement by looking at what is left in the buffer after parsing. Trailing whitespace and comments are OK. */ if (start == single_input) { char *cur = tok->cur; char c = *tok->cur; for (;;) { while (c == ' ' || c == '\t' || c == '\n' || c == '\014') c = *++cur; if (!c) break; if (c != '#') { err_ret->error = E_BADSINGLE; PyNode_Free(n); n = NULL; break; } /* Suck up comment. */ while (c && c != '\n') c = *++cur; } } #endif } else n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD *flags = ps->p_flags; #endif PyParser_Delete(ps); if (n == NULL) { if (tok->done == E_EOF) err_ret->error = E_EOF; err_ret->lineno = tok->lineno; if (tok->buf != NULL) { size_t len; assert(tok->cur - tok->buf < INT_MAX); /* if we've managed to parse a token, point the offset to its start, * else use the current reading position of the tokenizer */ err_ret->offset = col_offset != -1 ? col_offset + 1 : ((int)(tok->cur - tok->buf)); len = tok->inp - tok->buf; err_ret->text = (char *) PyObject_MALLOC(len + 1); if (err_ret->text != NULL) { if (len > 0) strncpy(err_ret->text, tok->buf, len); err_ret->text[len] = '\0'; } } } else if (tok->encoding != NULL) { /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was * allocated using PyMem_ */ node* r = PyNode_New(encoding_decl); if (r) r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); if (!r || !r->n_str) { err_ret->error = E_NOMEM; if (r) PyObject_FREE(r); n = NULL; goto done; } strcpy(r->n_str, tok->encoding); PyMem_FREE(tok->encoding); tok->encoding = NULL; r->n_nchildren = 1; r->n_child = n; n = r; } done: PyTokenizer_Free(tok); if (n != NULL) { _PyNode_FinalizeEndPos(n); } return n; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PyParser_ParseFileObject(FILE *fp, PyObject *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags) { struct tok_state *tok; if (initerr(err_ret, filename) < 0) return NULL; if ((tok = PyTokenizer_FromFile(fp, enc, ps1, ps2)) == NULL) { err_ret->error = E_NOMEM; return NULL; } #ifndef PGEN Py_INCREF(err_ret->filename); tok->filename = err_ret->filename; #endif return parsetok(tok, g, start, err_ret, flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast_for_with_stmt(struct compiling *c, const node *n0, bool is_async) { const node * const n = is_async ? CHILD(n0, 1) : n0; int i, n_items, end_lineno, end_col_offset; asdl_seq *items, *body; REQ(n, with_stmt); n_items = (NCH(n) - 2) / 2; items = _Py_asdl_seq_new(n_items, c->c_arena); if (!items) return NULL; for (i = 1; i < NCH(n) - 2; i += 2) { withitem_ty item = ast_for_with_item(c, CHILD(n, i)); if (!item) return NULL; asdl_seq_SET(items, (i - 1) / 2, item); } body = ast_for_suite(c, CHILD(n, NCH(n) - 1)); if (!body) return NULL; get_last_end_pos(body, &end_lineno, &end_col_offset); if (is_async) return AsyncWith(items, body, LINENO(n0), n0->n_col_offset, end_lineno, end_col_offset, c->c_arena); else return With(items, body, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: AsyncWith(asdl_seq * items, asdl_seq * body, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena) { stmt_ty p; p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = AsyncWith_kind; p->v.AsyncWith.items = items; p->v.AsyncWith.body = body; p->lineno = lineno; p->col_offset = col_offset; p->end_lineno = end_lineno; p->end_col_offset = end_col_offset; return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast_for_atom(struct compiling *c, const node *n) { /* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False' */ node *ch = CHILD(n, 0); switch (TYPE(ch)) { case NAME: { PyObject *name; const char *s = STR(ch); size_t len = strlen(s); if (len >= 4 && len <= 5) { if (!strcmp(s, "None")) return Constant(Py_None, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!strcmp(s, "True")) return Constant(Py_True, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!strcmp(s, "False")) return Constant(Py_False, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } name = new_identifier(s, c); if (!name) return NULL; /* All names start in Load context, but may later be changed. */ return Name(name, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } case STRING: { expr_ty str = parsestrplus(c, n); if (!str) { const char *errtype = NULL; if (PyErr_ExceptionMatches(PyExc_UnicodeError)) errtype = "unicode error"; else if (PyErr_ExceptionMatches(PyExc_ValueError)) errtype = "value error"; if (errtype) { PyObject *type, *value, *tback, *errstr; PyErr_Fetch(&type, &value, &tback); errstr = PyObject_Str(value); if (errstr) { ast_error(c, n, "(%s) %U", errtype, errstr); Py_DECREF(errstr); } else { PyErr_Clear(); ast_error(c, n, "(%s) unknown error", errtype); } Py_DECREF(type); Py_XDECREF(value); Py_XDECREF(tback); } return NULL; } return str; } case NUMBER: { PyObject *pynum = parsenumber(c, STR(ch)); if (!pynum) return NULL; if (PyArena_AddPyObject(c->c_arena, pynum) < 0) { Py_DECREF(pynum); return NULL; } return Constant(pynum, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } case ELLIPSIS: /* Ellipsis */ return Constant(Py_Ellipsis, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ if (NCH(ch) == 1) { return ast_for_testlist(c, ch); } if (TYPE(CHILD(ch, 1)) == comp_for) { return copy_location(ast_for_genexp(c, ch), n); } else { return copy_location(ast_for_testlist(c, ch), n); } case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); REQ(ch, testlist_comp); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); if (!elts) return NULL; return List(elts, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else { return copy_location(ast_for_listcomp(c, ch), n); } case LBRACE: { /* dictorsetmaker: ( ((test ':' test | '**' test) * (comp_for | (',' (test ':' test | '**' test))* [','])) | * ((test | '*' test) * (comp_for | (',' (test | '*' test))* [','])) ) */ expr_ty res; ch = CHILD(n, 1); if (TYPE(ch) == RBRACE) { /* It's an empty dict. */ return Dict(NULL, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else { int is_dict = (TYPE(CHILD(ch, 0)) == DOUBLESTAR); if (NCH(ch) == 1 || (NCH(ch) > 1 && TYPE(CHILD(ch, 1)) == COMMA)) { /* It's a set display. */ res = ast_for_setdisplay(c, ch); } else if (NCH(ch) > 1 && TYPE(CHILD(ch, 1)) == comp_for) { /* It's a set comprehension. */ res = ast_for_setcomp(c, ch); } else if (NCH(ch) > 3 - is_dict && TYPE(CHILD(ch, 3 - is_dict)) == comp_for) { /* It's a dictionary comprehension. */ if (is_dict) { ast_error(c, n, "dict unpacking cannot be used in " "dict comprehension"); return NULL; } res = ast_for_dictcomp(c, ch); } else { /* It's a dictionary display. */ res = ast_for_dictdisplay(c, ch); } return copy_location(res, n); } } default: PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch)); return NULL; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq * decorator_list, expr_ty returns, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena) { stmt_ty p; if (!name) { PyErr_SetString(PyExc_ValueError, "field name is required for FunctionDef"); return NULL; } if (!args) { PyErr_SetString(PyExc_ValueError, "field args is required for FunctionDef"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = FunctionDef_kind; p->v.FunctionDef.name = name; p->v.FunctionDef.args = args; p->v.FunctionDef.body = body; p->v.FunctionDef.decorator_list = decorator_list; p->v.FunctionDef.returns = returns; p->lineno = lineno; p->col_offset = col_offset; p->end_lineno = end_lineno; p->end_col_offset = end_col_offset; return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena) { int isinstance; PyObject *tmp = NULL; int lineno; int col_offset; int end_lineno; int end_col_offset; if (obj == Py_None) { *out = NULL; return 0; } if (_PyObject_LookupAttrId(obj, &PyId_lineno, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"lineno\" missing from stmt"); return 1; } else { int res; res = obj2ast_int(tmp, &lineno, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_col_offset, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"col_offset\" missing from stmt"); return 1; } else { int res; res = obj2ast_int(tmp, &col_offset, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_end_lineno, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); end_lineno = 0; } else { int res; res = obj2ast_int(tmp, &end_lineno, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_end_col_offset, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); end_col_offset = 0; } else { int res; res = obj2ast_int(tmp, &end_col_offset, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } isinstance = PyObject_IsInstance(obj, (PyObject*)FunctionDef_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier name; arguments_ty args; asdl_seq* body; asdl_seq* decorator_list; expr_ty returns; if (_PyObject_LookupAttrId(obj, &PyId_name, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from FunctionDef"); return 1; } else { int res; res = obj2ast_identifier(tmp, &name, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_args, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from FunctionDef"); return 1; } else { int res; res = obj2ast_arguments(tmp, &args, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from FunctionDef"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "FunctionDef field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "FunctionDef field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_decorator_list, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"decorator_list\" missing from FunctionDef"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "FunctionDef field \"decorator_list\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); decorator_list = _Py_asdl_seq_new(len, arena); if (decorator_list == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "FunctionDef field \"decorator_list\" changed size during iteration"); goto failed; } asdl_seq_SET(decorator_list, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_returns, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); returns = NULL; } else { int res; res = obj2ast_expr(tmp, &returns, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = FunctionDef(name, args, body, decorator_list, returns, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AsyncFunctionDef_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier name; arguments_ty args; asdl_seq* body; asdl_seq* decorator_list; expr_ty returns; if (_PyObject_LookupAttrId(obj, &PyId_name, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from AsyncFunctionDef"); return 1; } else { int res; res = obj2ast_identifier(tmp, &name, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_args, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"args\" missing from AsyncFunctionDef"); return 1; } else { int res; res = obj2ast_arguments(tmp, &args, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from AsyncFunctionDef"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncFunctionDef field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncFunctionDef field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_decorator_list, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"decorator_list\" missing from AsyncFunctionDef"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncFunctionDef field \"decorator_list\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); decorator_list = _Py_asdl_seq_new(len, arena); if (decorator_list == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncFunctionDef field \"decorator_list\" changed size during iteration"); goto failed; } asdl_seq_SET(decorator_list, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_returns, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); returns = NULL; } else { int res; res = obj2ast_expr(tmp, &returns, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = AsyncFunctionDef(name, args, body, decorator_list, returns, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)ClassDef_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier name; asdl_seq* bases; asdl_seq* keywords; asdl_seq* body; asdl_seq* decorator_list; if (_PyObject_LookupAttrId(obj, &PyId_name, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"name\" missing from ClassDef"); return 1; } else { int res; res = obj2ast_identifier(tmp, &name, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_bases, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"bases\" missing from ClassDef"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ClassDef field \"bases\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); bases = _Py_asdl_seq_new(len, arena); if (bases == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"bases\" changed size during iteration"); goto failed; } asdl_seq_SET(bases, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_keywords, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"keywords\" missing from ClassDef"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ClassDef field \"keywords\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); keywords = _Py_asdl_seq_new(len, arena); if (keywords == NULL) goto failed; for (i = 0; i < len; i++) { keyword_ty val; res = obj2ast_keyword(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"keywords\" changed size during iteration"); goto failed; } asdl_seq_SET(keywords, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from ClassDef"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ClassDef field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_decorator_list, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"decorator_list\" missing from ClassDef"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ClassDef field \"decorator_list\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); decorator_list = _Py_asdl_seq_new(len, arena); if (decorator_list == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"decorator_list\" changed size during iteration"); goto failed; } asdl_seq_SET(decorator_list, i, val); } Py_CLEAR(tmp); } *out = ClassDef(name, bases, keywords, body, decorator_list, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Return_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; if (_PyObject_LookupAttrId(obj, &PyId_value, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); value = NULL; } else { int res; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = Return(value, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Delete_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* targets; if (_PyObject_LookupAttrId(obj, &PyId_targets, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"targets\" missing from Delete"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Delete field \"targets\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); targets = _Py_asdl_seq_new(len, arena); if (targets == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Delete field \"targets\" changed size during iteration"); goto failed; } asdl_seq_SET(targets, i, val); } Py_CLEAR(tmp); } *out = Delete(targets, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Assign_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* targets; expr_ty value; if (_PyObject_LookupAttrId(obj, &PyId_targets, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"targets\" missing from Assign"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Assign field \"targets\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); targets = _Py_asdl_seq_new(len, arena); if (targets == NULL) goto failed; for (i = 0; i < len; i++) { expr_ty val; res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Assign field \"targets\" changed size during iteration"); goto failed; } asdl_seq_SET(targets, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_value, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Assign"); return 1; } else { int res; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = Assign(targets, value, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AugAssign_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty target; operator_ty op; expr_ty value; if (_PyObject_LookupAttrId(obj, &PyId_target, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from AugAssign"); return 1; } else { int res; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_op, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"op\" missing from AugAssign"); return 1; } else { int res; res = obj2ast_operator(tmp, &op, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_value, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from AugAssign"); return 1; } else { int res; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = AugAssign(target, op, value, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AnnAssign_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty target; expr_ty annotation; expr_ty value; int simple; if (_PyObject_LookupAttrId(obj, &PyId_target, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from AnnAssign"); return 1; } else { int res; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_annotation, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"annotation\" missing from AnnAssign"); return 1; } else { int res; res = obj2ast_expr(tmp, &annotation, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_value, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); value = NULL; } else { int res; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_simple, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"simple\" missing from AnnAssign"); return 1; } else { int res; res = obj2ast_int(tmp, &simple, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = AnnAssign(target, annotation, value, simple, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)For_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty target; expr_ty iter; asdl_seq* body; asdl_seq* orelse; if (_PyObject_LookupAttrId(obj, &PyId_target, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from For"); return 1; } else { int res; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_iter, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"iter\" missing from For"); return 1; } else { int res; res = obj2ast_expr(tmp, &iter, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from For"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "For field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "For field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_orelse, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from For"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "For field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "For field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } *out = For(target, iter, body, orelse, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AsyncFor_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty target; expr_ty iter; asdl_seq* body; asdl_seq* orelse; if (_PyObject_LookupAttrId(obj, &PyId_target, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"target\" missing from AsyncFor"); return 1; } else { int res; res = obj2ast_expr(tmp, &target, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_iter, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"iter\" missing from AsyncFor"); return 1; } else { int res; res = obj2ast_expr(tmp, &iter, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from AsyncFor"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncFor field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncFor field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_orelse, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from AsyncFor"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncFor field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncFor field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } *out = AsyncFor(target, iter, body, orelse, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)While_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty test; asdl_seq* body; asdl_seq* orelse; if (_PyObject_LookupAttrId(obj, &PyId_test, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from While"); return 1; } else { int res; res = obj2ast_expr(tmp, &test, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from While"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "While field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "While field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_orelse, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from While"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "While field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "While field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } *out = While(test, body, orelse, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)If_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty test; asdl_seq* body; asdl_seq* orelse; if (_PyObject_LookupAttrId(obj, &PyId_test, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from If"); return 1; } else { int res; res = obj2ast_expr(tmp, &test, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from If"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "If field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "If field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_orelse, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from If"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "If field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "If field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } *out = If(test, body, orelse, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)With_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* items; asdl_seq* body; if (_PyObject_LookupAttrId(obj, &PyId_items, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"items\" missing from With"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "With field \"items\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); items = _Py_asdl_seq_new(len, arena); if (items == NULL) goto failed; for (i = 0; i < len; i++) { withitem_ty val; res = obj2ast_withitem(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "With field \"items\" changed size during iteration"); goto failed; } asdl_seq_SET(items, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from With"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "With field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "With field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } *out = With(items, body, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)AsyncWith_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* items; asdl_seq* body; if (_PyObject_LookupAttrId(obj, &PyId_items, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"items\" missing from AsyncWith"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncWith field \"items\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); items = _Py_asdl_seq_new(len, arena); if (items == NULL) goto failed; for (i = 0; i < len; i++) { withitem_ty val; res = obj2ast_withitem(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncWith field \"items\" changed size during iteration"); goto failed; } asdl_seq_SET(items, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from AsyncWith"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "AsyncWith field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "AsyncWith field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } *out = AsyncWith(items, body, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Raise_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty exc; expr_ty cause; if (_PyObject_LookupAttrId(obj, &PyId_exc, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); exc = NULL; } else { int res; res = obj2ast_expr(tmp, &exc, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_cause, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); cause = NULL; } else { int res; res = obj2ast_expr(tmp, &cause, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = Raise(exc, cause, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Try_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* body; asdl_seq* handlers; asdl_seq* orelse; asdl_seq* finalbody; if (_PyObject_LookupAttrId(obj, &PyId_body, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"body\" missing from Try"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Try field \"body\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); body = _Py_asdl_seq_new(len, arena); if (body == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Try field \"body\" changed size during iteration"); goto failed; } asdl_seq_SET(body, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_handlers, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"handlers\" missing from Try"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Try field \"handlers\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); handlers = _Py_asdl_seq_new(len, arena); if (handlers == NULL) goto failed; for (i = 0; i < len; i++) { excepthandler_ty val; res = obj2ast_excepthandler(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Try field \"handlers\" changed size during iteration"); goto failed; } asdl_seq_SET(handlers, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_orelse, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"orelse\" missing from Try"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Try field \"orelse\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); orelse = _Py_asdl_seq_new(len, arena); if (orelse == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Try field \"orelse\" changed size during iteration"); goto failed; } asdl_seq_SET(orelse, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_finalbody, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"finalbody\" missing from Try"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Try field \"finalbody\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); finalbody = _Py_asdl_seq_new(len, arena); if (finalbody == NULL) goto failed; for (i = 0; i < len; i++) { stmt_ty val; res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Try field \"finalbody\" changed size during iteration"); goto failed; } asdl_seq_SET(finalbody, i, val); } Py_CLEAR(tmp); } *out = Try(body, handlers, orelse, finalbody, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Assert_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty test; expr_ty msg; if (_PyObject_LookupAttrId(obj, &PyId_test, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"test\" missing from Assert"); return 1; } else { int res; res = obj2ast_expr(tmp, &test, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_msg, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); msg = NULL; } else { int res; res = obj2ast_expr(tmp, &msg, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = Assert(test, msg, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Import_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* names; if (_PyObject_LookupAttrId(obj, &PyId_names, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Import"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Import field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); names = _Py_asdl_seq_new(len, arena); if (names == NULL) goto failed; for (i = 0; i < len; i++) { alias_ty val; res = obj2ast_alias(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Import field \"names\" changed size during iteration"); goto failed; } asdl_seq_SET(names, i, val); } Py_CLEAR(tmp); } *out = Import(names, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)ImportFrom_type); if (isinstance == -1) { return 1; } if (isinstance) { identifier module; asdl_seq* names; int level; if (_PyObject_LookupAttrId(obj, &PyId_module, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); module = NULL; } else { int res; res = obj2ast_identifier(tmp, &module, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_names, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from ImportFrom"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "ImportFrom field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); names = _Py_asdl_seq_new(len, arena); if (names == NULL) goto failed; for (i = 0; i < len; i++) { alias_ty val; res = obj2ast_alias(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "ImportFrom field \"names\" changed size during iteration"); goto failed; } asdl_seq_SET(names, i, val); } Py_CLEAR(tmp); } if (_PyObject_LookupAttrId(obj, &PyId_level, &tmp) < 0) { return 1; } if (tmp == NULL || tmp == Py_None) { Py_CLEAR(tmp); level = 0; } else { int res; res = obj2ast_int(tmp, &level, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = ImportFrom(module, names, level, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Global_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* names; if (_PyObject_LookupAttrId(obj, &PyId_names, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Global"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Global field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); names = _Py_asdl_seq_new(len, arena); if (names == NULL) goto failed; for (i = 0; i < len; i++) { identifier val; res = obj2ast_identifier(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Global field \"names\" changed size during iteration"); goto failed; } asdl_seq_SET(names, i, val); } Py_CLEAR(tmp); } *out = Global(names, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Nonlocal_type); if (isinstance == -1) { return 1; } if (isinstance) { asdl_seq* names; if (_PyObject_LookupAttrId(obj, &PyId_names, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"names\" missing from Nonlocal"); return 1; } else { int res; Py_ssize_t len; Py_ssize_t i; if (!PyList_Check(tmp)) { PyErr_Format(PyExc_TypeError, "Nonlocal field \"names\" must be a list, not a %.200s", tmp->ob_type->tp_name); goto failed; } len = PyList_GET_SIZE(tmp); names = _Py_asdl_seq_new(len, arena); if (names == NULL) goto failed; for (i = 0; i < len; i++) { identifier val; res = obj2ast_identifier(PyList_GET_ITEM(tmp, i), &val, arena); if (res != 0) goto failed; if (len != PyList_GET_SIZE(tmp)) { PyErr_SetString(PyExc_RuntimeError, "Nonlocal field \"names\" changed size during iteration"); goto failed; } asdl_seq_SET(names, i, val); } Py_CLEAR(tmp); } *out = Nonlocal(names, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Expr_type); if (isinstance == -1) { return 1; } if (isinstance) { expr_ty value; if (_PyObject_LookupAttrId(obj, &PyId_value, &tmp) < 0) { return 1; } if (tmp == NULL) { PyErr_SetString(PyExc_TypeError, "required field \"value\" missing from Expr"); return 1; } else { int res; res = obj2ast_expr(tmp, &value, arena); if (res != 0) goto failed; Py_CLEAR(tmp); } *out = Expr(value, lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Pass_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Pass(lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Break_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Break(lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } isinstance = PyObject_IsInstance(obj, (PyObject*)Continue_type); if (isinstance == -1) { return 1; } if (isinstance) { *out = Continue(lineno, col_offset, end_lineno, end_col_offset, arena); if (*out == NULL) goto failed; return 0; } PyErr_Format(PyExc_TypeError, "expected some sort of stmt, but got %R", obj); failed: Py_XDECREF(tmp); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tok_new(void) { struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( sizeof(struct tok_state)); if (tok == NULL) return NULL; tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; tok->done = E_OK; tok->fp = NULL; tok->input = NULL; tok->tabsize = TABSIZE; tok->indent = 0; tok->indstack[0] = 0; tok->atbol = 1; tok->pendin = 0; tok->prompt = tok->nextprompt = NULL; tok->lineno = 0; tok->level = 0; tok->altindstack[0] = 0; tok->decoding_state = STATE_INIT; tok->decoding_erred = 0; tok->read_coding_spec = 0; tok->enc = NULL; tok->encoding = NULL; tok->cont_line = 0; #ifndef PGEN tok->filename = NULL; tok->decoding_readline = NULL; tok->decoding_buffer = NULL; #endif return tok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena) { stmt_ty p; if (!value) { PyErr_SetString(PyExc_ValueError, "field value is required for Assign"); return NULL; } p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p)); if (!p) return NULL; p->kind = Assign_kind; p->v.Assign.targets = targets; p->v.Assign.value = value; p->lineno = lineno; p->col_offset = col_offset; p->end_lineno = end_lineno; p->end_col_offset = end_col_offset; return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast2obj_mod(void* _o) { mod_ty o = (mod_ty)_o; PyObject *result = NULL, *value = NULL; if (!o) { Py_RETURN_NONE; } switch (o->kind) { case Module_kind: result = PyType_GenericNew(Module_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Module.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case Interactive_kind: result = PyType_GenericNew(Interactive_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Interactive.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case Expression_kind: result = PyType_GenericNew(Expression_type, NULL, NULL); if (!result) goto failed; value = ast2obj_expr(o->v.Expression.body); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; case Suite_kind: result = PyType_GenericNew(Suite_type, NULL, NULL); if (!result) goto failed; value = ast2obj_list(o->v.Suite.body, ast2obj_stmt); if (!value) goto failed; if (_PyObject_SetAttrId(result, &PyId_body, value) == -1) goto failed; Py_DECREF(value); break; } return result; failed: Py_XDECREF(value); Py_XDECREF(result); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast_for_call(struct compiling *c, const node *n, expr_ty func, const node *maybegenbeg, const node *closepar) { /* arglist: argument (',' argument)* [','] argument: ( test [comp_for] | '*' test | test '=' test | '**' test ) */ int i, nargs, nkeywords; int ndoublestars; asdl_seq *args; asdl_seq *keywords; REQ(n, arglist); nargs = 0; nkeywords = 0; for (i = 0; i < NCH(n); i++) { node *ch = CHILD(n, i); if (TYPE(ch) == argument) { if (NCH(ch) == 1) nargs++; else if (TYPE(CHILD(ch, 1)) == comp_for) { nargs++; if (!maybegenbeg) { ast_error(c, ch, "invalid syntax"); return NULL; } if (NCH(n) > 1) { ast_error(c, ch, "Generator expression must be parenthesized"); return NULL; } } else if (TYPE(CHILD(ch, 0)) == STAR) nargs++; else if (TYPE(CHILD(ch, 1)) == COLONEQUAL) { nargs++; } else /* TYPE(CHILD(ch, 0)) == DOUBLESTAR or keyword argument */ nkeywords++; } } args = _Py_asdl_seq_new(nargs, c->c_arena); if (!args) return NULL; keywords = _Py_asdl_seq_new(nkeywords, c->c_arena); if (!keywords) return NULL; nargs = 0; /* positional arguments + iterable argument unpackings */ nkeywords = 0; /* keyword arguments + keyword argument unpackings */ ndoublestars = 0; /* just keyword argument unpackings */ for (i = 0; i < NCH(n); i++) { node *ch = CHILD(n, i); if (TYPE(ch) == argument) { expr_ty e; node *chch = CHILD(ch, 0); if (NCH(ch) == 1) { /* a positional argument */ if (nkeywords) { if (ndoublestars) { ast_error(c, chch, "positional argument follows " "keyword argument unpacking"); } else { ast_error(c, chch, "positional argument follows " "keyword argument"); } return NULL; } e = ast_for_expr(c, chch); if (!e) return NULL; asdl_seq_SET(args, nargs++, e); } else if (TYPE(chch) == STAR) { /* an iterable argument unpacking */ expr_ty starred; if (ndoublestars) { ast_error(c, chch, "iterable argument unpacking follows " "keyword argument unpacking"); return NULL; } e = ast_for_expr(c, CHILD(ch, 1)); if (!e) return NULL; starred = Starred(e, Load, LINENO(chch), chch->n_col_offset, chch->n_end_lineno, chch->n_end_col_offset, c->c_arena); if (!starred) return NULL; asdl_seq_SET(args, nargs++, starred); } else if (TYPE(chch) == DOUBLESTAR) { /* a keyword argument unpacking */ keyword_ty kw; i++; e = ast_for_expr(c, CHILD(ch, 1)); if (!e) return NULL; kw = keyword(NULL, e, c->c_arena); asdl_seq_SET(keywords, nkeywords++, kw); ndoublestars++; } else if (TYPE(CHILD(ch, 1)) == comp_for) { /* the lone generator expression */ e = copy_location(ast_for_genexp(c, ch), maybegenbeg); if (!e) return NULL; asdl_seq_SET(args, nargs++, e); } else if (TYPE(CHILD(ch, 1)) == COLONEQUAL) { /* treat colon equal as positional argument */ if (nkeywords) { if (ndoublestars) { ast_error(c, chch, "positional argument follows " "keyword argument unpacking"); } else { ast_error(c, chch, "positional argument follows " "keyword argument"); } return NULL; } e = ast_for_namedexpr(c, ch); if (!e) return NULL; asdl_seq_SET(args, nargs++, e); } else { /* a keyword argument */ keyword_ty kw; identifier key, tmp; int k; // To remain LL(1), the grammar accepts any test (basically, any // expression) in the keyword slot of a call site. So, we need // to manually enforce that the keyword is a NAME here. static const int name_tree[] = { test, or_test, and_test, not_test, comparison, expr, xor_expr, and_expr, shift_expr, arith_expr, term, factor, power, atom_expr, atom, 0, }; node *expr_node = chch; for (int i = 0; name_tree[i]; i++) { if (TYPE(expr_node) != name_tree[i]) break; if (NCH(expr_node) != 1) break; expr_node = CHILD(expr_node, 0); } if (TYPE(expr_node) != NAME) { ast_error(c, chch, "expression cannot contain assignment, " "perhaps you meant \"==\"?"); return NULL; } key = new_identifier(STR(expr_node), c); if (key == NULL) { return NULL; } if (forbidden_name(c, key, chch, 1)) { return NULL; } for (k = 0; k < nkeywords; k++) { tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg; if (tmp && !PyUnicode_Compare(tmp, key)) { ast_error(c, chch, "keyword argument repeated"); return NULL; } } e = ast_for_expr(c, CHILD(ch, 2)); if (!e) return NULL; kw = keyword(key, e, c->c_arena); if (!kw) return NULL; asdl_seq_SET(keywords, nkeywords++, kw); } } } return Call(func, args, keywords, func->lineno, func->col_offset, closepar->n_end_lineno, closepar->n_end_col_offset, c->c_arena); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ast_for_funcdef_impl(struct compiling *c, const node *n0, asdl_seq *decorator_seq, bool is_async) { /* funcdef: 'def' NAME parameters ['->' test] ':' suite */ const node * const n = is_async ? CHILD(n0, 1) : n0; identifier name; arguments_ty args; asdl_seq *body; expr_ty returns = NULL; int name_i = 1; int end_lineno, end_col_offset; REQ(n, funcdef); name = NEW_IDENTIFIER(CHILD(n, name_i)); if (!name) return NULL; if (forbidden_name(c, name, CHILD(n, name_i), 0)) return NULL; args = ast_for_arguments(c, CHILD(n, name_i + 1)); if (!args) return NULL; if (TYPE(CHILD(n, name_i+2)) == RARROW) { returns = ast_for_expr(c, CHILD(n, name_i + 3)); if (!returns) return NULL; name_i += 2; } body = ast_for_suite(c, CHILD(n, name_i + 3)); if (!body) return NULL; get_last_end_pos(body, &end_lineno, &end_col_offset); if (is_async) return AsyncFunctionDef(name, args, body, decorator_seq, returns, LINENO(n0), n0->n_col_offset, end_lineno, end_col_offset, c->c_arena); else return FunctionDef(name, args, body, decorator_seq, returns, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'bpo-35766: Merge typed_ast back into CPython (GH-11645)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: handle_keywordonly_args(struct compiling *c, const node *n, int start, asdl_seq *kwonlyargs, asdl_seq *kwdefaults) { PyObject *argname; node *ch; expr_ty expression, annotation; arg_ty arg = NULL; int i = start; int j = 0; /* index for kwdefaults and kwonlyargs */ if (kwonlyargs == NULL) { ast_error(c, CHILD(n, start), "named arguments must follow bare *"); return -1; } assert(kwdefaults != NULL); while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { case vfpdef: case tfpdef: if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) goto error; asdl_seq_SET(kwdefaults, j, expression); i += 2; /* '=' and test */ } else { /* setting NULL if no default value exists */ asdl_seq_SET(kwdefaults, j, NULL); } if (NCH(ch) == 3) { /* ch is NAME ':' test */ annotation = ast_for_expr(c, CHILD(ch, 2)); if (!annotation) goto error; } else { annotation = NULL; } ch = CHILD(ch, 0); argname = NEW_IDENTIFIER(ch); if (!argname) goto error; if (forbidden_name(c, argname, ch, 0)) goto error; arg = arg(argname, annotation, NULL, LINENO(ch), ch->n_col_offset, c->c_arena); if (!arg) goto error; asdl_seq_SET(kwonlyargs, j++, arg); i += 1; /* the name */ if (TYPE(CHILD(n, i)) == COMMA) i += 1; /* the comma, if present */ break; case TYPE_COMMENT: /* arg will be equal to the last argument processed */ arg->type_comment = NEW_TYPE_COMMENT(ch); if (!arg->type_comment) goto error; i += 1; break; case DOUBLESTAR: return i; default: ast_error(c, ch, "unexpected node"); goto error; } } return i; error: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix two out-of-bounds array reads (#99) The patch is taken from a commit to the CPython repo with the message: bpo-36495: Fix two out-of-bounds array reads (GH-12641) Research and fix by @bradlarsen.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CtPtr ProtocolV2::handle_keepalive2(ceph::bufferlist &payload) { ldout(cct, 20) << __func__ << " payload.length()=" << payload.length() << dendl; if (state != READY) { lderr(cct) << __func__ << " not in ready state!" << dendl; return _fault(); } auto keepalive_frame = KeepAliveFrame::Decode(payload); ldout(cct, 30) << __func__ << " got KEEPALIVE2 tag ..." << dendl; connection->write_lock.lock(); append_keepalive_ack(keepalive_frame.timestamp()); connection->write_lock.unlock(); ldout(cct, 20) << __func__ << " got KEEPALIVE2 " << keepalive_frame.timestamp() << dendl; connection->set_last_keepalive(ceph_clock_now()); if (is_connected()) { connection->center->dispatch_event_external(connection->write_handler); } return CONTINUE(read_frame); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/ProtocolV2: avoid AES-GCM nonce reuse vulnerabilities The secure mode uses AES-128-GCM with 96-bit nonces consisting of a 32-bit counter followed by a 64-bit salt. The counter is incremented after processing each frame, the salt is fixed for the duration of the session. Both are initialized from the session key generated during session negotiation, so the counter starts with essentially a random value. It is allowed to wrap, and, after 2**32 frames, it repeats, resulting in nonce reuse (the actual sequence numbers that the messenger works with are 64-bit, so the session continues on). Because of how GCM works, this completely breaks both confidentiality and integrity aspects of the secure mode. A single nonce reuse reveals the XOR of two plaintexts and almost completely reveals the subkey used for producing authentication tags. After a few nonces get used twice, all confidentiality and integrity goes out the window and the attacker can potentially encrypt-authenticate plaintext of their choice. We can't easily change the nonce format to extend the counter to 64 bits (and possibly XOR it with a longer salt). Instead, just remember the initial nonce and cut the session before it repeats, forcing renegotiation. Signed-off-by: Ilya Dryomov <idryomov@gmail.com> Reviewed-by: Radoslaw Zarzynski <rzarzyns@redhat.com> Reviewed-by: Sage Weil <sage@redhat.com> Conflicts: src/msg/async/ProtocolV2.h [ context: commit ed3ec4c01d17 ("msg: Build target 'common' without using namespace in headers") not in octopus ]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ~AES128GCM_OnWireTxHandler() override { ::ceph::crypto::zeroize_for_security(&nonce, sizeof(nonce)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/ProtocolV2: avoid AES-GCM nonce reuse vulnerabilities The secure mode uses AES-128-GCM with 96-bit nonces consisting of a 32-bit counter followed by a 64-bit salt. The counter is incremented after processing each frame, the salt is fixed for the duration of the session. Both are initialized from the session key generated during session negotiation, so the counter starts with essentially a random value. It is allowed to wrap, and, after 2**32 frames, it repeats, resulting in nonce reuse (the actual sequence numbers that the messenger works with are 64-bit, so the session continues on). Because of how GCM works, this completely breaks both confidentiality and integrity aspects of the secure mode. A single nonce reuse reveals the XOR of two plaintexts and almost completely reveals the subkey used for producing authentication tags. After a few nonces get used twice, all confidentiality and integrity goes out the window and the attacker can potentially encrypt-authenticate plaintext of their choice. We can't easily change the nonce format to extend the counter to 64 bits (and possibly XOR it with a longer salt). Instead, just remember the initial nonce and cut the session before it repeats, forcing renegotiation. Signed-off-by: Ilya Dryomov <idryomov@gmail.com> Reviewed-by: Radoslaw Zarzynski <rzarzyns@redhat.com> Reviewed-by: Sage Weil <sage@redhat.com> Conflicts: src/msg/async/ProtocolV2.h [ context: commit ed3ec4c01d17 ("msg: Build target 'common' without using namespace in headers") not in octopus ]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ProtocolV2::append_keepalive() { ldout(cct, 10) << __func__ << dendl; auto keepalive_frame = KeepAliveFrame::Encode(); connection->outgoing_bl.append(keepalive_frame.get_buffer(session_stream_handlers)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/ProtocolV2: avoid AES-GCM nonce reuse vulnerabilities The secure mode uses AES-128-GCM with 96-bit nonces consisting of a 32-bit counter followed by a 64-bit salt. The counter is incremented after processing each frame, the salt is fixed for the duration of the session. Both are initialized from the session key generated during session negotiation, so the counter starts with essentially a random value. It is allowed to wrap, and, after 2**32 frames, it repeats, resulting in nonce reuse (the actual sequence numbers that the messenger works with are 64-bit, so the session continues on). Because of how GCM works, this completely breaks both confidentiality and integrity aspects of the secure mode. A single nonce reuse reveals the XOR of two plaintexts and almost completely reveals the subkey used for producing authentication tags. After a few nonces get used twice, all confidentiality and integrity goes out the window and the attacker can potentially encrypt-authenticate plaintext of their choice. We can't easily change the nonce format to extend the counter to 64 bits (and possibly XOR it with a longer salt). Instead, just remember the initial nonce and cut the session before it repeats, forcing renegotiation. Signed-off-by: Ilya Dryomov <idryomov@gmail.com> Reviewed-by: Radoslaw Zarzynski <rzarzyns@redhat.com> Reviewed-by: Sage Weil <sage@redhat.com> Conflicts: src/msg/async/ProtocolV2.h [ context: commit ed3ec4c01d17 ("msg: Build target 'common' without using namespace in headers") not in octopus ]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void AES128GCM_OnWireTxHandler::reset_tx_handler( std::initializer_list<std::uint32_t> update_size_sequence) { if(1 != EVP_EncryptInit_ex(ectx.get(), nullptr, nullptr, nullptr, reinterpret_cast<const unsigned char*>(&nonce))) { throw std::runtime_error("EVP_EncryptInit_ex failed"); } buffer.reserve(std::accumulate(std::begin(update_size_sequence), std::end(update_size_sequence), AESGCM_TAG_LEN)); ++nonce.random_seq; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/ProtocolV2: avoid AES-GCM nonce reuse vulnerabilities The secure mode uses AES-128-GCM with 96-bit nonces consisting of a 32-bit counter followed by a 64-bit salt. The counter is incremented after processing each frame, the salt is fixed for the duration of the session. Both are initialized from the session key generated during session negotiation, so the counter starts with essentially a random value. It is allowed to wrap, and, after 2**32 frames, it repeats, resulting in nonce reuse (the actual sequence numbers that the messenger works with are 64-bit, so the session continues on). Because of how GCM works, this completely breaks both confidentiality and integrity aspects of the secure mode. A single nonce reuse reveals the XOR of two plaintexts and almost completely reveals the subkey used for producing authentication tags. After a few nonces get used twice, all confidentiality and integrity goes out the window and the attacker can potentially encrypt-authenticate plaintext of their choice. We can't easily change the nonce format to extend the counter to 64 bits (and possibly XOR it with a longer salt). Instead, just remember the initial nonce and cut the session before it repeats, forcing renegotiation. Signed-off-by: Ilya Dryomov <idryomov@gmail.com> Reviewed-by: Radoslaw Zarzynski <rzarzyns@redhat.com> Reviewed-by: Sage Weil <sage@redhat.com> Conflicts: src/msg/async/ProtocolV2.h [ context: commit ed3ec4c01d17 ("msg: Build target 'common' without using namespace in headers") not in octopus ]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: AES128GCM_OnWireTxHandler(CephContext* const cct, const key_t& key, const nonce_t& nonce) : cct(cct), ectx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free), nonce(nonce) { ceph_assert_always(ectx); ceph_assert_always(key.size() * CHAR_BIT == 128); if (1 != EVP_EncryptInit_ex(ectx.get(), EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) { throw std::runtime_error("EVP_EncryptInit_ex failed"); } if(1 != EVP_EncryptInit_ex(ectx.get(), nullptr, nullptr, key.data(), nullptr)) { throw std::runtime_error("EVP_EncryptInit_ex failed"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/ProtocolV2: avoid AES-GCM nonce reuse vulnerabilities The secure mode uses AES-128-GCM with 96-bit nonces consisting of a 32-bit counter followed by a 64-bit salt. The counter is incremented after processing each frame, the salt is fixed for the duration of the session. Both are initialized from the session key generated during session negotiation, so the counter starts with essentially a random value. It is allowed to wrap, and, after 2**32 frames, it repeats, resulting in nonce reuse (the actual sequence numbers that the messenger works with are 64-bit, so the session continues on). Because of how GCM works, this completely breaks both confidentiality and integrity aspects of the secure mode. A single nonce reuse reveals the XOR of two plaintexts and almost completely reveals the subkey used for producing authentication tags. After a few nonces get used twice, all confidentiality and integrity goes out the window and the attacker can potentially encrypt-authenticate plaintext of their choice. We can't easily change the nonce format to extend the counter to 64 bits (and possibly XOR it with a longer salt). Instead, just remember the initial nonce and cut the session before it repeats, forcing renegotiation. Signed-off-by: Ilya Dryomov <idryomov@gmail.com> Reviewed-by: Radoslaw Zarzynski <rzarzyns@redhat.com> Reviewed-by: Sage Weil <sage@redhat.com> Conflicts: src/msg/async/ProtocolV2.h [ context: commit ed3ec4c01d17 ("msg: Build target 'common' without using namespace in headers") not in octopus ]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void AES128GCM_OnWireRxHandler::reset_rx_handler() { if(1 != EVP_DecryptInit_ex(ectx.get(), nullptr, nullptr, nullptr, reinterpret_cast<const unsigned char*>(&nonce))) { throw std::runtime_error("EVP_DecryptInit_ex failed"); } ++nonce.random_seq; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/crypto_onwire: fix endianness of nonce_t As a AES-GCM IV, nonce_t is implicitly shared between server and client. Currently, if their endianness doesn't match, they are unable to communicate in secure mode because each gets its own idea of what the next nonce should be after the counter is incremented. Several RFCs state that the nonce counter should be BE, but since we use LE for everything on-disk and on-wire, make it LE. Signed-off-by: Ilya Dryomov <idryomov@gmail.com> Reviewed-by: Radoslaw Zarzynski <rzarzyns@redhat.com> Reviewed-by: Sage Weil <sage@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ssize_t ProtocolV2::write_message(Message *m, bool more) { FUNCTRACE(cct); ceph_assert(connection->center->in_thread()); m->set_seq(++out_seq); connection->lock.lock(); uint64_t ack_seq = in_seq; ack_left = 0; connection->lock.unlock(); ceph_msg_header &header = m->get_header(); ceph_msg_footer &footer = m->get_footer(); ceph_msg_header2 header2{header.seq, header.tid, header.type, header.priority, header.version, init_le32(0), header.data_off, init_le64(ack_seq), footer.flags, header.compat_version, header.reserved}; auto message = MessageFrame::Encode( header2, m->get_payload(), m->get_middle(), m->get_data()); connection->outgoing_bl.append(message.get_buffer(session_stream_handlers)); ldout(cct, 5) << __func__ << " sending message m=" << m << " seq=" << m->get_seq() << " " << *m << dendl; m->trace.event("async writing message"); ldout(cct, 20) << __func__ << " sending m=" << m << " seq=" << m->get_seq() << " src=" << entity_name_t(messenger->get_myname()) << " off=" << header2.data_off << dendl; ssize_t total_send_size = connection->outgoing_bl.length(); ssize_t rc = connection->_try_send(more); if (rc < 0) { ldout(cct, 1) << __func__ << " error sending " << m << ", " << cpp_strerror(rc) << dendl; } else { connection->logger->inc( l_msgr_send_bytes, total_send_size - connection->outgoing_bl.length()); ldout(cct, 10) << __func__ << " sending " << m << (rc ? " continuely." : " done.") << dendl; } if (m->get_type() == CEPH_MSG_OSD_OP) OID_EVENT_TRACE_WITH_MSG(m, "SEND_MSG_OSD_OP_END", false); else if (m->get_type() == CEPH_MSG_OSD_OPREPLY) OID_EVENT_TRACE_WITH_MSG(m, "SEND_MSG_OSD_OPREPLY_END", false); m->put(); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-323'], 'message': 'msg/async/ProtocolV2: avoid AES-GCM nonce reuse vulnerabilities The secure mode uses AES-128-GCM with 96-bit nonces consisting of a 32-bit counter followed by a 64-bit salt. The counter is incremented after processing each frame, the salt is fixed for the duration of the session. Both are initialized from the session key generated during session negotiation, so the counter starts with essentially a random value. It is allowed to wrap, and, after 2**32 frames, it repeats, resulting in nonce reuse (the actual sequence numbers that the messenger works with are 64-bit, so the session continues on). Because of how GCM works, this completely breaks both confidentiality and integrity aspects of the secure mode. A single nonce reuse reveals the XOR of two plaintexts and almost completely reveals the subkey used for producing authentication tags. After a few nonces get used twice, all confidentiality and integrity goes out the window and the attacker can potentially encrypt-authenticate plaintext of their choice. We can't easily change the nonce format to extend the counter to 64 bits (and possibly XOR it with a longer salt). Instead, just remember the initial nonce and cut the session before it repeats, forcing renegotiation. Signed-off-by: Ilya Dryomov <idryomov@gmail.com> Reviewed-by: Radoslaw Zarzynski <rzarzyns@redhat.com> Reviewed-by: Sage Weil <sage@redhat.com> Conflicts: src/msg/async/ProtocolV2.cc [ context: commit 697aafa2aad2 ("msg/async/ProtocolV2: remove unused parameter") not in nautilus ] src/msg/async/ProtocolV2.h [ context: commit ed3ec4c01d17 ("msg: Build target 'common' without using namespace in headers") not in nautilus ]'</s>